example.e31bb0bc.js 1.4 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818
  1. // modules are defined as an array
  2. // [ module function, map of requires ]
  3. //
  4. // map of requires is short require name -> numeric require
  5. //
  6. // anything defined in a previous bundle is accessed via the
  7. // orig method which is the require for previous bundles
  8. parcelRequire = (function (modules, cache, entry, globalName) {
  9. // Save the require from previous bundle to this closure if any
  10. var previousRequire = typeof parcelRequire === 'function' && parcelRequire;
  11. var nodeRequire = typeof require === 'function' && require;
  12. function newRequire(name, jumped) {
  13. if (!cache[name]) {
  14. if (!modules[name]) {
  15. // if we cannot find the module within our internal map or
  16. // cache jump to the current global require ie. the last bundle
  17. // that was added to the page.
  18. var currentRequire = typeof parcelRequire === 'function' && parcelRequire;
  19. if (!jumped && currentRequire) {
  20. return currentRequire(name, true);
  21. }
  22. // If there are other bundles on this page the require from the
  23. // previous one is saved to 'previousRequire'. Repeat this as
  24. // many times as there are bundles until the module is found or
  25. // we exhaust the require chain.
  26. if (previousRequire) {
  27. return previousRequire(name, true);
  28. }
  29. // Try the node require function if it exists.
  30. if (nodeRequire && typeof name === 'string') {
  31. return nodeRequire(name);
  32. }
  33. var err = new Error('Cannot find module \'' + name + '\'');
  34. err.code = 'MODULE_NOT_FOUND';
  35. throw err;
  36. }
  37. localRequire.resolve = resolve;
  38. localRequire.cache = {};
  39. var module = cache[name] = new newRequire.Module(name);
  40. modules[name][0].call(module.exports, localRequire, module, module.exports, this);
  41. }
  42. return cache[name].exports;
  43. function localRequire(x){
  44. return newRequire(localRequire.resolve(x));
  45. }
  46. function resolve(x){
  47. return modules[name][1][x] || x;
  48. }
  49. }
  50. function Module(moduleName) {
  51. this.id = moduleName;
  52. this.bundle = newRequire;
  53. this.exports = {};
  54. }
  55. newRequire.isParcelRequire = true;
  56. newRequire.Module = Module;
  57. newRequire.modules = modules;
  58. newRequire.cache = cache;
  59. newRequire.parent = previousRequire;
  60. newRequire.register = function (id, exports) {
  61. modules[id] = [function (require, module) {
  62. module.exports = exports;
  63. }, {}];
  64. };
  65. var error;
  66. for (var i = 0; i < entry.length; i++) {
  67. try {
  68. newRequire(entry[i]);
  69. } catch (e) {
  70. // Save first error but execute all entries
  71. if (!error) {
  72. error = e;
  73. }
  74. }
  75. }
  76. if (entry.length) {
  77. // Expose entry point to Node, AMD or browser globals
  78. // Based on https://github.com/ForbesLindesay/umd/blob/master/template.js
  79. var mainExports = newRequire(entry[entry.length - 1]);
  80. // CommonJS
  81. if (typeof exports === "object" && typeof module !== "undefined") {
  82. module.exports = mainExports;
  83. // RequireJS
  84. } else if (typeof define === "function" && define.amd) {
  85. define(function () {
  86. return mainExports;
  87. });
  88. // <script>
  89. } else if (globalName) {
  90. this[globalName] = mainExports;
  91. }
  92. }
  93. // Override the current require with this new one
  94. parcelRequire = newRequire;
  95. if (error) {
  96. // throw error from earlier, _after updating parcelRequire_
  97. throw error;
  98. }
  99. return newRequire;
  100. })({"../node_modules/process/browser.js":[function(require,module,exports) {
  101. // shim for using process in browser
  102. var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it
  103. // don't break things. But we need to wrap it in a try catch in case it is
  104. // wrapped in strict mode code which doesn't define any globals. It's inside a
  105. // function because try/catches deoptimize in certain engines.
  106. var cachedSetTimeout;
  107. var cachedClearTimeout;
  108. function defaultSetTimout() {
  109. throw new Error('setTimeout has not been defined');
  110. }
  111. function defaultClearTimeout() {
  112. throw new Error('clearTimeout has not been defined');
  113. }
  114. (function () {
  115. try {
  116. if (typeof setTimeout === 'function') {
  117. cachedSetTimeout = setTimeout;
  118. } else {
  119. cachedSetTimeout = defaultSetTimout;
  120. }
  121. } catch (e) {
  122. cachedSetTimeout = defaultSetTimout;
  123. }
  124. try {
  125. if (typeof clearTimeout === 'function') {
  126. cachedClearTimeout = clearTimeout;
  127. } else {
  128. cachedClearTimeout = defaultClearTimeout;
  129. }
  130. } catch (e) {
  131. cachedClearTimeout = defaultClearTimeout;
  132. }
  133. })();
  134. function runTimeout(fun) {
  135. if (cachedSetTimeout === setTimeout) {
  136. //normal enviroments in sane situations
  137. return setTimeout(fun, 0);
  138. } // if setTimeout wasn't available but was latter defined
  139. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  140. cachedSetTimeout = setTimeout;
  141. return setTimeout(fun, 0);
  142. }
  143. try {
  144. // when when somebody has screwed with setTimeout but no I.E. maddness
  145. return cachedSetTimeout(fun, 0);
  146. } catch (e) {
  147. try {
  148. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  149. return cachedSetTimeout.call(null, fun, 0);
  150. } catch (e) {
  151. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  152. return cachedSetTimeout.call(this, fun, 0);
  153. }
  154. }
  155. }
  156. function runClearTimeout(marker) {
  157. if (cachedClearTimeout === clearTimeout) {
  158. //normal enviroments in sane situations
  159. return clearTimeout(marker);
  160. } // if clearTimeout wasn't available but was latter defined
  161. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  162. cachedClearTimeout = clearTimeout;
  163. return clearTimeout(marker);
  164. }
  165. try {
  166. // when when somebody has screwed with setTimeout but no I.E. maddness
  167. return cachedClearTimeout(marker);
  168. } catch (e) {
  169. try {
  170. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  171. return cachedClearTimeout.call(null, marker);
  172. } catch (e) {
  173. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  174. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  175. return cachedClearTimeout.call(this, marker);
  176. }
  177. }
  178. }
  179. var queue = [];
  180. var draining = false;
  181. var currentQueue;
  182. var queueIndex = -1;
  183. function cleanUpNextTick() {
  184. if (!draining || !currentQueue) {
  185. return;
  186. }
  187. draining = false;
  188. if (currentQueue.length) {
  189. queue = currentQueue.concat(queue);
  190. } else {
  191. queueIndex = -1;
  192. }
  193. if (queue.length) {
  194. drainQueue();
  195. }
  196. }
  197. function drainQueue() {
  198. if (draining) {
  199. return;
  200. }
  201. var timeout = runTimeout(cleanUpNextTick);
  202. draining = true;
  203. var len = queue.length;
  204. while (len) {
  205. currentQueue = queue;
  206. queue = [];
  207. while (++queueIndex < len) {
  208. if (currentQueue) {
  209. currentQueue[queueIndex].run();
  210. }
  211. }
  212. queueIndex = -1;
  213. len = queue.length;
  214. }
  215. currentQueue = null;
  216. draining = false;
  217. runClearTimeout(timeout);
  218. }
  219. process.nextTick = function (fun) {
  220. var args = new Array(arguments.length - 1);
  221. if (arguments.length > 1) {
  222. for (var i = 1; i < arguments.length; i++) {
  223. args[i - 1] = arguments[i];
  224. }
  225. }
  226. queue.push(new Item(fun, args));
  227. if (queue.length === 1 && !draining) {
  228. runTimeout(drainQueue);
  229. }
  230. }; // v8 likes predictible objects
  231. function Item(fun, array) {
  232. this.fun = fun;
  233. this.array = array;
  234. }
  235. Item.prototype.run = function () {
  236. this.fun.apply(null, this.array);
  237. };
  238. process.title = 'browser';
  239. process.env = {};
  240. process.argv = [];
  241. process.version = ''; // empty string to avoid regexp issues
  242. process.versions = {};
  243. function noop() {}
  244. process.on = noop;
  245. process.addListener = noop;
  246. process.once = noop;
  247. process.off = noop;
  248. process.removeListener = noop;
  249. process.removeAllListeners = noop;
  250. process.emit = noop;
  251. process.prependListener = noop;
  252. process.prependOnceListener = noop;
  253. process.listeners = function (name) {
  254. return [];
  255. };
  256. process.binding = function (name) {
  257. throw new Error('process.binding is not supported');
  258. };
  259. process.cwd = function () {
  260. return '/';
  261. };
  262. process.chdir = function (dir) {
  263. throw new Error('process.chdir is not supported');
  264. };
  265. process.umask = function () {
  266. return 0;
  267. };
  268. },{}],"../node_modules/path-browserify/index.js":[function(require,module,exports) {
  269. var process = require("process");
  270. // .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1,
  271. // backported and transplited with Babel, with backwards-compat fixes
  272. // Copyright Joyent, Inc. and other Node contributors.
  273. //
  274. // Permission is hereby granted, free of charge, to any person obtaining a
  275. // copy of this software and associated documentation files (the
  276. // "Software"), to deal in the Software without restriction, including
  277. // without limitation the rights to use, copy, modify, merge, publish,
  278. // distribute, sublicense, and/or sell copies of the Software, and to permit
  279. // persons to whom the Software is furnished to do so, subject to the
  280. // following conditions:
  281. //
  282. // The above copyright notice and this permission notice shall be included
  283. // in all copies or substantial portions of the Software.
  284. //
  285. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  286. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  287. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  288. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  289. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  290. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  291. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  292. // resolves . and .. elements in a path array with directory names there
  293. // must be no slashes, empty elements, or device names (c:\) in the array
  294. // (so also no leading and trailing slashes - it does not distinguish
  295. // relative and absolute paths)
  296. function normalizeArray(parts, allowAboveRoot) {
  297. // if the path tries to go above the root, `up` ends up > 0
  298. var up = 0;
  299. for (var i = parts.length - 1; i >= 0; i--) {
  300. var last = parts[i];
  301. if (last === '.') {
  302. parts.splice(i, 1);
  303. } else if (last === '..') {
  304. parts.splice(i, 1);
  305. up++;
  306. } else if (up) {
  307. parts.splice(i, 1);
  308. up--;
  309. }
  310. }
  311. // if the path is allowed to go above the root, restore leading ..s
  312. if (allowAboveRoot) {
  313. for (; up--; up) {
  314. parts.unshift('..');
  315. }
  316. }
  317. return parts;
  318. }
  319. // path.resolve([from ...], to)
  320. // posix version
  321. exports.resolve = function() {
  322. var resolvedPath = '',
  323. resolvedAbsolute = false;
  324. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  325. var path = (i >= 0) ? arguments[i] : process.cwd();
  326. // Skip empty and invalid entries
  327. if (typeof path !== 'string') {
  328. throw new TypeError('Arguments to path.resolve must be strings');
  329. } else if (!path) {
  330. continue;
  331. }
  332. resolvedPath = path + '/' + resolvedPath;
  333. resolvedAbsolute = path.charAt(0) === '/';
  334. }
  335. // At this point the path should be resolved to a full absolute path, but
  336. // handle relative paths to be safe (might happen when process.cwd() fails)
  337. // Normalize the path
  338. resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
  339. return !!p;
  340. }), !resolvedAbsolute).join('/');
  341. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  342. };
  343. // path.normalize(path)
  344. // posix version
  345. exports.normalize = function(path) {
  346. var isAbsolute = exports.isAbsolute(path),
  347. trailingSlash = substr(path, -1) === '/';
  348. // Normalize the path
  349. path = normalizeArray(filter(path.split('/'), function(p) {
  350. return !!p;
  351. }), !isAbsolute).join('/');
  352. if (!path && !isAbsolute) {
  353. path = '.';
  354. }
  355. if (path && trailingSlash) {
  356. path += '/';
  357. }
  358. return (isAbsolute ? '/' : '') + path;
  359. };
  360. // posix version
  361. exports.isAbsolute = function(path) {
  362. return path.charAt(0) === '/';
  363. };
  364. // posix version
  365. exports.join = function() {
  366. var paths = Array.prototype.slice.call(arguments, 0);
  367. return exports.normalize(filter(paths, function(p, index) {
  368. if (typeof p !== 'string') {
  369. throw new TypeError('Arguments to path.join must be strings');
  370. }
  371. return p;
  372. }).join('/'));
  373. };
  374. // path.relative(from, to)
  375. // posix version
  376. exports.relative = function(from, to) {
  377. from = exports.resolve(from).substr(1);
  378. to = exports.resolve(to).substr(1);
  379. function trim(arr) {
  380. var start = 0;
  381. for (; start < arr.length; start++) {
  382. if (arr[start] !== '') break;
  383. }
  384. var end = arr.length - 1;
  385. for (; end >= 0; end--) {
  386. if (arr[end] !== '') break;
  387. }
  388. if (start > end) return [];
  389. return arr.slice(start, end - start + 1);
  390. }
  391. var fromParts = trim(from.split('/'));
  392. var toParts = trim(to.split('/'));
  393. var length = Math.min(fromParts.length, toParts.length);
  394. var samePartsLength = length;
  395. for (var i = 0; i < length; i++) {
  396. if (fromParts[i] !== toParts[i]) {
  397. samePartsLength = i;
  398. break;
  399. }
  400. }
  401. var outputParts = [];
  402. for (var i = samePartsLength; i < fromParts.length; i++) {
  403. outputParts.push('..');
  404. }
  405. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  406. return outputParts.join('/');
  407. };
  408. exports.sep = '/';
  409. exports.delimiter = ':';
  410. exports.dirname = function (path) {
  411. if (typeof path !== 'string') path = path + '';
  412. if (path.length === 0) return '.';
  413. var code = path.charCodeAt(0);
  414. var hasRoot = code === 47 /*/*/;
  415. var end = -1;
  416. var matchedSlash = true;
  417. for (var i = path.length - 1; i >= 1; --i) {
  418. code = path.charCodeAt(i);
  419. if (code === 47 /*/*/) {
  420. if (!matchedSlash) {
  421. end = i;
  422. break;
  423. }
  424. } else {
  425. // We saw the first non-path separator
  426. matchedSlash = false;
  427. }
  428. }
  429. if (end === -1) return hasRoot ? '/' : '.';
  430. if (hasRoot && end === 1) {
  431. // return '//';
  432. // Backwards-compat fix:
  433. return '/';
  434. }
  435. return path.slice(0, end);
  436. };
  437. function basename(path) {
  438. if (typeof path !== 'string') path = path + '';
  439. var start = 0;
  440. var end = -1;
  441. var matchedSlash = true;
  442. var i;
  443. for (i = path.length - 1; i >= 0; --i) {
  444. if (path.charCodeAt(i) === 47 /*/*/) {
  445. // If we reached a path separator that was not part of a set of path
  446. // separators at the end of the string, stop now
  447. if (!matchedSlash) {
  448. start = i + 1;
  449. break;
  450. }
  451. } else if (end === -1) {
  452. // We saw the first non-path separator, mark this as the end of our
  453. // path component
  454. matchedSlash = false;
  455. end = i + 1;
  456. }
  457. }
  458. if (end === -1) return '';
  459. return path.slice(start, end);
  460. }
  461. // Uses a mixed approach for backwards-compatibility, as ext behavior changed
  462. // in new Node.js versions, so only basename() above is backported here
  463. exports.basename = function (path, ext) {
  464. var f = basename(path);
  465. if (ext && f.substr(-1 * ext.length) === ext) {
  466. f = f.substr(0, f.length - ext.length);
  467. }
  468. return f;
  469. };
  470. exports.extname = function (path) {
  471. if (typeof path !== 'string') path = path + '';
  472. var startDot = -1;
  473. var startPart = 0;
  474. var end = -1;
  475. var matchedSlash = true;
  476. // Track the state of characters (if any) we see before our first dot and
  477. // after any path separator we find
  478. var preDotState = 0;
  479. for (var i = path.length - 1; i >= 0; --i) {
  480. var code = path.charCodeAt(i);
  481. if (code === 47 /*/*/) {
  482. // If we reached a path separator that was not part of a set of path
  483. // separators at the end of the string, stop now
  484. if (!matchedSlash) {
  485. startPart = i + 1;
  486. break;
  487. }
  488. continue;
  489. }
  490. if (end === -1) {
  491. // We saw the first non-path separator, mark this as the end of our
  492. // extension
  493. matchedSlash = false;
  494. end = i + 1;
  495. }
  496. if (code === 46 /*.*/) {
  497. // If this is our first dot, mark it as the start of our extension
  498. if (startDot === -1)
  499. startDot = i;
  500. else if (preDotState !== 1)
  501. preDotState = 1;
  502. } else if (startDot !== -1) {
  503. // We saw a non-dot and non-path separator before our dot, so we should
  504. // have a good chance at having a non-empty extension
  505. preDotState = -1;
  506. }
  507. }
  508. if (startDot === -1 || end === -1 ||
  509. // We saw a non-dot character immediately before the dot
  510. preDotState === 0 ||
  511. // The (right-most) trimmed path component is exactly '..'
  512. preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
  513. return '';
  514. }
  515. return path.slice(startDot, end);
  516. };
  517. function filter (xs, f) {
  518. if (xs.filter) return xs.filter(f);
  519. var res = [];
  520. for (var i = 0; i < xs.length; i++) {
  521. if (f(xs[i], i, xs)) res.push(xs[i]);
  522. }
  523. return res;
  524. }
  525. // String.prototype.substr - negative index don't work in IE8
  526. var substr = 'ab'.substr(-1) === 'b'
  527. ? function (str, start, len) { return str.substr(start, len) }
  528. : function (str, start, len) {
  529. if (start < 0) start = str.length + start;
  530. return str.substr(start, len);
  531. }
  532. ;
  533. },{"process":"../node_modules/process/browser.js"}],"../src/LRUCache.js":[function(require,module,exports) {
  534. "use strict";
  535. Object.defineProperty(exports, "__esModule", {
  536. value: true
  537. });
  538. exports.LRUCache = void 0;
  539. class LRUCache {
  540. constructor() {
  541. // options
  542. this.maxSize = 800;
  543. this.minSize = 600;
  544. this.unloadPercent = 0.2;
  545. this.usedSet = new Set();
  546. this.itemSet = new Set();
  547. this.itemList = [];
  548. this.callbacks = new Map();
  549. } // Returns whether or not the cache has reached the maximum size
  550. isFull() {
  551. return this.itemSet.size >= this.maxSize;
  552. }
  553. add(item, removeCb) {
  554. const itemSet = this.itemSet;
  555. if (itemSet.has(item)) {
  556. return false;
  557. }
  558. if (this.isFull()) {
  559. return false;
  560. }
  561. const usedSet = this.usedSet;
  562. const itemList = this.itemList;
  563. const callbacks = this.callbacks;
  564. itemList.push(item);
  565. usedSet.add(item);
  566. itemSet.add(item);
  567. callbacks.set(item, removeCb);
  568. return true;
  569. }
  570. remove(item) {
  571. const usedSet = this.usedSet;
  572. const itemSet = this.itemSet;
  573. const itemList = this.itemList;
  574. const callbacks = this.callbacks;
  575. if (itemSet.has(item)) {
  576. callbacks.get(item)(item);
  577. const index = itemList.indexOf(item);
  578. itemList.splice(index, 1);
  579. usedSet.delete(item);
  580. itemSet.delete(item);
  581. callbacks.delete(item);
  582. return true;
  583. }
  584. return false;
  585. }
  586. markUsed(item) {
  587. const itemSet = this.itemSet;
  588. const usedSet = this.usedSet;
  589. if (itemSet.has(item) && !usedSet.has(item)) {
  590. const itemList = this.itemList;
  591. const index = itemList.indexOf(item);
  592. itemList.splice(index, 1);
  593. itemList.push(item);
  594. usedSet.add(item);
  595. }
  596. }
  597. markAllUnused() {
  598. this.usedSet.clear();
  599. }
  600. unloadUnusedContent(prioritySortCb) {
  601. const unloadPercent = this.unloadPercent;
  602. const targetSize = this.minSize;
  603. const itemList = this.itemList;
  604. const itemSet = this.itemSet;
  605. const usedSet = this.usedSet;
  606. const callbacks = this.callbacks;
  607. const unused = itemList.length - usedSet.size;
  608. if (itemList.length > targetSize && unused > 0) {
  609. // TODO: sort by priority
  610. let nodesToUnload = Math.max(itemList.length - targetSize, targetSize) * unloadPercent;
  611. nodesToUnload = Math.ceil(nodesToUnload);
  612. nodesToUnload = Math.min(unused, nodesToUnload);
  613. const removedItems = itemList.splice(0, nodesToUnload);
  614. for (let i = 0, l = removedItems.length; i < l; i++) {
  615. const item = removedItems[i];
  616. callbacks.get(item)(item);
  617. itemSet.delete(item);
  618. callbacks.delete(item);
  619. }
  620. }
  621. }
  622. scheduleUnload(prioritySortCb, markAllUnused = true) {
  623. if (!this.scheduled) {
  624. this.scheduled = true;
  625. Promise.resolve().then(() => {
  626. this.scheduled = false;
  627. this.unloadUnusedContent(prioritySortCb);
  628. if (markAllUnused) {
  629. this.markAllUnused();
  630. }
  631. });
  632. }
  633. }
  634. }
  635. exports.LRUCache = LRUCache;
  636. },{}],"../src/PriorityQueue.js":[function(require,module,exports) {
  637. "use strict";
  638. Object.defineProperty(exports, "__esModule", {
  639. value: true
  640. });
  641. exports.PriorityQueue = void 0;
  642. class PriorityQueue {
  643. constructor(maxJobs = 6) {
  644. // options
  645. this.maxJobs = maxJobs;
  646. this.items = [];
  647. this.currJobs = 0;
  648. this.scheduled = false;
  649. }
  650. add(item, priority, callback) {
  651. return new Promise((resolve, reject) => {
  652. const prCallback = (...args) => callback(...args).then(resolve).catch(reject);
  653. const items = this.items;
  654. for (let i = 0, l = items.length; i < l; i++) {
  655. const thisItem = items[i];
  656. if (thisItem.priority > priority) {
  657. items.splice(i, 0, {
  658. priority,
  659. item,
  660. callback: prCallback
  661. });
  662. this.scheduleJobRun();
  663. return;
  664. }
  665. }
  666. items.push({
  667. priority,
  668. item,
  669. callback: prCallback
  670. });
  671. this.scheduleJobRun();
  672. });
  673. }
  674. remove(item) {
  675. const items = this.items;
  676. for (let i = 0, l = items.length; i < l; i++) {
  677. const thisItem = items[i];
  678. if (thisItem.item === item) {
  679. items.splice(i, 1);
  680. break;
  681. }
  682. }
  683. }
  684. tryRunJobs() {
  685. const items = this.items;
  686. const maxJobs = this.maxJobs;
  687. while (maxJobs > this.currJobs && items.length > 0) {
  688. this.currJobs++;
  689. const {
  690. item,
  691. priority,
  692. callback
  693. } = items.pop();
  694. callback(item, priority).then(() => {
  695. this.currJobs--;
  696. this.scheduleJobRun();
  697. }).catch(() => {
  698. this.currJobs--;
  699. this.scheduleJobRun();
  700. });
  701. }
  702. }
  703. scheduleJobRun() {
  704. if (!this.scheduled) {
  705. Promise.resolve().then(() => {
  706. this.tryRunJobs();
  707. this.scheduled = false;
  708. });
  709. this.scheduled = true;
  710. }
  711. }
  712. }
  713. exports.PriorityQueue = PriorityQueue;
  714. },{}],"../src/TilesRenderer.js":[function(require,module,exports) {
  715. "use strict";
  716. Object.defineProperty(exports, "__esModule", {
  717. value: true
  718. });
  719. exports.TilesRenderer = void 0;
  720. var _path = _interopRequireDefault(require("path"));
  721. var _LRUCache = require("./LRUCache.js");
  722. var _PriorityQueue = require("./PriorityQueue.js");
  723. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  724. // TODO: find out why tiles are left dangling in the hierarchy
  725. // TODO: Address the issue of too many promises, garbage collection
  726. // TODO: remove more redundant computation
  727. // TODO: See if using classes improves performance
  728. // TODO: See if declaring function inline improves performance
  729. // TODO: Make sure active state works as expected
  730. const UNLOADED = 0;
  731. const LOADING = 1;
  732. const PARSING = 2;
  733. const LOADED = 3;
  734. const FAILED = 4;
  735. function traverseSet(tile, beforeCb = null, afterCb = null, parent = null, depth = 0) {
  736. if (beforeCb && beforeCb(tile, parent, depth)) {
  737. if (afterCb) {
  738. afterCb(tile, parent, depth);
  739. }
  740. return;
  741. }
  742. const children = tile.children;
  743. for (let i = 0, l = children.length; i < l; i++) {
  744. traverseSet(children[i], beforeCb, afterCb, tile, depth + 1);
  745. }
  746. if (afterCb) {
  747. afterCb(tile, parent, depth);
  748. }
  749. }
  750. function isUsedThisFrame(tile, frameCount) {
  751. return tile.__lastFrameVisited === frameCount && tile.__used;
  752. }
  753. function resetFrameState(tile, frameCount) {
  754. if (tile.__lastFrameVisited !== frameCount) {
  755. tile.__lastFrameVisited = frameCount;
  756. tile.__used = false;
  757. tile.__inFrustum = false;
  758. tile.__isLeaf = false;
  759. tile.__visible = false;
  760. tile.__active = false;
  761. tile.__error = 0;
  762. }
  763. }
  764. function recursivelyMarkUsed(tile, frameCount, lruCache) {
  765. resetFrameState(tile, frameCount);
  766. tile.__used = true;
  767. lruCache.markUsed(tile);
  768. if (tile.__contentEmpty) {
  769. const children = tile.children;
  770. for (let i = 0, l = children.length; i < l; i++) {
  771. recursivelyMarkUsed(children[i], frameCount, lruCache);
  772. }
  773. }
  774. } // TODO: include frustum mask here?
  775. function determineFrustumSet(tile, renderer) {
  776. const stats = renderer.stats;
  777. const frameCount = renderer.frameCount;
  778. const errorTarget = renderer.errorTarget;
  779. const maxDepth = renderer.maxDepth;
  780. const loadSiblings = renderer.loadSiblings;
  781. const lruCache = renderer.lruCache;
  782. resetFrameState(tile, frameCount);
  783. const inFrustum = renderer.tileInView(tile);
  784. if (inFrustum === false) {
  785. return false;
  786. }
  787. tile.__used = true;
  788. lruCache.markUsed(tile);
  789. tile.__inFrustum = true;
  790. stats.inFrustum++;
  791. if (!tile.__contentEmpty) {
  792. const error = renderer.calculateError(tile);
  793. tile.__error = error;
  794. if (error <= errorTarget) {
  795. return true;
  796. }
  797. }
  798. if (renderer.maxDepth > 0 && tile.__depth + 1 >= maxDepth) {
  799. return true;
  800. }
  801. let anyChildrenUsed = false;
  802. const children = tile.children;
  803. for (let i = 0, l = children.length; i < l; i++) {
  804. const c = children[i];
  805. const r = determineFrustumSet(c, renderer);
  806. anyChildrenUsed = anyChildrenUsed || r;
  807. }
  808. if (anyChildrenUsed && loadSiblings) {
  809. for (let i = 0, l = children.length; i < l; i++) {
  810. recursivelyMarkUsed(tile, frameCount, lruCache);
  811. }
  812. }
  813. return true;
  814. }
  815. function markUsedSetLeaves(tile, renderer) {
  816. const stats = renderer.stats;
  817. const frameCount = renderer.frameCount;
  818. if (!isUsedThisFrame(tile, frameCount)) {
  819. return;
  820. }
  821. stats.used++;
  822. const children = tile.children;
  823. let anyChildrenUsed = false;
  824. for (let i = 0, l = children.length; i < l; i++) {
  825. const c = children[i];
  826. anyChildrenUsed = anyChildrenUsed || isUsedThisFrame(c, frameCount);
  827. }
  828. if (!anyChildrenUsed) {
  829. tile.__isLeaf = true; // TODO: stats
  830. } else {
  831. for (let i = 0, l = children.length; i < l; i++) {
  832. const c = children[i];
  833. markUsedSetLeaves(c, renderer);
  834. }
  835. }
  836. }
  837. function skipTraversal(tile, renderer) {
  838. const stats = renderer.stats;
  839. const frameCount = renderer.frameCount;
  840. if (!isUsedThisFrame(tile, frameCount)) {
  841. return;
  842. }
  843. const lruCache = renderer.lruCache;
  844. if (tile.__isLeaf) {
  845. if (tile.__loadingState === LOADED) {
  846. if (tile.__inFrustum) {
  847. tile.__visible = true;
  848. stats.visible++;
  849. }
  850. tile.__active = true;
  851. stats.active++;
  852. } else if (!lruCache.isFull()) {
  853. renderer.requestTileContents(tile);
  854. }
  855. return;
  856. }
  857. const errorRequirement = renderer.errorTarget * renderer.errorThreshold;
  858. const meetsSSE = tile.__error < errorRequirement;
  859. const hasContent = tile.__loadingState === LOADED && !tile.__contentEmpty;
  860. const children = tile.children;
  861. let allChildrenHaveContent = true;
  862. for (let i = 0, l = children.length; i < l; i++) {
  863. const c = children[i];
  864. if (isUsedThisFrame(c, frameCount)) {
  865. const childContent = c.__loadingState === LOADED || tile.__contentEmpty;
  866. allChildrenHaveContent = allChildrenHaveContent && childContent;
  867. }
  868. }
  869. if (meetsSSE && !hasContent && !lruCache.isFull()) {
  870. renderer.requestTileContents(tile);
  871. }
  872. if (meetsSSE && hasContent && !allChildrenHaveContent) {
  873. if (tile.__inFrustum) {
  874. tile.__visible = true;
  875. stats.visible++;
  876. }
  877. tile.__active = true;
  878. stats.active++;
  879. for (let i = 0, l = children.length; i < l; i++) {
  880. const c = children[i];
  881. if (isUsedThisFrame(c, frameCount) && !lruCache.isFull()) {
  882. renderer.requestTileContents(c);
  883. }
  884. }
  885. return;
  886. }
  887. for (let i = 0, l = children.length; i < l; i++) {
  888. const c = children[i];
  889. if (isUsedThisFrame(c, frameCount)) {
  890. skipTraversal(c, renderer);
  891. }
  892. }
  893. }
  894. function toggleTiles(tile, renderer) {
  895. const frameCount = renderer.frameCount;
  896. const isUsed = isUsedThisFrame(tile, frameCount);
  897. if (isUsed || tile.__usedLastFrame) {
  898. if (!isUsed) {
  899. if (!tile.__contentEmpty && tile.__loadingState === LOADED) {
  900. renderer.setTileVisible(tile, false);
  901. renderer.setTileActive(tile, false);
  902. }
  903. tile.__usedLastFrame = false;
  904. } else {
  905. if (!tile.__contentEmpty && tile.__loadingState === LOADED) {
  906. // enable visibility if active due to shadows
  907. renderer.setTileActive(tile, tile.__active);
  908. renderer.setTileVisible(tile, tile.__active || tile.__visible);
  909. }
  910. tile.__usedLastFrame = true;
  911. }
  912. const children = tile.children;
  913. for (let i = 0, l = children.length; i < l; i++) {
  914. const c = children[i];
  915. toggleTiles(c, renderer);
  916. }
  917. }
  918. }
  919. class TilesRenderer {
  920. get root() {
  921. const tileSet = this.tileSets[this.rootSet];
  922. if (!tileSet || tileSet instanceof Promise) {
  923. return null;
  924. } else {
  925. return tileSet.root;
  926. }
  927. }
  928. constructor(url, cache = new _LRUCache.LRUCache(), downloadQueue = new _PriorityQueue.PriorityQueue(6), parseQueue = new _PriorityQueue.PriorityQueue(2)) {
  929. // state
  930. this.tileSets = {};
  931. this.rootSet = url;
  932. this.lruCache = cache;
  933. this.downloadQueue = downloadQueue;
  934. this.parseQueue = parseQueue;
  935. this.stats = {
  936. parsing: 0,
  937. downloading: 0,
  938. inFrustum: 0,
  939. used: 0,
  940. active: 0,
  941. visible: 0
  942. };
  943. this.frameCount = 0; // options
  944. this.errorTarget = 6.0;
  945. this.errorThreshold = 6.0;
  946. this.loadSiblings = true;
  947. this.maxDepth = Infinity;
  948. this.loadSiblings = true;
  949. this.loadTileSet(url);
  950. }
  951. traverse(cb) {
  952. const tileSets = this.tileSets;
  953. const rootTileSet = tileSets[this.rootSet];
  954. if (!rootTileSet || !rootTileSet.root) return;
  955. traverseSet(rootTileSet.root, cb);
  956. } // Public API
  957. update() {
  958. const stats = this.stats;
  959. const lruCache = this.lruCache;
  960. const tileSets = this.tileSets;
  961. const rootTileSet = tileSets[this.rootSet];
  962. if (!rootTileSet || !rootTileSet.root) return;
  963. const root = rootTileSet.root;
  964. stats.inFrustum = 0, stats.used = 0, stats.active = 0, stats.visible = 0, this.frameCount++;
  965. determineFrustumSet(root, this);
  966. markUsedSetLeaves(root, this);
  967. skipTraversal(root, this);
  968. toggleTiles(root, this); // TODO: We may want to add this function in the requestTileContents function
  969. lruCache.scheduleUnload(null);
  970. } // Overrideable
  971. parseTile(buffer, tile) {
  972. return null;
  973. }
  974. disposeTile(tile) {}
  975. preprocessNode(tile, parentTile, tileSetDir) {
  976. if (tile.content) {
  977. if (!('uri' in tile.content) && 'url' in tile.content) {
  978. tile.content.uri = tile.content.url;
  979. delete tile.content.url;
  980. }
  981. if (tile.content.uri) {
  982. tile.content.uri = _path.default.join(tileSetDir, tile.content.uri);
  983. } // TODO: fix for some cases where tilesets provide the bounding volume
  984. // but volumes are not present. See
  985. if (tile.content.boundingVolume && !('box' in tile.content.boundingVolume || 'sphere' in tile.content.boundingVolume || 'region' in tile.content.boundingVolume)) {
  986. delete tile.content.boundingVolume;
  987. }
  988. }
  989. tile.parent = parentTile;
  990. tile.children = tile.children || [];
  991. tile.__contentEmpty = !tile.content || !tile.content.uri;
  992. tile.__error = 0.0;
  993. tile.__inFrustum = false;
  994. tile.__isLeaf = false;
  995. tile.__wasUsed = false;
  996. tile.__used = false;
  997. tile.__wasVisible = false;
  998. tile.__visible = false;
  999. tile.__wasActive = false;
  1000. tile.__active = false;
  1001. tile.__childrenActive = false;
  1002. tile.__loadingState = UNLOADED;
  1003. tile.__loadIndex = 0;
  1004. tile.__loadAbort = null;
  1005. if (parentTile === null) {
  1006. tile.__depth = 0;
  1007. } else {
  1008. tile.__depth = parentTile.__depth + 1;
  1009. }
  1010. }
  1011. setTileActive(tile, state) {}
  1012. setTileVisible(tile, state) {}
  1013. calculateError(tile) {
  1014. return 0;
  1015. }
  1016. tileInView(tile) {
  1017. return true;
  1018. } // Private Functions
  1019. loadTileSet(url) {
  1020. const tileSets = this.tileSets;
  1021. if (!(url in tileSets)) {
  1022. const pr = fetch(url, {
  1023. credentials: 'same-origin'
  1024. }).then(res => {
  1025. if (res.ok) {
  1026. return res.json();
  1027. } else {
  1028. throw new Error(`Status ${res.status} (${res.statusText})`);
  1029. }
  1030. }).then(json => {
  1031. // TODO: Add version query?
  1032. const version = json.asset.version;
  1033. console.assert(version === '1.0' || version === '0.0');
  1034. const basePath = _path.default.dirname(url);
  1035. traverseSet(json.root, (node, parent) => this.preprocessNode(node, parent, basePath));
  1036. tileSets[url] = json; // TODO: schedule an update to avoid doing this too many times
  1037. this.update();
  1038. });
  1039. pr.catch(e => {
  1040. console.error(`TilesLoader: Failed to load tile set json "${url}"`);
  1041. console.error(e);
  1042. delete tileSets[url];
  1043. });
  1044. tileSets[url] = pr;
  1045. }
  1046. return Promise.resolve(tileSets[url]);
  1047. }
  1048. requestTileContents(tile) {
  1049. // If the tile is already being loaded then don't
  1050. // start it again.
  1051. if (tile.__loadingState !== UNLOADED) {
  1052. return;
  1053. } // TODO: reuse the functions created here?
  1054. const lruCache = this.lruCache;
  1055. const downloadQueue = this.downloadQueue;
  1056. const parseQueue = this.parseQueue;
  1057. lruCache.add(tile, t => {
  1058. if (t.__loadingState === LOADING) {
  1059. t.__loadAbort.abort();
  1060. t.__loadAbort = null;
  1061. } else {
  1062. this.disposeTile(t);
  1063. }
  1064. if (t.__loadingState === LOADING) {
  1065. stats.downloading--;
  1066. } else if (t.__loadingState === PARSING) {
  1067. stats.parsing--;
  1068. }
  1069. t.__loadingState = UNLOADED;
  1070. t.__loadIndex++; // TODO: Removing from the queues here is slow
  1071. // parseQueue.remove( t );
  1072. // downloadQueue.remove( t );
  1073. });
  1074. tile.__loadIndex++;
  1075. const loadIndex = tile.__loadIndex;
  1076. const priority = 1 / (tile.__depth + 1);
  1077. const stats = this.stats;
  1078. const controller = new AbortController();
  1079. const signal = controller.signal;
  1080. stats.downloading++;
  1081. tile.__loadAbort = controller;
  1082. tile.__loadingState = LOADING;
  1083. downloadQueue.add(tile, priority, tile => {
  1084. if (tile.__loadIndex !== loadIndex) {
  1085. return Promise.resolve();
  1086. }
  1087. return fetch(tile.content.uri, {
  1088. credentials: 'same-origin',
  1089. signal
  1090. });
  1091. }).then(res => {
  1092. if (tile.__loadIndex !== loadIndex) {
  1093. return;
  1094. }
  1095. if (res.ok) {
  1096. return res.arrayBuffer();
  1097. } else {
  1098. throw new Error(`Failed to load model with error code ${res.status}`);
  1099. }
  1100. }).then(buffer => {
  1101. if (tile.__loadIndex !== loadIndex) {
  1102. return;
  1103. }
  1104. stats.downloading--;
  1105. stats.parsing++;
  1106. tile.__loadAbort = null;
  1107. tile.__loadingState = PARSING;
  1108. return parseQueue.add(buffer, priority, buffer => {
  1109. if (tile.__loadIndex !== loadIndex) {
  1110. return Promise.resolve();
  1111. }
  1112. return this.parseTile(buffer, tile);
  1113. });
  1114. }).then(() => {
  1115. if (tile.__loadIndex !== loadIndex) {
  1116. return;
  1117. }
  1118. stats.parsing--;
  1119. tile.__loadingState = LOADED;
  1120. this.setTileActive(tile, tile.__active);
  1121. this.setTileVisible(tile, tile.__visible);
  1122. }).catch(e => {
  1123. // if it has been unloaded then the tile has been disposed
  1124. if (tile.__loadIndex !== loadIndex) {
  1125. return;
  1126. }
  1127. if (e.name !== 'AbortError') {
  1128. console.error('TilesRenderer : Failed to load tile.');
  1129. console.error(e);
  1130. tile.__loadingState = FAILED;
  1131. } else {
  1132. lruCache.remove(tile);
  1133. }
  1134. });
  1135. }
  1136. }
  1137. exports.TilesRenderer = TilesRenderer;
  1138. },{"path":"../node_modules/path-browserify/index.js","./LRUCache.js":"../src/LRUCache.js","./PriorityQueue.js":"../src/PriorityQueue.js"}],"../src/B3DMLoader.js":[function(require,module,exports) {
  1139. "use strict";
  1140. Object.defineProperty(exports, "__esModule", {
  1141. value: true
  1142. });
  1143. exports.B3DMLoader = void 0;
  1144. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/Batched3DModel/README.md
  1145. // convert an array of numbers to a string
  1146. function arrayToString(array) {
  1147. let str = '';
  1148. for (let i = 0, l = array.length; i < l; i++) {
  1149. str += String.fromCharCode(array[i]);
  1150. }
  1151. return str;
  1152. }
  1153. class B3DMLoader {
  1154. load(url) {
  1155. return fetch(url, {
  1156. credentials: 'same-origin'
  1157. }).then(res => res.arrayBuffer()).then(buffer => this.parse(buffer));
  1158. }
  1159. parse(buffer) {
  1160. const dataView = new DataView(buffer); // 28-byte header
  1161. // 4 bytes
  1162. const magic = String.fromCharCode(dataView.getUint8(0)) + String.fromCharCode(dataView.getUint8(1)) + String.fromCharCode(dataView.getUint8(2)) + String.fromCharCode(dataView.getUint8(3));
  1163. console.assert(magic === 'b3dm'); // 4 bytes
  1164. const version = dataView.getUint32(4, true);
  1165. console.assert(version === 1); // 4 bytes
  1166. const byteLength = dataView.getUint32(8, true);
  1167. console.assert(byteLength === buffer.byteLength); // 4 bytes
  1168. const featureTableJSONByteLength = dataView.getUint32(12, true); // 4 bytes
  1169. const featureTableBinaryByteLength = dataView.getUint32(16, true); // 4 bytes
  1170. const batchTableJSONByteLength = dataView.getUint32(20, true); // 4 bytes
  1171. const batchTableBinaryByteLength = dataView.getUint32(24, true); // Feature Table
  1172. const featureTableStart = 28;
  1173. const jsonFeatureTableData = new Uint8Array(buffer, featureTableStart, featureTableJSONByteLength);
  1174. const jsonFeatureTable = featureTableJSONByteLength === 0 ? {} : JSON.parse(arrayToString(jsonFeatureTableData));
  1175. const binFeatureTableData = new Uint8Array(buffer, featureTableStart + featureTableJSONByteLength, featureTableBinaryByteLength); // TODO: dereference the json feature table data in to the binary array.
  1176. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/FeatureTable/README.md#json-header
  1177. // Batch Table
  1178. const batchTableStart = featureTableStart + featureTableJSONByteLength + featureTableBinaryByteLength;
  1179. const jsonBatchTableData = new Uint8Array(buffer, batchTableStart, batchTableJSONByteLength);
  1180. const jsonBatchTable = batchTableJSONByteLength === 0 ? {} : JSON.parse(arrayToString(jsonBatchTableData));
  1181. const binBatchTableData = new Uint8Array(buffer, batchTableStart + batchTableJSONByteLength, batchTableBinaryByteLength); // TODO: dereference the json batch table data in to the binary array.
  1182. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/FeatureTable/README.md#json-header
  1183. const glbStart = batchTableStart + batchTableJSONByteLength + batchTableBinaryByteLength;
  1184. const glbBytes = new Uint8Array(buffer, glbStart, byteLength - glbStart); // TODO: Understand how to apply the batchId semantics
  1185. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/Batched3DModel/README.md#binary-gltf
  1186. return {
  1187. version,
  1188. featureTable: jsonFeatureTable,
  1189. batchTable: jsonBatchTable,
  1190. glbBytes
  1191. };
  1192. }
  1193. }
  1194. exports.B3DMLoader = B3DMLoader;
  1195. },{}],"../node_modules/three/build/three.module.js":[function(require,module,exports) {
  1196. "use strict";
  1197. Object.defineProperty(exports, "__esModule", {
  1198. value: true
  1199. });
  1200. exports.AmbientLight = AmbientLight;
  1201. exports.AmbientLightProbe = AmbientLightProbe;
  1202. exports.AnimationClip = AnimationClip;
  1203. exports.AnimationLoader = AnimationLoader;
  1204. exports.AnimationMixer = AnimationMixer;
  1205. exports.AnimationObjectGroup = AnimationObjectGroup;
  1206. exports.ArcCurve = ArcCurve;
  1207. exports.ArrayCamera = ArrayCamera;
  1208. exports.ArrowHelper = ArrowHelper;
  1209. exports.Audio = Audio;
  1210. exports.AudioAnalyser = AudioAnalyser;
  1211. exports.AudioListener = AudioListener;
  1212. exports.AudioLoader = AudioLoader;
  1213. exports.AxesHelper = AxesHelper;
  1214. exports.AxisHelper = AxisHelper;
  1215. exports.BinaryTextureLoader = BinaryTextureLoader;
  1216. exports.Bone = Bone;
  1217. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  1218. exports.BoundingBoxHelper = BoundingBoxHelper;
  1219. exports.Box2 = Box2;
  1220. exports.Box3 = Box3;
  1221. exports.Box3Helper = Box3Helper;
  1222. exports.BoxHelper = BoxHelper;
  1223. exports.BufferAttribute = BufferAttribute;
  1224. exports.BufferGeometry = BufferGeometry;
  1225. exports.BufferGeometryLoader = BufferGeometryLoader;
  1226. exports.Camera = Camera;
  1227. exports.CameraHelper = CameraHelper;
  1228. exports.CanvasRenderer = CanvasRenderer;
  1229. exports.CanvasTexture = CanvasTexture;
  1230. exports.CatmullRomCurve3 = CatmullRomCurve3;
  1231. exports.CircleBufferGeometry = CircleBufferGeometry;
  1232. exports.CircleGeometry = CircleGeometry;
  1233. exports.Clock = Clock;
  1234. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  1235. exports.Color = Color;
  1236. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  1237. exports.CompressedTexture = CompressedTexture;
  1238. exports.CompressedTextureLoader = CompressedTextureLoader;
  1239. exports.ConeBufferGeometry = ConeBufferGeometry;
  1240. exports.ConeGeometry = ConeGeometry;
  1241. exports.CubeCamera = CubeCamera;
  1242. exports.CubeTexture = CubeTexture;
  1243. exports.CubeTextureLoader = CubeTextureLoader;
  1244. exports.CubicBezierCurve = CubicBezierCurve;
  1245. exports.CubicBezierCurve3 = CubicBezierCurve3;
  1246. exports.CubicInterpolant = CubicInterpolant;
  1247. exports.Curve = Curve;
  1248. exports.CurvePath = CurvePath;
  1249. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  1250. exports.CylinderGeometry = CylinderGeometry;
  1251. exports.Cylindrical = Cylindrical;
  1252. exports.DataTexture = DataTexture;
  1253. exports.DataTexture2DArray = DataTexture2DArray;
  1254. exports.DataTexture3D = DataTexture3D;
  1255. exports.DataTextureLoader = DataTextureLoader;
  1256. exports.DepthTexture = DepthTexture;
  1257. exports.DirectionalLight = DirectionalLight;
  1258. exports.DirectionalLightHelper = DirectionalLightHelper;
  1259. exports.DirectionalLightShadow = DirectionalLightShadow;
  1260. exports.DiscreteInterpolant = DiscreteInterpolant;
  1261. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  1262. exports.DodecahedronGeometry = DodecahedronGeometry;
  1263. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  1264. exports.EdgesGeometry = EdgesGeometry;
  1265. exports.EdgesHelper = EdgesHelper;
  1266. exports.EllipseCurve = EllipseCurve;
  1267. exports.Euler = Euler;
  1268. exports.EventDispatcher = EventDispatcher;
  1269. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  1270. exports.ExtrudeGeometry = ExtrudeGeometry;
  1271. exports.Face3 = Face3;
  1272. exports.Face4 = Face4;
  1273. exports.FaceNormalsHelper = FaceNormalsHelper;
  1274. exports.FileLoader = FileLoader;
  1275. exports.Float32Attribute = Float32Attribute;
  1276. exports.Float32BufferAttribute = Float32BufferAttribute;
  1277. exports.Float64Attribute = Float64Attribute;
  1278. exports.Float64BufferAttribute = Float64BufferAttribute;
  1279. exports.Fog = Fog;
  1280. exports.FogExp2 = FogExp2;
  1281. exports.Font = Font;
  1282. exports.FontLoader = FontLoader;
  1283. exports.Frustum = Frustum;
  1284. exports.Geometry = Geometry;
  1285. exports.GridHelper = GridHelper;
  1286. exports.Group = Group;
  1287. exports.HemisphereLight = HemisphereLight;
  1288. exports.HemisphereLightHelper = HemisphereLightHelper;
  1289. exports.HemisphereLightProbe = HemisphereLightProbe;
  1290. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  1291. exports.IcosahedronGeometry = IcosahedronGeometry;
  1292. exports.ImageBitmapLoader = ImageBitmapLoader;
  1293. exports.ImageLoader = ImageLoader;
  1294. exports.ImmediateRenderObject = ImmediateRenderObject;
  1295. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  1296. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  1297. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  1298. exports.InstancedMesh = InstancedMesh;
  1299. exports.Int16Attribute = Int16Attribute;
  1300. exports.Int16BufferAttribute = Int16BufferAttribute;
  1301. exports.Int32Attribute = Int32Attribute;
  1302. exports.Int32BufferAttribute = Int32BufferAttribute;
  1303. exports.Int8Attribute = Int8Attribute;
  1304. exports.Int8BufferAttribute = Int8BufferAttribute;
  1305. exports.InterleavedBuffer = InterleavedBuffer;
  1306. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  1307. exports.Interpolant = Interpolant;
  1308. exports.JSONLoader = JSONLoader;
  1309. exports.KeyframeTrack = KeyframeTrack;
  1310. exports.LOD = LOD;
  1311. exports.LatheBufferGeometry = LatheBufferGeometry;
  1312. exports.LatheGeometry = LatheGeometry;
  1313. exports.Layers = Layers;
  1314. exports.LensFlare = LensFlare;
  1315. exports.Light = Light;
  1316. exports.LightProbe = LightProbe;
  1317. exports.LightProbeHelper = LightProbeHelper;
  1318. exports.LightShadow = LightShadow;
  1319. exports.Line = Line;
  1320. exports.Line3 = Line3;
  1321. exports.LineBasicMaterial = LineBasicMaterial;
  1322. exports.LineCurve = LineCurve;
  1323. exports.LineCurve3 = LineCurve3;
  1324. exports.LineDashedMaterial = LineDashedMaterial;
  1325. exports.LineLoop = LineLoop;
  1326. exports.LineSegments = LineSegments;
  1327. exports.LinearInterpolant = LinearInterpolant;
  1328. exports.Loader = Loader;
  1329. exports.LoadingManager = LoadingManager;
  1330. exports.Material = Material;
  1331. exports.MaterialLoader = MaterialLoader;
  1332. exports.Matrix3 = Matrix3;
  1333. exports.Matrix4 = Matrix4;
  1334. exports.Mesh = Mesh;
  1335. exports.MeshBasicMaterial = MeshBasicMaterial;
  1336. exports.MeshDepthMaterial = MeshDepthMaterial;
  1337. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  1338. exports.MeshFaceMaterial = MeshFaceMaterial;
  1339. exports.MeshLambertMaterial = MeshLambertMaterial;
  1340. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  1341. exports.MeshNormalMaterial = MeshNormalMaterial;
  1342. exports.MeshPhongMaterial = MeshPhongMaterial;
  1343. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  1344. exports.MeshStandardMaterial = MeshStandardMaterial;
  1345. exports.MeshToonMaterial = MeshToonMaterial;
  1346. exports.MultiMaterial = MultiMaterial;
  1347. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  1348. exports.Object3D = Object3D;
  1349. exports.ObjectLoader = ObjectLoader;
  1350. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  1351. exports.OctahedronGeometry = OctahedronGeometry;
  1352. exports.OrthographicCamera = OrthographicCamera;
  1353. exports.ParametricBufferGeometry = ParametricBufferGeometry;
  1354. exports.ParametricGeometry = ParametricGeometry;
  1355. exports.Particle = Particle;
  1356. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  1357. exports.ParticleSystem = ParticleSystem;
  1358. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  1359. exports.Path = Path;
  1360. exports.PerspectiveCamera = PerspectiveCamera;
  1361. exports.Plane = Plane;
  1362. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  1363. exports.PlaneGeometry = PlaneGeometry;
  1364. exports.PlaneHelper = PlaneHelper;
  1365. exports.PointCloud = PointCloud;
  1366. exports.PointCloudMaterial = PointCloudMaterial;
  1367. exports.PointLight = PointLight;
  1368. exports.PointLightHelper = PointLightHelper;
  1369. exports.Points = Points;
  1370. exports.PointsMaterial = PointsMaterial;
  1371. exports.PolarGridHelper = PolarGridHelper;
  1372. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  1373. exports.PolyhedronGeometry = PolyhedronGeometry;
  1374. exports.PositionalAudio = PositionalAudio;
  1375. exports.PositionalAudioHelper = PositionalAudioHelper;
  1376. exports.PropertyBinding = PropertyBinding;
  1377. exports.PropertyMixer = PropertyMixer;
  1378. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  1379. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  1380. exports.Quaternion = Quaternion;
  1381. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  1382. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  1383. exports.RawShaderMaterial = RawShaderMaterial;
  1384. exports.Ray = Ray;
  1385. exports.Raycaster = Raycaster;
  1386. exports.RectAreaLight = RectAreaLight;
  1387. exports.RectAreaLightHelper = RectAreaLightHelper;
  1388. exports.RingBufferGeometry = RingBufferGeometry;
  1389. exports.RingGeometry = RingGeometry;
  1390. exports.Scene = Scene;
  1391. exports.ShaderMaterial = ShaderMaterial;
  1392. exports.ShadowMaterial = ShadowMaterial;
  1393. exports.Shape = Shape;
  1394. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  1395. exports.ShapeGeometry = ShapeGeometry;
  1396. exports.ShapePath = ShapePath;
  1397. exports.Skeleton = Skeleton;
  1398. exports.SkeletonHelper = SkeletonHelper;
  1399. exports.SkinnedMesh = SkinnedMesh;
  1400. exports.Sphere = Sphere;
  1401. exports.SphereBufferGeometry = SphereBufferGeometry;
  1402. exports.SphereGeometry = SphereGeometry;
  1403. exports.Spherical = Spherical;
  1404. exports.SphericalHarmonics3 = SphericalHarmonics3;
  1405. exports.Spline = Spline;
  1406. exports.SplineCurve = SplineCurve;
  1407. exports.SplineCurve3 = SplineCurve3;
  1408. exports.SpotLight = SpotLight;
  1409. exports.SpotLightHelper = SpotLightHelper;
  1410. exports.SpotLightShadow = SpotLightShadow;
  1411. exports.Sprite = Sprite;
  1412. exports.SpriteMaterial = SpriteMaterial;
  1413. exports.StereoCamera = StereoCamera;
  1414. exports.StringKeyframeTrack = StringKeyframeTrack;
  1415. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  1416. exports.TetrahedronGeometry = TetrahedronGeometry;
  1417. exports.TextBufferGeometry = TextBufferGeometry;
  1418. exports.TextGeometry = TextGeometry;
  1419. exports.Texture = Texture;
  1420. exports.TextureLoader = TextureLoader;
  1421. exports.TorusBufferGeometry = TorusBufferGeometry;
  1422. exports.TorusGeometry = TorusGeometry;
  1423. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  1424. exports.TorusKnotGeometry = TorusKnotGeometry;
  1425. exports.Triangle = Triangle;
  1426. exports.TubeBufferGeometry = TubeBufferGeometry;
  1427. exports.TubeGeometry = TubeGeometry;
  1428. exports.Uint16Attribute = Uint16Attribute;
  1429. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  1430. exports.Uint32Attribute = Uint32Attribute;
  1431. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  1432. exports.Uint8Attribute = Uint8Attribute;
  1433. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  1434. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  1435. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  1436. exports.Uniform = Uniform;
  1437. exports.Vector2 = Vector2;
  1438. exports.Vector3 = Vector3;
  1439. exports.Vector4 = Vector4;
  1440. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  1441. exports.Vertex = Vertex;
  1442. exports.VertexNormalsHelper = VertexNormalsHelper;
  1443. exports.VideoTexture = VideoTexture;
  1444. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  1445. exports.WebGLRenderTarget = WebGLRenderTarget;
  1446. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  1447. exports.WebGLRenderer = WebGLRenderer;
  1448. exports.WebGLUtils = WebGLUtils;
  1449. exports.WireframeGeometry = WireframeGeometry;
  1450. exports.WireframeHelper = WireframeHelper;
  1451. exports.XHRLoader = XHRLoader;
  1452. 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;
  1453. 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;
  1454. // Polyfills
  1455. if (Number.EPSILON === undefined) {
  1456. Number.EPSILON = Math.pow(2, -52);
  1457. }
  1458. if (Number.isInteger === undefined) {
  1459. // Missing in IE
  1460. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
  1461. Number.isInteger = function (value) {
  1462. return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
  1463. };
  1464. } //
  1465. if (Math.sign === undefined) {
  1466. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  1467. Math.sign = function (x) {
  1468. return x < 0 ? -1 : x > 0 ? 1 : +x;
  1469. };
  1470. }
  1471. if ('name' in Function.prototype === false) {
  1472. // Missing in IE
  1473. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  1474. Object.defineProperty(Function.prototype, 'name', {
  1475. get: function () {
  1476. return this.toString().match(/^\s*function\s*([^\(\s]*)/)[1];
  1477. }
  1478. });
  1479. }
  1480. if (Object.assign === undefined) {
  1481. // Missing in IE
  1482. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  1483. Object.assign = function (target) {
  1484. if (target === undefined || target === null) {
  1485. throw new TypeError('Cannot convert undefined or null to object');
  1486. }
  1487. var output = Object(target);
  1488. for (var index = 1; index < arguments.length; index++) {
  1489. var source = arguments[index];
  1490. if (source !== undefined && source !== null) {
  1491. for (var nextKey in source) {
  1492. if (Object.prototype.hasOwnProperty.call(source, nextKey)) {
  1493. output[nextKey] = source[nextKey];
  1494. }
  1495. }
  1496. }
  1497. }
  1498. return output;
  1499. };
  1500. }
  1501. var REVISION = '109';
  1502. exports.REVISION = REVISION;
  1503. var MOUSE = {
  1504. LEFT: 0,
  1505. MIDDLE: 1,
  1506. RIGHT: 2,
  1507. ROTATE: 0,
  1508. DOLLY: 1,
  1509. PAN: 2
  1510. };
  1511. exports.MOUSE = MOUSE;
  1512. var TOUCH = {
  1513. ROTATE: 0,
  1514. PAN: 1,
  1515. DOLLY_PAN: 2,
  1516. DOLLY_ROTATE: 3
  1517. };
  1518. exports.TOUCH = TOUCH;
  1519. var CullFaceNone = 0;
  1520. exports.CullFaceNone = CullFaceNone;
  1521. var CullFaceBack = 1;
  1522. exports.CullFaceBack = CullFaceBack;
  1523. var CullFaceFront = 2;
  1524. exports.CullFaceFront = CullFaceFront;
  1525. var CullFaceFrontBack = 3;
  1526. exports.CullFaceFrontBack = CullFaceFrontBack;
  1527. var FrontFaceDirectionCW = 0;
  1528. exports.FrontFaceDirectionCW = FrontFaceDirectionCW;
  1529. var FrontFaceDirectionCCW = 1;
  1530. exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW;
  1531. var BasicShadowMap = 0;
  1532. exports.BasicShadowMap = BasicShadowMap;
  1533. var PCFShadowMap = 1;
  1534. exports.PCFShadowMap = PCFShadowMap;
  1535. var PCFSoftShadowMap = 2;
  1536. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  1537. var VSMShadowMap = 3;
  1538. exports.VSMShadowMap = VSMShadowMap;
  1539. var FrontSide = 0;
  1540. exports.FrontSide = FrontSide;
  1541. var BackSide = 1;
  1542. exports.BackSide = BackSide;
  1543. var DoubleSide = 2;
  1544. exports.DoubleSide = DoubleSide;
  1545. var FlatShading = 1;
  1546. exports.FlatShading = FlatShading;
  1547. var SmoothShading = 2;
  1548. exports.SmoothShading = SmoothShading;
  1549. var NoColors = 0;
  1550. exports.NoColors = NoColors;
  1551. var FaceColors = 1;
  1552. exports.FaceColors = FaceColors;
  1553. var VertexColors = 2;
  1554. exports.VertexColors = VertexColors;
  1555. var NoBlending = 0;
  1556. exports.NoBlending = NoBlending;
  1557. var NormalBlending = 1;
  1558. exports.NormalBlending = NormalBlending;
  1559. var AdditiveBlending = 2;
  1560. exports.AdditiveBlending = AdditiveBlending;
  1561. var SubtractiveBlending = 3;
  1562. exports.SubtractiveBlending = SubtractiveBlending;
  1563. var MultiplyBlending = 4;
  1564. exports.MultiplyBlending = MultiplyBlending;
  1565. var CustomBlending = 5;
  1566. exports.CustomBlending = CustomBlending;
  1567. var AddEquation = 100;
  1568. exports.AddEquation = AddEquation;
  1569. var SubtractEquation = 101;
  1570. exports.SubtractEquation = SubtractEquation;
  1571. var ReverseSubtractEquation = 102;
  1572. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  1573. var MinEquation = 103;
  1574. exports.MinEquation = MinEquation;
  1575. var MaxEquation = 104;
  1576. exports.MaxEquation = MaxEquation;
  1577. var ZeroFactor = 200;
  1578. exports.ZeroFactor = ZeroFactor;
  1579. var OneFactor = 201;
  1580. exports.OneFactor = OneFactor;
  1581. var SrcColorFactor = 202;
  1582. exports.SrcColorFactor = SrcColorFactor;
  1583. var OneMinusSrcColorFactor = 203;
  1584. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  1585. var SrcAlphaFactor = 204;
  1586. exports.SrcAlphaFactor = SrcAlphaFactor;
  1587. var OneMinusSrcAlphaFactor = 205;
  1588. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  1589. var DstAlphaFactor = 206;
  1590. exports.DstAlphaFactor = DstAlphaFactor;
  1591. var OneMinusDstAlphaFactor = 207;
  1592. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  1593. var DstColorFactor = 208;
  1594. exports.DstColorFactor = DstColorFactor;
  1595. var OneMinusDstColorFactor = 209;
  1596. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  1597. var SrcAlphaSaturateFactor = 210;
  1598. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  1599. var NeverDepth = 0;
  1600. exports.NeverDepth = NeverDepth;
  1601. var AlwaysDepth = 1;
  1602. exports.AlwaysDepth = AlwaysDepth;
  1603. var LessDepth = 2;
  1604. exports.LessDepth = LessDepth;
  1605. var LessEqualDepth = 3;
  1606. exports.LessEqualDepth = LessEqualDepth;
  1607. var EqualDepth = 4;
  1608. exports.EqualDepth = EqualDepth;
  1609. var GreaterEqualDepth = 5;
  1610. exports.GreaterEqualDepth = GreaterEqualDepth;
  1611. var GreaterDepth = 6;
  1612. exports.GreaterDepth = GreaterDepth;
  1613. var NotEqualDepth = 7;
  1614. exports.NotEqualDepth = NotEqualDepth;
  1615. var MultiplyOperation = 0;
  1616. exports.MultiplyOperation = MultiplyOperation;
  1617. var MixOperation = 1;
  1618. exports.MixOperation = MixOperation;
  1619. var AddOperation = 2;
  1620. exports.AddOperation = AddOperation;
  1621. var NoToneMapping = 0;
  1622. exports.NoToneMapping = NoToneMapping;
  1623. var LinearToneMapping = 1;
  1624. exports.LinearToneMapping = LinearToneMapping;
  1625. var ReinhardToneMapping = 2;
  1626. exports.ReinhardToneMapping = ReinhardToneMapping;
  1627. var Uncharted2ToneMapping = 3;
  1628. exports.Uncharted2ToneMapping = Uncharted2ToneMapping;
  1629. var CineonToneMapping = 4;
  1630. exports.CineonToneMapping = CineonToneMapping;
  1631. var ACESFilmicToneMapping = 5;
  1632. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  1633. var UVMapping = 300;
  1634. exports.UVMapping = UVMapping;
  1635. var CubeReflectionMapping = 301;
  1636. exports.CubeReflectionMapping = CubeReflectionMapping;
  1637. var CubeRefractionMapping = 302;
  1638. exports.CubeRefractionMapping = CubeRefractionMapping;
  1639. var EquirectangularReflectionMapping = 303;
  1640. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  1641. var EquirectangularRefractionMapping = 304;
  1642. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  1643. var SphericalReflectionMapping = 305;
  1644. exports.SphericalReflectionMapping = SphericalReflectionMapping;
  1645. var CubeUVReflectionMapping = 306;
  1646. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  1647. var CubeUVRefractionMapping = 307;
  1648. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  1649. var RepeatWrapping = 1000;
  1650. exports.RepeatWrapping = RepeatWrapping;
  1651. var ClampToEdgeWrapping = 1001;
  1652. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  1653. var MirroredRepeatWrapping = 1002;
  1654. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  1655. var NearestFilter = 1003;
  1656. exports.NearestFilter = NearestFilter;
  1657. var NearestMipmapNearestFilter = 1004;
  1658. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  1659. var NearestMipMapNearestFilter = 1004;
  1660. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  1661. var NearestMipmapLinearFilter = 1005;
  1662. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  1663. var NearestMipMapLinearFilter = 1005;
  1664. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  1665. var LinearFilter = 1006;
  1666. exports.LinearFilter = LinearFilter;
  1667. var LinearMipmapNearestFilter = 1007;
  1668. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  1669. var LinearMipMapNearestFilter = 1007;
  1670. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  1671. var LinearMipmapLinearFilter = 1008;
  1672. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  1673. var LinearMipMapLinearFilter = 1008;
  1674. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  1675. var UnsignedByteType = 1009;
  1676. exports.UnsignedByteType = UnsignedByteType;
  1677. var ByteType = 1010;
  1678. exports.ByteType = ByteType;
  1679. var ShortType = 1011;
  1680. exports.ShortType = ShortType;
  1681. var UnsignedShortType = 1012;
  1682. exports.UnsignedShortType = UnsignedShortType;
  1683. var IntType = 1013;
  1684. exports.IntType = IntType;
  1685. var UnsignedIntType = 1014;
  1686. exports.UnsignedIntType = UnsignedIntType;
  1687. var FloatType = 1015;
  1688. exports.FloatType = FloatType;
  1689. var HalfFloatType = 1016;
  1690. exports.HalfFloatType = HalfFloatType;
  1691. var UnsignedShort4444Type = 1017;
  1692. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  1693. var UnsignedShort5551Type = 1018;
  1694. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  1695. var UnsignedShort565Type = 1019;
  1696. exports.UnsignedShort565Type = UnsignedShort565Type;
  1697. var UnsignedInt248Type = 1020;
  1698. exports.UnsignedInt248Type = UnsignedInt248Type;
  1699. var AlphaFormat = 1021;
  1700. exports.AlphaFormat = AlphaFormat;
  1701. var RGBFormat = 1022;
  1702. exports.RGBFormat = RGBFormat;
  1703. var RGBAFormat = 1023;
  1704. exports.RGBAFormat = RGBAFormat;
  1705. var LuminanceFormat = 1024;
  1706. exports.LuminanceFormat = LuminanceFormat;
  1707. var LuminanceAlphaFormat = 1025;
  1708. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  1709. var RGBEFormat = RGBAFormat;
  1710. exports.RGBEFormat = RGBEFormat;
  1711. var DepthFormat = 1026;
  1712. exports.DepthFormat = DepthFormat;
  1713. var DepthStencilFormat = 1027;
  1714. exports.DepthStencilFormat = DepthStencilFormat;
  1715. var RedFormat = 1028;
  1716. exports.RedFormat = RedFormat;
  1717. var RGB_S3TC_DXT1_Format = 33776;
  1718. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  1719. var RGBA_S3TC_DXT1_Format = 33777;
  1720. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  1721. var RGBA_S3TC_DXT3_Format = 33778;
  1722. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  1723. var RGBA_S3TC_DXT5_Format = 33779;
  1724. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  1725. var RGB_PVRTC_4BPPV1_Format = 35840;
  1726. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  1727. var RGB_PVRTC_2BPPV1_Format = 35841;
  1728. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  1729. var RGBA_PVRTC_4BPPV1_Format = 35842;
  1730. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  1731. var RGBA_PVRTC_2BPPV1_Format = 35843;
  1732. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  1733. var RGB_ETC1_Format = 36196;
  1734. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  1735. var RGBA_ASTC_4x4_Format = 37808;
  1736. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  1737. var RGBA_ASTC_5x4_Format = 37809;
  1738. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  1739. var RGBA_ASTC_5x5_Format = 37810;
  1740. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  1741. var RGBA_ASTC_6x5_Format = 37811;
  1742. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  1743. var RGBA_ASTC_6x6_Format = 37812;
  1744. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  1745. var RGBA_ASTC_8x5_Format = 37813;
  1746. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  1747. var RGBA_ASTC_8x6_Format = 37814;
  1748. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  1749. var RGBA_ASTC_8x8_Format = 37815;
  1750. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  1751. var RGBA_ASTC_10x5_Format = 37816;
  1752. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  1753. var RGBA_ASTC_10x6_Format = 37817;
  1754. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  1755. var RGBA_ASTC_10x8_Format = 37818;
  1756. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  1757. var RGBA_ASTC_10x10_Format = 37819;
  1758. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  1759. var RGBA_ASTC_12x10_Format = 37820;
  1760. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  1761. var RGBA_ASTC_12x12_Format = 37821;
  1762. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  1763. var LoopOnce = 2200;
  1764. exports.LoopOnce = LoopOnce;
  1765. var LoopRepeat = 2201;
  1766. exports.LoopRepeat = LoopRepeat;
  1767. var LoopPingPong = 2202;
  1768. exports.LoopPingPong = LoopPingPong;
  1769. var InterpolateDiscrete = 2300;
  1770. exports.InterpolateDiscrete = InterpolateDiscrete;
  1771. var InterpolateLinear = 2301;
  1772. exports.InterpolateLinear = InterpolateLinear;
  1773. var InterpolateSmooth = 2302;
  1774. exports.InterpolateSmooth = InterpolateSmooth;
  1775. var ZeroCurvatureEnding = 2400;
  1776. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  1777. var ZeroSlopeEnding = 2401;
  1778. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  1779. var WrapAroundEnding = 2402;
  1780. exports.WrapAroundEnding = WrapAroundEnding;
  1781. var TrianglesDrawMode = 0;
  1782. exports.TrianglesDrawMode = TrianglesDrawMode;
  1783. var TriangleStripDrawMode = 1;
  1784. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  1785. var TriangleFanDrawMode = 2;
  1786. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  1787. var LinearEncoding = 3000;
  1788. exports.LinearEncoding = LinearEncoding;
  1789. var sRGBEncoding = 3001;
  1790. exports.sRGBEncoding = sRGBEncoding;
  1791. var GammaEncoding = 3007;
  1792. exports.GammaEncoding = GammaEncoding;
  1793. var RGBEEncoding = 3002;
  1794. exports.RGBEEncoding = RGBEEncoding;
  1795. var LogLuvEncoding = 3003;
  1796. exports.LogLuvEncoding = LogLuvEncoding;
  1797. var RGBM7Encoding = 3004;
  1798. exports.RGBM7Encoding = RGBM7Encoding;
  1799. var RGBM16Encoding = 3005;
  1800. exports.RGBM16Encoding = RGBM16Encoding;
  1801. var RGBDEncoding = 3006;
  1802. exports.RGBDEncoding = RGBDEncoding;
  1803. var BasicDepthPacking = 3200;
  1804. exports.BasicDepthPacking = BasicDepthPacking;
  1805. var RGBADepthPacking = 3201;
  1806. exports.RGBADepthPacking = RGBADepthPacking;
  1807. var TangentSpaceNormalMap = 0;
  1808. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  1809. var ObjectSpaceNormalMap = 1;
  1810. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  1811. var ZeroStencilOp = 0;
  1812. exports.ZeroStencilOp = ZeroStencilOp;
  1813. var KeepStencilOp = 7680;
  1814. exports.KeepStencilOp = KeepStencilOp;
  1815. var ReplaceStencilOp = 7681;
  1816. exports.ReplaceStencilOp = ReplaceStencilOp;
  1817. var IncrementStencilOp = 7682;
  1818. exports.IncrementStencilOp = IncrementStencilOp;
  1819. var DecrementStencilOp = 7683;
  1820. exports.DecrementStencilOp = DecrementStencilOp;
  1821. var IncrementWrapStencilOp = 34055;
  1822. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  1823. var DecrementWrapStencilOp = 34056;
  1824. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  1825. var InvertStencilOp = 5386;
  1826. exports.InvertStencilOp = InvertStencilOp;
  1827. var NeverStencilFunc = 512;
  1828. exports.NeverStencilFunc = NeverStencilFunc;
  1829. var LessStencilFunc = 513;
  1830. exports.LessStencilFunc = LessStencilFunc;
  1831. var EqualStencilFunc = 514;
  1832. exports.EqualStencilFunc = EqualStencilFunc;
  1833. var LessEqualStencilFunc = 515;
  1834. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  1835. var GreaterStencilFunc = 516;
  1836. exports.GreaterStencilFunc = GreaterStencilFunc;
  1837. var NotEqualStencilFunc = 517;
  1838. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  1839. var GreaterEqualStencilFunc = 518;
  1840. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  1841. var AlwaysStencilFunc = 519;
  1842. /**
  1843. * https://github.com/mrdoob/eventdispatcher.js/
  1844. */
  1845. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  1846. function EventDispatcher() {}
  1847. Object.assign(EventDispatcher.prototype, {
  1848. addEventListener: function (type, listener) {
  1849. if (this._listeners === undefined) this._listeners = {};
  1850. var listeners = this._listeners;
  1851. if (listeners[type] === undefined) {
  1852. listeners[type] = [];
  1853. }
  1854. if (listeners[type].indexOf(listener) === -1) {
  1855. listeners[type].push(listener);
  1856. }
  1857. },
  1858. hasEventListener: function (type, listener) {
  1859. if (this._listeners === undefined) return false;
  1860. var listeners = this._listeners;
  1861. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  1862. },
  1863. removeEventListener: function (type, listener) {
  1864. if (this._listeners === undefined) return;
  1865. var listeners = this._listeners;
  1866. var listenerArray = listeners[type];
  1867. if (listenerArray !== undefined) {
  1868. var index = listenerArray.indexOf(listener);
  1869. if (index !== -1) {
  1870. listenerArray.splice(index, 1);
  1871. }
  1872. }
  1873. },
  1874. dispatchEvent: function (event) {
  1875. if (this._listeners === undefined) return;
  1876. var listeners = this._listeners;
  1877. var listenerArray = listeners[event.type];
  1878. if (listenerArray !== undefined) {
  1879. event.target = this;
  1880. var array = listenerArray.slice(0);
  1881. for (var i = 0, l = array.length; i < l; i++) {
  1882. array[i].call(this, event);
  1883. }
  1884. }
  1885. }
  1886. });
  1887. /**
  1888. * @author alteredq / http://alteredqualia.com/
  1889. * @author mrdoob / http://mrdoob.com/
  1890. */
  1891. var _lut = [];
  1892. for (var i = 0; i < 256; i++) {
  1893. _lut[i] = (i < 16 ? '0' : '') + i.toString(16);
  1894. }
  1895. var _Math = {
  1896. DEG2RAD: Math.PI / 180,
  1897. RAD2DEG: 180 / Math.PI,
  1898. generateUUID: function () {
  1899. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  1900. var d0 = Math.random() * 0xffffffff | 0;
  1901. var d1 = Math.random() * 0xffffffff | 0;
  1902. var d2 = Math.random() * 0xffffffff | 0;
  1903. var d3 = Math.random() * 0xffffffff | 0;
  1904. 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.
  1905. return uuid.toUpperCase();
  1906. },
  1907. clamp: function (value, min, max) {
  1908. return Math.max(min, Math.min(max, value));
  1909. },
  1910. // compute euclidian modulo of m % n
  1911. // https://en.wikipedia.org/wiki/Modulo_operation
  1912. euclideanModulo: function (n, m) {
  1913. return (n % m + m) % m;
  1914. },
  1915. // Linear mapping from range <a1, a2> to range <b1, b2>
  1916. mapLinear: function (x, a1, a2, b1, b2) {
  1917. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  1918. },
  1919. // https://en.wikipedia.org/wiki/Linear_interpolation
  1920. lerp: function (x, y, t) {
  1921. return (1 - t) * x + t * y;
  1922. },
  1923. // http://en.wikipedia.org/wiki/Smoothstep
  1924. smoothstep: function (x, min, max) {
  1925. if (x <= min) return 0;
  1926. if (x >= max) return 1;
  1927. x = (x - min) / (max - min);
  1928. return x * x * (3 - 2 * x);
  1929. },
  1930. smootherstep: function (x, min, max) {
  1931. if (x <= min) return 0;
  1932. if (x >= max) return 1;
  1933. x = (x - min) / (max - min);
  1934. return x * x * x * (x * (x * 6 - 15) + 10);
  1935. },
  1936. // Random integer from <low, high> interval
  1937. randInt: function (low, high) {
  1938. return low + Math.floor(Math.random() * (high - low + 1));
  1939. },
  1940. // Random float from <low, high> interval
  1941. randFloat: function (low, high) {
  1942. return low + Math.random() * (high - low);
  1943. },
  1944. // Random float from <-range/2, range/2> interval
  1945. randFloatSpread: function (range) {
  1946. return range * (0.5 - Math.random());
  1947. },
  1948. degToRad: function (degrees) {
  1949. return degrees * _Math.DEG2RAD;
  1950. },
  1951. radToDeg: function (radians) {
  1952. return radians * _Math.RAD2DEG;
  1953. },
  1954. isPowerOfTwo: function (value) {
  1955. return (value & value - 1) === 0 && value !== 0;
  1956. },
  1957. ceilPowerOfTwo: function (value) {
  1958. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  1959. },
  1960. floorPowerOfTwo: function (value) {
  1961. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  1962. }
  1963. };
  1964. /**
  1965. * @author mrdoob / http://mrdoob.com/
  1966. * @author philogb / http://blog.thejit.org/
  1967. * @author egraether / http://egraether.com/
  1968. * @author zz85 / http://www.lab4games.net/zz85/blog
  1969. */
  1970. exports.Math = _Math;
  1971. function Vector2(x, y) {
  1972. this.x = x || 0;
  1973. this.y = y || 0;
  1974. }
  1975. Object.defineProperties(Vector2.prototype, {
  1976. "width": {
  1977. get: function () {
  1978. return this.x;
  1979. },
  1980. set: function (value) {
  1981. this.x = value;
  1982. }
  1983. },
  1984. "height": {
  1985. get: function () {
  1986. return this.y;
  1987. },
  1988. set: function (value) {
  1989. this.y = value;
  1990. }
  1991. }
  1992. });
  1993. Object.assign(Vector2.prototype, {
  1994. isVector2: true,
  1995. set: function (x, y) {
  1996. this.x = x;
  1997. this.y = y;
  1998. return this;
  1999. },
  2000. setScalar: function (scalar) {
  2001. this.x = scalar;
  2002. this.y = scalar;
  2003. return this;
  2004. },
  2005. setX: function (x) {
  2006. this.x = x;
  2007. return this;
  2008. },
  2009. setY: function (y) {
  2010. this.y = y;
  2011. return this;
  2012. },
  2013. setComponent: function (index, value) {
  2014. switch (index) {
  2015. case 0:
  2016. this.x = value;
  2017. break;
  2018. case 1:
  2019. this.y = value;
  2020. break;
  2021. default:
  2022. throw new Error('index is out of range: ' + index);
  2023. }
  2024. return this;
  2025. },
  2026. getComponent: function (index) {
  2027. switch (index) {
  2028. case 0:
  2029. return this.x;
  2030. case 1:
  2031. return this.y;
  2032. default:
  2033. throw new Error('index is out of range: ' + index);
  2034. }
  2035. },
  2036. clone: function () {
  2037. return new this.constructor(this.x, this.y);
  2038. },
  2039. copy: function (v) {
  2040. this.x = v.x;
  2041. this.y = v.y;
  2042. return this;
  2043. },
  2044. add: function (v, w) {
  2045. if (w !== undefined) {
  2046. console.warn('THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  2047. return this.addVectors(v, w);
  2048. }
  2049. this.x += v.x;
  2050. this.y += v.y;
  2051. return this;
  2052. },
  2053. addScalar: function (s) {
  2054. this.x += s;
  2055. this.y += s;
  2056. return this;
  2057. },
  2058. addVectors: function (a, b) {
  2059. this.x = a.x + b.x;
  2060. this.y = a.y + b.y;
  2061. return this;
  2062. },
  2063. addScaledVector: function (v, s) {
  2064. this.x += v.x * s;
  2065. this.y += v.y * s;
  2066. return this;
  2067. },
  2068. sub: function (v, w) {
  2069. if (w !== undefined) {
  2070. console.warn('THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  2071. return this.subVectors(v, w);
  2072. }
  2073. this.x -= v.x;
  2074. this.y -= v.y;
  2075. return this;
  2076. },
  2077. subScalar: function (s) {
  2078. this.x -= s;
  2079. this.y -= s;
  2080. return this;
  2081. },
  2082. subVectors: function (a, b) {
  2083. this.x = a.x - b.x;
  2084. this.y = a.y - b.y;
  2085. return this;
  2086. },
  2087. multiply: function (v) {
  2088. this.x *= v.x;
  2089. this.y *= v.y;
  2090. return this;
  2091. },
  2092. multiplyScalar: function (scalar) {
  2093. this.x *= scalar;
  2094. this.y *= scalar;
  2095. return this;
  2096. },
  2097. divide: function (v) {
  2098. this.x /= v.x;
  2099. this.y /= v.y;
  2100. return this;
  2101. },
  2102. divideScalar: function (scalar) {
  2103. return this.multiplyScalar(1 / scalar);
  2104. },
  2105. applyMatrix3: function (m) {
  2106. var x = this.x,
  2107. y = this.y;
  2108. var e = m.elements;
  2109. this.x = e[0] * x + e[3] * y + e[6];
  2110. this.y = e[1] * x + e[4] * y + e[7];
  2111. return this;
  2112. },
  2113. min: function (v) {
  2114. this.x = Math.min(this.x, v.x);
  2115. this.y = Math.min(this.y, v.y);
  2116. return this;
  2117. },
  2118. max: function (v) {
  2119. this.x = Math.max(this.x, v.x);
  2120. this.y = Math.max(this.y, v.y);
  2121. return this;
  2122. },
  2123. clamp: function (min, max) {
  2124. // assumes min < max, componentwise
  2125. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2126. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2127. return this;
  2128. },
  2129. clampScalar: function (minVal, maxVal) {
  2130. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2131. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2132. return this;
  2133. },
  2134. clampLength: function (min, max) {
  2135. var length = this.length();
  2136. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2137. },
  2138. floor: function () {
  2139. this.x = Math.floor(this.x);
  2140. this.y = Math.floor(this.y);
  2141. return this;
  2142. },
  2143. ceil: function () {
  2144. this.x = Math.ceil(this.x);
  2145. this.y = Math.ceil(this.y);
  2146. return this;
  2147. },
  2148. round: function () {
  2149. this.x = Math.round(this.x);
  2150. this.y = Math.round(this.y);
  2151. return this;
  2152. },
  2153. roundToZero: function () {
  2154. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2155. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2156. return this;
  2157. },
  2158. negate: function () {
  2159. this.x = -this.x;
  2160. this.y = -this.y;
  2161. return this;
  2162. },
  2163. dot: function (v) {
  2164. return this.x * v.x + this.y * v.y;
  2165. },
  2166. cross: function (v) {
  2167. return this.x * v.y - this.y * v.x;
  2168. },
  2169. lengthSq: function () {
  2170. return this.x * this.x + this.y * this.y;
  2171. },
  2172. length: function () {
  2173. return Math.sqrt(this.x * this.x + this.y * this.y);
  2174. },
  2175. manhattanLength: function () {
  2176. return Math.abs(this.x) + Math.abs(this.y);
  2177. },
  2178. normalize: function () {
  2179. return this.divideScalar(this.length() || 1);
  2180. },
  2181. angle: function () {
  2182. // computes the angle in radians with respect to the positive x-axis
  2183. var angle = Math.atan2(this.y, this.x);
  2184. if (angle < 0) angle += 2 * Math.PI;
  2185. return angle;
  2186. },
  2187. distanceTo: function (v) {
  2188. return Math.sqrt(this.distanceToSquared(v));
  2189. },
  2190. distanceToSquared: function (v) {
  2191. var dx = this.x - v.x,
  2192. dy = this.y - v.y;
  2193. return dx * dx + dy * dy;
  2194. },
  2195. manhattanDistanceTo: function (v) {
  2196. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  2197. },
  2198. setLength: function (length) {
  2199. return this.normalize().multiplyScalar(length);
  2200. },
  2201. lerp: function (v, alpha) {
  2202. this.x += (v.x - this.x) * alpha;
  2203. this.y += (v.y - this.y) * alpha;
  2204. return this;
  2205. },
  2206. lerpVectors: function (v1, v2, alpha) {
  2207. return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
  2208. },
  2209. equals: function (v) {
  2210. return v.x === this.x && v.y === this.y;
  2211. },
  2212. fromArray: function (array, offset) {
  2213. if (offset === undefined) offset = 0;
  2214. this.x = array[offset];
  2215. this.y = array[offset + 1];
  2216. return this;
  2217. },
  2218. toArray: function (array, offset) {
  2219. if (array === undefined) array = [];
  2220. if (offset === undefined) offset = 0;
  2221. array[offset] = this.x;
  2222. array[offset + 1] = this.y;
  2223. return array;
  2224. },
  2225. fromBufferAttribute: function (attribute, index, offset) {
  2226. if (offset !== undefined) {
  2227. console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');
  2228. }
  2229. this.x = attribute.getX(index);
  2230. this.y = attribute.getY(index);
  2231. return this;
  2232. },
  2233. rotateAround: function (center, angle) {
  2234. var c = Math.cos(angle),
  2235. s = Math.sin(angle);
  2236. var x = this.x - center.x;
  2237. var y = this.y - center.y;
  2238. this.x = x * c - y * s + center.x;
  2239. this.y = x * s + y * c + center.y;
  2240. return this;
  2241. }
  2242. });
  2243. /**
  2244. * @author mikael emtinger / http://gomo.se/
  2245. * @author alteredq / http://alteredqualia.com/
  2246. * @author WestLangley / http://github.com/WestLangley
  2247. * @author bhouston / http://clara.io
  2248. */
  2249. function Quaternion(x, y, z, w) {
  2250. this._x = x || 0;
  2251. this._y = y || 0;
  2252. this._z = z || 0;
  2253. this._w = w !== undefined ? w : 1;
  2254. }
  2255. Object.assign(Quaternion, {
  2256. slerp: function (qa, qb, qm, t) {
  2257. return qm.copy(qa).slerp(qb, t);
  2258. },
  2259. slerpFlat: function (dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  2260. // fuzz-free, array-based Quaternion SLERP operation
  2261. var x0 = src0[srcOffset0 + 0],
  2262. y0 = src0[srcOffset0 + 1],
  2263. z0 = src0[srcOffset0 + 2],
  2264. w0 = src0[srcOffset0 + 3],
  2265. x1 = src1[srcOffset1 + 0],
  2266. y1 = src1[srcOffset1 + 1],
  2267. z1 = src1[srcOffset1 + 2],
  2268. w1 = src1[srcOffset1 + 3];
  2269. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  2270. var s = 1 - t,
  2271. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2272. dir = cos >= 0 ? 1 : -1,
  2273. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  2274. if (sqrSin > Number.EPSILON) {
  2275. var sin = Math.sqrt(sqrSin),
  2276. len = Math.atan2(sin, cos * dir);
  2277. s = Math.sin(s * len) / sin;
  2278. t = Math.sin(t * len) / sin;
  2279. }
  2280. var tDir = t * dir;
  2281. x0 = x0 * s + x1 * tDir;
  2282. y0 = y0 * s + y1 * tDir;
  2283. z0 = z0 * s + z1 * tDir;
  2284. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  2285. if (s === 1 - t) {
  2286. var f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  2287. x0 *= f;
  2288. y0 *= f;
  2289. z0 *= f;
  2290. w0 *= f;
  2291. }
  2292. }
  2293. dst[dstOffset] = x0;
  2294. dst[dstOffset + 1] = y0;
  2295. dst[dstOffset + 2] = z0;
  2296. dst[dstOffset + 3] = w0;
  2297. }
  2298. });
  2299. Object.defineProperties(Quaternion.prototype, {
  2300. x: {
  2301. get: function () {
  2302. return this._x;
  2303. },
  2304. set: function (value) {
  2305. this._x = value;
  2306. this._onChangeCallback();
  2307. }
  2308. },
  2309. y: {
  2310. get: function () {
  2311. return this._y;
  2312. },
  2313. set: function (value) {
  2314. this._y = value;
  2315. this._onChangeCallback();
  2316. }
  2317. },
  2318. z: {
  2319. get: function () {
  2320. return this._z;
  2321. },
  2322. set: function (value) {
  2323. this._z = value;
  2324. this._onChangeCallback();
  2325. }
  2326. },
  2327. w: {
  2328. get: function () {
  2329. return this._w;
  2330. },
  2331. set: function (value) {
  2332. this._w = value;
  2333. this._onChangeCallback();
  2334. }
  2335. }
  2336. });
  2337. Object.assign(Quaternion.prototype, {
  2338. isQuaternion: true,
  2339. set: function (x, y, z, w) {
  2340. this._x = x;
  2341. this._y = y;
  2342. this._z = z;
  2343. this._w = w;
  2344. this._onChangeCallback();
  2345. return this;
  2346. },
  2347. clone: function () {
  2348. return new this.constructor(this._x, this._y, this._z, this._w);
  2349. },
  2350. copy: function (quaternion) {
  2351. this._x = quaternion.x;
  2352. this._y = quaternion.y;
  2353. this._z = quaternion.z;
  2354. this._w = quaternion.w;
  2355. this._onChangeCallback();
  2356. return this;
  2357. },
  2358. setFromEuler: function (euler, update) {
  2359. if (!(euler && euler.isEuler)) {
  2360. throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2361. }
  2362. var x = euler._x,
  2363. y = euler._y,
  2364. z = euler._z,
  2365. order = euler.order; // http://www.mathworks.com/matlabcentral/fileexchange/
  2366. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2367. // content/SpinCalc.m
  2368. var cos = Math.cos;
  2369. var sin = Math.sin;
  2370. var c1 = cos(x / 2);
  2371. var c2 = cos(y / 2);
  2372. var c3 = cos(z / 2);
  2373. var s1 = sin(x / 2);
  2374. var s2 = sin(y / 2);
  2375. var s3 = sin(z / 2);
  2376. if (order === 'XYZ') {
  2377. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2378. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2379. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2380. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2381. } else if (order === 'YXZ') {
  2382. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2383. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2384. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2385. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2386. } else if (order === 'ZXY') {
  2387. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2388. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2389. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2390. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2391. } else if (order === 'ZYX') {
  2392. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2393. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2394. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2395. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2396. } else if (order === 'YZX') {
  2397. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2398. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2399. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2400. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2401. } else if (order === 'XZY') {
  2402. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2403. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2404. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2405. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2406. }
  2407. if (update !== false) this._onChangeCallback();
  2408. return this;
  2409. },
  2410. setFromAxisAngle: function (axis, angle) {
  2411. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2412. // assumes axis is normalized
  2413. var halfAngle = angle / 2,
  2414. s = Math.sin(halfAngle);
  2415. this._x = axis.x * s;
  2416. this._y = axis.y * s;
  2417. this._z = axis.z * s;
  2418. this._w = Math.cos(halfAngle);
  2419. this._onChangeCallback();
  2420. return this;
  2421. },
  2422. setFromRotationMatrix: function (m) {
  2423. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2424. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2425. var te = m.elements,
  2426. m11 = te[0],
  2427. m12 = te[4],
  2428. m13 = te[8],
  2429. m21 = te[1],
  2430. m22 = te[5],
  2431. m23 = te[9],
  2432. m31 = te[2],
  2433. m32 = te[6],
  2434. m33 = te[10],
  2435. trace = m11 + m22 + m33,
  2436. s;
  2437. if (trace > 0) {
  2438. s = 0.5 / Math.sqrt(trace + 1.0);
  2439. this._w = 0.25 / s;
  2440. this._x = (m32 - m23) * s;
  2441. this._y = (m13 - m31) * s;
  2442. this._z = (m21 - m12) * s;
  2443. } else if (m11 > m22 && m11 > m33) {
  2444. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2445. this._w = (m32 - m23) / s;
  2446. this._x = 0.25 * s;
  2447. this._y = (m12 + m21) / s;
  2448. this._z = (m13 + m31) / s;
  2449. } else if (m22 > m33) {
  2450. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2451. this._w = (m13 - m31) / s;
  2452. this._x = (m12 + m21) / s;
  2453. this._y = 0.25 * s;
  2454. this._z = (m23 + m32) / s;
  2455. } else {
  2456. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2457. this._w = (m21 - m12) / s;
  2458. this._x = (m13 + m31) / s;
  2459. this._y = (m23 + m32) / s;
  2460. this._z = 0.25 * s;
  2461. }
  2462. this._onChangeCallback();
  2463. return this;
  2464. },
  2465. setFromUnitVectors: function (vFrom, vTo) {
  2466. // assumes direction vectors vFrom and vTo are normalized
  2467. var EPS = 0.000001;
  2468. var r = vFrom.dot(vTo) + 1;
  2469. if (r < EPS) {
  2470. r = 0;
  2471. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  2472. this._x = -vFrom.y;
  2473. this._y = vFrom.x;
  2474. this._z = 0;
  2475. this._w = r;
  2476. } else {
  2477. this._x = 0;
  2478. this._y = -vFrom.z;
  2479. this._z = vFrom.y;
  2480. this._w = r;
  2481. }
  2482. } else {
  2483. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2484. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2485. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2486. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2487. this._w = r;
  2488. }
  2489. return this.normalize();
  2490. },
  2491. angleTo: function (q) {
  2492. return 2 * Math.acos(Math.abs(_Math.clamp(this.dot(q), -1, 1)));
  2493. },
  2494. rotateTowards: function (q, step) {
  2495. var angle = this.angleTo(q);
  2496. if (angle === 0) return this;
  2497. var t = Math.min(1, step / angle);
  2498. this.slerp(q, t);
  2499. return this;
  2500. },
  2501. inverse: function () {
  2502. // quaternion is assumed to have unit length
  2503. return this.conjugate();
  2504. },
  2505. conjugate: function () {
  2506. this._x *= -1;
  2507. this._y *= -1;
  2508. this._z *= -1;
  2509. this._onChangeCallback();
  2510. return this;
  2511. },
  2512. dot: function (v) {
  2513. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2514. },
  2515. lengthSq: function () {
  2516. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2517. },
  2518. length: function () {
  2519. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  2520. },
  2521. normalize: function () {
  2522. var l = this.length();
  2523. if (l === 0) {
  2524. this._x = 0;
  2525. this._y = 0;
  2526. this._z = 0;
  2527. this._w = 1;
  2528. } else {
  2529. l = 1 / l;
  2530. this._x = this._x * l;
  2531. this._y = this._y * l;
  2532. this._z = this._z * l;
  2533. this._w = this._w * l;
  2534. }
  2535. this._onChangeCallback();
  2536. return this;
  2537. },
  2538. multiply: function (q, p) {
  2539. if (p !== undefined) {
  2540. console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
  2541. return this.multiplyQuaternions(q, p);
  2542. }
  2543. return this.multiplyQuaternions(this, q);
  2544. },
  2545. premultiply: function (q) {
  2546. return this.multiplyQuaternions(q, this);
  2547. },
  2548. multiplyQuaternions: function (a, b) {
  2549. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2550. var qax = a._x,
  2551. qay = a._y,
  2552. qaz = a._z,
  2553. qaw = a._w;
  2554. var qbx = b._x,
  2555. qby = b._y,
  2556. qbz = b._z,
  2557. qbw = b._w;
  2558. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2559. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2560. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2561. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2562. this._onChangeCallback();
  2563. return this;
  2564. },
  2565. slerp: function (qb, t) {
  2566. if (t === 0) return this;
  2567. if (t === 1) return this.copy(qb);
  2568. var x = this._x,
  2569. y = this._y,
  2570. z = this._z,
  2571. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2572. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2573. if (cosHalfTheta < 0) {
  2574. this._w = -qb._w;
  2575. this._x = -qb._x;
  2576. this._y = -qb._y;
  2577. this._z = -qb._z;
  2578. cosHalfTheta = -cosHalfTheta;
  2579. } else {
  2580. this.copy(qb);
  2581. }
  2582. if (cosHalfTheta >= 1.0) {
  2583. this._w = w;
  2584. this._x = x;
  2585. this._y = y;
  2586. this._z = z;
  2587. return this;
  2588. }
  2589. var sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2590. if (sqrSinHalfTheta <= Number.EPSILON) {
  2591. var s = 1 - t;
  2592. this._w = s * w + t * this._w;
  2593. this._x = s * x + t * this._x;
  2594. this._y = s * y + t * this._y;
  2595. this._z = s * z + t * this._z;
  2596. this.normalize();
  2597. this._onChangeCallback();
  2598. return this;
  2599. }
  2600. var sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  2601. var halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  2602. var ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  2603. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  2604. this._w = w * ratioA + this._w * ratioB;
  2605. this._x = x * ratioA + this._x * ratioB;
  2606. this._y = y * ratioA + this._y * ratioB;
  2607. this._z = z * ratioA + this._z * ratioB;
  2608. this._onChangeCallback();
  2609. return this;
  2610. },
  2611. equals: function (quaternion) {
  2612. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  2613. },
  2614. fromArray: function (array, offset) {
  2615. if (offset === undefined) offset = 0;
  2616. this._x = array[offset];
  2617. this._y = array[offset + 1];
  2618. this._z = array[offset + 2];
  2619. this._w = array[offset + 3];
  2620. this._onChangeCallback();
  2621. return this;
  2622. },
  2623. toArray: function (array, offset) {
  2624. if (array === undefined) array = [];
  2625. if (offset === undefined) offset = 0;
  2626. array[offset] = this._x;
  2627. array[offset + 1] = this._y;
  2628. array[offset + 2] = this._z;
  2629. array[offset + 3] = this._w;
  2630. return array;
  2631. },
  2632. _onChange: function (callback) {
  2633. this._onChangeCallback = callback;
  2634. return this;
  2635. },
  2636. _onChangeCallback: function () {}
  2637. });
  2638. /**
  2639. * @author mrdoob / http://mrdoob.com/
  2640. * @author kile / http://kile.stravaganza.org/
  2641. * @author philogb / http://blog.thejit.org/
  2642. * @author mikael emtinger / http://gomo.se/
  2643. * @author egraether / http://egraether.com/
  2644. * @author WestLangley / http://github.com/WestLangley
  2645. */
  2646. var _vector = new Vector3();
  2647. var _quaternion = new Quaternion();
  2648. function Vector3(x, y, z) {
  2649. this.x = x || 0;
  2650. this.y = y || 0;
  2651. this.z = z || 0;
  2652. }
  2653. Object.assign(Vector3.prototype, {
  2654. isVector3: true,
  2655. set: function (x, y, z) {
  2656. this.x = x;
  2657. this.y = y;
  2658. this.z = z;
  2659. return this;
  2660. },
  2661. setScalar: function (scalar) {
  2662. this.x = scalar;
  2663. this.y = scalar;
  2664. this.z = scalar;
  2665. return this;
  2666. },
  2667. setX: function (x) {
  2668. this.x = x;
  2669. return this;
  2670. },
  2671. setY: function (y) {
  2672. this.y = y;
  2673. return this;
  2674. },
  2675. setZ: function (z) {
  2676. this.z = z;
  2677. return this;
  2678. },
  2679. setComponent: function (index, value) {
  2680. switch (index) {
  2681. case 0:
  2682. this.x = value;
  2683. break;
  2684. case 1:
  2685. this.y = value;
  2686. break;
  2687. case 2:
  2688. this.z = value;
  2689. break;
  2690. default:
  2691. throw new Error('index is out of range: ' + index);
  2692. }
  2693. return this;
  2694. },
  2695. getComponent: function (index) {
  2696. switch (index) {
  2697. case 0:
  2698. return this.x;
  2699. case 1:
  2700. return this.y;
  2701. case 2:
  2702. return this.z;
  2703. default:
  2704. throw new Error('index is out of range: ' + index);
  2705. }
  2706. },
  2707. clone: function () {
  2708. return new this.constructor(this.x, this.y, this.z);
  2709. },
  2710. copy: function (v) {
  2711. this.x = v.x;
  2712. this.y = v.y;
  2713. this.z = v.z;
  2714. return this;
  2715. },
  2716. add: function (v, w) {
  2717. if (w !== undefined) {
  2718. console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  2719. return this.addVectors(v, w);
  2720. }
  2721. this.x += v.x;
  2722. this.y += v.y;
  2723. this.z += v.z;
  2724. return this;
  2725. },
  2726. addScalar: function (s) {
  2727. this.x += s;
  2728. this.y += s;
  2729. this.z += s;
  2730. return this;
  2731. },
  2732. addVectors: function (a, b) {
  2733. this.x = a.x + b.x;
  2734. this.y = a.y + b.y;
  2735. this.z = a.z + b.z;
  2736. return this;
  2737. },
  2738. addScaledVector: function (v, s) {
  2739. this.x += v.x * s;
  2740. this.y += v.y * s;
  2741. this.z += v.z * s;
  2742. return this;
  2743. },
  2744. sub: function (v, w) {
  2745. if (w !== undefined) {
  2746. console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  2747. return this.subVectors(v, w);
  2748. }
  2749. this.x -= v.x;
  2750. this.y -= v.y;
  2751. this.z -= v.z;
  2752. return this;
  2753. },
  2754. subScalar: function (s) {
  2755. this.x -= s;
  2756. this.y -= s;
  2757. this.z -= s;
  2758. return this;
  2759. },
  2760. subVectors: function (a, b) {
  2761. this.x = a.x - b.x;
  2762. this.y = a.y - b.y;
  2763. this.z = a.z - b.z;
  2764. return this;
  2765. },
  2766. multiply: function (v, w) {
  2767. if (w !== undefined) {
  2768. console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');
  2769. return this.multiplyVectors(v, w);
  2770. }
  2771. this.x *= v.x;
  2772. this.y *= v.y;
  2773. this.z *= v.z;
  2774. return this;
  2775. },
  2776. multiplyScalar: function (scalar) {
  2777. this.x *= scalar;
  2778. this.y *= scalar;
  2779. this.z *= scalar;
  2780. return this;
  2781. },
  2782. multiplyVectors: function (a, b) {
  2783. this.x = a.x * b.x;
  2784. this.y = a.y * b.y;
  2785. this.z = a.z * b.z;
  2786. return this;
  2787. },
  2788. applyEuler: function (euler) {
  2789. if (!(euler && euler.isEuler)) {
  2790. console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2791. }
  2792. return this.applyQuaternion(_quaternion.setFromEuler(euler));
  2793. },
  2794. applyAxisAngle: function (axis, angle) {
  2795. return this.applyQuaternion(_quaternion.setFromAxisAngle(axis, angle));
  2796. },
  2797. applyMatrix3: function (m) {
  2798. var x = this.x,
  2799. y = this.y,
  2800. z = this.z;
  2801. var e = m.elements;
  2802. this.x = e[0] * x + e[3] * y + e[6] * z;
  2803. this.y = e[1] * x + e[4] * y + e[7] * z;
  2804. this.z = e[2] * x + e[5] * y + e[8] * z;
  2805. return this;
  2806. },
  2807. applyMatrix4: function (m) {
  2808. var x = this.x,
  2809. y = this.y,
  2810. z = this.z;
  2811. var e = m.elements;
  2812. var w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  2813. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  2814. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  2815. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  2816. return this;
  2817. },
  2818. applyQuaternion: function (q) {
  2819. var x = this.x,
  2820. y = this.y,
  2821. z = this.z;
  2822. var qx = q.x,
  2823. qy = q.y,
  2824. qz = q.z,
  2825. qw = q.w; // calculate quat * vector
  2826. var ix = qw * x + qy * z - qz * y;
  2827. var iy = qw * y + qz * x - qx * z;
  2828. var iz = qw * z + qx * y - qy * x;
  2829. var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  2830. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2831. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2832. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2833. return this;
  2834. },
  2835. project: function (camera) {
  2836. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  2837. },
  2838. unproject: function (camera) {
  2839. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  2840. },
  2841. transformDirection: function (m) {
  2842. // input: THREE.Matrix4 affine matrix
  2843. // vector interpreted as a direction
  2844. var x = this.x,
  2845. y = this.y,
  2846. z = this.z;
  2847. var e = m.elements;
  2848. this.x = e[0] * x + e[4] * y + e[8] * z;
  2849. this.y = e[1] * x + e[5] * y + e[9] * z;
  2850. this.z = e[2] * x + e[6] * y + e[10] * z;
  2851. return this.normalize();
  2852. },
  2853. divide: function (v) {
  2854. this.x /= v.x;
  2855. this.y /= v.y;
  2856. this.z /= v.z;
  2857. return this;
  2858. },
  2859. divideScalar: function (scalar) {
  2860. return this.multiplyScalar(1 / scalar);
  2861. },
  2862. min: function (v) {
  2863. this.x = Math.min(this.x, v.x);
  2864. this.y = Math.min(this.y, v.y);
  2865. this.z = Math.min(this.z, v.z);
  2866. return this;
  2867. },
  2868. max: function (v) {
  2869. this.x = Math.max(this.x, v.x);
  2870. this.y = Math.max(this.y, v.y);
  2871. this.z = Math.max(this.z, v.z);
  2872. return this;
  2873. },
  2874. clamp: function (min, max) {
  2875. // assumes min < max, componentwise
  2876. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2877. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2878. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2879. return this;
  2880. },
  2881. clampScalar: function (minVal, maxVal) {
  2882. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2883. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2884. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2885. return this;
  2886. },
  2887. clampLength: function (min, max) {
  2888. var length = this.length();
  2889. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2890. },
  2891. floor: function () {
  2892. this.x = Math.floor(this.x);
  2893. this.y = Math.floor(this.y);
  2894. this.z = Math.floor(this.z);
  2895. return this;
  2896. },
  2897. ceil: function () {
  2898. this.x = Math.ceil(this.x);
  2899. this.y = Math.ceil(this.y);
  2900. this.z = Math.ceil(this.z);
  2901. return this;
  2902. },
  2903. round: function () {
  2904. this.x = Math.round(this.x);
  2905. this.y = Math.round(this.y);
  2906. this.z = Math.round(this.z);
  2907. return this;
  2908. },
  2909. roundToZero: function () {
  2910. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2911. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2912. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2913. return this;
  2914. },
  2915. negate: function () {
  2916. this.x = -this.x;
  2917. this.y = -this.y;
  2918. this.z = -this.z;
  2919. return this;
  2920. },
  2921. dot: function (v) {
  2922. return this.x * v.x + this.y * v.y + this.z * v.z;
  2923. },
  2924. // TODO lengthSquared?
  2925. lengthSq: function () {
  2926. return this.x * this.x + this.y * this.y + this.z * this.z;
  2927. },
  2928. length: function () {
  2929. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2930. },
  2931. manhattanLength: function () {
  2932. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  2933. },
  2934. normalize: function () {
  2935. return this.divideScalar(this.length() || 1);
  2936. },
  2937. setLength: function (length) {
  2938. return this.normalize().multiplyScalar(length);
  2939. },
  2940. lerp: function (v, alpha) {
  2941. this.x += (v.x - this.x) * alpha;
  2942. this.y += (v.y - this.y) * alpha;
  2943. this.z += (v.z - this.z) * alpha;
  2944. return this;
  2945. },
  2946. lerpVectors: function (v1, v2, alpha) {
  2947. return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
  2948. },
  2949. cross: function (v, w) {
  2950. if (w !== undefined) {
  2951. console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
  2952. return this.crossVectors(v, w);
  2953. }
  2954. return this.crossVectors(this, v);
  2955. },
  2956. crossVectors: function (a, b) {
  2957. var ax = a.x,
  2958. ay = a.y,
  2959. az = a.z;
  2960. var bx = b.x,
  2961. by = b.y,
  2962. bz = b.z;
  2963. this.x = ay * bz - az * by;
  2964. this.y = az * bx - ax * bz;
  2965. this.z = ax * by - ay * bx;
  2966. return this;
  2967. },
  2968. projectOnVector: function (v) {
  2969. // v cannot be the zero v
  2970. var scalar = v.dot(this) / v.lengthSq();
  2971. return this.copy(v).multiplyScalar(scalar);
  2972. },
  2973. projectOnPlane: function (planeNormal) {
  2974. _vector.copy(this).projectOnVector(planeNormal);
  2975. return this.sub(_vector);
  2976. },
  2977. reflect: function (normal) {
  2978. // reflect incident vector off plane orthogonal to normal
  2979. // normal is assumed to have unit length
  2980. return this.sub(_vector.copy(normal).multiplyScalar(2 * this.dot(normal)));
  2981. },
  2982. angleTo: function (v) {
  2983. var denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  2984. if (denominator === 0) console.error('THREE.Vector3: angleTo() can\'t handle zero length vectors.');
  2985. var theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  2986. return Math.acos(_Math.clamp(theta, -1, 1));
  2987. },
  2988. distanceTo: function (v) {
  2989. return Math.sqrt(this.distanceToSquared(v));
  2990. },
  2991. distanceToSquared: function (v) {
  2992. var dx = this.x - v.x,
  2993. dy = this.y - v.y,
  2994. dz = this.z - v.z;
  2995. return dx * dx + dy * dy + dz * dz;
  2996. },
  2997. manhattanDistanceTo: function (v) {
  2998. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  2999. },
  3000. setFromSpherical: function (s) {
  3001. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  3002. },
  3003. setFromSphericalCoords: function (radius, phi, theta) {
  3004. var sinPhiRadius = Math.sin(phi) * radius;
  3005. this.x = sinPhiRadius * Math.sin(theta);
  3006. this.y = Math.cos(phi) * radius;
  3007. this.z = sinPhiRadius * Math.cos(theta);
  3008. return this;
  3009. },
  3010. setFromCylindrical: function (c) {
  3011. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  3012. },
  3013. setFromCylindricalCoords: function (radius, theta, y) {
  3014. this.x = radius * Math.sin(theta);
  3015. this.y = y;
  3016. this.z = radius * Math.cos(theta);
  3017. return this;
  3018. },
  3019. setFromMatrixPosition: function (m) {
  3020. var e = m.elements;
  3021. this.x = e[12];
  3022. this.y = e[13];
  3023. this.z = e[14];
  3024. return this;
  3025. },
  3026. setFromMatrixScale: function (m) {
  3027. var sx = this.setFromMatrixColumn(m, 0).length();
  3028. var sy = this.setFromMatrixColumn(m, 1).length();
  3029. var sz = this.setFromMatrixColumn(m, 2).length();
  3030. this.x = sx;
  3031. this.y = sy;
  3032. this.z = sz;
  3033. return this;
  3034. },
  3035. setFromMatrixColumn: function (m, index) {
  3036. return this.fromArray(m.elements, index * 4);
  3037. },
  3038. equals: function (v) {
  3039. return v.x === this.x && v.y === this.y && v.z === this.z;
  3040. },
  3041. fromArray: function (array, offset) {
  3042. if (offset === undefined) offset = 0;
  3043. this.x = array[offset];
  3044. this.y = array[offset + 1];
  3045. this.z = array[offset + 2];
  3046. return this;
  3047. },
  3048. toArray: function (array, offset) {
  3049. if (array === undefined) array = [];
  3050. if (offset === undefined) offset = 0;
  3051. array[offset] = this.x;
  3052. array[offset + 1] = this.y;
  3053. array[offset + 2] = this.z;
  3054. return array;
  3055. },
  3056. fromBufferAttribute: function (attribute, index, offset) {
  3057. if (offset !== undefined) {
  3058. console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
  3059. }
  3060. this.x = attribute.getX(index);
  3061. this.y = attribute.getY(index);
  3062. this.z = attribute.getZ(index);
  3063. return this;
  3064. }
  3065. });
  3066. /**
  3067. * @author alteredq / http://alteredqualia.com/
  3068. * @author WestLangley / http://github.com/WestLangley
  3069. * @author bhouston / http://clara.io
  3070. * @author tschw
  3071. */
  3072. var _vector$1 = new Vector3();
  3073. function Matrix3() {
  3074. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  3075. if (arguments.length > 0) {
  3076. console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');
  3077. }
  3078. }
  3079. Object.assign(Matrix3.prototype, {
  3080. isMatrix3: true,
  3081. set: function (n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  3082. var te = this.elements;
  3083. te[0] = n11;
  3084. te[1] = n21;
  3085. te[2] = n31;
  3086. te[3] = n12;
  3087. te[4] = n22;
  3088. te[5] = n32;
  3089. te[6] = n13;
  3090. te[7] = n23;
  3091. te[8] = n33;
  3092. return this;
  3093. },
  3094. identity: function () {
  3095. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  3096. return this;
  3097. },
  3098. clone: function () {
  3099. return new this.constructor().fromArray(this.elements);
  3100. },
  3101. copy: function (m) {
  3102. var te = this.elements;
  3103. var me = m.elements;
  3104. te[0] = me[0];
  3105. te[1] = me[1];
  3106. te[2] = me[2];
  3107. te[3] = me[3];
  3108. te[4] = me[4];
  3109. te[5] = me[5];
  3110. te[6] = me[6];
  3111. te[7] = me[7];
  3112. te[8] = me[8];
  3113. return this;
  3114. },
  3115. setFromMatrix4: function (m) {
  3116. var me = m.elements;
  3117. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  3118. return this;
  3119. },
  3120. applyToBufferAttribute: function (attribute) {
  3121. for (var i = 0, l = attribute.count; i < l; i++) {
  3122. _vector$1.x = attribute.getX(i);
  3123. _vector$1.y = attribute.getY(i);
  3124. _vector$1.z = attribute.getZ(i);
  3125. _vector$1.applyMatrix3(this);
  3126. attribute.setXYZ(i, _vector$1.x, _vector$1.y, _vector$1.z);
  3127. }
  3128. return attribute;
  3129. },
  3130. multiply: function (m) {
  3131. return this.multiplyMatrices(this, m);
  3132. },
  3133. premultiply: function (m) {
  3134. return this.multiplyMatrices(m, this);
  3135. },
  3136. multiplyMatrices: function (a, b) {
  3137. var ae = a.elements;
  3138. var be = b.elements;
  3139. var te = this.elements;
  3140. var a11 = ae[0],
  3141. a12 = ae[3],
  3142. a13 = ae[6];
  3143. var a21 = ae[1],
  3144. a22 = ae[4],
  3145. a23 = ae[7];
  3146. var a31 = ae[2],
  3147. a32 = ae[5],
  3148. a33 = ae[8];
  3149. var b11 = be[0],
  3150. b12 = be[3],
  3151. b13 = be[6];
  3152. var b21 = be[1],
  3153. b22 = be[4],
  3154. b23 = be[7];
  3155. var b31 = be[2],
  3156. b32 = be[5],
  3157. b33 = be[8];
  3158. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  3159. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  3160. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  3161. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  3162. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  3163. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  3164. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  3165. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  3166. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  3167. return this;
  3168. },
  3169. multiplyScalar: function (s) {
  3170. var te = this.elements;
  3171. te[0] *= s;
  3172. te[3] *= s;
  3173. te[6] *= s;
  3174. te[1] *= s;
  3175. te[4] *= s;
  3176. te[7] *= s;
  3177. te[2] *= s;
  3178. te[5] *= s;
  3179. te[8] *= s;
  3180. return this;
  3181. },
  3182. determinant: function () {
  3183. var te = this.elements;
  3184. var a = te[0],
  3185. b = te[1],
  3186. c = te[2],
  3187. d = te[3],
  3188. e = te[4],
  3189. f = te[5],
  3190. g = te[6],
  3191. h = te[7],
  3192. i = te[8];
  3193. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  3194. },
  3195. getInverse: function (matrix, throwOnDegenerate) {
  3196. if (matrix && matrix.isMatrix4) {
  3197. console.error("THREE.Matrix3: .getInverse() no longer takes a Matrix4 argument.");
  3198. }
  3199. var me = matrix.elements,
  3200. te = this.elements,
  3201. n11 = me[0],
  3202. n21 = me[1],
  3203. n31 = me[2],
  3204. n12 = me[3],
  3205. n22 = me[4],
  3206. n32 = me[5],
  3207. n13 = me[6],
  3208. n23 = me[7],
  3209. n33 = me[8],
  3210. t11 = n33 * n22 - n32 * n23,
  3211. t12 = n32 * n13 - n33 * n12,
  3212. t13 = n23 * n12 - n22 * n13,
  3213. det = n11 * t11 + n21 * t12 + n31 * t13;
  3214. if (det === 0) {
  3215. var msg = "THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0";
  3216. if (throwOnDegenerate === true) {
  3217. throw new Error(msg);
  3218. } else {
  3219. console.warn(msg);
  3220. }
  3221. return this.identity();
  3222. }
  3223. var detInv = 1 / det;
  3224. te[0] = t11 * detInv;
  3225. te[1] = (n31 * n23 - n33 * n21) * detInv;
  3226. te[2] = (n32 * n21 - n31 * n22) * detInv;
  3227. te[3] = t12 * detInv;
  3228. te[4] = (n33 * n11 - n31 * n13) * detInv;
  3229. te[5] = (n31 * n12 - n32 * n11) * detInv;
  3230. te[6] = t13 * detInv;
  3231. te[7] = (n21 * n13 - n23 * n11) * detInv;
  3232. te[8] = (n22 * n11 - n21 * n12) * detInv;
  3233. return this;
  3234. },
  3235. transpose: function () {
  3236. var tmp,
  3237. m = this.elements;
  3238. tmp = m[1];
  3239. m[1] = m[3];
  3240. m[3] = tmp;
  3241. tmp = m[2];
  3242. m[2] = m[6];
  3243. m[6] = tmp;
  3244. tmp = m[5];
  3245. m[5] = m[7];
  3246. m[7] = tmp;
  3247. return this;
  3248. },
  3249. getNormalMatrix: function (matrix4) {
  3250. return this.setFromMatrix4(matrix4).getInverse(this).transpose();
  3251. },
  3252. transposeIntoArray: function (r) {
  3253. var m = this.elements;
  3254. r[0] = m[0];
  3255. r[1] = m[3];
  3256. r[2] = m[6];
  3257. r[3] = m[1];
  3258. r[4] = m[4];
  3259. r[5] = m[7];
  3260. r[6] = m[2];
  3261. r[7] = m[5];
  3262. r[8] = m[8];
  3263. return this;
  3264. },
  3265. setUvTransform: function (tx, ty, sx, sy, rotation, cx, cy) {
  3266. var c = Math.cos(rotation);
  3267. var s = Math.sin(rotation);
  3268. 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);
  3269. },
  3270. scale: function (sx, sy) {
  3271. var te = this.elements;
  3272. te[0] *= sx;
  3273. te[3] *= sx;
  3274. te[6] *= sx;
  3275. te[1] *= sy;
  3276. te[4] *= sy;
  3277. te[7] *= sy;
  3278. return this;
  3279. },
  3280. rotate: function (theta) {
  3281. var c = Math.cos(theta);
  3282. var s = Math.sin(theta);
  3283. var te = this.elements;
  3284. var a11 = te[0],
  3285. a12 = te[3],
  3286. a13 = te[6];
  3287. var a21 = te[1],
  3288. a22 = te[4],
  3289. a23 = te[7];
  3290. te[0] = c * a11 + s * a21;
  3291. te[3] = c * a12 + s * a22;
  3292. te[6] = c * a13 + s * a23;
  3293. te[1] = -s * a11 + c * a21;
  3294. te[4] = -s * a12 + c * a22;
  3295. te[7] = -s * a13 + c * a23;
  3296. return this;
  3297. },
  3298. translate: function (tx, ty) {
  3299. var te = this.elements;
  3300. te[0] += tx * te[2];
  3301. te[3] += tx * te[5];
  3302. te[6] += tx * te[8];
  3303. te[1] += ty * te[2];
  3304. te[4] += ty * te[5];
  3305. te[7] += ty * te[8];
  3306. return this;
  3307. },
  3308. equals: function (matrix) {
  3309. var te = this.elements;
  3310. var me = matrix.elements;
  3311. for (var i = 0; i < 9; i++) {
  3312. if (te[i] !== me[i]) return false;
  3313. }
  3314. return true;
  3315. },
  3316. fromArray: function (array, offset) {
  3317. if (offset === undefined) offset = 0;
  3318. for (var i = 0; i < 9; i++) {
  3319. this.elements[i] = array[i + offset];
  3320. }
  3321. return this;
  3322. },
  3323. toArray: function (array, offset) {
  3324. if (array === undefined) array = [];
  3325. if (offset === undefined) offset = 0;
  3326. var te = this.elements;
  3327. array[offset] = te[0];
  3328. array[offset + 1] = te[1];
  3329. array[offset + 2] = te[2];
  3330. array[offset + 3] = te[3];
  3331. array[offset + 4] = te[4];
  3332. array[offset + 5] = te[5];
  3333. array[offset + 6] = te[6];
  3334. array[offset + 7] = te[7];
  3335. array[offset + 8] = te[8];
  3336. return array;
  3337. }
  3338. });
  3339. /**
  3340. * @author mrdoob / http://mrdoob.com/
  3341. * @author alteredq / http://alteredqualia.com/
  3342. * @author szimek / https://github.com/szimek/
  3343. */
  3344. var _canvas;
  3345. var ImageUtils = {
  3346. getDataURL: function (image) {
  3347. var canvas;
  3348. if (typeof HTMLCanvasElement == 'undefined') {
  3349. return image.src;
  3350. } else if (image instanceof HTMLCanvasElement) {
  3351. canvas = image;
  3352. } else {
  3353. if (_canvas === undefined) _canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  3354. _canvas.width = image.width;
  3355. _canvas.height = image.height;
  3356. var context = _canvas.getContext('2d');
  3357. if (image instanceof ImageData) {
  3358. context.putImageData(image, 0, 0);
  3359. } else {
  3360. context.drawImage(image, 0, 0, image.width, image.height);
  3361. }
  3362. canvas = _canvas;
  3363. }
  3364. if (canvas.width > 2048 || canvas.height > 2048) {
  3365. return canvas.toDataURL('image/jpeg', 0.6);
  3366. } else {
  3367. return canvas.toDataURL('image/png');
  3368. }
  3369. }
  3370. };
  3371. /**
  3372. * @author mrdoob / http://mrdoob.com/
  3373. * @author alteredq / http://alteredqualia.com/
  3374. * @author szimek / https://github.com/szimek/
  3375. */
  3376. exports.ImageUtils = ImageUtils;
  3377. var textureId = 0;
  3378. function Texture(image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  3379. Object.defineProperty(this, 'id', {
  3380. value: textureId++
  3381. });
  3382. this.uuid = _Math.generateUUID();
  3383. this.name = '';
  3384. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  3385. this.mipmaps = [];
  3386. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  3387. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  3388. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  3389. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  3390. this.minFilter = minFilter !== undefined ? minFilter : LinearMipmapLinearFilter;
  3391. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  3392. this.format = format !== undefined ? format : RGBAFormat;
  3393. this.type = type !== undefined ? type : UnsignedByteType;
  3394. this.offset = new Vector2(0, 0);
  3395. this.repeat = new Vector2(1, 1);
  3396. this.center = new Vector2(0, 0);
  3397. this.rotation = 0;
  3398. this.matrixAutoUpdate = true;
  3399. this.matrix = new Matrix3();
  3400. this.generateMipmaps = true;
  3401. this.premultiplyAlpha = false;
  3402. this.flipY = true;
  3403. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  3404. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  3405. //
  3406. // Also changing the encoding after already used by a Material will not automatically make the Material
  3407. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  3408. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  3409. this.version = 0;
  3410. this.onUpdate = null;
  3411. }
  3412. Texture.DEFAULT_IMAGE = undefined;
  3413. Texture.DEFAULT_MAPPING = UVMapping;
  3414. Texture.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  3415. constructor: Texture,
  3416. isTexture: true,
  3417. updateMatrix: function () {
  3418. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  3419. },
  3420. clone: function () {
  3421. return new this.constructor().copy(this);
  3422. },
  3423. copy: function (source) {
  3424. this.name = source.name;
  3425. this.image = source.image;
  3426. this.mipmaps = source.mipmaps.slice(0);
  3427. this.mapping = source.mapping;
  3428. this.wrapS = source.wrapS;
  3429. this.wrapT = source.wrapT;
  3430. this.magFilter = source.magFilter;
  3431. this.minFilter = source.minFilter;
  3432. this.anisotropy = source.anisotropy;
  3433. this.format = source.format;
  3434. this.type = source.type;
  3435. this.offset.copy(source.offset);
  3436. this.repeat.copy(source.repeat);
  3437. this.center.copy(source.center);
  3438. this.rotation = source.rotation;
  3439. this.matrixAutoUpdate = source.matrixAutoUpdate;
  3440. this.matrix.copy(source.matrix);
  3441. this.generateMipmaps = source.generateMipmaps;
  3442. this.premultiplyAlpha = source.premultiplyAlpha;
  3443. this.flipY = source.flipY;
  3444. this.unpackAlignment = source.unpackAlignment;
  3445. this.encoding = source.encoding;
  3446. return this;
  3447. },
  3448. toJSON: function (meta) {
  3449. var isRootObject = meta === undefined || typeof meta === 'string';
  3450. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  3451. return meta.textures[this.uuid];
  3452. }
  3453. var output = {
  3454. metadata: {
  3455. version: 4.5,
  3456. type: 'Texture',
  3457. generator: 'Texture.toJSON'
  3458. },
  3459. uuid: this.uuid,
  3460. name: this.name,
  3461. mapping: this.mapping,
  3462. repeat: [this.repeat.x, this.repeat.y],
  3463. offset: [this.offset.x, this.offset.y],
  3464. center: [this.center.x, this.center.y],
  3465. rotation: this.rotation,
  3466. wrap: [this.wrapS, this.wrapT],
  3467. format: this.format,
  3468. type: this.type,
  3469. encoding: this.encoding,
  3470. minFilter: this.minFilter,
  3471. magFilter: this.magFilter,
  3472. anisotropy: this.anisotropy,
  3473. flipY: this.flipY,
  3474. premultiplyAlpha: this.premultiplyAlpha,
  3475. unpackAlignment: this.unpackAlignment
  3476. };
  3477. if (this.image !== undefined) {
  3478. // TODO: Move to THREE.Image
  3479. var image = this.image;
  3480. if (image.uuid === undefined) {
  3481. image.uuid = _Math.generateUUID(); // UGH
  3482. }
  3483. if (!isRootObject && meta.images[image.uuid] === undefined) {
  3484. var url;
  3485. if (Array.isArray(image)) {
  3486. // process array of images e.g. CubeTexture
  3487. url = [];
  3488. for (var i = 0, l = image.length; i < l; i++) {
  3489. url.push(ImageUtils.getDataURL(image[i]));
  3490. }
  3491. } else {
  3492. // process single image
  3493. url = ImageUtils.getDataURL(image);
  3494. }
  3495. meta.images[image.uuid] = {
  3496. uuid: image.uuid,
  3497. url: url
  3498. };
  3499. }
  3500. output.image = image.uuid;
  3501. }
  3502. if (!isRootObject) {
  3503. meta.textures[this.uuid] = output;
  3504. }
  3505. return output;
  3506. },
  3507. dispose: function () {
  3508. this.dispatchEvent({
  3509. type: 'dispose'
  3510. });
  3511. },
  3512. transformUv: function (uv) {
  3513. if (this.mapping !== UVMapping) return uv;
  3514. uv.applyMatrix3(this.matrix);
  3515. if (uv.x < 0 || uv.x > 1) {
  3516. switch (this.wrapS) {
  3517. case RepeatWrapping:
  3518. uv.x = uv.x - Math.floor(uv.x);
  3519. break;
  3520. case ClampToEdgeWrapping:
  3521. uv.x = uv.x < 0 ? 0 : 1;
  3522. break;
  3523. case MirroredRepeatWrapping:
  3524. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  3525. uv.x = Math.ceil(uv.x) - uv.x;
  3526. } else {
  3527. uv.x = uv.x - Math.floor(uv.x);
  3528. }
  3529. break;
  3530. }
  3531. }
  3532. if (uv.y < 0 || uv.y > 1) {
  3533. switch (this.wrapT) {
  3534. case RepeatWrapping:
  3535. uv.y = uv.y - Math.floor(uv.y);
  3536. break;
  3537. case ClampToEdgeWrapping:
  3538. uv.y = uv.y < 0 ? 0 : 1;
  3539. break;
  3540. case MirroredRepeatWrapping:
  3541. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  3542. uv.y = Math.ceil(uv.y) - uv.y;
  3543. } else {
  3544. uv.y = uv.y - Math.floor(uv.y);
  3545. }
  3546. break;
  3547. }
  3548. }
  3549. if (this.flipY) {
  3550. uv.y = 1 - uv.y;
  3551. }
  3552. return uv;
  3553. }
  3554. });
  3555. Object.defineProperty(Texture.prototype, "needsUpdate", {
  3556. set: function (value) {
  3557. if (value === true) this.version++;
  3558. }
  3559. });
  3560. /**
  3561. * @author supereggbert / http://www.paulbrunt.co.uk/
  3562. * @author philogb / http://blog.thejit.org/
  3563. * @author mikael emtinger / http://gomo.se/
  3564. * @author egraether / http://egraether.com/
  3565. * @author WestLangley / http://github.com/WestLangley
  3566. */
  3567. function Vector4(x, y, z, w) {
  3568. this.x = x || 0;
  3569. this.y = y || 0;
  3570. this.z = z || 0;
  3571. this.w = w !== undefined ? w : 1;
  3572. }
  3573. Object.defineProperties(Vector4.prototype, {
  3574. "width": {
  3575. get: function () {
  3576. return this.z;
  3577. },
  3578. set: function (value) {
  3579. this.z = value;
  3580. }
  3581. },
  3582. "height": {
  3583. get: function () {
  3584. return this.w;
  3585. },
  3586. set: function (value) {
  3587. this.w = value;
  3588. }
  3589. }
  3590. });
  3591. Object.assign(Vector4.prototype, {
  3592. isVector4: true,
  3593. set: function (x, y, z, w) {
  3594. this.x = x;
  3595. this.y = y;
  3596. this.z = z;
  3597. this.w = w;
  3598. return this;
  3599. },
  3600. setScalar: function (scalar) {
  3601. this.x = scalar;
  3602. this.y = scalar;
  3603. this.z = scalar;
  3604. this.w = scalar;
  3605. return this;
  3606. },
  3607. setX: function (x) {
  3608. this.x = x;
  3609. return this;
  3610. },
  3611. setY: function (y) {
  3612. this.y = y;
  3613. return this;
  3614. },
  3615. setZ: function (z) {
  3616. this.z = z;
  3617. return this;
  3618. },
  3619. setW: function (w) {
  3620. this.w = w;
  3621. return this;
  3622. },
  3623. setComponent: function (index, value) {
  3624. switch (index) {
  3625. case 0:
  3626. this.x = value;
  3627. break;
  3628. case 1:
  3629. this.y = value;
  3630. break;
  3631. case 2:
  3632. this.z = value;
  3633. break;
  3634. case 3:
  3635. this.w = value;
  3636. break;
  3637. default:
  3638. throw new Error('index is out of range: ' + index);
  3639. }
  3640. return this;
  3641. },
  3642. getComponent: function (index) {
  3643. switch (index) {
  3644. case 0:
  3645. return this.x;
  3646. case 1:
  3647. return this.y;
  3648. case 2:
  3649. return this.z;
  3650. case 3:
  3651. return this.w;
  3652. default:
  3653. throw new Error('index is out of range: ' + index);
  3654. }
  3655. },
  3656. clone: function () {
  3657. return new this.constructor(this.x, this.y, this.z, this.w);
  3658. },
  3659. copy: function (v) {
  3660. this.x = v.x;
  3661. this.y = v.y;
  3662. this.z = v.z;
  3663. this.w = v.w !== undefined ? v.w : 1;
  3664. return this;
  3665. },
  3666. add: function (v, w) {
  3667. if (w !== undefined) {
  3668. console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  3669. return this.addVectors(v, w);
  3670. }
  3671. this.x += v.x;
  3672. this.y += v.y;
  3673. this.z += v.z;
  3674. this.w += v.w;
  3675. return this;
  3676. },
  3677. addScalar: function (s) {
  3678. this.x += s;
  3679. this.y += s;
  3680. this.z += s;
  3681. this.w += s;
  3682. return this;
  3683. },
  3684. addVectors: function (a, b) {
  3685. this.x = a.x + b.x;
  3686. this.y = a.y + b.y;
  3687. this.z = a.z + b.z;
  3688. this.w = a.w + b.w;
  3689. return this;
  3690. },
  3691. addScaledVector: function (v, s) {
  3692. this.x += v.x * s;
  3693. this.y += v.y * s;
  3694. this.z += v.z * s;
  3695. this.w += v.w * s;
  3696. return this;
  3697. },
  3698. sub: function (v, w) {
  3699. if (w !== undefined) {
  3700. console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  3701. return this.subVectors(v, w);
  3702. }
  3703. this.x -= v.x;
  3704. this.y -= v.y;
  3705. this.z -= v.z;
  3706. this.w -= v.w;
  3707. return this;
  3708. },
  3709. subScalar: function (s) {
  3710. this.x -= s;
  3711. this.y -= s;
  3712. this.z -= s;
  3713. this.w -= s;
  3714. return this;
  3715. },
  3716. subVectors: function (a, b) {
  3717. this.x = a.x - b.x;
  3718. this.y = a.y - b.y;
  3719. this.z = a.z - b.z;
  3720. this.w = a.w - b.w;
  3721. return this;
  3722. },
  3723. multiplyScalar: function (scalar) {
  3724. this.x *= scalar;
  3725. this.y *= scalar;
  3726. this.z *= scalar;
  3727. this.w *= scalar;
  3728. return this;
  3729. },
  3730. applyMatrix4: function (m) {
  3731. var x = this.x,
  3732. y = this.y,
  3733. z = this.z,
  3734. w = this.w;
  3735. var e = m.elements;
  3736. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  3737. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  3738. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  3739. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  3740. return this;
  3741. },
  3742. divideScalar: function (scalar) {
  3743. return this.multiplyScalar(1 / scalar);
  3744. },
  3745. setAxisAngleFromQuaternion: function (q) {
  3746. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  3747. // q is assumed to be normalized
  3748. this.w = 2 * Math.acos(q.w);
  3749. var s = Math.sqrt(1 - q.w * q.w);
  3750. if (s < 0.0001) {
  3751. this.x = 1;
  3752. this.y = 0;
  3753. this.z = 0;
  3754. } else {
  3755. this.x = q.x / s;
  3756. this.y = q.y / s;
  3757. this.z = q.z / s;
  3758. }
  3759. return this;
  3760. },
  3761. setAxisAngleFromRotationMatrix: function (m) {
  3762. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  3763. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3764. var angle,
  3765. x,
  3766. y,
  3767. z,
  3768. // variables for result
  3769. epsilon = 0.01,
  3770. // margin to allow for rounding errors
  3771. epsilon2 = 0.1,
  3772. // margin to distinguish between 0 and 180 degrees
  3773. te = m.elements,
  3774. m11 = te[0],
  3775. m12 = te[4],
  3776. m13 = te[8],
  3777. m21 = te[1],
  3778. m22 = te[5],
  3779. m23 = te[9],
  3780. m31 = te[2],
  3781. m32 = te[6],
  3782. m33 = te[10];
  3783. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  3784. // singularity found
  3785. // first check for identity matrix which must have +1 for all terms
  3786. // in leading diagonal and zero in other terms
  3787. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  3788. // this singularity is identity matrix so angle = 0
  3789. this.set(1, 0, 0, 0);
  3790. return this; // zero angle, arbitrary axis
  3791. } // otherwise this singularity is angle = 180
  3792. angle = Math.PI;
  3793. var xx = (m11 + 1) / 2;
  3794. var yy = (m22 + 1) / 2;
  3795. var zz = (m33 + 1) / 2;
  3796. var xy = (m12 + m21) / 4;
  3797. var xz = (m13 + m31) / 4;
  3798. var yz = (m23 + m32) / 4;
  3799. if (xx > yy && xx > zz) {
  3800. // m11 is the largest diagonal term
  3801. if (xx < epsilon) {
  3802. x = 0;
  3803. y = 0.707106781;
  3804. z = 0.707106781;
  3805. } else {
  3806. x = Math.sqrt(xx);
  3807. y = xy / x;
  3808. z = xz / x;
  3809. }
  3810. } else if (yy > zz) {
  3811. // m22 is the largest diagonal term
  3812. if (yy < epsilon) {
  3813. x = 0.707106781;
  3814. y = 0;
  3815. z = 0.707106781;
  3816. } else {
  3817. y = Math.sqrt(yy);
  3818. x = xy / y;
  3819. z = yz / y;
  3820. }
  3821. } else {
  3822. // m33 is the largest diagonal term so base result on this
  3823. if (zz < epsilon) {
  3824. x = 0.707106781;
  3825. y = 0.707106781;
  3826. z = 0;
  3827. } else {
  3828. z = Math.sqrt(zz);
  3829. x = xz / z;
  3830. y = yz / z;
  3831. }
  3832. }
  3833. this.set(x, y, z, angle);
  3834. return this; // return 180 deg rotation
  3835. } // as we have reached here there are no singularities so we can handle normally
  3836. var s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  3837. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  3838. // caught by singularity test above, but I've left it in just in case
  3839. this.x = (m32 - m23) / s;
  3840. this.y = (m13 - m31) / s;
  3841. this.z = (m21 - m12) / s;
  3842. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  3843. return this;
  3844. },
  3845. min: function (v) {
  3846. this.x = Math.min(this.x, v.x);
  3847. this.y = Math.min(this.y, v.y);
  3848. this.z = Math.min(this.z, v.z);
  3849. this.w = Math.min(this.w, v.w);
  3850. return this;
  3851. },
  3852. max: function (v) {
  3853. this.x = Math.max(this.x, v.x);
  3854. this.y = Math.max(this.y, v.y);
  3855. this.z = Math.max(this.z, v.z);
  3856. this.w = Math.max(this.w, v.w);
  3857. return this;
  3858. },
  3859. clamp: function (min, max) {
  3860. // assumes min < max, componentwise
  3861. this.x = Math.max(min.x, Math.min(max.x, this.x));
  3862. this.y = Math.max(min.y, Math.min(max.y, this.y));
  3863. this.z = Math.max(min.z, Math.min(max.z, this.z));
  3864. this.w = Math.max(min.w, Math.min(max.w, this.w));
  3865. return this;
  3866. },
  3867. clampScalar: function (minVal, maxVal) {
  3868. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  3869. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  3870. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  3871. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  3872. return this;
  3873. },
  3874. clampLength: function (min, max) {
  3875. var length = this.length();
  3876. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  3877. },
  3878. floor: function () {
  3879. this.x = Math.floor(this.x);
  3880. this.y = Math.floor(this.y);
  3881. this.z = Math.floor(this.z);
  3882. this.w = Math.floor(this.w);
  3883. return this;
  3884. },
  3885. ceil: function () {
  3886. this.x = Math.ceil(this.x);
  3887. this.y = Math.ceil(this.y);
  3888. this.z = Math.ceil(this.z);
  3889. this.w = Math.ceil(this.w);
  3890. return this;
  3891. },
  3892. round: function () {
  3893. this.x = Math.round(this.x);
  3894. this.y = Math.round(this.y);
  3895. this.z = Math.round(this.z);
  3896. this.w = Math.round(this.w);
  3897. return this;
  3898. },
  3899. roundToZero: function () {
  3900. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  3901. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  3902. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  3903. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  3904. return this;
  3905. },
  3906. negate: function () {
  3907. this.x = -this.x;
  3908. this.y = -this.y;
  3909. this.z = -this.z;
  3910. this.w = -this.w;
  3911. return this;
  3912. },
  3913. dot: function (v) {
  3914. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  3915. },
  3916. lengthSq: function () {
  3917. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  3918. },
  3919. length: function () {
  3920. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3921. },
  3922. manhattanLength: function () {
  3923. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  3924. },
  3925. normalize: function () {
  3926. return this.divideScalar(this.length() || 1);
  3927. },
  3928. setLength: function (length) {
  3929. return this.normalize().multiplyScalar(length);
  3930. },
  3931. lerp: function (v, alpha) {
  3932. this.x += (v.x - this.x) * alpha;
  3933. this.y += (v.y - this.y) * alpha;
  3934. this.z += (v.z - this.z) * alpha;
  3935. this.w += (v.w - this.w) * alpha;
  3936. return this;
  3937. },
  3938. lerpVectors: function (v1, v2, alpha) {
  3939. return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
  3940. },
  3941. equals: function (v) {
  3942. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  3943. },
  3944. fromArray: function (array, offset) {
  3945. if (offset === undefined) offset = 0;
  3946. this.x = array[offset];
  3947. this.y = array[offset + 1];
  3948. this.z = array[offset + 2];
  3949. this.w = array[offset + 3];
  3950. return this;
  3951. },
  3952. toArray: function (array, offset) {
  3953. if (array === undefined) array = [];
  3954. if (offset === undefined) offset = 0;
  3955. array[offset] = this.x;
  3956. array[offset + 1] = this.y;
  3957. array[offset + 2] = this.z;
  3958. array[offset + 3] = this.w;
  3959. return array;
  3960. },
  3961. fromBufferAttribute: function (attribute, index, offset) {
  3962. if (offset !== undefined) {
  3963. console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');
  3964. }
  3965. this.x = attribute.getX(index);
  3966. this.y = attribute.getY(index);
  3967. this.z = attribute.getZ(index);
  3968. this.w = attribute.getW(index);
  3969. return this;
  3970. }
  3971. });
  3972. /**
  3973. * @author szimek / https://github.com/szimek/
  3974. * @author alteredq / http://alteredqualia.com/
  3975. * @author Marius Kintel / https://github.com/kintel
  3976. */
  3977. /*
  3978. In options, we can specify:
  3979. * Texture parameters for an auto-generated target texture
  3980. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  3981. */
  3982. function WebGLRenderTarget(width, height, options) {
  3983. this.width = width;
  3984. this.height = height;
  3985. this.scissor = new Vector4(0, 0, width, height);
  3986. this.scissorTest = false;
  3987. this.viewport = new Vector4(0, 0, width, height);
  3988. options = options || {};
  3989. this.texture = new Texture(undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  3990. this.texture.image = {};
  3991. this.texture.image.width = width;
  3992. this.texture.image.height = height;
  3993. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  3994. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  3995. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  3996. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  3997. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  3998. }
  3999. WebGLRenderTarget.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  4000. constructor: WebGLRenderTarget,
  4001. isWebGLRenderTarget: true,
  4002. setSize: function (width, height) {
  4003. if (this.width !== width || this.height !== height) {
  4004. this.width = width;
  4005. this.height = height;
  4006. this.texture.image.width = width;
  4007. this.texture.image.height = height;
  4008. this.dispose();
  4009. }
  4010. this.viewport.set(0, 0, width, height);
  4011. this.scissor.set(0, 0, width, height);
  4012. },
  4013. clone: function () {
  4014. return new this.constructor().copy(this);
  4015. },
  4016. copy: function (source) {
  4017. this.width = source.width;
  4018. this.height = source.height;
  4019. this.viewport.copy(source.viewport);
  4020. this.texture = source.texture.clone();
  4021. this.depthBuffer = source.depthBuffer;
  4022. this.stencilBuffer = source.stencilBuffer;
  4023. this.depthTexture = source.depthTexture;
  4024. return this;
  4025. },
  4026. dispose: function () {
  4027. this.dispatchEvent({
  4028. type: 'dispose'
  4029. });
  4030. }
  4031. });
  4032. /**
  4033. * @author Mugen87 / https://github.com/Mugen87
  4034. * @author Matt DesLauriers / @mattdesl
  4035. */
  4036. function WebGLMultisampleRenderTarget(width, height, options) {
  4037. WebGLRenderTarget.call(this, width, height, options);
  4038. this.samples = 4;
  4039. }
  4040. WebGLMultisampleRenderTarget.prototype = Object.assign(Object.create(WebGLRenderTarget.prototype), {
  4041. constructor: WebGLMultisampleRenderTarget,
  4042. isWebGLMultisampleRenderTarget: true,
  4043. copy: function (source) {
  4044. WebGLRenderTarget.prototype.copy.call(this, source);
  4045. this.samples = source.samples;
  4046. return this;
  4047. }
  4048. });
  4049. var _v1 = new Vector3();
  4050. var _m1 = new Matrix4();
  4051. var _zero = new Vector3(0, 0, 0);
  4052. var _one = new Vector3(1, 1, 1);
  4053. var _x = new Vector3();
  4054. var _y = new Vector3();
  4055. var _z = new Vector3();
  4056. /**
  4057. * @author mrdoob / http://mrdoob.com/
  4058. * @author supereggbert / http://www.paulbrunt.co.uk/
  4059. * @author philogb / http://blog.thejit.org/
  4060. * @author jordi_ros / http://plattsoft.com
  4061. * @author D1plo1d / http://github.com/D1plo1d
  4062. * @author alteredq / http://alteredqualia.com/
  4063. * @author mikael emtinger / http://gomo.se/
  4064. * @author timknip / http://www.floorplanner.com/
  4065. * @author bhouston / http://clara.io
  4066. * @author WestLangley / http://github.com/WestLangley
  4067. */
  4068. function Matrix4() {
  4069. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  4070. if (arguments.length > 0) {
  4071. console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
  4072. }
  4073. }
  4074. Object.assign(Matrix4.prototype, {
  4075. isMatrix4: true,
  4076. set: function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  4077. var te = this.elements;
  4078. te[0] = n11;
  4079. te[4] = n12;
  4080. te[8] = n13;
  4081. te[12] = n14;
  4082. te[1] = n21;
  4083. te[5] = n22;
  4084. te[9] = n23;
  4085. te[13] = n24;
  4086. te[2] = n31;
  4087. te[6] = n32;
  4088. te[10] = n33;
  4089. te[14] = n34;
  4090. te[3] = n41;
  4091. te[7] = n42;
  4092. te[11] = n43;
  4093. te[15] = n44;
  4094. return this;
  4095. },
  4096. identity: function () {
  4097. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  4098. return this;
  4099. },
  4100. clone: function () {
  4101. return new Matrix4().fromArray(this.elements);
  4102. },
  4103. copy: function (m) {
  4104. var te = this.elements;
  4105. var me = m.elements;
  4106. te[0] = me[0];
  4107. te[1] = me[1];
  4108. te[2] = me[2];
  4109. te[3] = me[3];
  4110. te[4] = me[4];
  4111. te[5] = me[5];
  4112. te[6] = me[6];
  4113. te[7] = me[7];
  4114. te[8] = me[8];
  4115. te[9] = me[9];
  4116. te[10] = me[10];
  4117. te[11] = me[11];
  4118. te[12] = me[12];
  4119. te[13] = me[13];
  4120. te[14] = me[14];
  4121. te[15] = me[15];
  4122. return this;
  4123. },
  4124. copyPosition: function (m) {
  4125. var te = this.elements,
  4126. me = m.elements;
  4127. te[12] = me[12];
  4128. te[13] = me[13];
  4129. te[14] = me[14];
  4130. return this;
  4131. },
  4132. extractBasis: function (xAxis, yAxis, zAxis) {
  4133. xAxis.setFromMatrixColumn(this, 0);
  4134. yAxis.setFromMatrixColumn(this, 1);
  4135. zAxis.setFromMatrixColumn(this, 2);
  4136. return this;
  4137. },
  4138. makeBasis: function (xAxis, yAxis, zAxis) {
  4139. 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);
  4140. return this;
  4141. },
  4142. extractRotation: function (m) {
  4143. // this method does not support reflection matrices
  4144. var te = this.elements;
  4145. var me = m.elements;
  4146. var scaleX = 1 / _v1.setFromMatrixColumn(m, 0).length();
  4147. var scaleY = 1 / _v1.setFromMatrixColumn(m, 1).length();
  4148. var scaleZ = 1 / _v1.setFromMatrixColumn(m, 2).length();
  4149. te[0] = me[0] * scaleX;
  4150. te[1] = me[1] * scaleX;
  4151. te[2] = me[2] * scaleX;
  4152. te[3] = 0;
  4153. te[4] = me[4] * scaleY;
  4154. te[5] = me[5] * scaleY;
  4155. te[6] = me[6] * scaleY;
  4156. te[7] = 0;
  4157. te[8] = me[8] * scaleZ;
  4158. te[9] = me[9] * scaleZ;
  4159. te[10] = me[10] * scaleZ;
  4160. te[11] = 0;
  4161. te[12] = 0;
  4162. te[13] = 0;
  4163. te[14] = 0;
  4164. te[15] = 1;
  4165. return this;
  4166. },
  4167. makeRotationFromEuler: function (euler) {
  4168. if (!(euler && euler.isEuler)) {
  4169. console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
  4170. }
  4171. var te = this.elements;
  4172. var x = euler.x,
  4173. y = euler.y,
  4174. z = euler.z;
  4175. var a = Math.cos(x),
  4176. b = Math.sin(x);
  4177. var c = Math.cos(y),
  4178. d = Math.sin(y);
  4179. var e = Math.cos(z),
  4180. f = Math.sin(z);
  4181. if (euler.order === 'XYZ') {
  4182. var ae = a * e,
  4183. af = a * f,
  4184. be = b * e,
  4185. bf = b * f;
  4186. te[0] = c * e;
  4187. te[4] = -c * f;
  4188. te[8] = d;
  4189. te[1] = af + be * d;
  4190. te[5] = ae - bf * d;
  4191. te[9] = -b * c;
  4192. te[2] = bf - ae * d;
  4193. te[6] = be + af * d;
  4194. te[10] = a * c;
  4195. } else if (euler.order === 'YXZ') {
  4196. var ce = c * e,
  4197. cf = c * f,
  4198. de = d * e,
  4199. df = d * f;
  4200. te[0] = ce + df * b;
  4201. te[4] = de * b - cf;
  4202. te[8] = a * d;
  4203. te[1] = a * f;
  4204. te[5] = a * e;
  4205. te[9] = -b;
  4206. te[2] = cf * b - de;
  4207. te[6] = df + ce * b;
  4208. te[10] = a * c;
  4209. } else if (euler.order === 'ZXY') {
  4210. var ce = c * e,
  4211. cf = c * f,
  4212. de = d * e,
  4213. df = d * f;
  4214. te[0] = ce - df * b;
  4215. te[4] = -a * f;
  4216. te[8] = de + cf * b;
  4217. te[1] = cf + de * b;
  4218. te[5] = a * e;
  4219. te[9] = df - ce * b;
  4220. te[2] = -a * d;
  4221. te[6] = b;
  4222. te[10] = a * c;
  4223. } else if (euler.order === 'ZYX') {
  4224. var ae = a * e,
  4225. af = a * f,
  4226. be = b * e,
  4227. bf = b * f;
  4228. te[0] = c * e;
  4229. te[4] = be * d - af;
  4230. te[8] = ae * d + bf;
  4231. te[1] = c * f;
  4232. te[5] = bf * d + ae;
  4233. te[9] = af * d - be;
  4234. te[2] = -d;
  4235. te[6] = b * c;
  4236. te[10] = a * c;
  4237. } else if (euler.order === 'YZX') {
  4238. var ac = a * c,
  4239. ad = a * d,
  4240. bc = b * c,
  4241. bd = b * d;
  4242. te[0] = c * e;
  4243. te[4] = bd - ac * f;
  4244. te[8] = bc * f + ad;
  4245. te[1] = f;
  4246. te[5] = a * e;
  4247. te[9] = -b * e;
  4248. te[2] = -d * e;
  4249. te[6] = ad * f + bc;
  4250. te[10] = ac - bd * f;
  4251. } else if (euler.order === 'XZY') {
  4252. var ac = a * c,
  4253. ad = a * d,
  4254. bc = b * c,
  4255. bd = b * d;
  4256. te[0] = c * e;
  4257. te[4] = -f;
  4258. te[8] = d * e;
  4259. te[1] = ac * f + bd;
  4260. te[5] = a * e;
  4261. te[9] = ad * f - bc;
  4262. te[2] = bc * f - ad;
  4263. te[6] = b * e;
  4264. te[10] = bd * f + ac;
  4265. } // bottom row
  4266. te[3] = 0;
  4267. te[7] = 0;
  4268. te[11] = 0; // last column
  4269. te[12] = 0;
  4270. te[13] = 0;
  4271. te[14] = 0;
  4272. te[15] = 1;
  4273. return this;
  4274. },
  4275. makeRotationFromQuaternion: function (q) {
  4276. return this.compose(_zero, q, _one);
  4277. },
  4278. lookAt: function (eye, target, up) {
  4279. var te = this.elements;
  4280. _z.subVectors(eye, target);
  4281. if (_z.lengthSq() === 0) {
  4282. // eye and target are in the same position
  4283. _z.z = 1;
  4284. }
  4285. _z.normalize();
  4286. _x.crossVectors(up, _z);
  4287. if (_x.lengthSq() === 0) {
  4288. // up and z are parallel
  4289. if (Math.abs(up.z) === 1) {
  4290. _z.x += 0.0001;
  4291. } else {
  4292. _z.z += 0.0001;
  4293. }
  4294. _z.normalize();
  4295. _x.crossVectors(up, _z);
  4296. }
  4297. _x.normalize();
  4298. _y.crossVectors(_z, _x);
  4299. te[0] = _x.x;
  4300. te[4] = _y.x;
  4301. te[8] = _z.x;
  4302. te[1] = _x.y;
  4303. te[5] = _y.y;
  4304. te[9] = _z.y;
  4305. te[2] = _x.z;
  4306. te[6] = _y.z;
  4307. te[10] = _z.z;
  4308. return this;
  4309. },
  4310. multiply: function (m, n) {
  4311. if (n !== undefined) {
  4312. console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
  4313. return this.multiplyMatrices(m, n);
  4314. }
  4315. return this.multiplyMatrices(this, m);
  4316. },
  4317. premultiply: function (m) {
  4318. return this.multiplyMatrices(m, this);
  4319. },
  4320. multiplyMatrices: function (a, b) {
  4321. var ae = a.elements;
  4322. var be = b.elements;
  4323. var te = this.elements;
  4324. var a11 = ae[0],
  4325. a12 = ae[4],
  4326. a13 = ae[8],
  4327. a14 = ae[12];
  4328. var a21 = ae[1],
  4329. a22 = ae[5],
  4330. a23 = ae[9],
  4331. a24 = ae[13];
  4332. var a31 = ae[2],
  4333. a32 = ae[6],
  4334. a33 = ae[10],
  4335. a34 = ae[14];
  4336. var a41 = ae[3],
  4337. a42 = ae[7],
  4338. a43 = ae[11],
  4339. a44 = ae[15];
  4340. var b11 = be[0],
  4341. b12 = be[4],
  4342. b13 = be[8],
  4343. b14 = be[12];
  4344. var b21 = be[1],
  4345. b22 = be[5],
  4346. b23 = be[9],
  4347. b24 = be[13];
  4348. var b31 = be[2],
  4349. b32 = be[6],
  4350. b33 = be[10],
  4351. b34 = be[14];
  4352. var b41 = be[3],
  4353. b42 = be[7],
  4354. b43 = be[11],
  4355. b44 = be[15];
  4356. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  4357. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  4358. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  4359. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  4360. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  4361. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  4362. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  4363. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  4364. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  4365. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  4366. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  4367. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  4368. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  4369. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  4370. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  4371. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  4372. return this;
  4373. },
  4374. multiplyScalar: function (s) {
  4375. var te = this.elements;
  4376. te[0] *= s;
  4377. te[4] *= s;
  4378. te[8] *= s;
  4379. te[12] *= s;
  4380. te[1] *= s;
  4381. te[5] *= s;
  4382. te[9] *= s;
  4383. te[13] *= s;
  4384. te[2] *= s;
  4385. te[6] *= s;
  4386. te[10] *= s;
  4387. te[14] *= s;
  4388. te[3] *= s;
  4389. te[7] *= s;
  4390. te[11] *= s;
  4391. te[15] *= s;
  4392. return this;
  4393. },
  4394. applyToBufferAttribute: function (attribute) {
  4395. for (var i = 0, l = attribute.count; i < l; i++) {
  4396. _v1.x = attribute.getX(i);
  4397. _v1.y = attribute.getY(i);
  4398. _v1.z = attribute.getZ(i);
  4399. _v1.applyMatrix4(this);
  4400. attribute.setXYZ(i, _v1.x, _v1.y, _v1.z);
  4401. }
  4402. return attribute;
  4403. },
  4404. determinant: function () {
  4405. var te = this.elements;
  4406. var n11 = te[0],
  4407. n12 = te[4],
  4408. n13 = te[8],
  4409. n14 = te[12];
  4410. var n21 = te[1],
  4411. n22 = te[5],
  4412. n23 = te[9],
  4413. n24 = te[13];
  4414. var n31 = te[2],
  4415. n32 = te[6],
  4416. n33 = te[10],
  4417. n34 = te[14];
  4418. var n41 = te[3],
  4419. n42 = te[7],
  4420. n43 = te[11],
  4421. n44 = te[15]; //TODO: make this more efficient
  4422. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  4423. 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);
  4424. },
  4425. transpose: function () {
  4426. var te = this.elements;
  4427. var tmp;
  4428. tmp = te[1];
  4429. te[1] = te[4];
  4430. te[4] = tmp;
  4431. tmp = te[2];
  4432. te[2] = te[8];
  4433. te[8] = tmp;
  4434. tmp = te[6];
  4435. te[6] = te[9];
  4436. te[9] = tmp;
  4437. tmp = te[3];
  4438. te[3] = te[12];
  4439. te[12] = tmp;
  4440. tmp = te[7];
  4441. te[7] = te[13];
  4442. te[13] = tmp;
  4443. tmp = te[11];
  4444. te[11] = te[14];
  4445. te[14] = tmp;
  4446. return this;
  4447. },
  4448. setPosition: function (x, y, z) {
  4449. var te = this.elements;
  4450. if (x.isVector3) {
  4451. te[12] = x.x;
  4452. te[13] = x.y;
  4453. te[14] = x.z;
  4454. } else {
  4455. te[12] = x;
  4456. te[13] = y;
  4457. te[14] = z;
  4458. }
  4459. return this;
  4460. },
  4461. getInverse: function (m, throwOnDegenerate) {
  4462. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  4463. var te = this.elements,
  4464. me = m.elements,
  4465. n11 = me[0],
  4466. n21 = me[1],
  4467. n31 = me[2],
  4468. n41 = me[3],
  4469. n12 = me[4],
  4470. n22 = me[5],
  4471. n32 = me[6],
  4472. n42 = me[7],
  4473. n13 = me[8],
  4474. n23 = me[9],
  4475. n33 = me[10],
  4476. n43 = me[11],
  4477. n14 = me[12],
  4478. n24 = me[13],
  4479. n34 = me[14],
  4480. n44 = me[15],
  4481. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  4482. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  4483. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  4484. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  4485. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  4486. if (det === 0) {
  4487. var msg = "THREE.Matrix4: .getInverse() can't invert matrix, determinant is 0";
  4488. if (throwOnDegenerate === true) {
  4489. throw new Error(msg);
  4490. } else {
  4491. console.warn(msg);
  4492. }
  4493. return this.identity();
  4494. }
  4495. var detInv = 1 / det;
  4496. te[0] = t11 * detInv;
  4497. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  4498. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  4499. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  4500. te[4] = t12 * detInv;
  4501. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  4502. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  4503. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  4504. te[8] = t13 * detInv;
  4505. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  4506. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  4507. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  4508. te[12] = t14 * detInv;
  4509. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  4510. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  4511. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  4512. return this;
  4513. },
  4514. scale: function (v) {
  4515. var te = this.elements;
  4516. var x = v.x,
  4517. y = v.y,
  4518. z = v.z;
  4519. te[0] *= x;
  4520. te[4] *= y;
  4521. te[8] *= z;
  4522. te[1] *= x;
  4523. te[5] *= y;
  4524. te[9] *= z;
  4525. te[2] *= x;
  4526. te[6] *= y;
  4527. te[10] *= z;
  4528. te[3] *= x;
  4529. te[7] *= y;
  4530. te[11] *= z;
  4531. return this;
  4532. },
  4533. getMaxScaleOnAxis: function () {
  4534. var te = this.elements;
  4535. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  4536. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  4537. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  4538. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  4539. },
  4540. makeTranslation: function (x, y, z) {
  4541. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  4542. return this;
  4543. },
  4544. makeRotationX: function (theta) {
  4545. var c = Math.cos(theta),
  4546. s = Math.sin(theta);
  4547. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  4548. return this;
  4549. },
  4550. makeRotationY: function (theta) {
  4551. var c = Math.cos(theta),
  4552. s = Math.sin(theta);
  4553. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  4554. return this;
  4555. },
  4556. makeRotationZ: function (theta) {
  4557. var c = Math.cos(theta),
  4558. s = Math.sin(theta);
  4559. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  4560. return this;
  4561. },
  4562. makeRotationAxis: function (axis, angle) {
  4563. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4564. var c = Math.cos(angle);
  4565. var s = Math.sin(angle);
  4566. var t = 1 - c;
  4567. var x = axis.x,
  4568. y = axis.y,
  4569. z = axis.z;
  4570. var tx = t * x,
  4571. ty = t * y;
  4572. 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);
  4573. return this;
  4574. },
  4575. makeScale: function (x, y, z) {
  4576. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  4577. return this;
  4578. },
  4579. makeShear: function (x, y, z) {
  4580. this.set(1, y, z, 0, x, 1, z, 0, x, y, 1, 0, 0, 0, 0, 1);
  4581. return this;
  4582. },
  4583. compose: function (position, quaternion, scale) {
  4584. var te = this.elements;
  4585. var x = quaternion._x,
  4586. y = quaternion._y,
  4587. z = quaternion._z,
  4588. w = quaternion._w;
  4589. var x2 = x + x,
  4590. y2 = y + y,
  4591. z2 = z + z;
  4592. var xx = x * x2,
  4593. xy = x * y2,
  4594. xz = x * z2;
  4595. var yy = y * y2,
  4596. yz = y * z2,
  4597. zz = z * z2;
  4598. var wx = w * x2,
  4599. wy = w * y2,
  4600. wz = w * z2;
  4601. var sx = scale.x,
  4602. sy = scale.y,
  4603. sz = scale.z;
  4604. te[0] = (1 - (yy + zz)) * sx;
  4605. te[1] = (xy + wz) * sx;
  4606. te[2] = (xz - wy) * sx;
  4607. te[3] = 0;
  4608. te[4] = (xy - wz) * sy;
  4609. te[5] = (1 - (xx + zz)) * sy;
  4610. te[6] = (yz + wx) * sy;
  4611. te[7] = 0;
  4612. te[8] = (xz + wy) * sz;
  4613. te[9] = (yz - wx) * sz;
  4614. te[10] = (1 - (xx + yy)) * sz;
  4615. te[11] = 0;
  4616. te[12] = position.x;
  4617. te[13] = position.y;
  4618. te[14] = position.z;
  4619. te[15] = 1;
  4620. return this;
  4621. },
  4622. decompose: function (position, quaternion, scale) {
  4623. var te = this.elements;
  4624. var sx = _v1.set(te[0], te[1], te[2]).length();
  4625. var sy = _v1.set(te[4], te[5], te[6]).length();
  4626. var sz = _v1.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  4627. var det = this.determinant();
  4628. if (det < 0) sx = -sx;
  4629. position.x = te[12];
  4630. position.y = te[13];
  4631. position.z = te[14]; // scale the rotation part
  4632. _m1.copy(this);
  4633. var invSX = 1 / sx;
  4634. var invSY = 1 / sy;
  4635. var invSZ = 1 / sz;
  4636. _m1.elements[0] *= invSX;
  4637. _m1.elements[1] *= invSX;
  4638. _m1.elements[2] *= invSX;
  4639. _m1.elements[4] *= invSY;
  4640. _m1.elements[5] *= invSY;
  4641. _m1.elements[6] *= invSY;
  4642. _m1.elements[8] *= invSZ;
  4643. _m1.elements[9] *= invSZ;
  4644. _m1.elements[10] *= invSZ;
  4645. quaternion.setFromRotationMatrix(_m1);
  4646. scale.x = sx;
  4647. scale.y = sy;
  4648. scale.z = sz;
  4649. return this;
  4650. },
  4651. makePerspective: function (left, right, top, bottom, near, far) {
  4652. if (far === undefined) {
  4653. console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
  4654. }
  4655. var te = this.elements;
  4656. var x = 2 * near / (right - left);
  4657. var y = 2 * near / (top - bottom);
  4658. var a = (right + left) / (right - left);
  4659. var b = (top + bottom) / (top - bottom);
  4660. var c = -(far + near) / (far - near);
  4661. var d = -2 * far * near / (far - near);
  4662. te[0] = x;
  4663. te[4] = 0;
  4664. te[8] = a;
  4665. te[12] = 0;
  4666. te[1] = 0;
  4667. te[5] = y;
  4668. te[9] = b;
  4669. te[13] = 0;
  4670. te[2] = 0;
  4671. te[6] = 0;
  4672. te[10] = c;
  4673. te[14] = d;
  4674. te[3] = 0;
  4675. te[7] = 0;
  4676. te[11] = -1;
  4677. te[15] = 0;
  4678. return this;
  4679. },
  4680. makeOrthographic: function (left, right, top, bottom, near, far) {
  4681. var te = this.elements;
  4682. var w = 1.0 / (right - left);
  4683. var h = 1.0 / (top - bottom);
  4684. var p = 1.0 / (far - near);
  4685. var x = (right + left) * w;
  4686. var y = (top + bottom) * h;
  4687. var z = (far + near) * p;
  4688. te[0] = 2 * w;
  4689. te[4] = 0;
  4690. te[8] = 0;
  4691. te[12] = -x;
  4692. te[1] = 0;
  4693. te[5] = 2 * h;
  4694. te[9] = 0;
  4695. te[13] = -y;
  4696. te[2] = 0;
  4697. te[6] = 0;
  4698. te[10] = -2 * p;
  4699. te[14] = -z;
  4700. te[3] = 0;
  4701. te[7] = 0;
  4702. te[11] = 0;
  4703. te[15] = 1;
  4704. return this;
  4705. },
  4706. equals: function (matrix) {
  4707. var te = this.elements;
  4708. var me = matrix.elements;
  4709. for (var i = 0; i < 16; i++) {
  4710. if (te[i] !== me[i]) return false;
  4711. }
  4712. return true;
  4713. },
  4714. fromArray: function (array, offset) {
  4715. if (offset === undefined) offset = 0;
  4716. for (var i = 0; i < 16; i++) {
  4717. this.elements[i] = array[i + offset];
  4718. }
  4719. return this;
  4720. },
  4721. toArray: function (array, offset) {
  4722. if (array === undefined) array = [];
  4723. if (offset === undefined) offset = 0;
  4724. var te = this.elements;
  4725. array[offset] = te[0];
  4726. array[offset + 1] = te[1];
  4727. array[offset + 2] = te[2];
  4728. array[offset + 3] = te[3];
  4729. array[offset + 4] = te[4];
  4730. array[offset + 5] = te[5];
  4731. array[offset + 6] = te[6];
  4732. array[offset + 7] = te[7];
  4733. array[offset + 8] = te[8];
  4734. array[offset + 9] = te[9];
  4735. array[offset + 10] = te[10];
  4736. array[offset + 11] = te[11];
  4737. array[offset + 12] = te[12];
  4738. array[offset + 13] = te[13];
  4739. array[offset + 14] = te[14];
  4740. array[offset + 15] = te[15];
  4741. return array;
  4742. }
  4743. });
  4744. /**
  4745. * @author mrdoob / http://mrdoob.com/
  4746. * @author WestLangley / http://github.com/WestLangley
  4747. * @author bhouston / http://clara.io
  4748. */
  4749. var _matrix = new Matrix4();
  4750. var _quaternion$1 = new Quaternion();
  4751. function Euler(x, y, z, order) {
  4752. this._x = x || 0;
  4753. this._y = y || 0;
  4754. this._z = z || 0;
  4755. this._order = order || Euler.DefaultOrder;
  4756. }
  4757. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  4758. Euler.DefaultOrder = 'XYZ';
  4759. Object.defineProperties(Euler.prototype, {
  4760. x: {
  4761. get: function () {
  4762. return this._x;
  4763. },
  4764. set: function (value) {
  4765. this._x = value;
  4766. this._onChangeCallback();
  4767. }
  4768. },
  4769. y: {
  4770. get: function () {
  4771. return this._y;
  4772. },
  4773. set: function (value) {
  4774. this._y = value;
  4775. this._onChangeCallback();
  4776. }
  4777. },
  4778. z: {
  4779. get: function () {
  4780. return this._z;
  4781. },
  4782. set: function (value) {
  4783. this._z = value;
  4784. this._onChangeCallback();
  4785. }
  4786. },
  4787. order: {
  4788. get: function () {
  4789. return this._order;
  4790. },
  4791. set: function (value) {
  4792. this._order = value;
  4793. this._onChangeCallback();
  4794. }
  4795. }
  4796. });
  4797. Object.assign(Euler.prototype, {
  4798. isEuler: true,
  4799. set: function (x, y, z, order) {
  4800. this._x = x;
  4801. this._y = y;
  4802. this._z = z;
  4803. this._order = order || this._order;
  4804. this._onChangeCallback();
  4805. return this;
  4806. },
  4807. clone: function () {
  4808. return new this.constructor(this._x, this._y, this._z, this._order);
  4809. },
  4810. copy: function (euler) {
  4811. this._x = euler._x;
  4812. this._y = euler._y;
  4813. this._z = euler._z;
  4814. this._order = euler._order;
  4815. this._onChangeCallback();
  4816. return this;
  4817. },
  4818. setFromRotationMatrix: function (m, order, update) {
  4819. var clamp = _Math.clamp; // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4820. var te = m.elements;
  4821. var m11 = te[0],
  4822. m12 = te[4],
  4823. m13 = te[8];
  4824. var m21 = te[1],
  4825. m22 = te[5],
  4826. m23 = te[9];
  4827. var m31 = te[2],
  4828. m32 = te[6],
  4829. m33 = te[10];
  4830. order = order || this._order;
  4831. if (order === 'XYZ') {
  4832. this._y = Math.asin(clamp(m13, -1, 1));
  4833. if (Math.abs(m13) < 0.9999999) {
  4834. this._x = Math.atan2(-m23, m33);
  4835. this._z = Math.atan2(-m12, m11);
  4836. } else {
  4837. this._x = Math.atan2(m32, m22);
  4838. this._z = 0;
  4839. }
  4840. } else if (order === 'YXZ') {
  4841. this._x = Math.asin(-clamp(m23, -1, 1));
  4842. if (Math.abs(m23) < 0.9999999) {
  4843. this._y = Math.atan2(m13, m33);
  4844. this._z = Math.atan2(m21, m22);
  4845. } else {
  4846. this._y = Math.atan2(-m31, m11);
  4847. this._z = 0;
  4848. }
  4849. } else if (order === 'ZXY') {
  4850. this._x = Math.asin(clamp(m32, -1, 1));
  4851. if (Math.abs(m32) < 0.9999999) {
  4852. this._y = Math.atan2(-m31, m33);
  4853. this._z = Math.atan2(-m12, m22);
  4854. } else {
  4855. this._y = 0;
  4856. this._z = Math.atan2(m21, m11);
  4857. }
  4858. } else if (order === 'ZYX') {
  4859. this._y = Math.asin(-clamp(m31, -1, 1));
  4860. if (Math.abs(m31) < 0.9999999) {
  4861. this._x = Math.atan2(m32, m33);
  4862. this._z = Math.atan2(m21, m11);
  4863. } else {
  4864. this._x = 0;
  4865. this._z = Math.atan2(-m12, m22);
  4866. }
  4867. } else if (order === 'YZX') {
  4868. this._z = Math.asin(clamp(m21, -1, 1));
  4869. if (Math.abs(m21) < 0.9999999) {
  4870. this._x = Math.atan2(-m23, m22);
  4871. this._y = Math.atan2(-m31, m11);
  4872. } else {
  4873. this._x = 0;
  4874. this._y = Math.atan2(m13, m33);
  4875. }
  4876. } else if (order === 'XZY') {
  4877. this._z = Math.asin(-clamp(m12, -1, 1));
  4878. if (Math.abs(m12) < 0.9999999) {
  4879. this._x = Math.atan2(m32, m22);
  4880. this._y = Math.atan2(m13, m11);
  4881. } else {
  4882. this._x = Math.atan2(-m23, m33);
  4883. this._y = 0;
  4884. }
  4885. } else {
  4886. console.warn('THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order);
  4887. }
  4888. this._order = order;
  4889. if (update !== false) this._onChangeCallback();
  4890. return this;
  4891. },
  4892. setFromQuaternion: function (q, order, update) {
  4893. _matrix.makeRotationFromQuaternion(q);
  4894. return this.setFromRotationMatrix(_matrix, order, update);
  4895. },
  4896. setFromVector3: function (v, order) {
  4897. return this.set(v.x, v.y, v.z, order || this._order);
  4898. },
  4899. reorder: function (newOrder) {
  4900. // WARNING: this discards revolution information -bhouston
  4901. _quaternion$1.setFromEuler(this);
  4902. return this.setFromQuaternion(_quaternion$1, newOrder);
  4903. },
  4904. equals: function (euler) {
  4905. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  4906. },
  4907. fromArray: function (array) {
  4908. this._x = array[0];
  4909. this._y = array[1];
  4910. this._z = array[2];
  4911. if (array[3] !== undefined) this._order = array[3];
  4912. this._onChangeCallback();
  4913. return this;
  4914. },
  4915. toArray: function (array, offset) {
  4916. if (array === undefined) array = [];
  4917. if (offset === undefined) offset = 0;
  4918. array[offset] = this._x;
  4919. array[offset + 1] = this._y;
  4920. array[offset + 2] = this._z;
  4921. array[offset + 3] = this._order;
  4922. return array;
  4923. },
  4924. toVector3: function (optionalResult) {
  4925. if (optionalResult) {
  4926. return optionalResult.set(this._x, this._y, this._z);
  4927. } else {
  4928. return new Vector3(this._x, this._y, this._z);
  4929. }
  4930. },
  4931. _onChange: function (callback) {
  4932. this._onChangeCallback = callback;
  4933. return this;
  4934. },
  4935. _onChangeCallback: function () {}
  4936. });
  4937. /**
  4938. * @author mrdoob / http://mrdoob.com/
  4939. */
  4940. function Layers() {
  4941. this.mask = 1 | 0;
  4942. }
  4943. Object.assign(Layers.prototype, {
  4944. set: function (channel) {
  4945. this.mask = 1 << channel | 0;
  4946. },
  4947. enable: function (channel) {
  4948. this.mask |= 1 << channel | 0;
  4949. },
  4950. enableAll: function () {
  4951. this.mask = 0xffffffff | 0;
  4952. },
  4953. toggle: function (channel) {
  4954. this.mask ^= 1 << channel | 0;
  4955. },
  4956. disable: function (channel) {
  4957. this.mask &= ~(1 << channel | 0);
  4958. },
  4959. disableAll: function () {
  4960. this.mask = 0;
  4961. },
  4962. test: function (layers) {
  4963. return (this.mask & layers.mask) !== 0;
  4964. }
  4965. });
  4966. var _object3DId = 0;
  4967. var _v1$1 = new Vector3();
  4968. var _q1 = new Quaternion();
  4969. var _m1$1 = new Matrix4();
  4970. var _target = new Vector3();
  4971. var _position = new Vector3();
  4972. var _scale = new Vector3();
  4973. var _quaternion$2 = new Quaternion();
  4974. var _xAxis = new Vector3(1, 0, 0);
  4975. var _yAxis = new Vector3(0, 1, 0);
  4976. var _zAxis = new Vector3(0, 0, 1);
  4977. var _addedEvent = {
  4978. type: 'added'
  4979. };
  4980. var _removedEvent = {
  4981. type: 'removed'
  4982. };
  4983. /**
  4984. * @author mrdoob / http://mrdoob.com/
  4985. * @author mikael emtinger / http://gomo.se/
  4986. * @author alteredq / http://alteredqualia.com/
  4987. * @author WestLangley / http://github.com/WestLangley
  4988. * @author elephantatwork / www.elephantatwork.ch
  4989. */
  4990. function Object3D() {
  4991. Object.defineProperty(this, 'id', {
  4992. value: _object3DId++
  4993. });
  4994. this.uuid = _Math.generateUUID();
  4995. this.name = '';
  4996. this.type = 'Object3D';
  4997. this.parent = null;
  4998. this.children = [];
  4999. this.up = Object3D.DefaultUp.clone();
  5000. var position = new Vector3();
  5001. var rotation = new Euler();
  5002. var quaternion = new Quaternion();
  5003. var scale = new Vector3(1, 1, 1);
  5004. function onRotationChange() {
  5005. quaternion.setFromEuler(rotation, false);
  5006. }
  5007. function onQuaternionChange() {
  5008. rotation.setFromQuaternion(quaternion, undefined, false);
  5009. }
  5010. rotation._onChange(onRotationChange);
  5011. quaternion._onChange(onQuaternionChange);
  5012. Object.defineProperties(this, {
  5013. position: {
  5014. configurable: true,
  5015. enumerable: true,
  5016. value: position
  5017. },
  5018. rotation: {
  5019. configurable: true,
  5020. enumerable: true,
  5021. value: rotation
  5022. },
  5023. quaternion: {
  5024. configurable: true,
  5025. enumerable: true,
  5026. value: quaternion
  5027. },
  5028. scale: {
  5029. configurable: true,
  5030. enumerable: true,
  5031. value: scale
  5032. },
  5033. modelViewMatrix: {
  5034. value: new Matrix4()
  5035. },
  5036. normalMatrix: {
  5037. value: new Matrix3()
  5038. }
  5039. });
  5040. this.matrix = new Matrix4();
  5041. this.matrixWorld = new Matrix4();
  5042. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  5043. this.matrixWorldNeedsUpdate = false;
  5044. this.layers = new Layers();
  5045. this.visible = true;
  5046. this.castShadow = false;
  5047. this.receiveShadow = false;
  5048. this.frustumCulled = true;
  5049. this.renderOrder = 0;
  5050. this.userData = {};
  5051. }
  5052. Object3D.DefaultUp = new Vector3(0, 1, 0);
  5053. Object3D.DefaultMatrixAutoUpdate = true;
  5054. Object3D.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  5055. constructor: Object3D,
  5056. isObject3D: true,
  5057. onBeforeRender: function () {},
  5058. onAfterRender: function () {},
  5059. applyMatrix: function (matrix) {
  5060. if (this.matrixAutoUpdate) this.updateMatrix();
  5061. this.matrix.premultiply(matrix);
  5062. this.matrix.decompose(this.position, this.quaternion, this.scale);
  5063. },
  5064. applyQuaternion: function (q) {
  5065. this.quaternion.premultiply(q);
  5066. return this;
  5067. },
  5068. setRotationFromAxisAngle: function (axis, angle) {
  5069. // assumes axis is normalized
  5070. this.quaternion.setFromAxisAngle(axis, angle);
  5071. },
  5072. setRotationFromEuler: function (euler) {
  5073. this.quaternion.setFromEuler(euler, true);
  5074. },
  5075. setRotationFromMatrix: function (m) {
  5076. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  5077. this.quaternion.setFromRotationMatrix(m);
  5078. },
  5079. setRotationFromQuaternion: function (q) {
  5080. // assumes q is normalized
  5081. this.quaternion.copy(q);
  5082. },
  5083. rotateOnAxis: function (axis, angle) {
  5084. // rotate object on axis in object space
  5085. // axis is assumed to be normalized
  5086. _q1.setFromAxisAngle(axis, angle);
  5087. this.quaternion.multiply(_q1);
  5088. return this;
  5089. },
  5090. rotateOnWorldAxis: function (axis, angle) {
  5091. // rotate object on axis in world space
  5092. // axis is assumed to be normalized
  5093. // method assumes no rotated parent
  5094. _q1.setFromAxisAngle(axis, angle);
  5095. this.quaternion.premultiply(_q1);
  5096. return this;
  5097. },
  5098. rotateX: function (angle) {
  5099. return this.rotateOnAxis(_xAxis, angle);
  5100. },
  5101. rotateY: function (angle) {
  5102. return this.rotateOnAxis(_yAxis, angle);
  5103. },
  5104. rotateZ: function (angle) {
  5105. return this.rotateOnAxis(_zAxis, angle);
  5106. },
  5107. translateOnAxis: function (axis, distance) {
  5108. // translate object by distance along axis in object space
  5109. // axis is assumed to be normalized
  5110. _v1$1.copy(axis).applyQuaternion(this.quaternion);
  5111. this.position.add(_v1$1.multiplyScalar(distance));
  5112. return this;
  5113. },
  5114. translateX: function (distance) {
  5115. return this.translateOnAxis(_xAxis, distance);
  5116. },
  5117. translateY: function (distance) {
  5118. return this.translateOnAxis(_yAxis, distance);
  5119. },
  5120. translateZ: function (distance) {
  5121. return this.translateOnAxis(_zAxis, distance);
  5122. },
  5123. localToWorld: function (vector) {
  5124. return vector.applyMatrix4(this.matrixWorld);
  5125. },
  5126. worldToLocal: function (vector) {
  5127. return vector.applyMatrix4(_m1$1.getInverse(this.matrixWorld));
  5128. },
  5129. lookAt: function (x, y, z) {
  5130. // This method does not support objects having non-uniformly-scaled parent(s)
  5131. if (x.isVector3) {
  5132. _target.copy(x);
  5133. } else {
  5134. _target.set(x, y, z);
  5135. }
  5136. var parent = this.parent;
  5137. this.updateWorldMatrix(true, false);
  5138. _position.setFromMatrixPosition(this.matrixWorld);
  5139. if (this.isCamera || this.isLight) {
  5140. _m1$1.lookAt(_position, _target, this.up);
  5141. } else {
  5142. _m1$1.lookAt(_target, _position, this.up);
  5143. }
  5144. this.quaternion.setFromRotationMatrix(_m1$1);
  5145. if (parent) {
  5146. _m1$1.extractRotation(parent.matrixWorld);
  5147. _q1.setFromRotationMatrix(_m1$1);
  5148. this.quaternion.premultiply(_q1.inverse());
  5149. }
  5150. },
  5151. add: function (object) {
  5152. if (arguments.length > 1) {
  5153. for (var i = 0; i < arguments.length; i++) {
  5154. this.add(arguments[i]);
  5155. }
  5156. return this;
  5157. }
  5158. if (object === this) {
  5159. console.error("THREE.Object3D.add: object can't be added as a child of itself.", object);
  5160. return this;
  5161. }
  5162. if (object && object.isObject3D) {
  5163. if (object.parent !== null) {
  5164. object.parent.remove(object);
  5165. }
  5166. object.parent = this;
  5167. this.children.push(object);
  5168. object.dispatchEvent(_addedEvent);
  5169. } else {
  5170. console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.", object);
  5171. }
  5172. return this;
  5173. },
  5174. remove: function (object) {
  5175. if (arguments.length > 1) {
  5176. for (var i = 0; i < arguments.length; i++) {
  5177. this.remove(arguments[i]);
  5178. }
  5179. return this;
  5180. }
  5181. var index = this.children.indexOf(object);
  5182. if (index !== -1) {
  5183. object.parent = null;
  5184. this.children.splice(index, 1);
  5185. object.dispatchEvent(_removedEvent);
  5186. }
  5187. return this;
  5188. },
  5189. attach: function (object) {
  5190. // adds object as a child of this, while maintaining the object's world transform
  5191. this.updateWorldMatrix(true, false);
  5192. _m1$1.getInverse(this.matrixWorld);
  5193. if (object.parent !== null) {
  5194. object.parent.updateWorldMatrix(true, false);
  5195. _m1$1.multiply(object.parent.matrixWorld);
  5196. }
  5197. object.applyMatrix(_m1$1);
  5198. object.updateWorldMatrix(false, false);
  5199. this.add(object);
  5200. return this;
  5201. },
  5202. getObjectById: function (id) {
  5203. return this.getObjectByProperty('id', id);
  5204. },
  5205. getObjectByName: function (name) {
  5206. return this.getObjectByProperty('name', name);
  5207. },
  5208. getObjectByProperty: function (name, value) {
  5209. if (this[name] === value) return this;
  5210. for (var i = 0, l = this.children.length; i < l; i++) {
  5211. var child = this.children[i];
  5212. var object = child.getObjectByProperty(name, value);
  5213. if (object !== undefined) {
  5214. return object;
  5215. }
  5216. }
  5217. return undefined;
  5218. },
  5219. getWorldPosition: function (target) {
  5220. if (target === undefined) {
  5221. console.warn('THREE.Object3D: .getWorldPosition() target is now required');
  5222. target = new Vector3();
  5223. }
  5224. this.updateMatrixWorld(true);
  5225. return target.setFromMatrixPosition(this.matrixWorld);
  5226. },
  5227. getWorldQuaternion: function (target) {
  5228. if (target === undefined) {
  5229. console.warn('THREE.Object3D: .getWorldQuaternion() target is now required');
  5230. target = new Quaternion();
  5231. }
  5232. this.updateMatrixWorld(true);
  5233. this.matrixWorld.decompose(_position, target, _scale);
  5234. return target;
  5235. },
  5236. getWorldScale: function (target) {
  5237. if (target === undefined) {
  5238. console.warn('THREE.Object3D: .getWorldScale() target is now required');
  5239. target = new Vector3();
  5240. }
  5241. this.updateMatrixWorld(true);
  5242. this.matrixWorld.decompose(_position, _quaternion$2, target);
  5243. return target;
  5244. },
  5245. getWorldDirection: function (target) {
  5246. if (target === undefined) {
  5247. console.warn('THREE.Object3D: .getWorldDirection() target is now required');
  5248. target = new Vector3();
  5249. }
  5250. this.updateMatrixWorld(true);
  5251. var e = this.matrixWorld.elements;
  5252. return target.set(e[8], e[9], e[10]).normalize();
  5253. },
  5254. raycast: function () {},
  5255. traverse: function (callback) {
  5256. callback(this);
  5257. var children = this.children;
  5258. for (var i = 0, l = children.length; i < l; i++) {
  5259. children[i].traverse(callback);
  5260. }
  5261. },
  5262. traverseVisible: function (callback) {
  5263. if (this.visible === false) return;
  5264. callback(this);
  5265. var children = this.children;
  5266. for (var i = 0, l = children.length; i < l; i++) {
  5267. children[i].traverseVisible(callback);
  5268. }
  5269. },
  5270. traverseAncestors: function (callback) {
  5271. var parent = this.parent;
  5272. if (parent !== null) {
  5273. callback(parent);
  5274. parent.traverseAncestors(callback);
  5275. }
  5276. },
  5277. updateMatrix: function () {
  5278. this.matrix.compose(this.position, this.quaternion, this.scale);
  5279. this.matrixWorldNeedsUpdate = true;
  5280. },
  5281. updateMatrixWorld: function (force) {
  5282. if (this.matrixAutoUpdate) this.updateMatrix();
  5283. if (this.matrixWorldNeedsUpdate || force) {
  5284. if (this.parent === null) {
  5285. this.matrixWorld.copy(this.matrix);
  5286. } else {
  5287. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  5288. }
  5289. this.matrixWorldNeedsUpdate = false;
  5290. force = true;
  5291. } // update children
  5292. var children = this.children;
  5293. for (var i = 0, l = children.length; i < l; i++) {
  5294. children[i].updateMatrixWorld(force);
  5295. }
  5296. },
  5297. updateWorldMatrix: function (updateParents, updateChildren) {
  5298. var parent = this.parent;
  5299. if (updateParents === true && parent !== null) {
  5300. parent.updateWorldMatrix(true, false);
  5301. }
  5302. if (this.matrixAutoUpdate) this.updateMatrix();
  5303. if (this.parent === null) {
  5304. this.matrixWorld.copy(this.matrix);
  5305. } else {
  5306. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  5307. } // update children
  5308. if (updateChildren === true) {
  5309. var children = this.children;
  5310. for (var i = 0, l = children.length; i < l; i++) {
  5311. children[i].updateWorldMatrix(false, true);
  5312. }
  5313. }
  5314. },
  5315. toJSON: function (meta) {
  5316. // meta is a string when called from JSON.stringify
  5317. var isRootObject = meta === undefined || typeof meta === 'string';
  5318. var output = {}; // meta is a hash used to collect geometries, materials.
  5319. // not providing it implies that this is the root object
  5320. // being serialized.
  5321. if (isRootObject) {
  5322. // initialize meta obj
  5323. meta = {
  5324. geometries: {},
  5325. materials: {},
  5326. textures: {},
  5327. images: {},
  5328. shapes: {}
  5329. };
  5330. output.metadata = {
  5331. version: 4.5,
  5332. type: 'Object',
  5333. generator: 'Object3D.toJSON'
  5334. };
  5335. } // standard Object3D serialization
  5336. var object = {};
  5337. object.uuid = this.uuid;
  5338. object.type = this.type;
  5339. if (this.name !== '') object.name = this.name;
  5340. if (this.castShadow === true) object.castShadow = true;
  5341. if (this.receiveShadow === true) object.receiveShadow = true;
  5342. if (this.visible === false) object.visible = false;
  5343. if (this.frustumCulled === false) object.frustumCulled = false;
  5344. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  5345. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  5346. object.layers = this.layers.mask;
  5347. object.matrix = this.matrix.toArray();
  5348. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  5349. if (this.isMesh && this.drawMode !== TrianglesDrawMode) object.drawMode = this.drawMode; //
  5350. function serialize(library, element) {
  5351. if (library[element.uuid] === undefined) {
  5352. library[element.uuid] = element.toJSON(meta);
  5353. }
  5354. return element.uuid;
  5355. }
  5356. if (this.isMesh || this.isLine || this.isPoints) {
  5357. object.geometry = serialize(meta.geometries, this.geometry);
  5358. var parameters = this.geometry.parameters;
  5359. if (parameters !== undefined && parameters.shapes !== undefined) {
  5360. var shapes = parameters.shapes;
  5361. if (Array.isArray(shapes)) {
  5362. for (var i = 0, l = shapes.length; i < l; i++) {
  5363. var shape = shapes[i];
  5364. serialize(meta.shapes, shape);
  5365. }
  5366. } else {
  5367. serialize(meta.shapes, shapes);
  5368. }
  5369. }
  5370. }
  5371. if (this.material !== undefined) {
  5372. if (Array.isArray(this.material)) {
  5373. var uuids = [];
  5374. for (var i = 0, l = this.material.length; i < l; i++) {
  5375. uuids.push(serialize(meta.materials, this.material[i]));
  5376. }
  5377. object.material = uuids;
  5378. } else {
  5379. object.material = serialize(meta.materials, this.material);
  5380. }
  5381. } //
  5382. if (this.children.length > 0) {
  5383. object.children = [];
  5384. for (var i = 0; i < this.children.length; i++) {
  5385. object.children.push(this.children[i].toJSON(meta).object);
  5386. }
  5387. }
  5388. if (isRootObject) {
  5389. var geometries = extractFromCache(meta.geometries);
  5390. var materials = extractFromCache(meta.materials);
  5391. var textures = extractFromCache(meta.textures);
  5392. var images = extractFromCache(meta.images);
  5393. var shapes = extractFromCache(meta.shapes);
  5394. if (geometries.length > 0) output.geometries = geometries;
  5395. if (materials.length > 0) output.materials = materials;
  5396. if (textures.length > 0) output.textures = textures;
  5397. if (images.length > 0) output.images = images;
  5398. if (shapes.length > 0) output.shapes = shapes;
  5399. }
  5400. output.object = object;
  5401. return output; // extract data from the cache hash
  5402. // remove metadata on each item
  5403. // and return as array
  5404. function extractFromCache(cache) {
  5405. var values = [];
  5406. for (var key in cache) {
  5407. var data = cache[key];
  5408. delete data.metadata;
  5409. values.push(data);
  5410. }
  5411. return values;
  5412. }
  5413. },
  5414. clone: function (recursive) {
  5415. return new this.constructor().copy(this, recursive);
  5416. },
  5417. copy: function (source, recursive) {
  5418. if (recursive === undefined) recursive = true;
  5419. this.name = source.name;
  5420. this.up.copy(source.up);
  5421. this.position.copy(source.position);
  5422. this.quaternion.copy(source.quaternion);
  5423. this.scale.copy(source.scale);
  5424. this.matrix.copy(source.matrix);
  5425. this.matrixWorld.copy(source.matrixWorld);
  5426. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5427. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  5428. this.layers.mask = source.layers.mask;
  5429. this.visible = source.visible;
  5430. this.castShadow = source.castShadow;
  5431. this.receiveShadow = source.receiveShadow;
  5432. this.frustumCulled = source.frustumCulled;
  5433. this.renderOrder = source.renderOrder;
  5434. this.userData = JSON.parse(JSON.stringify(source.userData));
  5435. if (recursive === true) {
  5436. for (var i = 0; i < source.children.length; i++) {
  5437. var child = source.children[i];
  5438. this.add(child.clone());
  5439. }
  5440. }
  5441. return this;
  5442. }
  5443. });
  5444. /**
  5445. * @author mrdoob / http://mrdoob.com/
  5446. */
  5447. function Scene() {
  5448. Object3D.call(this);
  5449. this.type = 'Scene';
  5450. this.background = null;
  5451. this.fog = null;
  5452. this.overrideMaterial = null;
  5453. this.autoUpdate = true; // checked by the renderer
  5454. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  5455. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  5456. detail: this
  5457. })); // eslint-disable-line no-undef
  5458. }
  5459. }
  5460. Scene.prototype = Object.assign(Object.create(Object3D.prototype), {
  5461. constructor: Scene,
  5462. isScene: true,
  5463. copy: function (source, recursive) {
  5464. Object3D.prototype.copy.call(this, source, recursive);
  5465. if (source.background !== null) this.background = source.background.clone();
  5466. if (source.fog !== null) this.fog = source.fog.clone();
  5467. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  5468. this.autoUpdate = source.autoUpdate;
  5469. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5470. return this;
  5471. },
  5472. toJSON: function (meta) {
  5473. var data = Object3D.prototype.toJSON.call(this, meta);
  5474. if (this.background !== null) data.object.background = this.background.toJSON(meta);
  5475. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  5476. return data;
  5477. },
  5478. dispose: function () {
  5479. this.dispatchEvent({
  5480. type: 'dispose'
  5481. });
  5482. }
  5483. });
  5484. var _points = [new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3()];
  5485. var _vector$2 = new Vector3(); // triangle centered vertices
  5486. var _v0 = new Vector3();
  5487. var _v1$2 = new Vector3();
  5488. var _v2 = new Vector3(); // triangle edge vectors
  5489. var _f0 = new Vector3();
  5490. var _f1 = new Vector3();
  5491. var _f2 = new Vector3();
  5492. var _center = new Vector3();
  5493. var _extents = new Vector3();
  5494. var _triangleNormal = new Vector3();
  5495. var _testAxis = new Vector3();
  5496. /**
  5497. * @author bhouston / http://clara.io
  5498. * @author WestLangley / http://github.com/WestLangley
  5499. */
  5500. function Box3(min, max) {
  5501. this.min = min !== undefined ? min : new Vector3(+Infinity, +Infinity, +Infinity);
  5502. this.max = max !== undefined ? max : new Vector3(-Infinity, -Infinity, -Infinity);
  5503. }
  5504. Object.assign(Box3.prototype, {
  5505. isBox3: true,
  5506. set: function (min, max) {
  5507. this.min.copy(min);
  5508. this.max.copy(max);
  5509. return this;
  5510. },
  5511. setFromArray: function (array) {
  5512. var minX = +Infinity;
  5513. var minY = +Infinity;
  5514. var minZ = +Infinity;
  5515. var maxX = -Infinity;
  5516. var maxY = -Infinity;
  5517. var maxZ = -Infinity;
  5518. for (var i = 0, l = array.length; i < l; i += 3) {
  5519. var x = array[i];
  5520. var y = array[i + 1];
  5521. var z = array[i + 2];
  5522. if (x < minX) minX = x;
  5523. if (y < minY) minY = y;
  5524. if (z < minZ) minZ = z;
  5525. if (x > maxX) maxX = x;
  5526. if (y > maxY) maxY = y;
  5527. if (z > maxZ) maxZ = z;
  5528. }
  5529. this.min.set(minX, minY, minZ);
  5530. this.max.set(maxX, maxY, maxZ);
  5531. return this;
  5532. },
  5533. setFromBufferAttribute: function (attribute) {
  5534. var minX = +Infinity;
  5535. var minY = +Infinity;
  5536. var minZ = +Infinity;
  5537. var maxX = -Infinity;
  5538. var maxY = -Infinity;
  5539. var maxZ = -Infinity;
  5540. for (var i = 0, l = attribute.count; i < l; i++) {
  5541. var x = attribute.getX(i);
  5542. var y = attribute.getY(i);
  5543. var z = attribute.getZ(i);
  5544. if (x < minX) minX = x;
  5545. if (y < minY) minY = y;
  5546. if (z < minZ) minZ = z;
  5547. if (x > maxX) maxX = x;
  5548. if (y > maxY) maxY = y;
  5549. if (z > maxZ) maxZ = z;
  5550. }
  5551. this.min.set(minX, minY, minZ);
  5552. this.max.set(maxX, maxY, maxZ);
  5553. return this;
  5554. },
  5555. setFromPoints: function (points) {
  5556. this.makeEmpty();
  5557. for (var i = 0, il = points.length; i < il; i++) {
  5558. this.expandByPoint(points[i]);
  5559. }
  5560. return this;
  5561. },
  5562. setFromCenterAndSize: function (center, size) {
  5563. var halfSize = _vector$2.copy(size).multiplyScalar(0.5);
  5564. this.min.copy(center).sub(halfSize);
  5565. this.max.copy(center).add(halfSize);
  5566. return this;
  5567. },
  5568. setFromObject: function (object) {
  5569. this.makeEmpty();
  5570. return this.expandByObject(object);
  5571. },
  5572. clone: function () {
  5573. return new this.constructor().copy(this);
  5574. },
  5575. copy: function (box) {
  5576. this.min.copy(box.min);
  5577. this.max.copy(box.max);
  5578. return this;
  5579. },
  5580. makeEmpty: function () {
  5581. this.min.x = this.min.y = this.min.z = +Infinity;
  5582. this.max.x = this.max.y = this.max.z = -Infinity;
  5583. return this;
  5584. },
  5585. isEmpty: function () {
  5586. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  5587. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  5588. },
  5589. getCenter: function (target) {
  5590. if (target === undefined) {
  5591. console.warn('THREE.Box3: .getCenter() target is now required');
  5592. target = new Vector3();
  5593. }
  5594. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  5595. },
  5596. getSize: function (target) {
  5597. if (target === undefined) {
  5598. console.warn('THREE.Box3: .getSize() target is now required');
  5599. target = new Vector3();
  5600. }
  5601. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  5602. },
  5603. expandByPoint: function (point) {
  5604. this.min.min(point);
  5605. this.max.max(point);
  5606. return this;
  5607. },
  5608. expandByVector: function (vector) {
  5609. this.min.sub(vector);
  5610. this.max.add(vector);
  5611. return this;
  5612. },
  5613. expandByScalar: function (scalar) {
  5614. this.min.addScalar(-scalar);
  5615. this.max.addScalar(scalar);
  5616. return this;
  5617. },
  5618. expandByObject: function (object) {
  5619. var i, l; // Computes the world-axis-aligned bounding box of an object (including its children),
  5620. // accounting for both the object's, and children's, world transforms
  5621. object.updateWorldMatrix(false, false);
  5622. var geometry = object.geometry;
  5623. if (geometry !== undefined) {
  5624. if (geometry.isGeometry) {
  5625. var vertices = geometry.vertices;
  5626. for (i = 0, l = vertices.length; i < l; i++) {
  5627. _vector$2.copy(vertices[i]);
  5628. _vector$2.applyMatrix4(object.matrixWorld);
  5629. this.expandByPoint(_vector$2);
  5630. }
  5631. } else if (geometry.isBufferGeometry) {
  5632. var attribute = geometry.attributes.position;
  5633. if (attribute !== undefined) {
  5634. for (i = 0, l = attribute.count; i < l; i++) {
  5635. _vector$2.fromBufferAttribute(attribute, i).applyMatrix4(object.matrixWorld);
  5636. this.expandByPoint(_vector$2);
  5637. }
  5638. }
  5639. }
  5640. } //
  5641. var children = object.children;
  5642. for (i = 0, l = children.length; i < l; i++) {
  5643. this.expandByObject(children[i]);
  5644. }
  5645. return this;
  5646. },
  5647. containsPoint: function (point) {
  5648. 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;
  5649. },
  5650. containsBox: function (box) {
  5651. 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;
  5652. },
  5653. getParameter: function (point, target) {
  5654. // This can potentially have a divide by zero if the box
  5655. // has a size dimension of 0.
  5656. if (target === undefined) {
  5657. console.warn('THREE.Box3: .getParameter() target is now required');
  5658. target = new Vector3();
  5659. }
  5660. 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));
  5661. },
  5662. intersectsBox: function (box) {
  5663. // using 6 splitting planes to rule out intersections.
  5664. 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;
  5665. },
  5666. intersectsSphere: function (sphere) {
  5667. // Find the point on the AABB closest to the sphere center.
  5668. this.clampPoint(sphere.center, _vector$2); // If that point is inside the sphere, the AABB and sphere intersect.
  5669. return _vector$2.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  5670. },
  5671. intersectsPlane: function (plane) {
  5672. // We compute the minimum and maximum dot product values. If those values
  5673. // are on the same side (back or front) of the plane, then there is no intersection.
  5674. var min, max;
  5675. if (plane.normal.x > 0) {
  5676. min = plane.normal.x * this.min.x;
  5677. max = plane.normal.x * this.max.x;
  5678. } else {
  5679. min = plane.normal.x * this.max.x;
  5680. max = plane.normal.x * this.min.x;
  5681. }
  5682. if (plane.normal.y > 0) {
  5683. min += plane.normal.y * this.min.y;
  5684. max += plane.normal.y * this.max.y;
  5685. } else {
  5686. min += plane.normal.y * this.max.y;
  5687. max += plane.normal.y * this.min.y;
  5688. }
  5689. if (plane.normal.z > 0) {
  5690. min += plane.normal.z * this.min.z;
  5691. max += plane.normal.z * this.max.z;
  5692. } else {
  5693. min += plane.normal.z * this.max.z;
  5694. max += plane.normal.z * this.min.z;
  5695. }
  5696. return min <= -plane.constant && max >= -plane.constant;
  5697. },
  5698. intersectsTriangle: function (triangle) {
  5699. if (this.isEmpty()) {
  5700. return false;
  5701. } // compute box center and extents
  5702. this.getCenter(_center);
  5703. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  5704. _v0.subVectors(triangle.a, _center);
  5705. _v1$2.subVectors(triangle.b, _center);
  5706. _v2.subVectors(triangle.c, _center); // compute edge vectors for triangle
  5707. _f0.subVectors(_v1$2, _v0);
  5708. _f1.subVectors(_v2, _v1$2);
  5709. _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
  5710. // 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
  5711. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  5712. 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];
  5713. if (!satForAxes(axes, _v0, _v1$2, _v2, _extents)) {
  5714. return false;
  5715. } // test 3 face normals from the aabb
  5716. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  5717. if (!satForAxes(axes, _v0, _v1$2, _v2, _extents)) {
  5718. return false;
  5719. } // finally testing the face normal of the triangle
  5720. // use already existing triangle edge vectors here
  5721. _triangleNormal.crossVectors(_f0, _f1);
  5722. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  5723. return satForAxes(axes, _v0, _v1$2, _v2, _extents);
  5724. },
  5725. clampPoint: function (point, target) {
  5726. if (target === undefined) {
  5727. console.warn('THREE.Box3: .clampPoint() target is now required');
  5728. target = new Vector3();
  5729. }
  5730. return target.copy(point).clamp(this.min, this.max);
  5731. },
  5732. distanceToPoint: function (point) {
  5733. var clampedPoint = _vector$2.copy(point).clamp(this.min, this.max);
  5734. return clampedPoint.sub(point).length();
  5735. },
  5736. getBoundingSphere: function (target) {
  5737. if (target === undefined) {
  5738. console.error('THREE.Box3: .getBoundingSphere() target is now required'); //target = new Sphere(); // removed to avoid cyclic dependency
  5739. }
  5740. this.getCenter(target.center);
  5741. target.radius = this.getSize(_vector$2).length() * 0.5;
  5742. return target;
  5743. },
  5744. intersect: function (box) {
  5745. this.min.max(box.min);
  5746. 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.
  5747. if (this.isEmpty()) this.makeEmpty();
  5748. return this;
  5749. },
  5750. union: function (box) {
  5751. this.min.min(box.min);
  5752. this.max.max(box.max);
  5753. return this;
  5754. },
  5755. applyMatrix4: function (matrix) {
  5756. // transform of empty box is an empty box.
  5757. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  5758. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  5759. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  5760. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  5761. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  5762. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  5763. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  5764. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  5765. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  5766. this.setFromPoints(_points);
  5767. return this;
  5768. },
  5769. translate: function (offset) {
  5770. this.min.add(offset);
  5771. this.max.add(offset);
  5772. return this;
  5773. },
  5774. equals: function (box) {
  5775. return box.min.equals(this.min) && box.max.equals(this.max);
  5776. }
  5777. });
  5778. function satForAxes(axes, v0, v1, v2, extents) {
  5779. var i, j;
  5780. for (i = 0, j = axes.length - 3; i <= j; i += 3) {
  5781. _testAxis.fromArray(axes, i); // project the aabb onto the seperating axis
  5782. 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
  5783. var p0 = v0.dot(_testAxis);
  5784. var p1 = v1.dot(_testAxis);
  5785. var p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  5786. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  5787. // points of the projected triangle are outside the projected half-length of the aabb
  5788. // the axis is seperating and we can exit
  5789. return false;
  5790. }
  5791. }
  5792. return true;
  5793. }
  5794. var _box = new Box3();
  5795. /**
  5796. * @author bhouston / http://clara.io
  5797. * @author mrdoob / http://mrdoob.com/
  5798. */
  5799. function Sphere(center, radius) {
  5800. this.center = center !== undefined ? center : new Vector3();
  5801. this.radius = radius !== undefined ? radius : 0;
  5802. }
  5803. Object.assign(Sphere.prototype, {
  5804. set: function (center, radius) {
  5805. this.center.copy(center);
  5806. this.radius = radius;
  5807. return this;
  5808. },
  5809. setFromPoints: function (points, optionalCenter) {
  5810. var center = this.center;
  5811. if (optionalCenter !== undefined) {
  5812. center.copy(optionalCenter);
  5813. } else {
  5814. _box.setFromPoints(points).getCenter(center);
  5815. }
  5816. var maxRadiusSq = 0;
  5817. for (var i = 0, il = points.length; i < il; i++) {
  5818. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  5819. }
  5820. this.radius = Math.sqrt(maxRadiusSq);
  5821. return this;
  5822. },
  5823. clone: function () {
  5824. return new this.constructor().copy(this);
  5825. },
  5826. copy: function (sphere) {
  5827. this.center.copy(sphere.center);
  5828. this.radius = sphere.radius;
  5829. return this;
  5830. },
  5831. empty: function () {
  5832. return this.radius <= 0;
  5833. },
  5834. containsPoint: function (point) {
  5835. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  5836. },
  5837. distanceToPoint: function (point) {
  5838. return point.distanceTo(this.center) - this.radius;
  5839. },
  5840. intersectsSphere: function (sphere) {
  5841. var radiusSum = this.radius + sphere.radius;
  5842. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  5843. },
  5844. intersectsBox: function (box) {
  5845. return box.intersectsSphere(this);
  5846. },
  5847. intersectsPlane: function (plane) {
  5848. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  5849. },
  5850. clampPoint: function (point, target) {
  5851. var deltaLengthSq = this.center.distanceToSquared(point);
  5852. if (target === undefined) {
  5853. console.warn('THREE.Sphere: .clampPoint() target is now required');
  5854. target = new Vector3();
  5855. }
  5856. target.copy(point);
  5857. if (deltaLengthSq > this.radius * this.radius) {
  5858. target.sub(this.center).normalize();
  5859. target.multiplyScalar(this.radius).add(this.center);
  5860. }
  5861. return target;
  5862. },
  5863. getBoundingBox: function (target) {
  5864. if (target === undefined) {
  5865. console.warn('THREE.Sphere: .getBoundingBox() target is now required');
  5866. target = new Box3();
  5867. }
  5868. target.set(this.center, this.center);
  5869. target.expandByScalar(this.radius);
  5870. return target;
  5871. },
  5872. applyMatrix4: function (matrix) {
  5873. this.center.applyMatrix4(matrix);
  5874. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  5875. return this;
  5876. },
  5877. translate: function (offset) {
  5878. this.center.add(offset);
  5879. return this;
  5880. },
  5881. equals: function (sphere) {
  5882. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  5883. }
  5884. });
  5885. var _vector$3 = new Vector3();
  5886. var _segCenter = new Vector3();
  5887. var _segDir = new Vector3();
  5888. var _diff = new Vector3();
  5889. var _edge1 = new Vector3();
  5890. var _edge2 = new Vector3();
  5891. var _normal = new Vector3();
  5892. /**
  5893. * @author bhouston / http://clara.io
  5894. */
  5895. function Ray(origin, direction) {
  5896. this.origin = origin !== undefined ? origin : new Vector3();
  5897. this.direction = direction !== undefined ? direction : new Vector3();
  5898. }
  5899. Object.assign(Ray.prototype, {
  5900. set: function (origin, direction) {
  5901. this.origin.copy(origin);
  5902. this.direction.copy(direction);
  5903. return this;
  5904. },
  5905. clone: function () {
  5906. return new this.constructor().copy(this);
  5907. },
  5908. copy: function (ray) {
  5909. this.origin.copy(ray.origin);
  5910. this.direction.copy(ray.direction);
  5911. return this;
  5912. },
  5913. at: function (t, target) {
  5914. if (target === undefined) {
  5915. console.warn('THREE.Ray: .at() target is now required');
  5916. target = new Vector3();
  5917. }
  5918. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  5919. },
  5920. lookAt: function (v) {
  5921. this.direction.copy(v).sub(this.origin).normalize();
  5922. return this;
  5923. },
  5924. recast: function (t) {
  5925. this.origin.copy(this.at(t, _vector$3));
  5926. return this;
  5927. },
  5928. closestPointToPoint: function (point, target) {
  5929. if (target === undefined) {
  5930. console.warn('THREE.Ray: .closestPointToPoint() target is now required');
  5931. target = new Vector3();
  5932. }
  5933. target.subVectors(point, this.origin);
  5934. var directionDistance = target.dot(this.direction);
  5935. if (directionDistance < 0) {
  5936. return target.copy(this.origin);
  5937. }
  5938. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  5939. },
  5940. distanceToPoint: function (point) {
  5941. return Math.sqrt(this.distanceSqToPoint(point));
  5942. },
  5943. distanceSqToPoint: function (point) {
  5944. var directionDistance = _vector$3.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  5945. if (directionDistance < 0) {
  5946. return this.origin.distanceToSquared(point);
  5947. }
  5948. _vector$3.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  5949. return _vector$3.distanceToSquared(point);
  5950. },
  5951. distanceSqToSegment: function (v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  5952. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  5953. // It returns the min distance between the ray and the segment
  5954. // defined by v0 and v1
  5955. // It can also set two optional targets :
  5956. // - The closest point on the ray
  5957. // - The closest point on the segment
  5958. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  5959. _segDir.copy(v1).sub(v0).normalize();
  5960. _diff.copy(this.origin).sub(_segCenter);
  5961. var segExtent = v0.distanceTo(v1) * 0.5;
  5962. var a01 = -this.direction.dot(_segDir);
  5963. var b0 = _diff.dot(this.direction);
  5964. var b1 = -_diff.dot(_segDir);
  5965. var c = _diff.lengthSq();
  5966. var det = Math.abs(1 - a01 * a01);
  5967. var s0, s1, sqrDist, extDet;
  5968. if (det > 0) {
  5969. // The ray and segment are not parallel.
  5970. s0 = a01 * b1 - b0;
  5971. s1 = a01 * b0 - b1;
  5972. extDet = segExtent * det;
  5973. if (s0 >= 0) {
  5974. if (s1 >= -extDet) {
  5975. if (s1 <= extDet) {
  5976. // region 0
  5977. // Minimum at interior points of ray and segment.
  5978. var invDet = 1 / det;
  5979. s0 *= invDet;
  5980. s1 *= invDet;
  5981. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  5982. } else {
  5983. // region 1
  5984. s1 = segExtent;
  5985. s0 = Math.max(0, -(a01 * s1 + b0));
  5986. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  5987. }
  5988. } else {
  5989. // region 5
  5990. s1 = -segExtent;
  5991. s0 = Math.max(0, -(a01 * s1 + b0));
  5992. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  5993. }
  5994. } else {
  5995. if (s1 <= -extDet) {
  5996. // region 4
  5997. s0 = Math.max(0, -(-a01 * segExtent + b0));
  5998. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  5999. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  6000. } else if (s1 <= extDet) {
  6001. // region 3
  6002. s0 = 0;
  6003. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  6004. sqrDist = s1 * (s1 + 2 * b1) + c;
  6005. } else {
  6006. // region 2
  6007. s0 = Math.max(0, -(a01 * segExtent + b0));
  6008. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  6009. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  6010. }
  6011. }
  6012. } else {
  6013. // Ray and segment are parallel.
  6014. s1 = a01 > 0 ? -segExtent : segExtent;
  6015. s0 = Math.max(0, -(a01 * s1 + b0));
  6016. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  6017. }
  6018. if (optionalPointOnRay) {
  6019. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  6020. }
  6021. if (optionalPointOnSegment) {
  6022. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  6023. }
  6024. return sqrDist;
  6025. },
  6026. intersectSphere: function (sphere, target) {
  6027. _vector$3.subVectors(sphere.center, this.origin);
  6028. var tca = _vector$3.dot(this.direction);
  6029. var d2 = _vector$3.dot(_vector$3) - tca * tca;
  6030. var radius2 = sphere.radius * sphere.radius;
  6031. if (d2 > radius2) return null;
  6032. var thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  6033. var t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  6034. var t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  6035. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  6036. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  6037. // in order to always return an intersect point that is in front of the ray.
  6038. 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
  6039. return this.at(t0, target);
  6040. },
  6041. intersectsSphere: function (sphere) {
  6042. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  6043. },
  6044. distanceToPlane: function (plane) {
  6045. var denominator = plane.normal.dot(this.direction);
  6046. if (denominator === 0) {
  6047. // line is coplanar, return origin
  6048. if (plane.distanceToPoint(this.origin) === 0) {
  6049. return 0;
  6050. } // Null is preferable to undefined since undefined means.... it is undefined
  6051. return null;
  6052. }
  6053. var t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  6054. return t >= 0 ? t : null;
  6055. },
  6056. intersectPlane: function (plane, target) {
  6057. var t = this.distanceToPlane(plane);
  6058. if (t === null) {
  6059. return null;
  6060. }
  6061. return this.at(t, target);
  6062. },
  6063. intersectsPlane: function (plane) {
  6064. // check if the ray lies on the plane first
  6065. var distToPoint = plane.distanceToPoint(this.origin);
  6066. if (distToPoint === 0) {
  6067. return true;
  6068. }
  6069. var denominator = plane.normal.dot(this.direction);
  6070. if (denominator * distToPoint < 0) {
  6071. return true;
  6072. } // ray origin is behind the plane (and is pointing behind it)
  6073. return false;
  6074. },
  6075. intersectBox: function (box, target) {
  6076. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  6077. var invdirx = 1 / this.direction.x,
  6078. invdiry = 1 / this.direction.y,
  6079. invdirz = 1 / this.direction.z;
  6080. var origin = this.origin;
  6081. if (invdirx >= 0) {
  6082. tmin = (box.min.x - origin.x) * invdirx;
  6083. tmax = (box.max.x - origin.x) * invdirx;
  6084. } else {
  6085. tmin = (box.max.x - origin.x) * invdirx;
  6086. tmax = (box.min.x - origin.x) * invdirx;
  6087. }
  6088. if (invdiry >= 0) {
  6089. tymin = (box.min.y - origin.y) * invdiry;
  6090. tymax = (box.max.y - origin.y) * invdiry;
  6091. } else {
  6092. tymin = (box.max.y - origin.y) * invdiry;
  6093. tymax = (box.min.y - origin.y) * invdiry;
  6094. }
  6095. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  6096. // (result of 0 * Infinity). x !== x returns true if x is NaN
  6097. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  6098. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  6099. if (invdirz >= 0) {
  6100. tzmin = (box.min.z - origin.z) * invdirz;
  6101. tzmax = (box.max.z - origin.z) * invdirz;
  6102. } else {
  6103. tzmin = (box.max.z - origin.z) * invdirz;
  6104. tzmax = (box.min.z - origin.z) * invdirz;
  6105. }
  6106. if (tmin > tzmax || tzmin > tmax) return null;
  6107. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  6108. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  6109. if (tmax < 0) return null;
  6110. return this.at(tmin >= 0 ? tmin : tmax, target);
  6111. },
  6112. intersectsBox: function (box) {
  6113. return this.intersectBox(box, _vector$3) !== null;
  6114. },
  6115. intersectTriangle: function (a, b, c, backfaceCulling, target) {
  6116. // Compute the offset origin, edges, and normal.
  6117. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  6118. _edge1.subVectors(b, a);
  6119. _edge2.subVectors(c, a);
  6120. _normal.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  6121. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  6122. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  6123. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  6124. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  6125. var DdN = this.direction.dot(_normal);
  6126. var sign;
  6127. if (DdN > 0) {
  6128. if (backfaceCulling) return null;
  6129. sign = 1;
  6130. } else if (DdN < 0) {
  6131. sign = -1;
  6132. DdN = -DdN;
  6133. } else {
  6134. return null;
  6135. }
  6136. _diff.subVectors(this.origin, a);
  6137. var DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  6138. if (DdQxE2 < 0) {
  6139. return null;
  6140. }
  6141. var DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  6142. if (DdE1xQ < 0) {
  6143. return null;
  6144. } // b1+b2 > 1, no intersection
  6145. if (DdQxE2 + DdE1xQ > DdN) {
  6146. return null;
  6147. } // Line intersects triangle, check if ray does.
  6148. var QdN = -sign * _diff.dot(_normal); // t < 0, no intersection
  6149. if (QdN < 0) {
  6150. return null;
  6151. } // Ray intersects triangle.
  6152. return this.at(QdN / DdN, target);
  6153. },
  6154. applyMatrix4: function (matrix4) {
  6155. this.origin.applyMatrix4(matrix4);
  6156. this.direction.transformDirection(matrix4);
  6157. return this;
  6158. },
  6159. equals: function (ray) {
  6160. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  6161. }
  6162. });
  6163. /**
  6164. * @author bhouston / http://clara.io
  6165. * @author mrdoob / http://mrdoob.com/
  6166. */
  6167. var _v0$1 = new Vector3();
  6168. var _v1$3 = new Vector3();
  6169. var _v2$1 = new Vector3();
  6170. var _v3 = new Vector3();
  6171. var _vab = new Vector3();
  6172. var _vac = new Vector3();
  6173. var _vbc = new Vector3();
  6174. var _vap = new Vector3();
  6175. var _vbp = new Vector3();
  6176. var _vcp = new Vector3();
  6177. function Triangle(a, b, c) {
  6178. this.a = a !== undefined ? a : new Vector3();
  6179. this.b = b !== undefined ? b : new Vector3();
  6180. this.c = c !== undefined ? c : new Vector3();
  6181. }
  6182. Object.assign(Triangle, {
  6183. getNormal: function (a, b, c, target) {
  6184. if (target === undefined) {
  6185. console.warn('THREE.Triangle: .getNormal() target is now required');
  6186. target = new Vector3();
  6187. }
  6188. target.subVectors(c, b);
  6189. _v0$1.subVectors(a, b);
  6190. target.cross(_v0$1);
  6191. var targetLengthSq = target.lengthSq();
  6192. if (targetLengthSq > 0) {
  6193. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  6194. }
  6195. return target.set(0, 0, 0);
  6196. },
  6197. // static/instance method to calculate barycentric coordinates
  6198. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  6199. getBarycoord: function (point, a, b, c, target) {
  6200. _v0$1.subVectors(c, a);
  6201. _v1$3.subVectors(b, a);
  6202. _v2$1.subVectors(point, a);
  6203. var dot00 = _v0$1.dot(_v0$1);
  6204. var dot01 = _v0$1.dot(_v1$3);
  6205. var dot02 = _v0$1.dot(_v2$1);
  6206. var dot11 = _v1$3.dot(_v1$3);
  6207. var dot12 = _v1$3.dot(_v2$1);
  6208. var denom = dot00 * dot11 - dot01 * dot01;
  6209. if (target === undefined) {
  6210. console.warn('THREE.Triangle: .getBarycoord() target is now required');
  6211. target = new Vector3();
  6212. } // collinear or singular triangle
  6213. if (denom === 0) {
  6214. // arbitrary location outside of triangle?
  6215. // not sure if this is the best idea, maybe should be returning undefined
  6216. return target.set(-2, -1, -1);
  6217. }
  6218. var invDenom = 1 / denom;
  6219. var u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  6220. var v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  6221. return target.set(1 - u - v, v, u);
  6222. },
  6223. containsPoint: function (point, a, b, c) {
  6224. Triangle.getBarycoord(point, a, b, c, _v3);
  6225. return _v3.x >= 0 && _v3.y >= 0 && _v3.x + _v3.y <= 1;
  6226. },
  6227. getUV: function (point, p1, p2, p3, uv1, uv2, uv3, target) {
  6228. this.getBarycoord(point, p1, p2, p3, _v3);
  6229. target.set(0, 0);
  6230. target.addScaledVector(uv1, _v3.x);
  6231. target.addScaledVector(uv2, _v3.y);
  6232. target.addScaledVector(uv3, _v3.z);
  6233. return target;
  6234. },
  6235. isFrontFacing: function (a, b, c, direction) {
  6236. _v0$1.subVectors(c, b);
  6237. _v1$3.subVectors(a, b); // strictly front facing
  6238. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  6239. }
  6240. });
  6241. Object.assign(Triangle.prototype, {
  6242. set: function (a, b, c) {
  6243. this.a.copy(a);
  6244. this.b.copy(b);
  6245. this.c.copy(c);
  6246. return this;
  6247. },
  6248. setFromPointsAndIndices: function (points, i0, i1, i2) {
  6249. this.a.copy(points[i0]);
  6250. this.b.copy(points[i1]);
  6251. this.c.copy(points[i2]);
  6252. return this;
  6253. },
  6254. clone: function () {
  6255. return new this.constructor().copy(this);
  6256. },
  6257. copy: function (triangle) {
  6258. this.a.copy(triangle.a);
  6259. this.b.copy(triangle.b);
  6260. this.c.copy(triangle.c);
  6261. return this;
  6262. },
  6263. getArea: function () {
  6264. _v0$1.subVectors(this.c, this.b);
  6265. _v1$3.subVectors(this.a, this.b);
  6266. return _v0$1.cross(_v1$3).length() * 0.5;
  6267. },
  6268. getMidpoint: function (target) {
  6269. if (target === undefined) {
  6270. console.warn('THREE.Triangle: .getMidpoint() target is now required');
  6271. target = new Vector3();
  6272. }
  6273. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  6274. },
  6275. getNormal: function (target) {
  6276. return Triangle.getNormal(this.a, this.b, this.c, target);
  6277. },
  6278. getPlane: function (target) {
  6279. if (target === undefined) {
  6280. console.warn('THREE.Triangle: .getPlane() target is now required');
  6281. target = new Vector3();
  6282. }
  6283. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  6284. },
  6285. getBarycoord: function (point, target) {
  6286. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  6287. },
  6288. getUV: function (point, uv1, uv2, uv3, target) {
  6289. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  6290. },
  6291. containsPoint: function (point) {
  6292. return Triangle.containsPoint(point, this.a, this.b, this.c);
  6293. },
  6294. isFrontFacing: function (direction) {
  6295. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  6296. },
  6297. intersectsBox: function (box) {
  6298. return box.intersectsTriangle(this);
  6299. },
  6300. closestPointToPoint: function (p, target) {
  6301. if (target === undefined) {
  6302. console.warn('THREE.Triangle: .closestPointToPoint() target is now required');
  6303. target = new Vector3();
  6304. }
  6305. var a = this.a,
  6306. b = this.b,
  6307. c = this.c;
  6308. var v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  6309. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  6310. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  6311. // basically, we're distinguishing which of the voronoi regions of the triangle
  6312. // the point lies in with the minimum amount of redundant computation.
  6313. _vab.subVectors(b, a);
  6314. _vac.subVectors(c, a);
  6315. _vap.subVectors(p, a);
  6316. var d1 = _vab.dot(_vap);
  6317. var d2 = _vac.dot(_vap);
  6318. if (d1 <= 0 && d2 <= 0) {
  6319. // vertex region of A; barycentric coords (1, 0, 0)
  6320. return target.copy(a);
  6321. }
  6322. _vbp.subVectors(p, b);
  6323. var d3 = _vab.dot(_vbp);
  6324. var d4 = _vac.dot(_vbp);
  6325. if (d3 >= 0 && d4 <= d3) {
  6326. // vertex region of B; barycentric coords (0, 1, 0)
  6327. return target.copy(b);
  6328. }
  6329. var vc = d1 * d4 - d3 * d2;
  6330. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  6331. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  6332. return target.copy(a).addScaledVector(_vab, v);
  6333. }
  6334. _vcp.subVectors(p, c);
  6335. var d5 = _vab.dot(_vcp);
  6336. var d6 = _vac.dot(_vcp);
  6337. if (d6 >= 0 && d5 <= d6) {
  6338. // vertex region of C; barycentric coords (0, 0, 1)
  6339. return target.copy(c);
  6340. }
  6341. var vb = d5 * d2 - d1 * d6;
  6342. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  6343. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  6344. return target.copy(a).addScaledVector(_vac, w);
  6345. }
  6346. var va = d3 * d6 - d5 * d4;
  6347. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  6348. _vbc.subVectors(c, b);
  6349. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  6350. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  6351. } // face region
  6352. var denom = 1 / (va + vb + vc); // u = va * denom
  6353. v = vb * denom;
  6354. w = vc * denom;
  6355. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  6356. },
  6357. equals: function (triangle) {
  6358. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  6359. }
  6360. });
  6361. /**
  6362. * @author mrdoob / http://mrdoob.com/
  6363. */
  6364. var _colorKeywords = {
  6365. 'aliceblue': 0xF0F8FF,
  6366. 'antiquewhite': 0xFAEBD7,
  6367. 'aqua': 0x00FFFF,
  6368. 'aquamarine': 0x7FFFD4,
  6369. 'azure': 0xF0FFFF,
  6370. 'beige': 0xF5F5DC,
  6371. 'bisque': 0xFFE4C4,
  6372. 'black': 0x000000,
  6373. 'blanchedalmond': 0xFFEBCD,
  6374. 'blue': 0x0000FF,
  6375. 'blueviolet': 0x8A2BE2,
  6376. 'brown': 0xA52A2A,
  6377. 'burlywood': 0xDEB887,
  6378. 'cadetblue': 0x5F9EA0,
  6379. 'chartreuse': 0x7FFF00,
  6380. 'chocolate': 0xD2691E,
  6381. 'coral': 0xFF7F50,
  6382. 'cornflowerblue': 0x6495ED,
  6383. 'cornsilk': 0xFFF8DC,
  6384. 'crimson': 0xDC143C,
  6385. 'cyan': 0x00FFFF,
  6386. 'darkblue': 0x00008B,
  6387. 'darkcyan': 0x008B8B,
  6388. 'darkgoldenrod': 0xB8860B,
  6389. 'darkgray': 0xA9A9A9,
  6390. 'darkgreen': 0x006400,
  6391. 'darkgrey': 0xA9A9A9,
  6392. 'darkkhaki': 0xBDB76B,
  6393. 'darkmagenta': 0x8B008B,
  6394. 'darkolivegreen': 0x556B2F,
  6395. 'darkorange': 0xFF8C00,
  6396. 'darkorchid': 0x9932CC,
  6397. 'darkred': 0x8B0000,
  6398. 'darksalmon': 0xE9967A,
  6399. 'darkseagreen': 0x8FBC8F,
  6400. 'darkslateblue': 0x483D8B,
  6401. 'darkslategray': 0x2F4F4F,
  6402. 'darkslategrey': 0x2F4F4F,
  6403. 'darkturquoise': 0x00CED1,
  6404. 'darkviolet': 0x9400D3,
  6405. 'deeppink': 0xFF1493,
  6406. 'deepskyblue': 0x00BFFF,
  6407. 'dimgray': 0x696969,
  6408. 'dimgrey': 0x696969,
  6409. 'dodgerblue': 0x1E90FF,
  6410. 'firebrick': 0xB22222,
  6411. 'floralwhite': 0xFFFAF0,
  6412. 'forestgreen': 0x228B22,
  6413. 'fuchsia': 0xFF00FF,
  6414. 'gainsboro': 0xDCDCDC,
  6415. 'ghostwhite': 0xF8F8FF,
  6416. 'gold': 0xFFD700,
  6417. 'goldenrod': 0xDAA520,
  6418. 'gray': 0x808080,
  6419. 'green': 0x008000,
  6420. 'greenyellow': 0xADFF2F,
  6421. 'grey': 0x808080,
  6422. 'honeydew': 0xF0FFF0,
  6423. 'hotpink': 0xFF69B4,
  6424. 'indianred': 0xCD5C5C,
  6425. 'indigo': 0x4B0082,
  6426. 'ivory': 0xFFFFF0,
  6427. 'khaki': 0xF0E68C,
  6428. 'lavender': 0xE6E6FA,
  6429. 'lavenderblush': 0xFFF0F5,
  6430. 'lawngreen': 0x7CFC00,
  6431. 'lemonchiffon': 0xFFFACD,
  6432. 'lightblue': 0xADD8E6,
  6433. 'lightcoral': 0xF08080,
  6434. 'lightcyan': 0xE0FFFF,
  6435. 'lightgoldenrodyellow': 0xFAFAD2,
  6436. 'lightgray': 0xD3D3D3,
  6437. 'lightgreen': 0x90EE90,
  6438. 'lightgrey': 0xD3D3D3,
  6439. 'lightpink': 0xFFB6C1,
  6440. 'lightsalmon': 0xFFA07A,
  6441. 'lightseagreen': 0x20B2AA,
  6442. 'lightskyblue': 0x87CEFA,
  6443. 'lightslategray': 0x778899,
  6444. 'lightslategrey': 0x778899,
  6445. 'lightsteelblue': 0xB0C4DE,
  6446. 'lightyellow': 0xFFFFE0,
  6447. 'lime': 0x00FF00,
  6448. 'limegreen': 0x32CD32,
  6449. 'linen': 0xFAF0E6,
  6450. 'magenta': 0xFF00FF,
  6451. 'maroon': 0x800000,
  6452. 'mediumaquamarine': 0x66CDAA,
  6453. 'mediumblue': 0x0000CD,
  6454. 'mediumorchid': 0xBA55D3,
  6455. 'mediumpurple': 0x9370DB,
  6456. 'mediumseagreen': 0x3CB371,
  6457. 'mediumslateblue': 0x7B68EE,
  6458. 'mediumspringgreen': 0x00FA9A,
  6459. 'mediumturquoise': 0x48D1CC,
  6460. 'mediumvioletred': 0xC71585,
  6461. 'midnightblue': 0x191970,
  6462. 'mintcream': 0xF5FFFA,
  6463. 'mistyrose': 0xFFE4E1,
  6464. 'moccasin': 0xFFE4B5,
  6465. 'navajowhite': 0xFFDEAD,
  6466. 'navy': 0x000080,
  6467. 'oldlace': 0xFDF5E6,
  6468. 'olive': 0x808000,
  6469. 'olivedrab': 0x6B8E23,
  6470. 'orange': 0xFFA500,
  6471. 'orangered': 0xFF4500,
  6472. 'orchid': 0xDA70D6,
  6473. 'palegoldenrod': 0xEEE8AA,
  6474. 'palegreen': 0x98FB98,
  6475. 'paleturquoise': 0xAFEEEE,
  6476. 'palevioletred': 0xDB7093,
  6477. 'papayawhip': 0xFFEFD5,
  6478. 'peachpuff': 0xFFDAB9,
  6479. 'peru': 0xCD853F,
  6480. 'pink': 0xFFC0CB,
  6481. 'plum': 0xDDA0DD,
  6482. 'powderblue': 0xB0E0E6,
  6483. 'purple': 0x800080,
  6484. 'rebeccapurple': 0x663399,
  6485. 'red': 0xFF0000,
  6486. 'rosybrown': 0xBC8F8F,
  6487. 'royalblue': 0x4169E1,
  6488. 'saddlebrown': 0x8B4513,
  6489. 'salmon': 0xFA8072,
  6490. 'sandybrown': 0xF4A460,
  6491. 'seagreen': 0x2E8B57,
  6492. 'seashell': 0xFFF5EE,
  6493. 'sienna': 0xA0522D,
  6494. 'silver': 0xC0C0C0,
  6495. 'skyblue': 0x87CEEB,
  6496. 'slateblue': 0x6A5ACD,
  6497. 'slategray': 0x708090,
  6498. 'slategrey': 0x708090,
  6499. 'snow': 0xFFFAFA,
  6500. 'springgreen': 0x00FF7F,
  6501. 'steelblue': 0x4682B4,
  6502. 'tan': 0xD2B48C,
  6503. 'teal': 0x008080,
  6504. 'thistle': 0xD8BFD8,
  6505. 'tomato': 0xFF6347,
  6506. 'turquoise': 0x40E0D0,
  6507. 'violet': 0xEE82EE,
  6508. 'wheat': 0xF5DEB3,
  6509. 'white': 0xFFFFFF,
  6510. 'whitesmoke': 0xF5F5F5,
  6511. 'yellow': 0xFFFF00,
  6512. 'yellowgreen': 0x9ACD32
  6513. };
  6514. var _hslA = {
  6515. h: 0,
  6516. s: 0,
  6517. l: 0
  6518. };
  6519. var _hslB = {
  6520. h: 0,
  6521. s: 0,
  6522. l: 0
  6523. };
  6524. function Color(r, g, b) {
  6525. if (g === undefined && b === undefined) {
  6526. // r is THREE.Color, hex or string
  6527. return this.set(r);
  6528. }
  6529. return this.setRGB(r, g, b);
  6530. }
  6531. function hue2rgb(p, q, t) {
  6532. if (t < 0) t += 1;
  6533. if (t > 1) t -= 1;
  6534. if (t < 1 / 6) return p + (q - p) * 6 * t;
  6535. if (t < 1 / 2) return q;
  6536. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  6537. return p;
  6538. }
  6539. function SRGBToLinear(c) {
  6540. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  6541. }
  6542. function LinearToSRGB(c) {
  6543. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  6544. }
  6545. Object.assign(Color.prototype, {
  6546. isColor: true,
  6547. r: 1,
  6548. g: 1,
  6549. b: 1,
  6550. set: function (value) {
  6551. if (value && value.isColor) {
  6552. this.copy(value);
  6553. } else if (typeof value === 'number') {
  6554. this.setHex(value);
  6555. } else if (typeof value === 'string') {
  6556. this.setStyle(value);
  6557. }
  6558. return this;
  6559. },
  6560. setScalar: function (scalar) {
  6561. this.r = scalar;
  6562. this.g = scalar;
  6563. this.b = scalar;
  6564. return this;
  6565. },
  6566. setHex: function (hex) {
  6567. hex = Math.floor(hex);
  6568. this.r = (hex >> 16 & 255) / 255;
  6569. this.g = (hex >> 8 & 255) / 255;
  6570. this.b = (hex & 255) / 255;
  6571. return this;
  6572. },
  6573. setRGB: function (r, g, b) {
  6574. this.r = r;
  6575. this.g = g;
  6576. this.b = b;
  6577. return this;
  6578. },
  6579. setHSL: function (h, s, l) {
  6580. // h,s,l ranges are in 0.0 - 1.0
  6581. h = _Math.euclideanModulo(h, 1);
  6582. s = _Math.clamp(s, 0, 1);
  6583. l = _Math.clamp(l, 0, 1);
  6584. if (s === 0) {
  6585. this.r = this.g = this.b = l;
  6586. } else {
  6587. var p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  6588. var q = 2 * l - p;
  6589. this.r = hue2rgb(q, p, h + 1 / 3);
  6590. this.g = hue2rgb(q, p, h);
  6591. this.b = hue2rgb(q, p, h - 1 / 3);
  6592. }
  6593. return this;
  6594. },
  6595. setStyle: function (style) {
  6596. function handleAlpha(string) {
  6597. if (string === undefined) return;
  6598. if (parseFloat(string) < 1) {
  6599. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  6600. }
  6601. }
  6602. var m;
  6603. if (m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(style)) {
  6604. // rgb / hsl
  6605. var color;
  6606. var name = m[1];
  6607. var components = m[2];
  6608. switch (name) {
  6609. case 'rgb':
  6610. case 'rgba':
  6611. if (color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  6612. // rgb(255,0,0) rgba(255,0,0,0.5)
  6613. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  6614. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  6615. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  6616. handleAlpha(color[5]);
  6617. return this;
  6618. }
  6619. if (color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  6620. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  6621. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  6622. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  6623. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  6624. handleAlpha(color[5]);
  6625. return this;
  6626. }
  6627. break;
  6628. case 'hsl':
  6629. case 'hsla':
  6630. if (color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  6631. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  6632. var h = parseFloat(color[1]) / 360;
  6633. var s = parseInt(color[2], 10) / 100;
  6634. var l = parseInt(color[3], 10) / 100;
  6635. handleAlpha(color[5]);
  6636. return this.setHSL(h, s, l);
  6637. }
  6638. break;
  6639. }
  6640. } else if (m = /^\#([A-Fa-f0-9]+)$/.exec(style)) {
  6641. // hex color
  6642. var hex = m[1];
  6643. var size = hex.length;
  6644. if (size === 3) {
  6645. // #ff0
  6646. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  6647. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  6648. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  6649. return this;
  6650. } else if (size === 6) {
  6651. // #ff0000
  6652. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  6653. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  6654. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  6655. return this;
  6656. }
  6657. }
  6658. if (style && style.length > 0) {
  6659. // color keywords
  6660. var hex = _colorKeywords[style];
  6661. if (hex !== undefined) {
  6662. // red
  6663. this.setHex(hex);
  6664. } else {
  6665. // unknown color
  6666. console.warn('THREE.Color: Unknown color ' + style);
  6667. }
  6668. }
  6669. return this;
  6670. },
  6671. clone: function () {
  6672. return new this.constructor(this.r, this.g, this.b);
  6673. },
  6674. copy: function (color) {
  6675. this.r = color.r;
  6676. this.g = color.g;
  6677. this.b = color.b;
  6678. return this;
  6679. },
  6680. copyGammaToLinear: function (color, gammaFactor) {
  6681. if (gammaFactor === undefined) gammaFactor = 2.0;
  6682. this.r = Math.pow(color.r, gammaFactor);
  6683. this.g = Math.pow(color.g, gammaFactor);
  6684. this.b = Math.pow(color.b, gammaFactor);
  6685. return this;
  6686. },
  6687. copyLinearToGamma: function (color, gammaFactor) {
  6688. if (gammaFactor === undefined) gammaFactor = 2.0;
  6689. var safeInverse = gammaFactor > 0 ? 1.0 / gammaFactor : 1.0;
  6690. this.r = Math.pow(color.r, safeInverse);
  6691. this.g = Math.pow(color.g, safeInverse);
  6692. this.b = Math.pow(color.b, safeInverse);
  6693. return this;
  6694. },
  6695. convertGammaToLinear: function (gammaFactor) {
  6696. this.copyGammaToLinear(this, gammaFactor);
  6697. return this;
  6698. },
  6699. convertLinearToGamma: function (gammaFactor) {
  6700. this.copyLinearToGamma(this, gammaFactor);
  6701. return this;
  6702. },
  6703. copySRGBToLinear: function (color) {
  6704. this.r = SRGBToLinear(color.r);
  6705. this.g = SRGBToLinear(color.g);
  6706. this.b = SRGBToLinear(color.b);
  6707. return this;
  6708. },
  6709. copyLinearToSRGB: function (color) {
  6710. this.r = LinearToSRGB(color.r);
  6711. this.g = LinearToSRGB(color.g);
  6712. this.b = LinearToSRGB(color.b);
  6713. return this;
  6714. },
  6715. convertSRGBToLinear: function () {
  6716. this.copySRGBToLinear(this);
  6717. return this;
  6718. },
  6719. convertLinearToSRGB: function () {
  6720. this.copyLinearToSRGB(this);
  6721. return this;
  6722. },
  6723. getHex: function () {
  6724. return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
  6725. },
  6726. getHexString: function () {
  6727. return ('000000' + this.getHex().toString(16)).slice(-6);
  6728. },
  6729. getHSL: function (target) {
  6730. // h,s,l ranges are in 0.0 - 1.0
  6731. if (target === undefined) {
  6732. console.warn('THREE.Color: .getHSL() target is now required');
  6733. target = {
  6734. h: 0,
  6735. s: 0,
  6736. l: 0
  6737. };
  6738. }
  6739. var r = this.r,
  6740. g = this.g,
  6741. b = this.b;
  6742. var max = Math.max(r, g, b);
  6743. var min = Math.min(r, g, b);
  6744. var hue, saturation;
  6745. var lightness = (min + max) / 2.0;
  6746. if (min === max) {
  6747. hue = 0;
  6748. saturation = 0;
  6749. } else {
  6750. var delta = max - min;
  6751. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  6752. switch (max) {
  6753. case r:
  6754. hue = (g - b) / delta + (g < b ? 6 : 0);
  6755. break;
  6756. case g:
  6757. hue = (b - r) / delta + 2;
  6758. break;
  6759. case b:
  6760. hue = (r - g) / delta + 4;
  6761. break;
  6762. }
  6763. hue /= 6;
  6764. }
  6765. target.h = hue;
  6766. target.s = saturation;
  6767. target.l = lightness;
  6768. return target;
  6769. },
  6770. getStyle: function () {
  6771. return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
  6772. },
  6773. offsetHSL: function (h, s, l) {
  6774. this.getHSL(_hslA);
  6775. _hslA.h += h;
  6776. _hslA.s += s;
  6777. _hslA.l += l;
  6778. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  6779. return this;
  6780. },
  6781. add: function (color) {
  6782. this.r += color.r;
  6783. this.g += color.g;
  6784. this.b += color.b;
  6785. return this;
  6786. },
  6787. addColors: function (color1, color2) {
  6788. this.r = color1.r + color2.r;
  6789. this.g = color1.g + color2.g;
  6790. this.b = color1.b + color2.b;
  6791. return this;
  6792. },
  6793. addScalar: function (s) {
  6794. this.r += s;
  6795. this.g += s;
  6796. this.b += s;
  6797. return this;
  6798. },
  6799. sub: function (color) {
  6800. this.r = Math.max(0, this.r - color.r);
  6801. this.g = Math.max(0, this.g - color.g);
  6802. this.b = Math.max(0, this.b - color.b);
  6803. return this;
  6804. },
  6805. multiply: function (color) {
  6806. this.r *= color.r;
  6807. this.g *= color.g;
  6808. this.b *= color.b;
  6809. return this;
  6810. },
  6811. multiplyScalar: function (s) {
  6812. this.r *= s;
  6813. this.g *= s;
  6814. this.b *= s;
  6815. return this;
  6816. },
  6817. lerp: function (color, alpha) {
  6818. this.r += (color.r - this.r) * alpha;
  6819. this.g += (color.g - this.g) * alpha;
  6820. this.b += (color.b - this.b) * alpha;
  6821. return this;
  6822. },
  6823. lerpHSL: function (color, alpha) {
  6824. this.getHSL(_hslA);
  6825. color.getHSL(_hslB);
  6826. var h = _Math.lerp(_hslA.h, _hslB.h, alpha);
  6827. var s = _Math.lerp(_hslA.s, _hslB.s, alpha);
  6828. var l = _Math.lerp(_hslA.l, _hslB.l, alpha);
  6829. this.setHSL(h, s, l);
  6830. return this;
  6831. },
  6832. equals: function (c) {
  6833. return c.r === this.r && c.g === this.g && c.b === this.b;
  6834. },
  6835. fromArray: function (array, offset) {
  6836. if (offset === undefined) offset = 0;
  6837. this.r = array[offset];
  6838. this.g = array[offset + 1];
  6839. this.b = array[offset + 2];
  6840. return this;
  6841. },
  6842. toArray: function (array, offset) {
  6843. if (array === undefined) array = [];
  6844. if (offset === undefined) offset = 0;
  6845. array[offset] = this.r;
  6846. array[offset + 1] = this.g;
  6847. array[offset + 2] = this.b;
  6848. return array;
  6849. },
  6850. toJSON: function () {
  6851. return this.getHex();
  6852. }
  6853. });
  6854. /**
  6855. * @author mrdoob / http://mrdoob.com/
  6856. * @author alteredq / http://alteredqualia.com/
  6857. */
  6858. function Face3(a, b, c, normal, color, materialIndex) {
  6859. this.a = a;
  6860. this.b = b;
  6861. this.c = c;
  6862. this.normal = normal && normal.isVector3 ? normal : new Vector3();
  6863. this.vertexNormals = Array.isArray(normal) ? normal : [];
  6864. this.color = color && color.isColor ? color : new Color();
  6865. this.vertexColors = Array.isArray(color) ? color : [];
  6866. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  6867. }
  6868. Object.assign(Face3.prototype, {
  6869. clone: function () {
  6870. return new this.constructor().copy(this);
  6871. },
  6872. copy: function (source) {
  6873. this.a = source.a;
  6874. this.b = source.b;
  6875. this.c = source.c;
  6876. this.normal.copy(source.normal);
  6877. this.color.copy(source.color);
  6878. this.materialIndex = source.materialIndex;
  6879. for (var i = 0, il = source.vertexNormals.length; i < il; i++) {
  6880. this.vertexNormals[i] = source.vertexNormals[i].clone();
  6881. }
  6882. for (var i = 0, il = source.vertexColors.length; i < il; i++) {
  6883. this.vertexColors[i] = source.vertexColors[i].clone();
  6884. }
  6885. return this;
  6886. }
  6887. });
  6888. /**
  6889. * @author mrdoob / http://mrdoob.com/
  6890. * @author alteredq / http://alteredqualia.com/
  6891. */
  6892. var materialId = 0;
  6893. function Material() {
  6894. Object.defineProperty(this, 'id', {
  6895. value: materialId++
  6896. });
  6897. this.uuid = _Math.generateUUID();
  6898. this.name = '';
  6899. this.type = 'Material';
  6900. this.fog = true;
  6901. this.blending = NormalBlending;
  6902. this.side = FrontSide;
  6903. this.flatShading = false;
  6904. this.vertexTangents = false;
  6905. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  6906. this.opacity = 1;
  6907. this.transparent = false;
  6908. this.blendSrc = SrcAlphaFactor;
  6909. this.blendDst = OneMinusSrcAlphaFactor;
  6910. this.blendEquation = AddEquation;
  6911. this.blendSrcAlpha = null;
  6912. this.blendDstAlpha = null;
  6913. this.blendEquationAlpha = null;
  6914. this.depthFunc = LessEqualDepth;
  6915. this.depthTest = true;
  6916. this.depthWrite = true;
  6917. this.stencilWriteMask = 0xff;
  6918. this.stencilFunc = AlwaysStencilFunc;
  6919. this.stencilRef = 0;
  6920. this.stencilFuncMask = 0xff;
  6921. this.stencilFail = KeepStencilOp;
  6922. this.stencilZFail = KeepStencilOp;
  6923. this.stencilZPass = KeepStencilOp;
  6924. this.stencilWrite = false;
  6925. this.clippingPlanes = null;
  6926. this.clipIntersection = false;
  6927. this.clipShadows = false;
  6928. this.shadowSide = null;
  6929. this.colorWrite = true;
  6930. this.precision = null; // override the renderer's default precision for this material
  6931. this.polygonOffset = false;
  6932. this.polygonOffsetFactor = 0;
  6933. this.polygonOffsetUnits = 0;
  6934. this.dithering = false;
  6935. this.alphaTest = 0;
  6936. this.premultipliedAlpha = false;
  6937. this.visible = true;
  6938. this.toneMapped = true;
  6939. this.userData = {};
  6940. this.needsUpdate = true;
  6941. }
  6942. Material.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  6943. constructor: Material,
  6944. isMaterial: true,
  6945. onBeforeCompile: function () {},
  6946. setValues: function (values) {
  6947. if (values === undefined) return;
  6948. for (var key in values) {
  6949. var newValue = values[key];
  6950. if (newValue === undefined) {
  6951. console.warn("THREE.Material: '" + key + "' parameter is undefined.");
  6952. continue;
  6953. } // for backward compatability if shading is set in the constructor
  6954. if (key === 'shading') {
  6955. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  6956. this.flatShading = newValue === FlatShading ? true : false;
  6957. continue;
  6958. }
  6959. var currentValue = this[key];
  6960. if (currentValue === undefined) {
  6961. console.warn("THREE." + this.type + ": '" + key + "' is not a property of this material.");
  6962. continue;
  6963. }
  6964. if (currentValue && currentValue.isColor) {
  6965. currentValue.set(newValue);
  6966. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  6967. currentValue.copy(newValue);
  6968. } else {
  6969. this[key] = newValue;
  6970. }
  6971. }
  6972. },
  6973. toJSON: function (meta) {
  6974. var isRoot = meta === undefined || typeof meta === 'string';
  6975. if (isRoot) {
  6976. meta = {
  6977. textures: {},
  6978. images: {}
  6979. };
  6980. }
  6981. var data = {
  6982. metadata: {
  6983. version: 4.5,
  6984. type: 'Material',
  6985. generator: 'Material.toJSON'
  6986. }
  6987. }; // standard Material serialization
  6988. data.uuid = this.uuid;
  6989. data.type = this.type;
  6990. if (this.name !== '') data.name = this.name;
  6991. if (this.color && this.color.isColor) data.color = this.color.getHex();
  6992. if (this.roughness !== undefined) data.roughness = this.roughness;
  6993. if (this.metalness !== undefined) data.metalness = this.metalness;
  6994. if (this.sheen && this.sheen.isColor) data.sheen = this.sheen.getHex();
  6995. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  6996. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  6997. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  6998. if (this.shininess !== undefined) data.shininess = this.shininess;
  6999. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  7000. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  7001. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  7002. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  7003. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  7004. }
  7005. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  7006. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  7007. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  7008. if (this.lightMap && this.lightMap.isTexture) data.lightMap = this.lightMap.toJSON(meta).uuid;
  7009. if (this.aoMap && this.aoMap.isTexture) {
  7010. data.aoMap = this.aoMap.toJSON(meta).uuid;
  7011. data.aoMapIntensity = this.aoMapIntensity;
  7012. }
  7013. if (this.bumpMap && this.bumpMap.isTexture) {
  7014. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  7015. data.bumpScale = this.bumpScale;
  7016. }
  7017. if (this.normalMap && this.normalMap.isTexture) {
  7018. data.normalMap = this.normalMap.toJSON(meta).uuid;
  7019. data.normalMapType = this.normalMapType;
  7020. data.normalScale = this.normalScale.toArray();
  7021. }
  7022. if (this.displacementMap && this.displacementMap.isTexture) {
  7023. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  7024. data.displacementScale = this.displacementScale;
  7025. data.displacementBias = this.displacementBias;
  7026. }
  7027. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  7028. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  7029. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  7030. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  7031. if (this.envMap && this.envMap.isTexture) {
  7032. data.envMap = this.envMap.toJSON(meta).uuid;
  7033. data.reflectivity = this.reflectivity; // Scale behind envMap
  7034. data.refractionRatio = this.refractionRatio;
  7035. if (this.combine !== undefined) data.combine = this.combine;
  7036. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  7037. }
  7038. if (this.gradientMap && this.gradientMap.isTexture) {
  7039. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  7040. }
  7041. if (this.size !== undefined) data.size = this.size;
  7042. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  7043. if (this.blending !== NormalBlending) data.blending = this.blending;
  7044. if (this.flatShading === true) data.flatShading = this.flatShading;
  7045. if (this.side !== FrontSide) data.side = this.side;
  7046. if (this.vertexColors !== NoColors) data.vertexColors = this.vertexColors;
  7047. if (this.opacity < 1) data.opacity = this.opacity;
  7048. if (this.transparent === true) data.transparent = this.transparent;
  7049. data.depthFunc = this.depthFunc;
  7050. data.depthTest = this.depthTest;
  7051. data.depthWrite = this.depthWrite;
  7052. data.stencilWrite = this.stencilWrite;
  7053. data.stencilWriteMask = this.stencilWriteMask;
  7054. data.stencilFunc = this.stencilFunc;
  7055. data.stencilRef = this.stencilRef;
  7056. data.stencilFuncMask = this.stencilFuncMask;
  7057. data.stencilFail = this.stencilFail;
  7058. data.stencilZFail = this.stencilZFail;
  7059. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  7060. if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;
  7061. if (this.polygonOffset === true) data.polygonOffset = true;
  7062. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  7063. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  7064. if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;
  7065. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  7066. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  7067. if (this.scale !== undefined) data.scale = this.scale;
  7068. if (this.dithering === true) data.dithering = true;
  7069. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  7070. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  7071. if (this.wireframe === true) data.wireframe = this.wireframe;
  7072. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  7073. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  7074. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  7075. if (this.morphTargets === true) data.morphTargets = true;
  7076. if (this.morphNormals === true) data.morphNormals = true;
  7077. if (this.skinning === true) data.skinning = true;
  7078. if (this.visible === false) data.visible = false;
  7079. if (this.toneMapped === false) data.toneMapped = false;
  7080. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  7081. function extractFromCache(cache) {
  7082. var values = [];
  7083. for (var key in cache) {
  7084. var data = cache[key];
  7085. delete data.metadata;
  7086. values.push(data);
  7087. }
  7088. return values;
  7089. }
  7090. if (isRoot) {
  7091. var textures = extractFromCache(meta.textures);
  7092. var images = extractFromCache(meta.images);
  7093. if (textures.length > 0) data.textures = textures;
  7094. if (images.length > 0) data.images = images;
  7095. }
  7096. return data;
  7097. },
  7098. clone: function () {
  7099. return new this.constructor().copy(this);
  7100. },
  7101. copy: function (source) {
  7102. this.name = source.name;
  7103. this.fog = source.fog;
  7104. this.blending = source.blending;
  7105. this.side = source.side;
  7106. this.flatShading = source.flatShading;
  7107. this.vertexColors = source.vertexColors;
  7108. this.opacity = source.opacity;
  7109. this.transparent = source.transparent;
  7110. this.blendSrc = source.blendSrc;
  7111. this.blendDst = source.blendDst;
  7112. this.blendEquation = source.blendEquation;
  7113. this.blendSrcAlpha = source.blendSrcAlpha;
  7114. this.blendDstAlpha = source.blendDstAlpha;
  7115. this.blendEquationAlpha = source.blendEquationAlpha;
  7116. this.depthFunc = source.depthFunc;
  7117. this.depthTest = source.depthTest;
  7118. this.depthWrite = source.depthWrite;
  7119. this.stencilWrite = source.stencilWrite;
  7120. this.stencilWriteMask = source.stencilWriteMask;
  7121. this.stencilFunc = source.stencilFunc;
  7122. this.stencilRef = source.stencilRef;
  7123. this.stencilFuncMask = source.stencilFuncMask;
  7124. this.stencilFail = source.stencilFail;
  7125. this.stencilZFail = source.stencilZFail;
  7126. this.stencilZPass = source.stencilZPass;
  7127. this.colorWrite = source.colorWrite;
  7128. this.precision = source.precision;
  7129. this.polygonOffset = source.polygonOffset;
  7130. this.polygonOffsetFactor = source.polygonOffsetFactor;
  7131. this.polygonOffsetUnits = source.polygonOffsetUnits;
  7132. this.dithering = source.dithering;
  7133. this.alphaTest = source.alphaTest;
  7134. this.premultipliedAlpha = source.premultipliedAlpha;
  7135. this.visible = source.visible;
  7136. this.toneMapped = source.toneMapped;
  7137. this.userData = JSON.parse(JSON.stringify(source.userData));
  7138. this.clipShadows = source.clipShadows;
  7139. this.clipIntersection = source.clipIntersection;
  7140. var srcPlanes = source.clippingPlanes,
  7141. dstPlanes = null;
  7142. if (srcPlanes !== null) {
  7143. var n = srcPlanes.length;
  7144. dstPlanes = new Array(n);
  7145. for (var i = 0; i !== n; ++i) dstPlanes[i] = srcPlanes[i].clone();
  7146. }
  7147. this.clippingPlanes = dstPlanes;
  7148. this.shadowSide = source.shadowSide;
  7149. return this;
  7150. },
  7151. dispose: function () {
  7152. this.dispatchEvent({
  7153. type: 'dispose'
  7154. });
  7155. }
  7156. });
  7157. /**
  7158. * @author mrdoob / http://mrdoob.com/
  7159. * @author alteredq / http://alteredqualia.com/
  7160. *
  7161. * parameters = {
  7162. * color: <hex>,
  7163. * opacity: <float>,
  7164. * map: new THREE.Texture( <Image> ),
  7165. *
  7166. * lightMap: new THREE.Texture( <Image> ),
  7167. * lightMapIntensity: <float>
  7168. *
  7169. * aoMap: new THREE.Texture( <Image> ),
  7170. * aoMapIntensity: <float>
  7171. *
  7172. * specularMap: new THREE.Texture( <Image> ),
  7173. *
  7174. * alphaMap: new THREE.Texture( <Image> ),
  7175. *
  7176. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  7177. * combine: THREE.Multiply,
  7178. * reflectivity: <float>,
  7179. * refractionRatio: <float>,
  7180. *
  7181. * depthTest: <bool>,
  7182. * depthWrite: <bool>,
  7183. *
  7184. * wireframe: <boolean>,
  7185. * wireframeLinewidth: <float>,
  7186. *
  7187. * skinning: <bool>,
  7188. * morphTargets: <bool>
  7189. * }
  7190. */
  7191. function MeshBasicMaterial(parameters) {
  7192. Material.call(this);
  7193. this.type = 'MeshBasicMaterial';
  7194. this.color = new Color(0xffffff); // emissive
  7195. this.map = null;
  7196. this.lightMap = null;
  7197. this.lightMapIntensity = 1.0;
  7198. this.aoMap = null;
  7199. this.aoMapIntensity = 1.0;
  7200. this.specularMap = null;
  7201. this.alphaMap = null;
  7202. this.envMap = null;
  7203. this.combine = MultiplyOperation;
  7204. this.reflectivity = 1;
  7205. this.refractionRatio = 0.98;
  7206. this.wireframe = false;
  7207. this.wireframeLinewidth = 1;
  7208. this.wireframeLinecap = 'round';
  7209. this.wireframeLinejoin = 'round';
  7210. this.skinning = false;
  7211. this.morphTargets = false;
  7212. this.setValues(parameters);
  7213. }
  7214. MeshBasicMaterial.prototype = Object.create(Material.prototype);
  7215. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  7216. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  7217. MeshBasicMaterial.prototype.copy = function (source) {
  7218. Material.prototype.copy.call(this, source);
  7219. this.color.copy(source.color);
  7220. this.map = source.map;
  7221. this.lightMap = source.lightMap;
  7222. this.lightMapIntensity = source.lightMapIntensity;
  7223. this.aoMap = source.aoMap;
  7224. this.aoMapIntensity = source.aoMapIntensity;
  7225. this.specularMap = source.specularMap;
  7226. this.alphaMap = source.alphaMap;
  7227. this.envMap = source.envMap;
  7228. this.combine = source.combine;
  7229. this.reflectivity = source.reflectivity;
  7230. this.refractionRatio = source.refractionRatio;
  7231. this.wireframe = source.wireframe;
  7232. this.wireframeLinewidth = source.wireframeLinewidth;
  7233. this.wireframeLinecap = source.wireframeLinecap;
  7234. this.wireframeLinejoin = source.wireframeLinejoin;
  7235. this.skinning = source.skinning;
  7236. this.morphTargets = source.morphTargets;
  7237. return this;
  7238. };
  7239. /**
  7240. * @author mrdoob / http://mrdoob.com/
  7241. */
  7242. function BufferAttribute(array, itemSize, normalized) {
  7243. if (Array.isArray(array)) {
  7244. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  7245. }
  7246. this.name = '';
  7247. this.array = array;
  7248. this.itemSize = itemSize;
  7249. this.count = array !== undefined ? array.length / itemSize : 0;
  7250. this.normalized = normalized === true;
  7251. this.dynamic = false;
  7252. this.updateRange = {
  7253. offset: 0,
  7254. count: -1
  7255. };
  7256. this.version = 0;
  7257. }
  7258. Object.defineProperty(BufferAttribute.prototype, 'needsUpdate', {
  7259. set: function (value) {
  7260. if (value === true) this.version++;
  7261. }
  7262. });
  7263. Object.assign(BufferAttribute.prototype, {
  7264. isBufferAttribute: true,
  7265. onUploadCallback: function () {},
  7266. setDynamic: function (value) {
  7267. this.dynamic = value;
  7268. return this;
  7269. },
  7270. copy: function (source) {
  7271. this.name = source.name;
  7272. this.array = new source.array.constructor(source.array);
  7273. this.itemSize = source.itemSize;
  7274. this.count = source.count;
  7275. this.normalized = source.normalized;
  7276. this.dynamic = source.dynamic;
  7277. return this;
  7278. },
  7279. copyAt: function (index1, attribute, index2) {
  7280. index1 *= this.itemSize;
  7281. index2 *= attribute.itemSize;
  7282. for (var i = 0, l = this.itemSize; i < l; i++) {
  7283. this.array[index1 + i] = attribute.array[index2 + i];
  7284. }
  7285. return this;
  7286. },
  7287. copyArray: function (array) {
  7288. this.array.set(array);
  7289. return this;
  7290. },
  7291. copyColorsArray: function (colors) {
  7292. var array = this.array,
  7293. offset = 0;
  7294. for (var i = 0, l = colors.length; i < l; i++) {
  7295. var color = colors[i];
  7296. if (color === undefined) {
  7297. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  7298. color = new Color();
  7299. }
  7300. array[offset++] = color.r;
  7301. array[offset++] = color.g;
  7302. array[offset++] = color.b;
  7303. }
  7304. return this;
  7305. },
  7306. copyVector2sArray: function (vectors) {
  7307. var array = this.array,
  7308. offset = 0;
  7309. for (var i = 0, l = vectors.length; i < l; i++) {
  7310. var vector = vectors[i];
  7311. if (vector === undefined) {
  7312. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  7313. vector = new Vector2();
  7314. }
  7315. array[offset++] = vector.x;
  7316. array[offset++] = vector.y;
  7317. }
  7318. return this;
  7319. },
  7320. copyVector3sArray: function (vectors) {
  7321. var array = this.array,
  7322. offset = 0;
  7323. for (var i = 0, l = vectors.length; i < l; i++) {
  7324. var vector = vectors[i];
  7325. if (vector === undefined) {
  7326. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  7327. vector = new Vector3();
  7328. }
  7329. array[offset++] = vector.x;
  7330. array[offset++] = vector.y;
  7331. array[offset++] = vector.z;
  7332. }
  7333. return this;
  7334. },
  7335. copyVector4sArray: function (vectors) {
  7336. var array = this.array,
  7337. offset = 0;
  7338. for (var i = 0, l = vectors.length; i < l; i++) {
  7339. var vector = vectors[i];
  7340. if (vector === undefined) {
  7341. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  7342. vector = new Vector4();
  7343. }
  7344. array[offset++] = vector.x;
  7345. array[offset++] = vector.y;
  7346. array[offset++] = vector.z;
  7347. array[offset++] = vector.w;
  7348. }
  7349. return this;
  7350. },
  7351. set: function (value, offset) {
  7352. if (offset === undefined) offset = 0;
  7353. this.array.set(value, offset);
  7354. return this;
  7355. },
  7356. getX: function (index) {
  7357. return this.array[index * this.itemSize];
  7358. },
  7359. setX: function (index, x) {
  7360. this.array[index * this.itemSize] = x;
  7361. return this;
  7362. },
  7363. getY: function (index) {
  7364. return this.array[index * this.itemSize + 1];
  7365. },
  7366. setY: function (index, y) {
  7367. this.array[index * this.itemSize + 1] = y;
  7368. return this;
  7369. },
  7370. getZ: function (index) {
  7371. return this.array[index * this.itemSize + 2];
  7372. },
  7373. setZ: function (index, z) {
  7374. this.array[index * this.itemSize + 2] = z;
  7375. return this;
  7376. },
  7377. getW: function (index) {
  7378. return this.array[index * this.itemSize + 3];
  7379. },
  7380. setW: function (index, w) {
  7381. this.array[index * this.itemSize + 3] = w;
  7382. return this;
  7383. },
  7384. setXY: function (index, x, y) {
  7385. index *= this.itemSize;
  7386. this.array[index + 0] = x;
  7387. this.array[index + 1] = y;
  7388. return this;
  7389. },
  7390. setXYZ: function (index, x, y, z) {
  7391. index *= this.itemSize;
  7392. this.array[index + 0] = x;
  7393. this.array[index + 1] = y;
  7394. this.array[index + 2] = z;
  7395. return this;
  7396. },
  7397. setXYZW: function (index, x, y, z, w) {
  7398. index *= this.itemSize;
  7399. this.array[index + 0] = x;
  7400. this.array[index + 1] = y;
  7401. this.array[index + 2] = z;
  7402. this.array[index + 3] = w;
  7403. return this;
  7404. },
  7405. onUpload: function (callback) {
  7406. this.onUploadCallback = callback;
  7407. return this;
  7408. },
  7409. clone: function () {
  7410. return new this.constructor(this.array, this.itemSize).copy(this);
  7411. },
  7412. toJSON: function () {
  7413. return {
  7414. itemSize: this.itemSize,
  7415. type: this.array.constructor.name,
  7416. array: Array.prototype.slice.call(this.array),
  7417. normalized: this.normalized
  7418. };
  7419. }
  7420. }); //
  7421. function Int8BufferAttribute(array, itemSize, normalized) {
  7422. BufferAttribute.call(this, new Int8Array(array), itemSize, normalized);
  7423. }
  7424. Int8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7425. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  7426. function Uint8BufferAttribute(array, itemSize, normalized) {
  7427. BufferAttribute.call(this, new Uint8Array(array), itemSize, normalized);
  7428. }
  7429. Uint8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7430. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  7431. function Uint8ClampedBufferAttribute(array, itemSize, normalized) {
  7432. BufferAttribute.call(this, new Uint8ClampedArray(array), itemSize, normalized);
  7433. }
  7434. Uint8ClampedBufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7435. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  7436. function Int16BufferAttribute(array, itemSize, normalized) {
  7437. BufferAttribute.call(this, new Int16Array(array), itemSize, normalized);
  7438. }
  7439. Int16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7440. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  7441. function Uint16BufferAttribute(array, itemSize, normalized) {
  7442. BufferAttribute.call(this, new Uint16Array(array), itemSize, normalized);
  7443. }
  7444. Uint16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7445. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  7446. function Int32BufferAttribute(array, itemSize, normalized) {
  7447. BufferAttribute.call(this, new Int32Array(array), itemSize, normalized);
  7448. }
  7449. Int32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7450. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  7451. function Uint32BufferAttribute(array, itemSize, normalized) {
  7452. BufferAttribute.call(this, new Uint32Array(array), itemSize, normalized);
  7453. }
  7454. Uint32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7455. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  7456. function Float32BufferAttribute(array, itemSize, normalized) {
  7457. BufferAttribute.call(this, new Float32Array(array), itemSize, normalized);
  7458. }
  7459. Float32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7460. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  7461. function Float64BufferAttribute(array, itemSize, normalized) {
  7462. BufferAttribute.call(this, new Float64Array(array), itemSize, normalized);
  7463. }
  7464. Float64BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7465. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  7466. /**
  7467. * @author mrdoob / http://mrdoob.com/
  7468. */
  7469. function DirectGeometry() {
  7470. this.vertices = [];
  7471. this.normals = [];
  7472. this.colors = [];
  7473. this.uvs = [];
  7474. this.uvs2 = [];
  7475. this.groups = [];
  7476. this.morphTargets = {};
  7477. this.skinWeights = [];
  7478. this.skinIndices = []; // this.lineDistances = [];
  7479. this.boundingBox = null;
  7480. this.boundingSphere = null; // update flags
  7481. this.verticesNeedUpdate = false;
  7482. this.normalsNeedUpdate = false;
  7483. this.colorsNeedUpdate = false;
  7484. this.uvsNeedUpdate = false;
  7485. this.groupsNeedUpdate = false;
  7486. }
  7487. Object.assign(DirectGeometry.prototype, {
  7488. computeGroups: function (geometry) {
  7489. var group;
  7490. var groups = [];
  7491. var materialIndex = undefined;
  7492. var faces = geometry.faces;
  7493. for (var i = 0; i < faces.length; i++) {
  7494. var face = faces[i]; // materials
  7495. if (face.materialIndex !== materialIndex) {
  7496. materialIndex = face.materialIndex;
  7497. if (group !== undefined) {
  7498. group.count = i * 3 - group.start;
  7499. groups.push(group);
  7500. }
  7501. group = {
  7502. start: i * 3,
  7503. materialIndex: materialIndex
  7504. };
  7505. }
  7506. }
  7507. if (group !== undefined) {
  7508. group.count = i * 3 - group.start;
  7509. groups.push(group);
  7510. }
  7511. this.groups = groups;
  7512. },
  7513. fromGeometry: function (geometry) {
  7514. var faces = geometry.faces;
  7515. var vertices = geometry.vertices;
  7516. var faceVertexUvs = geometry.faceVertexUvs;
  7517. var hasFaceVertexUv = faceVertexUvs[0] && faceVertexUvs[0].length > 0;
  7518. var hasFaceVertexUv2 = faceVertexUvs[1] && faceVertexUvs[1].length > 0; // morphs
  7519. var morphTargets = geometry.morphTargets;
  7520. var morphTargetsLength = morphTargets.length;
  7521. var morphTargetsPosition;
  7522. if (morphTargetsLength > 0) {
  7523. morphTargetsPosition = [];
  7524. for (var i = 0; i < morphTargetsLength; i++) {
  7525. morphTargetsPosition[i] = {
  7526. name: morphTargets[i].name,
  7527. data: []
  7528. };
  7529. }
  7530. this.morphTargets.position = morphTargetsPosition;
  7531. }
  7532. var morphNormals = geometry.morphNormals;
  7533. var morphNormalsLength = morphNormals.length;
  7534. var morphTargetsNormal;
  7535. if (morphNormalsLength > 0) {
  7536. morphTargetsNormal = [];
  7537. for (var i = 0; i < morphNormalsLength; i++) {
  7538. morphTargetsNormal[i] = {
  7539. name: morphNormals[i].name,
  7540. data: []
  7541. };
  7542. }
  7543. this.morphTargets.normal = morphTargetsNormal;
  7544. } // skins
  7545. var skinIndices = geometry.skinIndices;
  7546. var skinWeights = geometry.skinWeights;
  7547. var hasSkinIndices = skinIndices.length === vertices.length;
  7548. var hasSkinWeights = skinWeights.length === vertices.length; //
  7549. if (vertices.length > 0 && faces.length === 0) {
  7550. console.error('THREE.DirectGeometry: Faceless geometries are not supported.');
  7551. }
  7552. for (var i = 0; i < faces.length; i++) {
  7553. var face = faces[i];
  7554. this.vertices.push(vertices[face.a], vertices[face.b], vertices[face.c]);
  7555. var vertexNormals = face.vertexNormals;
  7556. if (vertexNormals.length === 3) {
  7557. this.normals.push(vertexNormals[0], vertexNormals[1], vertexNormals[2]);
  7558. } else {
  7559. var normal = face.normal;
  7560. this.normals.push(normal, normal, normal);
  7561. }
  7562. var vertexColors = face.vertexColors;
  7563. if (vertexColors.length === 3) {
  7564. this.colors.push(vertexColors[0], vertexColors[1], vertexColors[2]);
  7565. } else {
  7566. var color = face.color;
  7567. this.colors.push(color, color, color);
  7568. }
  7569. if (hasFaceVertexUv === true) {
  7570. var vertexUvs = faceVertexUvs[0][i];
  7571. if (vertexUvs !== undefined) {
  7572. this.uvs.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]);
  7573. } else {
  7574. console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i);
  7575. this.uvs.push(new Vector2(), new Vector2(), new Vector2());
  7576. }
  7577. }
  7578. if (hasFaceVertexUv2 === true) {
  7579. var vertexUvs = faceVertexUvs[1][i];
  7580. if (vertexUvs !== undefined) {
  7581. this.uvs2.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]);
  7582. } else {
  7583. console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i);
  7584. this.uvs2.push(new Vector2(), new Vector2(), new Vector2());
  7585. }
  7586. } // morphs
  7587. for (var j = 0; j < morphTargetsLength; j++) {
  7588. var morphTarget = morphTargets[j].vertices;
  7589. morphTargetsPosition[j].data.push(morphTarget[face.a], morphTarget[face.b], morphTarget[face.c]);
  7590. }
  7591. for (var j = 0; j < morphNormalsLength; j++) {
  7592. var morphNormal = morphNormals[j].vertexNormals[i];
  7593. morphTargetsNormal[j].data.push(morphNormal.a, morphNormal.b, morphNormal.c);
  7594. } // skins
  7595. if (hasSkinIndices) {
  7596. this.skinIndices.push(skinIndices[face.a], skinIndices[face.b], skinIndices[face.c]);
  7597. }
  7598. if (hasSkinWeights) {
  7599. this.skinWeights.push(skinWeights[face.a], skinWeights[face.b], skinWeights[face.c]);
  7600. }
  7601. }
  7602. this.computeGroups(geometry);
  7603. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  7604. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  7605. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  7606. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  7607. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  7608. if (geometry.boundingSphere !== null) {
  7609. this.boundingSphere = geometry.boundingSphere.clone();
  7610. }
  7611. if (geometry.boundingBox !== null) {
  7612. this.boundingBox = geometry.boundingBox.clone();
  7613. }
  7614. return this;
  7615. }
  7616. });
  7617. /**
  7618. * @author mrdoob / http://mrdoob.com/
  7619. */
  7620. function arrayMax(array) {
  7621. if (array.length === 0) return -Infinity;
  7622. var max = array[0];
  7623. for (var i = 1, l = array.length; i < l; ++i) {
  7624. if (array[i] > max) max = array[i];
  7625. }
  7626. return max;
  7627. }
  7628. /**
  7629. * @author alteredq / http://alteredqualia.com/
  7630. * @author mrdoob / http://mrdoob.com/
  7631. */
  7632. var _bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id
  7633. var _m1$2 = new Matrix4();
  7634. var _obj = new Object3D();
  7635. var _offset = new Vector3();
  7636. var _box$1 = new Box3();
  7637. var _boxMorphTargets = new Box3();
  7638. var _vector$4 = new Vector3();
  7639. function BufferGeometry() {
  7640. Object.defineProperty(this, 'id', {
  7641. value: _bufferGeometryId += 2
  7642. });
  7643. this.uuid = _Math.generateUUID();
  7644. this.name = '';
  7645. this.type = 'BufferGeometry';
  7646. this.index = null;
  7647. this.attributes = {};
  7648. this.morphAttributes = {};
  7649. this.groups = [];
  7650. this.boundingBox = null;
  7651. this.boundingSphere = null;
  7652. this.drawRange = {
  7653. start: 0,
  7654. count: Infinity
  7655. };
  7656. this.userData = {};
  7657. }
  7658. BufferGeometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  7659. constructor: BufferGeometry,
  7660. isBufferGeometry: true,
  7661. getIndex: function () {
  7662. return this.index;
  7663. },
  7664. setIndex: function (index) {
  7665. if (Array.isArray(index)) {
  7666. this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  7667. } else {
  7668. this.index = index;
  7669. }
  7670. },
  7671. addAttribute: function (name, attribute) {
  7672. if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
  7673. console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
  7674. return this.addAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
  7675. }
  7676. if (name === 'index') {
  7677. console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
  7678. this.setIndex(attribute);
  7679. return this;
  7680. }
  7681. return this.setAttribute(name, attribute);
  7682. },
  7683. getAttribute: function (name) {
  7684. return this.attributes[name];
  7685. },
  7686. setAttribute: function (name, attribute) {
  7687. this.attributes[name] = attribute;
  7688. return this;
  7689. },
  7690. removeAttribute: function (name) {
  7691. delete this.attributes[name];
  7692. return this;
  7693. },
  7694. addGroup: function (start, count, materialIndex) {
  7695. this.groups.push({
  7696. start: start,
  7697. count: count,
  7698. materialIndex: materialIndex !== undefined ? materialIndex : 0
  7699. });
  7700. },
  7701. clearGroups: function () {
  7702. this.groups = [];
  7703. },
  7704. setDrawRange: function (start, count) {
  7705. this.drawRange.start = start;
  7706. this.drawRange.count = count;
  7707. },
  7708. applyMatrix: function (matrix) {
  7709. var position = this.attributes.position;
  7710. if (position !== undefined) {
  7711. matrix.applyToBufferAttribute(position);
  7712. position.needsUpdate = true;
  7713. }
  7714. var normal = this.attributes.normal;
  7715. if (normal !== undefined) {
  7716. var normalMatrix = new Matrix3().getNormalMatrix(matrix);
  7717. normalMatrix.applyToBufferAttribute(normal);
  7718. normal.needsUpdate = true;
  7719. }
  7720. var tangent = this.attributes.tangent;
  7721. if (tangent !== undefined) {
  7722. var normalMatrix = new Matrix3().getNormalMatrix(matrix); // Tangent is vec4, but the '.w' component is a sign value (+1/-1).
  7723. normalMatrix.applyToBufferAttribute(tangent);
  7724. tangent.needsUpdate = true;
  7725. }
  7726. if (this.boundingBox !== null) {
  7727. this.computeBoundingBox();
  7728. }
  7729. if (this.boundingSphere !== null) {
  7730. this.computeBoundingSphere();
  7731. }
  7732. return this;
  7733. },
  7734. rotateX: function (angle) {
  7735. // rotate geometry around world x-axis
  7736. _m1$2.makeRotationX(angle);
  7737. this.applyMatrix(_m1$2);
  7738. return this;
  7739. },
  7740. rotateY: function (angle) {
  7741. // rotate geometry around world y-axis
  7742. _m1$2.makeRotationY(angle);
  7743. this.applyMatrix(_m1$2);
  7744. return this;
  7745. },
  7746. rotateZ: function (angle) {
  7747. // rotate geometry around world z-axis
  7748. _m1$2.makeRotationZ(angle);
  7749. this.applyMatrix(_m1$2);
  7750. return this;
  7751. },
  7752. translate: function (x, y, z) {
  7753. // translate geometry
  7754. _m1$2.makeTranslation(x, y, z);
  7755. this.applyMatrix(_m1$2);
  7756. return this;
  7757. },
  7758. scale: function (x, y, z) {
  7759. // scale geometry
  7760. _m1$2.makeScale(x, y, z);
  7761. this.applyMatrix(_m1$2);
  7762. return this;
  7763. },
  7764. lookAt: function (vector) {
  7765. _obj.lookAt(vector);
  7766. _obj.updateMatrix();
  7767. this.applyMatrix(_obj.matrix);
  7768. return this;
  7769. },
  7770. center: function () {
  7771. this.computeBoundingBox();
  7772. this.boundingBox.getCenter(_offset).negate();
  7773. this.translate(_offset.x, _offset.y, _offset.z);
  7774. return this;
  7775. },
  7776. setFromObject: function (object) {
  7777. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  7778. var geometry = object.geometry;
  7779. if (object.isPoints || object.isLine) {
  7780. var positions = new Float32BufferAttribute(geometry.vertices.length * 3, 3);
  7781. var colors = new Float32BufferAttribute(geometry.colors.length * 3, 3);
  7782. this.addAttribute('position', positions.copyVector3sArray(geometry.vertices));
  7783. this.addAttribute('color', colors.copyColorsArray(geometry.colors));
  7784. if (geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length) {
  7785. var lineDistances = new Float32BufferAttribute(geometry.lineDistances.length, 1);
  7786. this.addAttribute('lineDistance', lineDistances.copyArray(geometry.lineDistances));
  7787. }
  7788. if (geometry.boundingSphere !== null) {
  7789. this.boundingSphere = geometry.boundingSphere.clone();
  7790. }
  7791. if (geometry.boundingBox !== null) {
  7792. this.boundingBox = geometry.boundingBox.clone();
  7793. }
  7794. } else if (object.isMesh) {
  7795. if (geometry && geometry.isGeometry) {
  7796. this.fromGeometry(geometry);
  7797. }
  7798. }
  7799. return this;
  7800. },
  7801. setFromPoints: function (points) {
  7802. var position = [];
  7803. for (var i = 0, l = points.length; i < l; i++) {
  7804. var point = points[i];
  7805. position.push(point.x, point.y, point.z || 0);
  7806. }
  7807. this.addAttribute('position', new Float32BufferAttribute(position, 3));
  7808. return this;
  7809. },
  7810. updateFromObject: function (object) {
  7811. var geometry = object.geometry;
  7812. if (object.isMesh) {
  7813. var direct = geometry.__directGeometry;
  7814. if (geometry.elementsNeedUpdate === true) {
  7815. direct = undefined;
  7816. geometry.elementsNeedUpdate = false;
  7817. }
  7818. if (direct === undefined) {
  7819. return this.fromGeometry(geometry);
  7820. }
  7821. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  7822. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  7823. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  7824. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  7825. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  7826. geometry.verticesNeedUpdate = false;
  7827. geometry.normalsNeedUpdate = false;
  7828. geometry.colorsNeedUpdate = false;
  7829. geometry.uvsNeedUpdate = false;
  7830. geometry.groupsNeedUpdate = false;
  7831. geometry = direct;
  7832. }
  7833. var attribute;
  7834. if (geometry.verticesNeedUpdate === true) {
  7835. attribute = this.attributes.position;
  7836. if (attribute !== undefined) {
  7837. attribute.copyVector3sArray(geometry.vertices);
  7838. attribute.needsUpdate = true;
  7839. }
  7840. geometry.verticesNeedUpdate = false;
  7841. }
  7842. if (geometry.normalsNeedUpdate === true) {
  7843. attribute = this.attributes.normal;
  7844. if (attribute !== undefined) {
  7845. attribute.copyVector3sArray(geometry.normals);
  7846. attribute.needsUpdate = true;
  7847. }
  7848. geometry.normalsNeedUpdate = false;
  7849. }
  7850. if (geometry.colorsNeedUpdate === true) {
  7851. attribute = this.attributes.color;
  7852. if (attribute !== undefined) {
  7853. attribute.copyColorsArray(geometry.colors);
  7854. attribute.needsUpdate = true;
  7855. }
  7856. geometry.colorsNeedUpdate = false;
  7857. }
  7858. if (geometry.uvsNeedUpdate) {
  7859. attribute = this.attributes.uv;
  7860. if (attribute !== undefined) {
  7861. attribute.copyVector2sArray(geometry.uvs);
  7862. attribute.needsUpdate = true;
  7863. }
  7864. geometry.uvsNeedUpdate = false;
  7865. }
  7866. if (geometry.lineDistancesNeedUpdate) {
  7867. attribute = this.attributes.lineDistance;
  7868. if (attribute !== undefined) {
  7869. attribute.copyArray(geometry.lineDistances);
  7870. attribute.needsUpdate = true;
  7871. }
  7872. geometry.lineDistancesNeedUpdate = false;
  7873. }
  7874. if (geometry.groupsNeedUpdate) {
  7875. geometry.computeGroups(object.geometry);
  7876. this.groups = geometry.groups;
  7877. geometry.groupsNeedUpdate = false;
  7878. }
  7879. return this;
  7880. },
  7881. fromGeometry: function (geometry) {
  7882. geometry.__directGeometry = new DirectGeometry().fromGeometry(geometry);
  7883. return this.fromDirectGeometry(geometry.__directGeometry);
  7884. },
  7885. fromDirectGeometry: function (geometry) {
  7886. var positions = new Float32Array(geometry.vertices.length * 3);
  7887. this.addAttribute('position', new BufferAttribute(positions, 3).copyVector3sArray(geometry.vertices));
  7888. if (geometry.normals.length > 0) {
  7889. var normals = new Float32Array(geometry.normals.length * 3);
  7890. this.addAttribute('normal', new BufferAttribute(normals, 3).copyVector3sArray(geometry.normals));
  7891. }
  7892. if (geometry.colors.length > 0) {
  7893. var colors = new Float32Array(geometry.colors.length * 3);
  7894. this.addAttribute('color', new BufferAttribute(colors, 3).copyColorsArray(geometry.colors));
  7895. }
  7896. if (geometry.uvs.length > 0) {
  7897. var uvs = new Float32Array(geometry.uvs.length * 2);
  7898. this.addAttribute('uv', new BufferAttribute(uvs, 2).copyVector2sArray(geometry.uvs));
  7899. }
  7900. if (geometry.uvs2.length > 0) {
  7901. var uvs2 = new Float32Array(geometry.uvs2.length * 2);
  7902. this.addAttribute('uv2', new BufferAttribute(uvs2, 2).copyVector2sArray(geometry.uvs2));
  7903. } // groups
  7904. this.groups = geometry.groups; // morphs
  7905. for (var name in geometry.morphTargets) {
  7906. var array = [];
  7907. var morphTargets = geometry.morphTargets[name];
  7908. for (var i = 0, l = morphTargets.length; i < l; i++) {
  7909. var morphTarget = morphTargets[i];
  7910. var attribute = new Float32BufferAttribute(morphTarget.data.length * 3, 3);
  7911. attribute.name = morphTarget.name;
  7912. array.push(attribute.copyVector3sArray(morphTarget.data));
  7913. }
  7914. this.morphAttributes[name] = array;
  7915. } // skinning
  7916. if (geometry.skinIndices.length > 0) {
  7917. var skinIndices = new Float32BufferAttribute(geometry.skinIndices.length * 4, 4);
  7918. this.addAttribute('skinIndex', skinIndices.copyVector4sArray(geometry.skinIndices));
  7919. }
  7920. if (geometry.skinWeights.length > 0) {
  7921. var skinWeights = new Float32BufferAttribute(geometry.skinWeights.length * 4, 4);
  7922. this.addAttribute('skinWeight', skinWeights.copyVector4sArray(geometry.skinWeights));
  7923. } //
  7924. if (geometry.boundingSphere !== null) {
  7925. this.boundingSphere = geometry.boundingSphere.clone();
  7926. }
  7927. if (geometry.boundingBox !== null) {
  7928. this.boundingBox = geometry.boundingBox.clone();
  7929. }
  7930. return this;
  7931. },
  7932. computeBoundingBox: function () {
  7933. if (this.boundingBox === null) {
  7934. this.boundingBox = new Box3();
  7935. }
  7936. var position = this.attributes.position;
  7937. var morphAttributesPosition = this.morphAttributes.position;
  7938. if (position !== undefined) {
  7939. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  7940. if (morphAttributesPosition) {
  7941. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7942. var morphAttribute = morphAttributesPosition[i];
  7943. _box$1.setFromBufferAttribute(morphAttribute);
  7944. this.boundingBox.expandByPoint(_box$1.min);
  7945. this.boundingBox.expandByPoint(_box$1.max);
  7946. }
  7947. }
  7948. } else {
  7949. this.boundingBox.makeEmpty();
  7950. }
  7951. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  7952. console.error('THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  7953. }
  7954. },
  7955. computeBoundingSphere: function () {
  7956. if (this.boundingSphere === null) {
  7957. this.boundingSphere = new Sphere();
  7958. }
  7959. var position = this.attributes.position;
  7960. var morphAttributesPosition = this.morphAttributes.position;
  7961. if (position) {
  7962. // first, find the center of the bounding sphere
  7963. var center = this.boundingSphere.center;
  7964. _box$1.setFromBufferAttribute(position); // process morph attributes if present
  7965. if (morphAttributesPosition) {
  7966. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7967. var morphAttribute = morphAttributesPosition[i];
  7968. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  7969. _box$1.expandByPoint(_boxMorphTargets.min);
  7970. _box$1.expandByPoint(_boxMorphTargets.max);
  7971. }
  7972. }
  7973. _box$1.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  7974. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  7975. var maxRadiusSq = 0;
  7976. for (var i = 0, il = position.count; i < il; i++) {
  7977. _vector$4.fromBufferAttribute(position, i);
  7978. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
  7979. } // process morph attributes if present
  7980. if (morphAttributesPosition) {
  7981. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7982. var morphAttribute = morphAttributesPosition[i];
  7983. for (var j = 0, jl = morphAttribute.count; j < jl; j++) {
  7984. _vector$4.fromBufferAttribute(morphAttribute, j);
  7985. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
  7986. }
  7987. }
  7988. }
  7989. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  7990. if (isNaN(this.boundingSphere.radius)) {
  7991. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  7992. }
  7993. }
  7994. },
  7995. computeFaceNormals: function () {// backwards compatibility
  7996. },
  7997. computeVertexNormals: function () {
  7998. var index = this.index;
  7999. var attributes = this.attributes;
  8000. if (attributes.position) {
  8001. var positions = attributes.position.array;
  8002. if (attributes.normal === undefined) {
  8003. this.addAttribute('normal', new BufferAttribute(new Float32Array(positions.length), 3));
  8004. } else {
  8005. // reset existing normals to zero
  8006. var array = attributes.normal.array;
  8007. for (var i = 0, il = array.length; i < il; i++) {
  8008. array[i] = 0;
  8009. }
  8010. }
  8011. var normals = attributes.normal.array;
  8012. var vA, vB, vC;
  8013. var pA = new Vector3(),
  8014. pB = new Vector3(),
  8015. pC = new Vector3();
  8016. var cb = new Vector3(),
  8017. ab = new Vector3(); // indexed elements
  8018. if (index) {
  8019. var indices = index.array;
  8020. for (var i = 0, il = index.count; i < il; i += 3) {
  8021. vA = indices[i + 0] * 3;
  8022. vB = indices[i + 1] * 3;
  8023. vC = indices[i + 2] * 3;
  8024. pA.fromArray(positions, vA);
  8025. pB.fromArray(positions, vB);
  8026. pC.fromArray(positions, vC);
  8027. cb.subVectors(pC, pB);
  8028. ab.subVectors(pA, pB);
  8029. cb.cross(ab);
  8030. normals[vA] += cb.x;
  8031. normals[vA + 1] += cb.y;
  8032. normals[vA + 2] += cb.z;
  8033. normals[vB] += cb.x;
  8034. normals[vB + 1] += cb.y;
  8035. normals[vB + 2] += cb.z;
  8036. normals[vC] += cb.x;
  8037. normals[vC + 1] += cb.y;
  8038. normals[vC + 2] += cb.z;
  8039. }
  8040. } else {
  8041. // non-indexed elements (unconnected triangle soup)
  8042. for (var i = 0, il = positions.length; i < il; i += 9) {
  8043. pA.fromArray(positions, i);
  8044. pB.fromArray(positions, i + 3);
  8045. pC.fromArray(positions, i + 6);
  8046. cb.subVectors(pC, pB);
  8047. ab.subVectors(pA, pB);
  8048. cb.cross(ab);
  8049. normals[i] = cb.x;
  8050. normals[i + 1] = cb.y;
  8051. normals[i + 2] = cb.z;
  8052. normals[i + 3] = cb.x;
  8053. normals[i + 4] = cb.y;
  8054. normals[i + 5] = cb.z;
  8055. normals[i + 6] = cb.x;
  8056. normals[i + 7] = cb.y;
  8057. normals[i + 8] = cb.z;
  8058. }
  8059. }
  8060. this.normalizeNormals();
  8061. attributes.normal.needsUpdate = true;
  8062. }
  8063. },
  8064. merge: function (geometry, offset) {
  8065. if (!(geometry && geometry.isBufferGeometry)) {
  8066. console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
  8067. return;
  8068. }
  8069. if (offset === undefined) {
  8070. offset = 0;
  8071. console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
  8072. }
  8073. var attributes = this.attributes;
  8074. for (var key in attributes) {
  8075. if (geometry.attributes[key] === undefined) continue;
  8076. var attribute1 = attributes[key];
  8077. var attributeArray1 = attribute1.array;
  8078. var attribute2 = geometry.attributes[key];
  8079. var attributeArray2 = attribute2.array;
  8080. var attributeOffset = attribute2.itemSize * offset;
  8081. var length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
  8082. for (var i = 0, j = attributeOffset; i < length; i++, j++) {
  8083. attributeArray1[j] = attributeArray2[i];
  8084. }
  8085. }
  8086. return this;
  8087. },
  8088. normalizeNormals: function () {
  8089. var normals = this.attributes.normal;
  8090. for (var i = 0, il = normals.count; i < il; i++) {
  8091. _vector$4.x = normals.getX(i);
  8092. _vector$4.y = normals.getY(i);
  8093. _vector$4.z = normals.getZ(i);
  8094. _vector$4.normalize();
  8095. normals.setXYZ(i, _vector$4.x, _vector$4.y, _vector$4.z);
  8096. }
  8097. },
  8098. toNonIndexed: function () {
  8099. function convertBufferAttribute(attribute, indices) {
  8100. var array = attribute.array;
  8101. var itemSize = attribute.itemSize;
  8102. var array2 = new array.constructor(indices.length * itemSize);
  8103. var index = 0,
  8104. index2 = 0;
  8105. for (var i = 0, l = indices.length; i < l; i++) {
  8106. index = indices[i] * itemSize;
  8107. for (var j = 0; j < itemSize; j++) {
  8108. array2[index2++] = array[index++];
  8109. }
  8110. }
  8111. return new BufferAttribute(array2, itemSize);
  8112. } //
  8113. if (this.index === null) {
  8114. console.warn('THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.');
  8115. return this;
  8116. }
  8117. var geometry2 = new BufferGeometry();
  8118. var indices = this.index.array;
  8119. var attributes = this.attributes; // attributes
  8120. for (var name in attributes) {
  8121. var attribute = attributes[name];
  8122. var newAttribute = convertBufferAttribute(attribute, indices);
  8123. geometry2.addAttribute(name, newAttribute);
  8124. } // morph attributes
  8125. var morphAttributes = this.morphAttributes;
  8126. for (name in morphAttributes) {
  8127. var morphArray = [];
  8128. var morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  8129. for (var i = 0, il = morphAttribute.length; i < il; i++) {
  8130. var attribute = morphAttribute[i];
  8131. var newAttribute = convertBufferAttribute(attribute, indices);
  8132. morphArray.push(newAttribute);
  8133. }
  8134. geometry2.morphAttributes[name] = morphArray;
  8135. } // groups
  8136. var groups = this.groups;
  8137. for (var i = 0, l = groups.length; i < l; i++) {
  8138. var group = groups[i];
  8139. geometry2.addGroup(group.start, group.count, group.materialIndex);
  8140. }
  8141. return geometry2;
  8142. },
  8143. toJSON: function () {
  8144. var data = {
  8145. metadata: {
  8146. version: 4.5,
  8147. type: 'BufferGeometry',
  8148. generator: 'BufferGeometry.toJSON'
  8149. }
  8150. }; // standard BufferGeometry serialization
  8151. data.uuid = this.uuid;
  8152. data.type = this.type;
  8153. if (this.name !== '') data.name = this.name;
  8154. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  8155. if (this.parameters !== undefined) {
  8156. var parameters = this.parameters;
  8157. for (var key in parameters) {
  8158. if (parameters[key] !== undefined) data[key] = parameters[key];
  8159. }
  8160. return data;
  8161. }
  8162. data.data = {
  8163. attributes: {}
  8164. };
  8165. var index = this.index;
  8166. if (index !== null) {
  8167. data.data.index = {
  8168. type: index.array.constructor.name,
  8169. array: Array.prototype.slice.call(index.array)
  8170. };
  8171. }
  8172. var attributes = this.attributes;
  8173. for (var key in attributes) {
  8174. var attribute = attributes[key];
  8175. var attributeData = attribute.toJSON();
  8176. if (attribute.name !== '') attributeData.name = attribute.name;
  8177. data.data.attributes[key] = attributeData;
  8178. }
  8179. var morphAttributes = {};
  8180. var hasMorphAttributes = false;
  8181. for (var key in this.morphAttributes) {
  8182. var attributeArray = this.morphAttributes[key];
  8183. var array = [];
  8184. for (var i = 0, il = attributeArray.length; i < il; i++) {
  8185. var attribute = attributeArray[i];
  8186. var attributeData = attribute.toJSON();
  8187. if (attribute.name !== '') attributeData.name = attribute.name;
  8188. array.push(attributeData);
  8189. }
  8190. if (array.length > 0) {
  8191. morphAttributes[key] = array;
  8192. hasMorphAttributes = true;
  8193. }
  8194. }
  8195. if (hasMorphAttributes) data.data.morphAttributes = morphAttributes;
  8196. var groups = this.groups;
  8197. if (groups.length > 0) {
  8198. data.data.groups = JSON.parse(JSON.stringify(groups));
  8199. }
  8200. var boundingSphere = this.boundingSphere;
  8201. if (boundingSphere !== null) {
  8202. data.data.boundingSphere = {
  8203. center: boundingSphere.center.toArray(),
  8204. radius: boundingSphere.radius
  8205. };
  8206. }
  8207. return data;
  8208. },
  8209. clone: function () {
  8210. /*
  8211. // Handle primitives
  8212. var parameters = this.parameters;
  8213. if ( parameters !== undefined ) {
  8214. var values = [];
  8215. for ( var key in parameters ) {
  8216. values.push( parameters[ key ] );
  8217. }
  8218. var geometry = Object.create( this.constructor.prototype );
  8219. this.constructor.apply( geometry, values );
  8220. return geometry;
  8221. }
  8222. return new this.constructor().copy( this );
  8223. */
  8224. return new BufferGeometry().copy(this);
  8225. },
  8226. copy: function (source) {
  8227. var name, i, l; // reset
  8228. this.index = null;
  8229. this.attributes = {};
  8230. this.morphAttributes = {};
  8231. this.groups = [];
  8232. this.boundingBox = null;
  8233. this.boundingSphere = null; // name
  8234. this.name = source.name; // index
  8235. var index = source.index;
  8236. if (index !== null) {
  8237. this.setIndex(index.clone());
  8238. } // attributes
  8239. var attributes = source.attributes;
  8240. for (name in attributes) {
  8241. var attribute = attributes[name];
  8242. this.addAttribute(name, attribute.clone());
  8243. } // morph attributes
  8244. var morphAttributes = source.morphAttributes;
  8245. for (name in morphAttributes) {
  8246. var array = [];
  8247. var morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  8248. for (i = 0, l = morphAttribute.length; i < l; i++) {
  8249. array.push(morphAttribute[i].clone());
  8250. }
  8251. this.morphAttributes[name] = array;
  8252. } // groups
  8253. var groups = source.groups;
  8254. for (i = 0, l = groups.length; i < l; i++) {
  8255. var group = groups[i];
  8256. this.addGroup(group.start, group.count, group.materialIndex);
  8257. } // bounding box
  8258. var boundingBox = source.boundingBox;
  8259. if (boundingBox !== null) {
  8260. this.boundingBox = boundingBox.clone();
  8261. } // bounding sphere
  8262. var boundingSphere = source.boundingSphere;
  8263. if (boundingSphere !== null) {
  8264. this.boundingSphere = boundingSphere.clone();
  8265. } // draw range
  8266. this.drawRange.start = source.drawRange.start;
  8267. this.drawRange.count = source.drawRange.count; // user data
  8268. this.userData = source.userData;
  8269. return this;
  8270. },
  8271. dispose: function () {
  8272. this.dispatchEvent({
  8273. type: 'dispose'
  8274. });
  8275. }
  8276. });
  8277. /**
  8278. * @author mrdoob / http://mrdoob.com/
  8279. * @author alteredq / http://alteredqualia.com/
  8280. * @author mikael emtinger / http://gomo.se/
  8281. * @author jonobr1 / http://jonobr1.com/
  8282. */
  8283. var _inverseMatrix = new Matrix4();
  8284. var _ray = new Ray();
  8285. var _sphere = new Sphere();
  8286. var _vA = new Vector3();
  8287. var _vB = new Vector3();
  8288. var _vC = new Vector3();
  8289. var _tempA = new Vector3();
  8290. var _tempB = new Vector3();
  8291. var _tempC = new Vector3();
  8292. var _morphA = new Vector3();
  8293. var _morphB = new Vector3();
  8294. var _morphC = new Vector3();
  8295. var _uvA = new Vector2();
  8296. var _uvB = new Vector2();
  8297. var _uvC = new Vector2();
  8298. var _intersectionPoint = new Vector3();
  8299. var _intersectionPointWorld = new Vector3();
  8300. function Mesh(geometry, material) {
  8301. Object3D.call(this);
  8302. this.type = 'Mesh';
  8303. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  8304. this.material = material !== undefined ? material : new MeshBasicMaterial({
  8305. color: Math.random() * 0xffffff
  8306. });
  8307. this.drawMode = TrianglesDrawMode;
  8308. this.updateMorphTargets();
  8309. }
  8310. Mesh.prototype = Object.assign(Object.create(Object3D.prototype), {
  8311. constructor: Mesh,
  8312. isMesh: true,
  8313. setDrawMode: function (value) {
  8314. this.drawMode = value;
  8315. },
  8316. copy: function (source) {
  8317. Object3D.prototype.copy.call(this, source);
  8318. this.drawMode = source.drawMode;
  8319. if (source.morphTargetInfluences !== undefined) {
  8320. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  8321. }
  8322. if (source.morphTargetDictionary !== undefined) {
  8323. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  8324. }
  8325. return this;
  8326. },
  8327. updateMorphTargets: function () {
  8328. var geometry = this.geometry;
  8329. var m, ml, name;
  8330. if (geometry.isBufferGeometry) {
  8331. var morphAttributes = geometry.morphAttributes;
  8332. var keys = Object.keys(morphAttributes);
  8333. if (keys.length > 0) {
  8334. var morphAttribute = morphAttributes[keys[0]];
  8335. if (morphAttribute !== undefined) {
  8336. this.morphTargetInfluences = [];
  8337. this.morphTargetDictionary = {};
  8338. for (m = 0, ml = morphAttribute.length; m < ml; m++) {
  8339. name = morphAttribute[m].name || String(m);
  8340. this.morphTargetInfluences.push(0);
  8341. this.morphTargetDictionary[name] = m;
  8342. }
  8343. }
  8344. }
  8345. } else {
  8346. var morphTargets = geometry.morphTargets;
  8347. if (morphTargets !== undefined && morphTargets.length > 0) {
  8348. console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  8349. }
  8350. }
  8351. },
  8352. raycast: function (raycaster, intersects) {
  8353. var geometry = this.geometry;
  8354. var material = this.material;
  8355. var matrixWorld = this.matrixWorld;
  8356. if (material === undefined) return; // Checking boundingSphere distance to ray
  8357. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  8358. _sphere.copy(geometry.boundingSphere);
  8359. _sphere.applyMatrix4(matrixWorld);
  8360. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  8361. _inverseMatrix.getInverse(matrixWorld);
  8362. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix); // Check boundingBox before continuing
  8363. if (geometry.boundingBox !== null) {
  8364. if (_ray.intersectsBox(geometry.boundingBox) === false) return;
  8365. }
  8366. var intersection;
  8367. if (geometry.isBufferGeometry) {
  8368. var a, b, c;
  8369. var index = geometry.index;
  8370. var position = geometry.attributes.position;
  8371. var morphPosition = geometry.morphAttributes.position;
  8372. var uv = geometry.attributes.uv;
  8373. var uv2 = geometry.attributes.uv2;
  8374. var groups = geometry.groups;
  8375. var drawRange = geometry.drawRange;
  8376. var i, j, il, jl;
  8377. var group, groupMaterial;
  8378. var start, end;
  8379. if (index !== null) {
  8380. // indexed buffer geometry
  8381. if (Array.isArray(material)) {
  8382. for (i = 0, il = groups.length; i < il; i++) {
  8383. group = groups[i];
  8384. groupMaterial = material[group.materialIndex];
  8385. start = Math.max(group.start, drawRange.start);
  8386. end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  8387. for (j = start, jl = end; j < jl; j += 3) {
  8388. a = index.getX(j);
  8389. b = index.getX(j + 1);
  8390. c = index.getX(j + 2);
  8391. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);
  8392. if (intersection) {
  8393. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  8394. intersection.face.materialIndex = group.materialIndex;
  8395. intersects.push(intersection);
  8396. }
  8397. }
  8398. }
  8399. } else {
  8400. start = Math.max(0, drawRange.start);
  8401. end = Math.min(index.count, drawRange.start + drawRange.count);
  8402. for (i = start, il = end; i < il; i += 3) {
  8403. a = index.getX(i);
  8404. b = index.getX(i + 1);
  8405. c = index.getX(i + 2);
  8406. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);
  8407. if (intersection) {
  8408. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  8409. intersects.push(intersection);
  8410. }
  8411. }
  8412. }
  8413. } else if (position !== undefined) {
  8414. // non-indexed buffer geometry
  8415. if (Array.isArray(material)) {
  8416. for (i = 0, il = groups.length; i < il; i++) {
  8417. group = groups[i];
  8418. groupMaterial = material[group.materialIndex];
  8419. start = Math.max(group.start, drawRange.start);
  8420. end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  8421. for (j = start, jl = end; j < jl; j += 3) {
  8422. a = j;
  8423. b = j + 1;
  8424. c = j + 2;
  8425. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);
  8426. if (intersection) {
  8427. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  8428. intersection.face.materialIndex = group.materialIndex;
  8429. intersects.push(intersection);
  8430. }
  8431. }
  8432. }
  8433. } else {
  8434. start = Math.max(0, drawRange.start);
  8435. end = Math.min(position.count, drawRange.start + drawRange.count);
  8436. for (i = start, il = end; i < il; i += 3) {
  8437. a = i;
  8438. b = i + 1;
  8439. c = i + 2;
  8440. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);
  8441. if (intersection) {
  8442. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  8443. intersects.push(intersection);
  8444. }
  8445. }
  8446. }
  8447. }
  8448. } else if (geometry.isGeometry) {
  8449. var fvA, fvB, fvC;
  8450. var isMultiMaterial = Array.isArray(material);
  8451. var vertices = geometry.vertices;
  8452. var faces = geometry.faces;
  8453. var uvs;
  8454. var faceVertexUvs = geometry.faceVertexUvs[0];
  8455. if (faceVertexUvs.length > 0) uvs = faceVertexUvs;
  8456. for (var f = 0, fl = faces.length; f < fl; f++) {
  8457. var face = faces[f];
  8458. var faceMaterial = isMultiMaterial ? material[face.materialIndex] : material;
  8459. if (faceMaterial === undefined) continue;
  8460. fvA = vertices[face.a];
  8461. fvB = vertices[face.b];
  8462. fvC = vertices[face.c];
  8463. intersection = checkIntersection(this, faceMaterial, raycaster, _ray, fvA, fvB, fvC, _intersectionPoint);
  8464. if (intersection) {
  8465. if (uvs && uvs[f]) {
  8466. var uvs_f = uvs[f];
  8467. _uvA.copy(uvs_f[0]);
  8468. _uvB.copy(uvs_f[1]);
  8469. _uvC.copy(uvs_f[2]);
  8470. intersection.uv = Triangle.getUV(_intersectionPoint, fvA, fvB, fvC, _uvA, _uvB, _uvC, new Vector2());
  8471. }
  8472. intersection.face = face;
  8473. intersection.faceIndex = f;
  8474. intersects.push(intersection);
  8475. }
  8476. }
  8477. }
  8478. },
  8479. clone: function () {
  8480. return new this.constructor(this.geometry, this.material).copy(this);
  8481. }
  8482. });
  8483. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  8484. var intersect;
  8485. if (material.side === BackSide) {
  8486. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  8487. } else {
  8488. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  8489. }
  8490. if (intersect === null) return null;
  8491. _intersectionPointWorld.copy(point);
  8492. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  8493. var distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  8494. if (distance < raycaster.near || distance > raycaster.far) return null;
  8495. return {
  8496. distance: distance,
  8497. point: _intersectionPointWorld.clone(),
  8498. object: object
  8499. };
  8500. }
  8501. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, uv, uv2, a, b, c) {
  8502. _vA.fromBufferAttribute(position, a);
  8503. _vB.fromBufferAttribute(position, b);
  8504. _vC.fromBufferAttribute(position, c);
  8505. var morphInfluences = object.morphTargetInfluences;
  8506. if (material.morphTargets && morphPosition && morphInfluences) {
  8507. _morphA.set(0, 0, 0);
  8508. _morphB.set(0, 0, 0);
  8509. _morphC.set(0, 0, 0);
  8510. for (var i = 0, il = morphPosition.length; i < il; i++) {
  8511. var influence = morphInfluences[i];
  8512. var morphAttribute = morphPosition[i];
  8513. if (influence === 0) continue;
  8514. _tempA.fromBufferAttribute(morphAttribute, a);
  8515. _tempB.fromBufferAttribute(morphAttribute, b);
  8516. _tempC.fromBufferAttribute(morphAttribute, c);
  8517. _morphA.addScaledVector(_tempA.sub(_vA), influence);
  8518. _morphB.addScaledVector(_tempB.sub(_vB), influence);
  8519. _morphC.addScaledVector(_tempC.sub(_vC), influence);
  8520. }
  8521. _vA.add(_morphA);
  8522. _vB.add(_morphB);
  8523. _vC.add(_morphC);
  8524. }
  8525. var intersection = checkIntersection(object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint);
  8526. if (intersection) {
  8527. if (uv) {
  8528. _uvA.fromBufferAttribute(uv, a);
  8529. _uvB.fromBufferAttribute(uv, b);
  8530. _uvC.fromBufferAttribute(uv, c);
  8531. intersection.uv = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
  8532. }
  8533. if (uv2) {
  8534. _uvA.fromBufferAttribute(uv2, a);
  8535. _uvB.fromBufferAttribute(uv2, b);
  8536. _uvC.fromBufferAttribute(uv2, c);
  8537. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
  8538. }
  8539. var face = new Face3(a, b, c);
  8540. Triangle.getNormal(_vA, _vB, _vC, face.normal);
  8541. intersection.face = face;
  8542. }
  8543. return intersection;
  8544. }
  8545. /**
  8546. * @author mrdoob / http://mrdoob.com/
  8547. * @author kile / http://kile.stravaganza.org/
  8548. * @author alteredq / http://alteredqualia.com/
  8549. * @author mikael emtinger / http://gomo.se/
  8550. * @author zz85 / http://www.lab4games.net/zz85/blog
  8551. * @author bhouston / http://clara.io
  8552. */
  8553. var _geometryId = 0; // Geometry uses even numbers as Id
  8554. var _m1$3 = new Matrix4();
  8555. var _obj$1 = new Object3D();
  8556. var _offset$1 = new Vector3();
  8557. function Geometry() {
  8558. Object.defineProperty(this, 'id', {
  8559. value: _geometryId += 2
  8560. });
  8561. this.uuid = _Math.generateUUID();
  8562. this.name = '';
  8563. this.type = 'Geometry';
  8564. this.vertices = [];
  8565. this.colors = [];
  8566. this.faces = [];
  8567. this.faceVertexUvs = [[]];
  8568. this.morphTargets = [];
  8569. this.morphNormals = [];
  8570. this.skinWeights = [];
  8571. this.skinIndices = [];
  8572. this.lineDistances = [];
  8573. this.boundingBox = null;
  8574. this.boundingSphere = null; // update flags
  8575. this.elementsNeedUpdate = false;
  8576. this.verticesNeedUpdate = false;
  8577. this.uvsNeedUpdate = false;
  8578. this.normalsNeedUpdate = false;
  8579. this.colorsNeedUpdate = false;
  8580. this.lineDistancesNeedUpdate = false;
  8581. this.groupsNeedUpdate = false;
  8582. }
  8583. Geometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  8584. constructor: Geometry,
  8585. isGeometry: true,
  8586. applyMatrix: function (matrix) {
  8587. var normalMatrix = new Matrix3().getNormalMatrix(matrix);
  8588. for (var i = 0, il = this.vertices.length; i < il; i++) {
  8589. var vertex = this.vertices[i];
  8590. vertex.applyMatrix4(matrix);
  8591. }
  8592. for (var i = 0, il = this.faces.length; i < il; i++) {
  8593. var face = this.faces[i];
  8594. face.normal.applyMatrix3(normalMatrix).normalize();
  8595. for (var j = 0, jl = face.vertexNormals.length; j < jl; j++) {
  8596. face.vertexNormals[j].applyMatrix3(normalMatrix).normalize();
  8597. }
  8598. }
  8599. if (this.boundingBox !== null) {
  8600. this.computeBoundingBox();
  8601. }
  8602. if (this.boundingSphere !== null) {
  8603. this.computeBoundingSphere();
  8604. }
  8605. this.verticesNeedUpdate = true;
  8606. this.normalsNeedUpdate = true;
  8607. return this;
  8608. },
  8609. rotateX: function (angle) {
  8610. // rotate geometry around world x-axis
  8611. _m1$3.makeRotationX(angle);
  8612. this.applyMatrix(_m1$3);
  8613. return this;
  8614. },
  8615. rotateY: function (angle) {
  8616. // rotate geometry around world y-axis
  8617. _m1$3.makeRotationY(angle);
  8618. this.applyMatrix(_m1$3);
  8619. return this;
  8620. },
  8621. rotateZ: function (angle) {
  8622. // rotate geometry around world z-axis
  8623. _m1$3.makeRotationZ(angle);
  8624. this.applyMatrix(_m1$3);
  8625. return this;
  8626. },
  8627. translate: function (x, y, z) {
  8628. // translate geometry
  8629. _m1$3.makeTranslation(x, y, z);
  8630. this.applyMatrix(_m1$3);
  8631. return this;
  8632. },
  8633. scale: function (x, y, z) {
  8634. // scale geometry
  8635. _m1$3.makeScale(x, y, z);
  8636. this.applyMatrix(_m1$3);
  8637. return this;
  8638. },
  8639. lookAt: function (vector) {
  8640. _obj$1.lookAt(vector);
  8641. _obj$1.updateMatrix();
  8642. this.applyMatrix(_obj$1.matrix);
  8643. return this;
  8644. },
  8645. fromBufferGeometry: function (geometry) {
  8646. var scope = this;
  8647. var indices = geometry.index !== null ? geometry.index.array : undefined;
  8648. var attributes = geometry.attributes;
  8649. if (attributes.position === undefined) {
  8650. console.error('THREE.Geometry.fromBufferGeometry(): Position attribute required for conversion.');
  8651. return this;
  8652. }
  8653. var positions = attributes.position.array;
  8654. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  8655. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  8656. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  8657. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  8658. if (uvs2 !== undefined) this.faceVertexUvs[1] = [];
  8659. for (var i = 0; i < positions.length; i += 3) {
  8660. scope.vertices.push(new Vector3().fromArray(positions, i));
  8661. if (colors !== undefined) {
  8662. scope.colors.push(new Color().fromArray(colors, i));
  8663. }
  8664. }
  8665. function addFace(a, b, c, materialIndex) {
  8666. var vertexColors = colors === undefined ? [] : [scope.colors[a].clone(), scope.colors[b].clone(), scope.colors[c].clone()];
  8667. var vertexNormals = normals === undefined ? [] : [new Vector3().fromArray(normals, a * 3), new Vector3().fromArray(normals, b * 3), new Vector3().fromArray(normals, c * 3)];
  8668. var face = new Face3(a, b, c, vertexNormals, vertexColors, materialIndex);
  8669. scope.faces.push(face);
  8670. if (uvs !== undefined) {
  8671. scope.faceVertexUvs[0].push([new Vector2().fromArray(uvs, a * 2), new Vector2().fromArray(uvs, b * 2), new Vector2().fromArray(uvs, c * 2)]);
  8672. }
  8673. if (uvs2 !== undefined) {
  8674. scope.faceVertexUvs[1].push([new Vector2().fromArray(uvs2, a * 2), new Vector2().fromArray(uvs2, b * 2), new Vector2().fromArray(uvs2, c * 2)]);
  8675. }
  8676. }
  8677. var groups = geometry.groups;
  8678. if (groups.length > 0) {
  8679. for (var i = 0; i < groups.length; i++) {
  8680. var group = groups[i];
  8681. var start = group.start;
  8682. var count = group.count;
  8683. for (var j = start, jl = start + count; j < jl; j += 3) {
  8684. if (indices !== undefined) {
  8685. addFace(indices[j], indices[j + 1], indices[j + 2], group.materialIndex);
  8686. } else {
  8687. addFace(j, j + 1, j + 2, group.materialIndex);
  8688. }
  8689. }
  8690. }
  8691. } else {
  8692. if (indices !== undefined) {
  8693. for (var i = 0; i < indices.length; i += 3) {
  8694. addFace(indices[i], indices[i + 1], indices[i + 2]);
  8695. }
  8696. } else {
  8697. for (var i = 0; i < positions.length / 3; i += 3) {
  8698. addFace(i, i + 1, i + 2);
  8699. }
  8700. }
  8701. }
  8702. this.computeFaceNormals();
  8703. if (geometry.boundingBox !== null) {
  8704. this.boundingBox = geometry.boundingBox.clone();
  8705. }
  8706. if (geometry.boundingSphere !== null) {
  8707. this.boundingSphere = geometry.boundingSphere.clone();
  8708. }
  8709. return this;
  8710. },
  8711. center: function () {
  8712. this.computeBoundingBox();
  8713. this.boundingBox.getCenter(_offset$1).negate();
  8714. this.translate(_offset$1.x, _offset$1.y, _offset$1.z);
  8715. return this;
  8716. },
  8717. normalize: function () {
  8718. this.computeBoundingSphere();
  8719. var center = this.boundingSphere.center;
  8720. var radius = this.boundingSphere.radius;
  8721. var s = radius === 0 ? 1 : 1.0 / radius;
  8722. var matrix = new Matrix4();
  8723. matrix.set(s, 0, 0, -s * center.x, 0, s, 0, -s * center.y, 0, 0, s, -s * center.z, 0, 0, 0, 1);
  8724. this.applyMatrix(matrix);
  8725. return this;
  8726. },
  8727. computeFaceNormals: function () {
  8728. var cb = new Vector3(),
  8729. ab = new Vector3();
  8730. for (var f = 0, fl = this.faces.length; f < fl; f++) {
  8731. var face = this.faces[f];
  8732. var vA = this.vertices[face.a];
  8733. var vB = this.vertices[face.b];
  8734. var vC = this.vertices[face.c];
  8735. cb.subVectors(vC, vB);
  8736. ab.subVectors(vA, vB);
  8737. cb.cross(ab);
  8738. cb.normalize();
  8739. face.normal.copy(cb);
  8740. }
  8741. },
  8742. computeVertexNormals: function (areaWeighted) {
  8743. if (areaWeighted === undefined) areaWeighted = true;
  8744. var v, vl, f, fl, face, vertices;
  8745. vertices = new Array(this.vertices.length);
  8746. for (v = 0, vl = this.vertices.length; v < vl; v++) {
  8747. vertices[v] = new Vector3();
  8748. }
  8749. if (areaWeighted) {
  8750. // vertex normals weighted by triangle areas
  8751. // http://www.iquilezles.org/www/articles/normals/normals.htm
  8752. var vA, vB, vC;
  8753. var cb = new Vector3(),
  8754. ab = new Vector3();
  8755. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8756. face = this.faces[f];
  8757. vA = this.vertices[face.a];
  8758. vB = this.vertices[face.b];
  8759. vC = this.vertices[face.c];
  8760. cb.subVectors(vC, vB);
  8761. ab.subVectors(vA, vB);
  8762. cb.cross(ab);
  8763. vertices[face.a].add(cb);
  8764. vertices[face.b].add(cb);
  8765. vertices[face.c].add(cb);
  8766. }
  8767. } else {
  8768. this.computeFaceNormals();
  8769. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8770. face = this.faces[f];
  8771. vertices[face.a].add(face.normal);
  8772. vertices[face.b].add(face.normal);
  8773. vertices[face.c].add(face.normal);
  8774. }
  8775. }
  8776. for (v = 0, vl = this.vertices.length; v < vl; v++) {
  8777. vertices[v].normalize();
  8778. }
  8779. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8780. face = this.faces[f];
  8781. var vertexNormals = face.vertexNormals;
  8782. if (vertexNormals.length === 3) {
  8783. vertexNormals[0].copy(vertices[face.a]);
  8784. vertexNormals[1].copy(vertices[face.b]);
  8785. vertexNormals[2].copy(vertices[face.c]);
  8786. } else {
  8787. vertexNormals[0] = vertices[face.a].clone();
  8788. vertexNormals[1] = vertices[face.b].clone();
  8789. vertexNormals[2] = vertices[face.c].clone();
  8790. }
  8791. }
  8792. if (this.faces.length > 0) {
  8793. this.normalsNeedUpdate = true;
  8794. }
  8795. },
  8796. computeFlatVertexNormals: function () {
  8797. var f, fl, face;
  8798. this.computeFaceNormals();
  8799. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8800. face = this.faces[f];
  8801. var vertexNormals = face.vertexNormals;
  8802. if (vertexNormals.length === 3) {
  8803. vertexNormals[0].copy(face.normal);
  8804. vertexNormals[1].copy(face.normal);
  8805. vertexNormals[2].copy(face.normal);
  8806. } else {
  8807. vertexNormals[0] = face.normal.clone();
  8808. vertexNormals[1] = face.normal.clone();
  8809. vertexNormals[2] = face.normal.clone();
  8810. }
  8811. }
  8812. if (this.faces.length > 0) {
  8813. this.normalsNeedUpdate = true;
  8814. }
  8815. },
  8816. computeMorphNormals: function () {
  8817. var i, il, f, fl, face; // save original normals
  8818. // - create temp variables on first access
  8819. // otherwise just copy (for faster repeated calls)
  8820. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8821. face = this.faces[f];
  8822. if (!face.__originalFaceNormal) {
  8823. face.__originalFaceNormal = face.normal.clone();
  8824. } else {
  8825. face.__originalFaceNormal.copy(face.normal);
  8826. }
  8827. if (!face.__originalVertexNormals) face.__originalVertexNormals = [];
  8828. for (i = 0, il = face.vertexNormals.length; i < il; i++) {
  8829. if (!face.__originalVertexNormals[i]) {
  8830. face.__originalVertexNormals[i] = face.vertexNormals[i].clone();
  8831. } else {
  8832. face.__originalVertexNormals[i].copy(face.vertexNormals[i]);
  8833. }
  8834. }
  8835. } // use temp geometry to compute face and vertex normals for each morph
  8836. var tmpGeo = new Geometry();
  8837. tmpGeo.faces = this.faces;
  8838. for (i = 0, il = this.morphTargets.length; i < il; i++) {
  8839. // create on first access
  8840. if (!this.morphNormals[i]) {
  8841. this.morphNormals[i] = {};
  8842. this.morphNormals[i].faceNormals = [];
  8843. this.morphNormals[i].vertexNormals = [];
  8844. var dstNormalsFace = this.morphNormals[i].faceNormals;
  8845. var dstNormalsVertex = this.morphNormals[i].vertexNormals;
  8846. var faceNormal, vertexNormals;
  8847. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8848. faceNormal = new Vector3();
  8849. vertexNormals = {
  8850. a: new Vector3(),
  8851. b: new Vector3(),
  8852. c: new Vector3()
  8853. };
  8854. dstNormalsFace.push(faceNormal);
  8855. dstNormalsVertex.push(vertexNormals);
  8856. }
  8857. }
  8858. var morphNormals = this.morphNormals[i]; // set vertices to morph target
  8859. tmpGeo.vertices = this.morphTargets[i].vertices; // compute morph normals
  8860. tmpGeo.computeFaceNormals();
  8861. tmpGeo.computeVertexNormals(); // store morph normals
  8862. var faceNormal, vertexNormals;
  8863. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8864. face = this.faces[f];
  8865. faceNormal = morphNormals.faceNormals[f];
  8866. vertexNormals = morphNormals.vertexNormals[f];
  8867. faceNormal.copy(face.normal);
  8868. vertexNormals.a.copy(face.vertexNormals[0]);
  8869. vertexNormals.b.copy(face.vertexNormals[1]);
  8870. vertexNormals.c.copy(face.vertexNormals[2]);
  8871. }
  8872. } // restore original normals
  8873. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8874. face = this.faces[f];
  8875. face.normal = face.__originalFaceNormal;
  8876. face.vertexNormals = face.__originalVertexNormals;
  8877. }
  8878. },
  8879. computeBoundingBox: function () {
  8880. if (this.boundingBox === null) {
  8881. this.boundingBox = new Box3();
  8882. }
  8883. this.boundingBox.setFromPoints(this.vertices);
  8884. },
  8885. computeBoundingSphere: function () {
  8886. if (this.boundingSphere === null) {
  8887. this.boundingSphere = new Sphere();
  8888. }
  8889. this.boundingSphere.setFromPoints(this.vertices);
  8890. },
  8891. merge: function (geometry, matrix, materialIndexOffset) {
  8892. if (!(geometry && geometry.isGeometry)) {
  8893. console.error('THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry);
  8894. return;
  8895. }
  8896. var normalMatrix,
  8897. vertexOffset = this.vertices.length,
  8898. vertices1 = this.vertices,
  8899. vertices2 = geometry.vertices,
  8900. faces1 = this.faces,
  8901. faces2 = geometry.faces,
  8902. colors1 = this.colors,
  8903. colors2 = geometry.colors;
  8904. if (materialIndexOffset === undefined) materialIndexOffset = 0;
  8905. if (matrix !== undefined) {
  8906. normalMatrix = new Matrix3().getNormalMatrix(matrix);
  8907. } // vertices
  8908. for (var i = 0, il = vertices2.length; i < il; i++) {
  8909. var vertex = vertices2[i];
  8910. var vertexCopy = vertex.clone();
  8911. if (matrix !== undefined) vertexCopy.applyMatrix4(matrix);
  8912. vertices1.push(vertexCopy);
  8913. } // colors
  8914. for (var i = 0, il = colors2.length; i < il; i++) {
  8915. colors1.push(colors2[i].clone());
  8916. } // faces
  8917. for (i = 0, il = faces2.length; i < il; i++) {
  8918. var face = faces2[i],
  8919. faceCopy,
  8920. normal,
  8921. color,
  8922. faceVertexNormals = face.vertexNormals,
  8923. faceVertexColors = face.vertexColors;
  8924. faceCopy = new Face3(face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset);
  8925. faceCopy.normal.copy(face.normal);
  8926. if (normalMatrix !== undefined) {
  8927. faceCopy.normal.applyMatrix3(normalMatrix).normalize();
  8928. }
  8929. for (var j = 0, jl = faceVertexNormals.length; j < jl; j++) {
  8930. normal = faceVertexNormals[j].clone();
  8931. if (normalMatrix !== undefined) {
  8932. normal.applyMatrix3(normalMatrix).normalize();
  8933. }
  8934. faceCopy.vertexNormals.push(normal);
  8935. }
  8936. faceCopy.color.copy(face.color);
  8937. for (var j = 0, jl = faceVertexColors.length; j < jl; j++) {
  8938. color = faceVertexColors[j];
  8939. faceCopy.vertexColors.push(color.clone());
  8940. }
  8941. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  8942. faces1.push(faceCopy);
  8943. } // uvs
  8944. for (var i = 0, il = geometry.faceVertexUvs.length; i < il; i++) {
  8945. var faceVertexUvs2 = geometry.faceVertexUvs[i];
  8946. if (this.faceVertexUvs[i] === undefined) this.faceVertexUvs[i] = [];
  8947. for (var j = 0, jl = faceVertexUvs2.length; j < jl; j++) {
  8948. var uvs2 = faceVertexUvs2[j],
  8949. uvsCopy = [];
  8950. for (var k = 0, kl = uvs2.length; k < kl; k++) {
  8951. uvsCopy.push(uvs2[k].clone());
  8952. }
  8953. this.faceVertexUvs[i].push(uvsCopy);
  8954. }
  8955. }
  8956. },
  8957. mergeMesh: function (mesh) {
  8958. if (!(mesh && mesh.isMesh)) {
  8959. console.error('THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh);
  8960. return;
  8961. }
  8962. if (mesh.matrixAutoUpdate) mesh.updateMatrix();
  8963. this.merge(mesh.geometry, mesh.matrix);
  8964. },
  8965. /*
  8966. * Checks for duplicate vertices with hashmap.
  8967. * Duplicated vertices are removed
  8968. * and faces' vertices are updated.
  8969. */
  8970. mergeVertices: function () {
  8971. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  8972. var unique = [],
  8973. changes = [];
  8974. var v, key;
  8975. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  8976. var precision = Math.pow(10, precisionPoints);
  8977. var i, il, face;
  8978. var indices, j, jl;
  8979. for (i = 0, il = this.vertices.length; i < il; i++) {
  8980. v = this.vertices[i];
  8981. key = Math.round(v.x * precision) + '_' + Math.round(v.y * precision) + '_' + Math.round(v.z * precision);
  8982. if (verticesMap[key] === undefined) {
  8983. verticesMap[key] = i;
  8984. unique.push(this.vertices[i]);
  8985. changes[i] = unique.length - 1;
  8986. } else {
  8987. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  8988. changes[i] = changes[verticesMap[key]];
  8989. }
  8990. } // if faces are completely degenerate after merging vertices, we
  8991. // have to remove them from the geometry.
  8992. var faceIndicesToRemove = [];
  8993. for (i = 0, il = this.faces.length; i < il; i++) {
  8994. face = this.faces[i];
  8995. face.a = changes[face.a];
  8996. face.b = changes[face.b];
  8997. face.c = changes[face.c];
  8998. indices = [face.a, face.b, face.c]; // if any duplicate vertices are found in a Face3
  8999. // we have to remove the face as nothing can be saved
  9000. for (var n = 0; n < 3; n++) {
  9001. if (indices[n] === indices[(n + 1) % 3]) {
  9002. faceIndicesToRemove.push(i);
  9003. break;
  9004. }
  9005. }
  9006. }
  9007. for (i = faceIndicesToRemove.length - 1; i >= 0; i--) {
  9008. var idx = faceIndicesToRemove[i];
  9009. this.faces.splice(idx, 1);
  9010. for (j = 0, jl = this.faceVertexUvs.length; j < jl; j++) {
  9011. this.faceVertexUvs[j].splice(idx, 1);
  9012. }
  9013. } // Use unique set of vertices
  9014. var diff = this.vertices.length - unique.length;
  9015. this.vertices = unique;
  9016. return diff;
  9017. },
  9018. setFromPoints: function (points) {
  9019. this.vertices = [];
  9020. for (var i = 0, l = points.length; i < l; i++) {
  9021. var point = points[i];
  9022. this.vertices.push(new Vector3(point.x, point.y, point.z || 0));
  9023. }
  9024. return this;
  9025. },
  9026. sortFacesByMaterialIndex: function () {
  9027. var faces = this.faces;
  9028. var length = faces.length; // tag faces
  9029. for (var i = 0; i < length; i++) {
  9030. faces[i]._id = i;
  9031. } // sort faces
  9032. function materialIndexSort(a, b) {
  9033. return a.materialIndex - b.materialIndex;
  9034. }
  9035. faces.sort(materialIndexSort); // sort uvs
  9036. var uvs1 = this.faceVertexUvs[0];
  9037. var uvs2 = this.faceVertexUvs[1];
  9038. var newUvs1, newUvs2;
  9039. if (uvs1 && uvs1.length === length) newUvs1 = [];
  9040. if (uvs2 && uvs2.length === length) newUvs2 = [];
  9041. for (var i = 0; i < length; i++) {
  9042. var id = faces[i]._id;
  9043. if (newUvs1) newUvs1.push(uvs1[id]);
  9044. if (newUvs2) newUvs2.push(uvs2[id]);
  9045. }
  9046. if (newUvs1) this.faceVertexUvs[0] = newUvs1;
  9047. if (newUvs2) this.faceVertexUvs[1] = newUvs2;
  9048. },
  9049. toJSON: function () {
  9050. var data = {
  9051. metadata: {
  9052. version: 4.5,
  9053. type: 'Geometry',
  9054. generator: 'Geometry.toJSON'
  9055. }
  9056. }; // standard Geometry serialization
  9057. data.uuid = this.uuid;
  9058. data.type = this.type;
  9059. if (this.name !== '') data.name = this.name;
  9060. if (this.parameters !== undefined) {
  9061. var parameters = this.parameters;
  9062. for (var key in parameters) {
  9063. if (parameters[key] !== undefined) data[key] = parameters[key];
  9064. }
  9065. return data;
  9066. }
  9067. var vertices = [];
  9068. for (var i = 0; i < this.vertices.length; i++) {
  9069. var vertex = this.vertices[i];
  9070. vertices.push(vertex.x, vertex.y, vertex.z);
  9071. }
  9072. var faces = [];
  9073. var normals = [];
  9074. var normalsHash = {};
  9075. var colors = [];
  9076. var colorsHash = {};
  9077. var uvs = [];
  9078. var uvsHash = {};
  9079. for (var i = 0; i < this.faces.length; i++) {
  9080. var face = this.faces[i];
  9081. var hasMaterial = true;
  9082. var hasFaceUv = false; // deprecated
  9083. var hasFaceVertexUv = this.faceVertexUvs[0][i] !== undefined;
  9084. var hasFaceNormal = face.normal.length() > 0;
  9085. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  9086. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  9087. var hasFaceVertexColor = face.vertexColors.length > 0;
  9088. var faceType = 0;
  9089. faceType = setBit(faceType, 0, 0); // isQuad
  9090. faceType = setBit(faceType, 1, hasMaterial);
  9091. faceType = setBit(faceType, 2, hasFaceUv);
  9092. faceType = setBit(faceType, 3, hasFaceVertexUv);
  9093. faceType = setBit(faceType, 4, hasFaceNormal);
  9094. faceType = setBit(faceType, 5, hasFaceVertexNormal);
  9095. faceType = setBit(faceType, 6, hasFaceColor);
  9096. faceType = setBit(faceType, 7, hasFaceVertexColor);
  9097. faces.push(faceType);
  9098. faces.push(face.a, face.b, face.c);
  9099. faces.push(face.materialIndex);
  9100. if (hasFaceVertexUv) {
  9101. var faceVertexUvs = this.faceVertexUvs[0][i];
  9102. faces.push(getUvIndex(faceVertexUvs[0]), getUvIndex(faceVertexUvs[1]), getUvIndex(faceVertexUvs[2]));
  9103. }
  9104. if (hasFaceNormal) {
  9105. faces.push(getNormalIndex(face.normal));
  9106. }
  9107. if (hasFaceVertexNormal) {
  9108. var vertexNormals = face.vertexNormals;
  9109. faces.push(getNormalIndex(vertexNormals[0]), getNormalIndex(vertexNormals[1]), getNormalIndex(vertexNormals[2]));
  9110. }
  9111. if (hasFaceColor) {
  9112. faces.push(getColorIndex(face.color));
  9113. }
  9114. if (hasFaceVertexColor) {
  9115. var vertexColors = face.vertexColors;
  9116. faces.push(getColorIndex(vertexColors[0]), getColorIndex(vertexColors[1]), getColorIndex(vertexColors[2]));
  9117. }
  9118. }
  9119. function setBit(value, position, enabled) {
  9120. return enabled ? value | 1 << position : value & ~(1 << position);
  9121. }
  9122. function getNormalIndex(normal) {
  9123. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  9124. if (normalsHash[hash] !== undefined) {
  9125. return normalsHash[hash];
  9126. }
  9127. normalsHash[hash] = normals.length / 3;
  9128. normals.push(normal.x, normal.y, normal.z);
  9129. return normalsHash[hash];
  9130. }
  9131. function getColorIndex(color) {
  9132. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  9133. if (colorsHash[hash] !== undefined) {
  9134. return colorsHash[hash];
  9135. }
  9136. colorsHash[hash] = colors.length;
  9137. colors.push(color.getHex());
  9138. return colorsHash[hash];
  9139. }
  9140. function getUvIndex(uv) {
  9141. var hash = uv.x.toString() + uv.y.toString();
  9142. if (uvsHash[hash] !== undefined) {
  9143. return uvsHash[hash];
  9144. }
  9145. uvsHash[hash] = uvs.length / 2;
  9146. uvs.push(uv.x, uv.y);
  9147. return uvsHash[hash];
  9148. }
  9149. data.data = {};
  9150. data.data.vertices = vertices;
  9151. data.data.normals = normals;
  9152. if (colors.length > 0) data.data.colors = colors;
  9153. if (uvs.length > 0) data.data.uvs = [uvs]; // temporal backward compatibility
  9154. data.data.faces = faces;
  9155. return data;
  9156. },
  9157. clone: function () {
  9158. /*
  9159. // Handle primitives
  9160. var parameters = this.parameters;
  9161. if ( parameters !== undefined ) {
  9162. var values = [];
  9163. for ( var key in parameters ) {
  9164. values.push( parameters[ key ] );
  9165. }
  9166. var geometry = Object.create( this.constructor.prototype );
  9167. this.constructor.apply( geometry, values );
  9168. return geometry;
  9169. }
  9170. return new this.constructor().copy( this );
  9171. */
  9172. return new Geometry().copy(this);
  9173. },
  9174. copy: function (source) {
  9175. var i, il, j, jl, k, kl; // reset
  9176. this.vertices = [];
  9177. this.colors = [];
  9178. this.faces = [];
  9179. this.faceVertexUvs = [[]];
  9180. this.morphTargets = [];
  9181. this.morphNormals = [];
  9182. this.skinWeights = [];
  9183. this.skinIndices = [];
  9184. this.lineDistances = [];
  9185. this.boundingBox = null;
  9186. this.boundingSphere = null; // name
  9187. this.name = source.name; // vertices
  9188. var vertices = source.vertices;
  9189. for (i = 0, il = vertices.length; i < il; i++) {
  9190. this.vertices.push(vertices[i].clone());
  9191. } // colors
  9192. var colors = source.colors;
  9193. for (i = 0, il = colors.length; i < il; i++) {
  9194. this.colors.push(colors[i].clone());
  9195. } // faces
  9196. var faces = source.faces;
  9197. for (i = 0, il = faces.length; i < il; i++) {
  9198. this.faces.push(faces[i].clone());
  9199. } // face vertex uvs
  9200. for (i = 0, il = source.faceVertexUvs.length; i < il; i++) {
  9201. var faceVertexUvs = source.faceVertexUvs[i];
  9202. if (this.faceVertexUvs[i] === undefined) {
  9203. this.faceVertexUvs[i] = [];
  9204. }
  9205. for (j = 0, jl = faceVertexUvs.length; j < jl; j++) {
  9206. var uvs = faceVertexUvs[j],
  9207. uvsCopy = [];
  9208. for (k = 0, kl = uvs.length; k < kl; k++) {
  9209. var uv = uvs[k];
  9210. uvsCopy.push(uv.clone());
  9211. }
  9212. this.faceVertexUvs[i].push(uvsCopy);
  9213. }
  9214. } // morph targets
  9215. var morphTargets = source.morphTargets;
  9216. for (i = 0, il = morphTargets.length; i < il; i++) {
  9217. var morphTarget = {};
  9218. morphTarget.name = morphTargets[i].name; // vertices
  9219. if (morphTargets[i].vertices !== undefined) {
  9220. morphTarget.vertices = [];
  9221. for (j = 0, jl = morphTargets[i].vertices.length; j < jl; j++) {
  9222. morphTarget.vertices.push(morphTargets[i].vertices[j].clone());
  9223. }
  9224. } // normals
  9225. if (morphTargets[i].normals !== undefined) {
  9226. morphTarget.normals = [];
  9227. for (j = 0, jl = morphTargets[i].normals.length; j < jl; j++) {
  9228. morphTarget.normals.push(morphTargets[i].normals[j].clone());
  9229. }
  9230. }
  9231. this.morphTargets.push(morphTarget);
  9232. } // morph normals
  9233. var morphNormals = source.morphNormals;
  9234. for (i = 0, il = morphNormals.length; i < il; i++) {
  9235. var morphNormal = {}; // vertex normals
  9236. if (morphNormals[i].vertexNormals !== undefined) {
  9237. morphNormal.vertexNormals = [];
  9238. for (j = 0, jl = morphNormals[i].vertexNormals.length; j < jl; j++) {
  9239. var srcVertexNormal = morphNormals[i].vertexNormals[j];
  9240. var destVertexNormal = {};
  9241. destVertexNormal.a = srcVertexNormal.a.clone();
  9242. destVertexNormal.b = srcVertexNormal.b.clone();
  9243. destVertexNormal.c = srcVertexNormal.c.clone();
  9244. morphNormal.vertexNormals.push(destVertexNormal);
  9245. }
  9246. } // face normals
  9247. if (morphNormals[i].faceNormals !== undefined) {
  9248. morphNormal.faceNormals = [];
  9249. for (j = 0, jl = morphNormals[i].faceNormals.length; j < jl; j++) {
  9250. morphNormal.faceNormals.push(morphNormals[i].faceNormals[j].clone());
  9251. }
  9252. }
  9253. this.morphNormals.push(morphNormal);
  9254. } // skin weights
  9255. var skinWeights = source.skinWeights;
  9256. for (i = 0, il = skinWeights.length; i < il; i++) {
  9257. this.skinWeights.push(skinWeights[i].clone());
  9258. } // skin indices
  9259. var skinIndices = source.skinIndices;
  9260. for (i = 0, il = skinIndices.length; i < il; i++) {
  9261. this.skinIndices.push(skinIndices[i].clone());
  9262. } // line distances
  9263. var lineDistances = source.lineDistances;
  9264. for (i = 0, il = lineDistances.length; i < il; i++) {
  9265. this.lineDistances.push(lineDistances[i]);
  9266. } // bounding box
  9267. var boundingBox = source.boundingBox;
  9268. if (boundingBox !== null) {
  9269. this.boundingBox = boundingBox.clone();
  9270. } // bounding sphere
  9271. var boundingSphere = source.boundingSphere;
  9272. if (boundingSphere !== null) {
  9273. this.boundingSphere = boundingSphere.clone();
  9274. } // update flags
  9275. this.elementsNeedUpdate = source.elementsNeedUpdate;
  9276. this.verticesNeedUpdate = source.verticesNeedUpdate;
  9277. this.uvsNeedUpdate = source.uvsNeedUpdate;
  9278. this.normalsNeedUpdate = source.normalsNeedUpdate;
  9279. this.colorsNeedUpdate = source.colorsNeedUpdate;
  9280. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  9281. this.groupsNeedUpdate = source.groupsNeedUpdate;
  9282. return this;
  9283. },
  9284. dispose: function () {
  9285. this.dispatchEvent({
  9286. type: 'dispose'
  9287. });
  9288. }
  9289. });
  9290. /**
  9291. * @author mrdoob / http://mrdoob.com/
  9292. * @author Mugen87 / https://github.com/Mugen87
  9293. */
  9294. // BoxGeometry
  9295. class BoxGeometry extends Geometry {
  9296. constructor(width, height, depth, widthSegments, heightSegments, depthSegments) {
  9297. super();
  9298. this.type = 'BoxGeometry';
  9299. this.parameters = {
  9300. width: width,
  9301. height: height,
  9302. depth: depth,
  9303. widthSegments: widthSegments,
  9304. heightSegments: heightSegments,
  9305. depthSegments: depthSegments
  9306. };
  9307. this.fromBufferGeometry(new BoxBufferGeometry(width, height, depth, widthSegments, heightSegments, depthSegments));
  9308. this.mergeVertices();
  9309. }
  9310. } // BoxBufferGeometry
  9311. exports.CubeGeometry = exports.BoxGeometry = BoxGeometry;
  9312. class BoxBufferGeometry extends BufferGeometry {
  9313. constructor(width, height, depth, widthSegments, heightSegments, depthSegments) {
  9314. super();
  9315. this.type = 'BoxBufferGeometry';
  9316. this.parameters = {
  9317. width: width,
  9318. height: height,
  9319. depth: depth,
  9320. widthSegments: widthSegments,
  9321. heightSegments: heightSegments,
  9322. depthSegments: depthSegments
  9323. };
  9324. var scope = this;
  9325. width = width || 1;
  9326. height = height || 1;
  9327. depth = depth || 1; // segments
  9328. widthSegments = Math.floor(widthSegments) || 1;
  9329. heightSegments = Math.floor(heightSegments) || 1;
  9330. depthSegments = Math.floor(depthSegments) || 1; // buffers
  9331. var indices = [];
  9332. var vertices = [];
  9333. var normals = [];
  9334. var uvs = []; // helper variables
  9335. var numberOfVertices = 0;
  9336. var groupStart = 0; // build each side of the box geometry
  9337. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  9338. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  9339. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  9340. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  9341. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  9342. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  9343. // build geometry
  9344. this.setIndex(indices);
  9345. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  9346. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  9347. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  9348. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  9349. var segmentWidth = width / gridX;
  9350. var segmentHeight = height / gridY;
  9351. var widthHalf = width / 2;
  9352. var heightHalf = height / 2;
  9353. var depthHalf = depth / 2;
  9354. var gridX1 = gridX + 1;
  9355. var gridY1 = gridY + 1;
  9356. var vertexCounter = 0;
  9357. var groupCount = 0;
  9358. var ix, iy;
  9359. var vector = new Vector3(); // generate vertices, normals and uvs
  9360. for (iy = 0; iy < gridY1; iy++) {
  9361. var y = iy * segmentHeight - heightHalf;
  9362. for (ix = 0; ix < gridX1; ix++) {
  9363. var x = ix * segmentWidth - widthHalf; // set values to correct vector component
  9364. vector[u] = x * udir;
  9365. vector[v] = y * vdir;
  9366. vector[w] = depthHalf; // now apply vector to vertex buffer
  9367. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  9368. vector[u] = 0;
  9369. vector[v] = 0;
  9370. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  9371. normals.push(vector.x, vector.y, vector.z); // uvs
  9372. uvs.push(ix / gridX);
  9373. uvs.push(1 - iy / gridY); // counters
  9374. vertexCounter += 1;
  9375. }
  9376. } // indices
  9377. // 1. you need three indices to draw a single face
  9378. // 2. a single segment consists of two faces
  9379. // 3. so we need to generate six (2*3) indices per segment
  9380. for (iy = 0; iy < gridY; iy++) {
  9381. for (ix = 0; ix < gridX; ix++) {
  9382. var a = numberOfVertices + ix + gridX1 * iy;
  9383. var b = numberOfVertices + ix + gridX1 * (iy + 1);
  9384. var c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  9385. var d = numberOfVertices + (ix + 1) + gridX1 * iy; // faces
  9386. indices.push(a, b, d);
  9387. indices.push(b, c, d); // increase counter
  9388. groupCount += 6;
  9389. }
  9390. } // add a group to the geometry. this will ensure multi material support
  9391. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  9392. groupStart += groupCount; // update total number of vertices
  9393. numberOfVertices += vertexCounter;
  9394. }
  9395. }
  9396. }
  9397. /**
  9398. * Uniform Utilities
  9399. */
  9400. exports.BoxBufferGeometry = BoxBufferGeometry;
  9401. function cloneUniforms(src) {
  9402. var dst = {};
  9403. for (var u in src) {
  9404. dst[u] = {};
  9405. for (var p in src[u]) {
  9406. var property = src[u][p];
  9407. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture)) {
  9408. dst[u][p] = property.clone();
  9409. } else if (Array.isArray(property)) {
  9410. dst[u][p] = property.slice();
  9411. } else {
  9412. dst[u][p] = property;
  9413. }
  9414. }
  9415. }
  9416. return dst;
  9417. }
  9418. function mergeUniforms(uniforms) {
  9419. var merged = {};
  9420. for (var u = 0; u < uniforms.length; u++) {
  9421. var tmp = cloneUniforms(uniforms[u]);
  9422. for (var p in tmp) {
  9423. merged[p] = tmp[p];
  9424. }
  9425. }
  9426. return merged;
  9427. } // Legacy
  9428. var UniformsUtils = {
  9429. clone: cloneUniforms,
  9430. merge: mergeUniforms
  9431. };
  9432. exports.UniformsUtils = UniformsUtils;
  9433. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  9434. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  9435. /**
  9436. * @author alteredq / http://alteredqualia.com/
  9437. *
  9438. * parameters = {
  9439. * defines: { "label" : "value" },
  9440. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  9441. *
  9442. * fragmentShader: <string>,
  9443. * vertexShader: <string>,
  9444. *
  9445. * wireframe: <boolean>,
  9446. * wireframeLinewidth: <float>,
  9447. *
  9448. * lights: <bool>,
  9449. *
  9450. * skinning: <bool>,
  9451. * morphTargets: <bool>,
  9452. * morphNormals: <bool>
  9453. * }
  9454. */
  9455. function ShaderMaterial(parameters) {
  9456. Material.call(this);
  9457. this.type = 'ShaderMaterial';
  9458. this.defines = {};
  9459. this.uniforms = {};
  9460. this.vertexShader = default_vertex;
  9461. this.fragmentShader = default_fragment;
  9462. this.linewidth = 1;
  9463. this.wireframe = false;
  9464. this.wireframeLinewidth = 1;
  9465. this.fog = false; // set to use scene fog
  9466. this.lights = false; // set to use scene lights
  9467. this.clipping = false; // set to use user-defined clipping planes
  9468. this.skinning = false; // set to use skinning attribute streams
  9469. this.morphTargets = false; // set to use morph targets
  9470. this.morphNormals = false; // set to use morph normals
  9471. this.extensions = {
  9472. derivatives: false,
  9473. // set to use derivatives
  9474. fragDepth: false,
  9475. // set to use fragment depth values
  9476. drawBuffers: false,
  9477. // set to use draw buffers
  9478. shaderTextureLOD: false // set to use shader texture LOD
  9479. }; // When rendered geometry doesn't include these attributes but the material does,
  9480. // use these default values in WebGL. This avoids errors when buffer data is missing.
  9481. this.defaultAttributeValues = {
  9482. 'color': [1, 1, 1],
  9483. 'uv': [0, 0],
  9484. 'uv2': [0, 0]
  9485. };
  9486. this.index0AttributeName = undefined;
  9487. this.uniformsNeedUpdate = false;
  9488. if (parameters !== undefined) {
  9489. if (parameters.attributes !== undefined) {
  9490. console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
  9491. }
  9492. this.setValues(parameters);
  9493. }
  9494. }
  9495. ShaderMaterial.prototype = Object.create(Material.prototype);
  9496. ShaderMaterial.prototype.constructor = ShaderMaterial;
  9497. ShaderMaterial.prototype.isShaderMaterial = true;
  9498. ShaderMaterial.prototype.copy = function (source) {
  9499. Material.prototype.copy.call(this, source);
  9500. this.fragmentShader = source.fragmentShader;
  9501. this.vertexShader = source.vertexShader;
  9502. this.uniforms = cloneUniforms(source.uniforms);
  9503. this.defines = Object.assign({}, source.defines);
  9504. this.wireframe = source.wireframe;
  9505. this.wireframeLinewidth = source.wireframeLinewidth;
  9506. this.lights = source.lights;
  9507. this.clipping = source.clipping;
  9508. this.skinning = source.skinning;
  9509. this.morphTargets = source.morphTargets;
  9510. this.morphNormals = source.morphNormals;
  9511. this.extensions = source.extensions;
  9512. return this;
  9513. };
  9514. ShaderMaterial.prototype.toJSON = function (meta) {
  9515. var data = Material.prototype.toJSON.call(this, meta);
  9516. data.uniforms = {};
  9517. for (var name in this.uniforms) {
  9518. var uniform = this.uniforms[name];
  9519. var value = uniform.value;
  9520. if (value && value.isTexture) {
  9521. data.uniforms[name] = {
  9522. type: 't',
  9523. value: value.toJSON(meta).uuid
  9524. };
  9525. } else if (value && value.isColor) {
  9526. data.uniforms[name] = {
  9527. type: 'c',
  9528. value: value.getHex()
  9529. };
  9530. } else if (value && value.isVector2) {
  9531. data.uniforms[name] = {
  9532. type: 'v2',
  9533. value: value.toArray()
  9534. };
  9535. } else if (value && value.isVector3) {
  9536. data.uniforms[name] = {
  9537. type: 'v3',
  9538. value: value.toArray()
  9539. };
  9540. } else if (value && value.isVector4) {
  9541. data.uniforms[name] = {
  9542. type: 'v4',
  9543. value: value.toArray()
  9544. };
  9545. } else if (value && value.isMatrix3) {
  9546. data.uniforms[name] = {
  9547. type: 'm3',
  9548. value: value.toArray()
  9549. };
  9550. } else if (value && value.isMatrix4) {
  9551. data.uniforms[name] = {
  9552. type: 'm4',
  9553. value: value.toArray()
  9554. };
  9555. } else {
  9556. data.uniforms[name] = {
  9557. value: value
  9558. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  9559. }
  9560. }
  9561. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  9562. data.vertexShader = this.vertexShader;
  9563. data.fragmentShader = this.fragmentShader;
  9564. var extensions = {};
  9565. for (var key in this.extensions) {
  9566. if (this.extensions[key] === true) extensions[key] = true;
  9567. }
  9568. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  9569. return data;
  9570. };
  9571. /**
  9572. * @author mrdoob / http://mrdoob.com/
  9573. * @author mikael emtinger / http://gomo.se/
  9574. * @author WestLangley / http://github.com/WestLangley
  9575. */
  9576. function Camera() {
  9577. Object3D.call(this);
  9578. this.type = 'Camera';
  9579. this.matrixWorldInverse = new Matrix4();
  9580. this.projectionMatrix = new Matrix4();
  9581. this.projectionMatrixInverse = new Matrix4();
  9582. }
  9583. Camera.prototype = Object.assign(Object.create(Object3D.prototype), {
  9584. constructor: Camera,
  9585. isCamera: true,
  9586. copy: function (source, recursive) {
  9587. Object3D.prototype.copy.call(this, source, recursive);
  9588. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  9589. this.projectionMatrix.copy(source.projectionMatrix);
  9590. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  9591. return this;
  9592. },
  9593. getWorldDirection: function (target) {
  9594. if (target === undefined) {
  9595. console.warn('THREE.Camera: .getWorldDirection() target is now required');
  9596. target = new Vector3();
  9597. }
  9598. this.updateMatrixWorld(true);
  9599. var e = this.matrixWorld.elements;
  9600. return target.set(-e[8], -e[9], -e[10]).normalize();
  9601. },
  9602. updateMatrixWorld: function (force) {
  9603. Object3D.prototype.updateMatrixWorld.call(this, force);
  9604. this.matrixWorldInverse.getInverse(this.matrixWorld);
  9605. },
  9606. clone: function () {
  9607. return new this.constructor().copy(this);
  9608. }
  9609. });
  9610. /**
  9611. * @author mrdoob / http://mrdoob.com/
  9612. * @author greggman / http://games.greggman.com/
  9613. * @author zz85 / http://www.lab4games.net/zz85/blog
  9614. * @author tschw
  9615. */
  9616. function PerspectiveCamera(fov, aspect, near, far) {
  9617. Camera.call(this);
  9618. this.type = 'PerspectiveCamera';
  9619. this.fov = fov !== undefined ? fov : 50;
  9620. this.zoom = 1;
  9621. this.near = near !== undefined ? near : 0.1;
  9622. this.far = far !== undefined ? far : 2000;
  9623. this.focus = 10;
  9624. this.aspect = aspect !== undefined ? aspect : 1;
  9625. this.view = null;
  9626. this.filmGauge = 35; // width of the film (default in millimeters)
  9627. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  9628. this.updateProjectionMatrix();
  9629. }
  9630. PerspectiveCamera.prototype = Object.assign(Object.create(Camera.prototype), {
  9631. constructor: PerspectiveCamera,
  9632. isPerspectiveCamera: true,
  9633. copy: function (source, recursive) {
  9634. Camera.prototype.copy.call(this, source, recursive);
  9635. this.fov = source.fov;
  9636. this.zoom = source.zoom;
  9637. this.near = source.near;
  9638. this.far = source.far;
  9639. this.focus = source.focus;
  9640. this.aspect = source.aspect;
  9641. this.view = source.view === null ? null : Object.assign({}, source.view);
  9642. this.filmGauge = source.filmGauge;
  9643. this.filmOffset = source.filmOffset;
  9644. return this;
  9645. },
  9646. /**
  9647. * Sets the FOV by focal length in respect to the current .filmGauge.
  9648. *
  9649. * The default film gauge is 35, so that the focal length can be specified for
  9650. * a 35mm (full frame) camera.
  9651. *
  9652. * Values for focal length and film gauge must have the same unit.
  9653. */
  9654. setFocalLength: function (focalLength) {
  9655. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  9656. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  9657. this.fov = _Math.RAD2DEG * 2 * Math.atan(vExtentSlope);
  9658. this.updateProjectionMatrix();
  9659. },
  9660. /**
  9661. * Calculates the focal length from the current .fov and .filmGauge.
  9662. */
  9663. getFocalLength: function () {
  9664. var vExtentSlope = Math.tan(_Math.DEG2RAD * 0.5 * this.fov);
  9665. return 0.5 * this.getFilmHeight() / vExtentSlope;
  9666. },
  9667. getEffectiveFOV: function () {
  9668. return _Math.RAD2DEG * 2 * Math.atan(Math.tan(_Math.DEG2RAD * 0.5 * this.fov) / this.zoom);
  9669. },
  9670. getFilmWidth: function () {
  9671. // film not completely covered in portrait format (aspect < 1)
  9672. return this.filmGauge * Math.min(this.aspect, 1);
  9673. },
  9674. getFilmHeight: function () {
  9675. // film not completely covered in landscape format (aspect > 1)
  9676. return this.filmGauge / Math.max(this.aspect, 1);
  9677. },
  9678. /**
  9679. * Sets an offset in a larger frustum. This is useful for multi-window or
  9680. * multi-monitor/multi-machine setups.
  9681. *
  9682. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  9683. * the monitors are in grid like this
  9684. *
  9685. * +---+---+---+
  9686. * | A | B | C |
  9687. * +---+---+---+
  9688. * | D | E | F |
  9689. * +---+---+---+
  9690. *
  9691. * then for each monitor you would call it like this
  9692. *
  9693. * var w = 1920;
  9694. * var h = 1080;
  9695. * var fullWidth = w * 3;
  9696. * var fullHeight = h * 2;
  9697. *
  9698. * --A--
  9699. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  9700. * --B--
  9701. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  9702. * --C--
  9703. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  9704. * --D--
  9705. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  9706. * --E--
  9707. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  9708. * --F--
  9709. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  9710. *
  9711. * Note there is no reason monitors have to be the same size or in a grid.
  9712. */
  9713. setViewOffset: function (fullWidth, fullHeight, x, y, width, height) {
  9714. this.aspect = fullWidth / fullHeight;
  9715. if (this.view === null) {
  9716. this.view = {
  9717. enabled: true,
  9718. fullWidth: 1,
  9719. fullHeight: 1,
  9720. offsetX: 0,
  9721. offsetY: 0,
  9722. width: 1,
  9723. height: 1
  9724. };
  9725. }
  9726. this.view.enabled = true;
  9727. this.view.fullWidth = fullWidth;
  9728. this.view.fullHeight = fullHeight;
  9729. this.view.offsetX = x;
  9730. this.view.offsetY = y;
  9731. this.view.width = width;
  9732. this.view.height = height;
  9733. this.updateProjectionMatrix();
  9734. },
  9735. clearViewOffset: function () {
  9736. if (this.view !== null) {
  9737. this.view.enabled = false;
  9738. }
  9739. this.updateProjectionMatrix();
  9740. },
  9741. updateProjectionMatrix: function () {
  9742. var near = this.near,
  9743. top = near * Math.tan(_Math.DEG2RAD * 0.5 * this.fov) / this.zoom,
  9744. height = 2 * top,
  9745. width = this.aspect * height,
  9746. left = -0.5 * width,
  9747. view = this.view;
  9748. if (this.view !== null && this.view.enabled) {
  9749. var fullWidth = view.fullWidth,
  9750. fullHeight = view.fullHeight;
  9751. left += view.offsetX * width / fullWidth;
  9752. top -= view.offsetY * height / fullHeight;
  9753. width *= view.width / fullWidth;
  9754. height *= view.height / fullHeight;
  9755. }
  9756. var skew = this.filmOffset;
  9757. if (skew !== 0) left += near * skew / this.getFilmWidth();
  9758. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  9759. this.projectionMatrixInverse.getInverse(this.projectionMatrix);
  9760. },
  9761. toJSON: function (meta) {
  9762. var data = Object3D.prototype.toJSON.call(this, meta);
  9763. data.object.fov = this.fov;
  9764. data.object.zoom = this.zoom;
  9765. data.object.near = this.near;
  9766. data.object.far = this.far;
  9767. data.object.focus = this.focus;
  9768. data.object.aspect = this.aspect;
  9769. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  9770. data.object.filmGauge = this.filmGauge;
  9771. data.object.filmOffset = this.filmOffset;
  9772. return data;
  9773. }
  9774. });
  9775. /**
  9776. * Camera for rendering cube maps
  9777. * - renders scene into axis-aligned cube
  9778. *
  9779. * @author alteredq / http://alteredqualia.com/
  9780. */
  9781. var fov = 90,
  9782. aspect = 1;
  9783. function CubeCamera(near, far, cubeResolution, options) {
  9784. Object3D.call(this);
  9785. this.type = 'CubeCamera';
  9786. var cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  9787. cameraPX.up.set(0, -1, 0);
  9788. cameraPX.lookAt(new Vector3(1, 0, 0));
  9789. this.add(cameraPX);
  9790. var cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  9791. cameraNX.up.set(0, -1, 0);
  9792. cameraNX.lookAt(new Vector3(-1, 0, 0));
  9793. this.add(cameraNX);
  9794. var cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  9795. cameraPY.up.set(0, 0, 1);
  9796. cameraPY.lookAt(new Vector3(0, 1, 0));
  9797. this.add(cameraPY);
  9798. var cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  9799. cameraNY.up.set(0, 0, -1);
  9800. cameraNY.lookAt(new Vector3(0, -1, 0));
  9801. this.add(cameraNY);
  9802. var cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  9803. cameraPZ.up.set(0, -1, 0);
  9804. cameraPZ.lookAt(new Vector3(0, 0, 1));
  9805. this.add(cameraPZ);
  9806. var cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  9807. cameraNZ.up.set(0, -1, 0);
  9808. cameraNZ.lookAt(new Vector3(0, 0, -1));
  9809. this.add(cameraNZ);
  9810. options = options || {
  9811. format: RGBFormat,
  9812. magFilter: LinearFilter,
  9813. minFilter: LinearFilter
  9814. };
  9815. this.renderTarget = new WebGLRenderTargetCube(cubeResolution, cubeResolution, options);
  9816. this.renderTarget.texture.name = "CubeCamera";
  9817. this.update = function (renderer, scene) {
  9818. if (this.parent === null) this.updateMatrixWorld();
  9819. var currentRenderTarget = renderer.getRenderTarget();
  9820. var renderTarget = this.renderTarget;
  9821. var generateMipmaps = renderTarget.texture.generateMipmaps;
  9822. renderTarget.texture.generateMipmaps = false;
  9823. renderer.setRenderTarget(renderTarget, 0);
  9824. renderer.render(scene, cameraPX);
  9825. renderer.setRenderTarget(renderTarget, 1);
  9826. renderer.render(scene, cameraNX);
  9827. renderer.setRenderTarget(renderTarget, 2);
  9828. renderer.render(scene, cameraPY);
  9829. renderer.setRenderTarget(renderTarget, 3);
  9830. renderer.render(scene, cameraNY);
  9831. renderer.setRenderTarget(renderTarget, 4);
  9832. renderer.render(scene, cameraPZ);
  9833. renderTarget.texture.generateMipmaps = generateMipmaps;
  9834. renderer.setRenderTarget(renderTarget, 5);
  9835. renderer.render(scene, cameraNZ);
  9836. renderer.setRenderTarget(currentRenderTarget);
  9837. };
  9838. this.clear = function (renderer, color, depth, stencil) {
  9839. var currentRenderTarget = renderer.getRenderTarget();
  9840. var renderTarget = this.renderTarget;
  9841. for (var i = 0; i < 6; i++) {
  9842. renderer.setRenderTarget(renderTarget, i);
  9843. renderer.clear(color, depth, stencil);
  9844. }
  9845. renderer.setRenderTarget(currentRenderTarget);
  9846. };
  9847. }
  9848. CubeCamera.prototype = Object.create(Object3D.prototype);
  9849. CubeCamera.prototype.constructor = CubeCamera;
  9850. /**
  9851. * @author alteredq / http://alteredqualia.com
  9852. * @author WestLangley / http://github.com/WestLangley
  9853. */
  9854. function WebGLRenderTargetCube(width, height, options) {
  9855. WebGLRenderTarget.call(this, width, height, options);
  9856. }
  9857. WebGLRenderTargetCube.prototype = Object.create(WebGLRenderTarget.prototype);
  9858. WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;
  9859. WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;
  9860. WebGLRenderTargetCube.prototype.fromEquirectangularTexture = function (renderer, texture) {
  9861. this.texture.type = texture.type;
  9862. this.texture.format = texture.format;
  9863. this.texture.encoding = texture.encoding;
  9864. var scene = new Scene();
  9865. var shader = {
  9866. uniforms: {
  9867. tEquirect: {
  9868. value: null
  9869. }
  9870. },
  9871. 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'),
  9872. 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')
  9873. };
  9874. var material = new ShaderMaterial({
  9875. type: 'CubemapFromEquirect',
  9876. uniforms: cloneUniforms(shader.uniforms),
  9877. vertexShader: shader.vertexShader,
  9878. fragmentShader: shader.fragmentShader,
  9879. side: BackSide,
  9880. blending: NoBlending
  9881. });
  9882. material.uniforms.tEquirect.value = texture;
  9883. var mesh = new Mesh(new BoxBufferGeometry(5, 5, 5), material);
  9884. scene.add(mesh);
  9885. var camera = new CubeCamera(1, 10, 1);
  9886. camera.renderTarget = this;
  9887. camera.renderTarget.texture.name = 'CubeCameraTexture';
  9888. camera.update(renderer, scene);
  9889. mesh.geometry.dispose();
  9890. mesh.material.dispose();
  9891. return this;
  9892. };
  9893. /**
  9894. * @author alteredq / http://alteredqualia.com/
  9895. */
  9896. function DataTexture(data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  9897. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  9898. this.image = {
  9899. data: data || null,
  9900. width: width || 1,
  9901. height: height || 1
  9902. };
  9903. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  9904. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  9905. this.generateMipmaps = false;
  9906. this.flipY = false;
  9907. this.unpackAlignment = 1;
  9908. this.needsUpdate = true;
  9909. }
  9910. DataTexture.prototype = Object.create(Texture.prototype);
  9911. DataTexture.prototype.constructor = DataTexture;
  9912. DataTexture.prototype.isDataTexture = true;
  9913. /**
  9914. * @author bhouston / http://clara.io
  9915. */
  9916. var _vector1 = new Vector3();
  9917. var _vector2 = new Vector3();
  9918. var _normalMatrix = new Matrix3();
  9919. function Plane(normal, constant) {
  9920. // normal is assumed to be normalized
  9921. this.normal = normal !== undefined ? normal : new Vector3(1, 0, 0);
  9922. this.constant = constant !== undefined ? constant : 0;
  9923. }
  9924. Object.assign(Plane.prototype, {
  9925. isPlane: true,
  9926. set: function (normal, constant) {
  9927. this.normal.copy(normal);
  9928. this.constant = constant;
  9929. return this;
  9930. },
  9931. setComponents: function (x, y, z, w) {
  9932. this.normal.set(x, y, z);
  9933. this.constant = w;
  9934. return this;
  9935. },
  9936. setFromNormalAndCoplanarPoint: function (normal, point) {
  9937. this.normal.copy(normal);
  9938. this.constant = -point.dot(this.normal);
  9939. return this;
  9940. },
  9941. setFromCoplanarPoints: function (a, b, c) {
  9942. 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)?
  9943. this.setFromNormalAndCoplanarPoint(normal, a);
  9944. return this;
  9945. },
  9946. clone: function () {
  9947. return new this.constructor().copy(this);
  9948. },
  9949. copy: function (plane) {
  9950. this.normal.copy(plane.normal);
  9951. this.constant = plane.constant;
  9952. return this;
  9953. },
  9954. normalize: function () {
  9955. // Note: will lead to a divide by zero if the plane is invalid.
  9956. var inverseNormalLength = 1.0 / this.normal.length();
  9957. this.normal.multiplyScalar(inverseNormalLength);
  9958. this.constant *= inverseNormalLength;
  9959. return this;
  9960. },
  9961. negate: function () {
  9962. this.constant *= -1;
  9963. this.normal.negate();
  9964. return this;
  9965. },
  9966. distanceToPoint: function (point) {
  9967. return this.normal.dot(point) + this.constant;
  9968. },
  9969. distanceToSphere: function (sphere) {
  9970. return this.distanceToPoint(sphere.center) - sphere.radius;
  9971. },
  9972. projectPoint: function (point, target) {
  9973. if (target === undefined) {
  9974. console.warn('THREE.Plane: .projectPoint() target is now required');
  9975. target = new Vector3();
  9976. }
  9977. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  9978. },
  9979. intersectLine: function (line, target) {
  9980. if (target === undefined) {
  9981. console.warn('THREE.Plane: .intersectLine() target is now required');
  9982. target = new Vector3();
  9983. }
  9984. var direction = line.delta(_vector1);
  9985. var denominator = this.normal.dot(direction);
  9986. if (denominator === 0) {
  9987. // line is coplanar, return origin
  9988. if (this.distanceToPoint(line.start) === 0) {
  9989. return target.copy(line.start);
  9990. } // Unsure if this is the correct method to handle this case.
  9991. return undefined;
  9992. }
  9993. var t = -(line.start.dot(this.normal) + this.constant) / denominator;
  9994. if (t < 0 || t > 1) {
  9995. return undefined;
  9996. }
  9997. return target.copy(direction).multiplyScalar(t).add(line.start);
  9998. },
  9999. intersectsLine: function (line) {
  10000. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  10001. var startSign = this.distanceToPoint(line.start);
  10002. var endSign = this.distanceToPoint(line.end);
  10003. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  10004. },
  10005. intersectsBox: function (box) {
  10006. return box.intersectsPlane(this);
  10007. },
  10008. intersectsSphere: function (sphere) {
  10009. return sphere.intersectsPlane(this);
  10010. },
  10011. coplanarPoint: function (target) {
  10012. if (target === undefined) {
  10013. console.warn('THREE.Plane: .coplanarPoint() target is now required');
  10014. target = new Vector3();
  10015. }
  10016. return target.copy(this.normal).multiplyScalar(-this.constant);
  10017. },
  10018. applyMatrix4: function (matrix, optionalNormalMatrix) {
  10019. var normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  10020. var referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  10021. var normal = this.normal.applyMatrix3(normalMatrix).normalize();
  10022. this.constant = -referencePoint.dot(normal);
  10023. return this;
  10024. },
  10025. translate: function (offset) {
  10026. this.constant -= offset.dot(this.normal);
  10027. return this;
  10028. },
  10029. equals: function (plane) {
  10030. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  10031. }
  10032. });
  10033. /**
  10034. * @author mrdoob / http://mrdoob.com/
  10035. * @author alteredq / http://alteredqualia.com/
  10036. * @author bhouston / http://clara.io
  10037. */
  10038. var _sphere$1 = new Sphere();
  10039. var _vector$5 = new Vector3();
  10040. function Frustum(p0, p1, p2, p3, p4, p5) {
  10041. 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()];
  10042. }
  10043. Object.assign(Frustum.prototype, {
  10044. set: function (p0, p1, p2, p3, p4, p5) {
  10045. var planes = this.planes;
  10046. planes[0].copy(p0);
  10047. planes[1].copy(p1);
  10048. planes[2].copy(p2);
  10049. planes[3].copy(p3);
  10050. planes[4].copy(p4);
  10051. planes[5].copy(p5);
  10052. return this;
  10053. },
  10054. clone: function () {
  10055. return new this.constructor().copy(this);
  10056. },
  10057. copy: function (frustum) {
  10058. var planes = this.planes;
  10059. for (var i = 0; i < 6; i++) {
  10060. planes[i].copy(frustum.planes[i]);
  10061. }
  10062. return this;
  10063. },
  10064. setFromMatrix: function (m) {
  10065. var planes = this.planes;
  10066. var me = m.elements;
  10067. var me0 = me[0],
  10068. me1 = me[1],
  10069. me2 = me[2],
  10070. me3 = me[3];
  10071. var me4 = me[4],
  10072. me5 = me[5],
  10073. me6 = me[6],
  10074. me7 = me[7];
  10075. var me8 = me[8],
  10076. me9 = me[9],
  10077. me10 = me[10],
  10078. me11 = me[11];
  10079. var me12 = me[12],
  10080. me13 = me[13],
  10081. me14 = me[14],
  10082. me15 = me[15];
  10083. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  10084. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  10085. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  10086. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  10087. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  10088. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  10089. return this;
  10090. },
  10091. intersectsObject: function (object) {
  10092. var geometry = object.geometry;
  10093. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  10094. _sphere$1.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  10095. return this.intersectsSphere(_sphere$1);
  10096. },
  10097. intersectsSprite: function (sprite) {
  10098. _sphere$1.center.set(0, 0, 0);
  10099. _sphere$1.radius = 0.7071067811865476;
  10100. _sphere$1.applyMatrix4(sprite.matrixWorld);
  10101. return this.intersectsSphere(_sphere$1);
  10102. },
  10103. intersectsSphere: function (sphere) {
  10104. var planes = this.planes;
  10105. var center = sphere.center;
  10106. var negRadius = -sphere.radius;
  10107. for (var i = 0; i < 6; i++) {
  10108. var distance = planes[i].distanceToPoint(center);
  10109. if (distance < negRadius) {
  10110. return false;
  10111. }
  10112. }
  10113. return true;
  10114. },
  10115. intersectsBox: function (box) {
  10116. var planes = this.planes;
  10117. for (var i = 0; i < 6; i++) {
  10118. var plane = planes[i]; // corner at max distance
  10119. _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  10120. _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  10121. _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  10122. if (plane.distanceToPoint(_vector$5) < 0) {
  10123. return false;
  10124. }
  10125. }
  10126. return true;
  10127. },
  10128. containsPoint: function (point) {
  10129. var planes = this.planes;
  10130. for (var i = 0; i < 6; i++) {
  10131. if (planes[i].distanceToPoint(point) < 0) {
  10132. return false;
  10133. }
  10134. }
  10135. return true;
  10136. }
  10137. });
  10138. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  10139. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  10140. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  10141. 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";
  10142. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  10143. var begin_vertex = "vec3 transformed = vec3( position );";
  10144. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  10145. 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";
  10146. 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";
  10147. 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";
  10148. 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";
  10149. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\tvarying vec3 vViewPosition;\n#endif";
  10150. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif";
  10151. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  10152. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  10153. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  10154. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  10155. 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}";
  10156. 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";
  10157. 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";
  10158. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  10159. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  10160. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  10161. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  10162. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  10163. 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}";
  10164. 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";
  10165. 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";
  10166. 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";
  10167. 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";
  10168. 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";
  10169. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = -mvPosition.z;\n#endif";
  10170. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  10171. 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";
  10172. 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";
  10173. 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";
  10174. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif";
  10175. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  10176. 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";
  10177. 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";
  10178. 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";
  10179. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  10180. 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)";
  10181. 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";
  10182. 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}";
  10183. 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";
  10184. 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";
  10185. 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";
  10186. 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";
  10187. 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";
  10188. 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";
  10189. 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";
  10190. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  10191. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  10192. 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";
  10193. var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform mat3 uvTransform;\n\tuniform sampler2D map;\n#endif";
  10194. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  10195. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  10196. 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";
  10197. 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";
  10198. 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";
  10199. 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;";
  10200. 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";
  10201. 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";
  10202. var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  10203. 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";
  10204. var clearcoat_normalmap_pars_fragment = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif";
  10205. 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}";
  10206. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  10207. 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;";
  10208. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  10209. 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";
  10210. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  10211. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  10212. 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";
  10213. 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";
  10214. 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";
  10215. 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}";
  10216. 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";
  10217. 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";
  10218. 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";
  10219. 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";
  10220. 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";
  10221. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  10222. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  10223. 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}";
  10224. var uv_pars_fragment = "#ifdef USE_UV\n\tvarying vec2 vUv;\n#endif";
  10225. var uv_pars_vertex = "#ifdef USE_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif";
  10226. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  10227. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  10228. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";
  10229. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";
  10230. 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";
  10231. 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}";
  10232. 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}";
  10233. 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}";
  10234. 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}";
  10235. 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}";
  10236. 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}";
  10237. 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}";
  10238. 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}";
  10239. 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}";
  10240. 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}";
  10241. 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}";
  10242. 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}";
  10243. 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}";
  10244. 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}";
  10245. 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}";
  10246. 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}";
  10247. 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}";
  10248. 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}";
  10249. 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}";
  10250. 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}";
  10251. 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}";
  10252. 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}";
  10253. 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}";
  10254. 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}";
  10255. 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}";
  10256. 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}";
  10257. 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}";
  10258. 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}";
  10259. 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}";
  10260. 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}";
  10261. var ShaderChunk = {
  10262. alphamap_fragment: alphamap_fragment,
  10263. alphamap_pars_fragment: alphamap_pars_fragment,
  10264. alphatest_fragment: alphatest_fragment,
  10265. aomap_fragment: aomap_fragment,
  10266. aomap_pars_fragment: aomap_pars_fragment,
  10267. begin_vertex: begin_vertex,
  10268. beginnormal_vertex: beginnormal_vertex,
  10269. bsdfs: bsdfs,
  10270. bumpmap_pars_fragment: bumpmap_pars_fragment,
  10271. clipping_planes_fragment: clipping_planes_fragment,
  10272. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  10273. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  10274. clipping_planes_vertex: clipping_planes_vertex,
  10275. color_fragment: color_fragment,
  10276. color_pars_fragment: color_pars_fragment,
  10277. color_pars_vertex: color_pars_vertex,
  10278. color_vertex: color_vertex,
  10279. common: common,
  10280. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  10281. defaultnormal_vertex: defaultnormal_vertex,
  10282. displacementmap_pars_vertex: displacementmap_pars_vertex,
  10283. displacementmap_vertex: displacementmap_vertex,
  10284. emissivemap_fragment: emissivemap_fragment,
  10285. emissivemap_pars_fragment: emissivemap_pars_fragment,
  10286. encodings_fragment: encodings_fragment,
  10287. encodings_pars_fragment: encodings_pars_fragment,
  10288. envmap_fragment: envmap_fragment,
  10289. envmap_common_pars_fragment: envmap_common_pars_fragment,
  10290. envmap_pars_fragment: envmap_pars_fragment,
  10291. envmap_pars_vertex: envmap_pars_vertex,
  10292. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  10293. envmap_vertex: envmap_vertex,
  10294. fog_vertex: fog_vertex,
  10295. fog_pars_vertex: fog_pars_vertex,
  10296. fog_fragment: fog_fragment,
  10297. fog_pars_fragment: fog_pars_fragment,
  10298. gradientmap_pars_fragment: gradientmap_pars_fragment,
  10299. lightmap_fragment: lightmap_fragment,
  10300. lightmap_pars_fragment: lightmap_pars_fragment,
  10301. lights_lambert_vertex: lights_lambert_vertex,
  10302. lights_pars_begin: lights_pars_begin,
  10303. lights_phong_fragment: lights_phong_fragment,
  10304. lights_phong_pars_fragment: lights_phong_pars_fragment,
  10305. lights_physical_fragment: lights_physical_fragment,
  10306. lights_physical_pars_fragment: lights_physical_pars_fragment,
  10307. lights_fragment_begin: lights_fragment_begin,
  10308. lights_fragment_maps: lights_fragment_maps,
  10309. lights_fragment_end: lights_fragment_end,
  10310. logdepthbuf_fragment: logdepthbuf_fragment,
  10311. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  10312. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  10313. logdepthbuf_vertex: logdepthbuf_vertex,
  10314. map_fragment: map_fragment,
  10315. map_pars_fragment: map_pars_fragment,
  10316. map_particle_fragment: map_particle_fragment,
  10317. map_particle_pars_fragment: map_particle_pars_fragment,
  10318. metalnessmap_fragment: metalnessmap_fragment,
  10319. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  10320. morphnormal_vertex: morphnormal_vertex,
  10321. morphtarget_pars_vertex: morphtarget_pars_vertex,
  10322. morphtarget_vertex: morphtarget_vertex,
  10323. normal_fragment_begin: normal_fragment_begin,
  10324. normal_fragment_maps: normal_fragment_maps,
  10325. normalmap_pars_fragment: normalmap_pars_fragment,
  10326. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  10327. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  10328. clearcoat_normalmap_pars_fragment: clearcoat_normalmap_pars_fragment,
  10329. packing: packing,
  10330. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  10331. project_vertex: project_vertex,
  10332. dithering_fragment: dithering_fragment,
  10333. dithering_pars_fragment: dithering_pars_fragment,
  10334. roughnessmap_fragment: roughnessmap_fragment,
  10335. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  10336. shadowmap_pars_fragment: shadowmap_pars_fragment,
  10337. shadowmap_pars_vertex: shadowmap_pars_vertex,
  10338. shadowmap_vertex: shadowmap_vertex,
  10339. shadowmask_pars_fragment: shadowmask_pars_fragment,
  10340. skinbase_vertex: skinbase_vertex,
  10341. skinning_pars_vertex: skinning_pars_vertex,
  10342. skinning_vertex: skinning_vertex,
  10343. skinnormal_vertex: skinnormal_vertex,
  10344. specularmap_fragment: specularmap_fragment,
  10345. specularmap_pars_fragment: specularmap_pars_fragment,
  10346. tonemapping_fragment: tonemapping_fragment,
  10347. tonemapping_pars_fragment: tonemapping_pars_fragment,
  10348. uv_pars_fragment: uv_pars_fragment,
  10349. uv_pars_vertex: uv_pars_vertex,
  10350. uv_vertex: uv_vertex,
  10351. uv2_pars_fragment: uv2_pars_fragment,
  10352. uv2_pars_vertex: uv2_pars_vertex,
  10353. uv2_vertex: uv2_vertex,
  10354. worldpos_vertex: worldpos_vertex,
  10355. background_frag: background_frag,
  10356. background_vert: background_vert,
  10357. cube_frag: cube_frag,
  10358. cube_vert: cube_vert,
  10359. depth_frag: depth_frag,
  10360. depth_vert: depth_vert,
  10361. distanceRGBA_frag: distanceRGBA_frag,
  10362. distanceRGBA_vert: distanceRGBA_vert,
  10363. equirect_frag: equirect_frag,
  10364. equirect_vert: equirect_vert,
  10365. linedashed_frag: linedashed_frag,
  10366. linedashed_vert: linedashed_vert,
  10367. meshbasic_frag: meshbasic_frag,
  10368. meshbasic_vert: meshbasic_vert,
  10369. meshlambert_frag: meshlambert_frag,
  10370. meshlambert_vert: meshlambert_vert,
  10371. meshmatcap_frag: meshmatcap_frag,
  10372. meshmatcap_vert: meshmatcap_vert,
  10373. meshphong_frag: meshphong_frag,
  10374. meshphong_vert: meshphong_vert,
  10375. meshphysical_frag: meshphysical_frag,
  10376. meshphysical_vert: meshphysical_vert,
  10377. normal_frag: normal_frag,
  10378. normal_vert: normal_vert,
  10379. points_frag: points_frag,
  10380. points_vert: points_vert,
  10381. shadow_frag: shadow_frag,
  10382. shadow_vert: shadow_vert,
  10383. sprite_frag: sprite_frag,
  10384. sprite_vert: sprite_vert
  10385. };
  10386. /**
  10387. * Uniforms library for shared webgl shaders
  10388. */
  10389. exports.ShaderChunk = ShaderChunk;
  10390. var UniformsLib = {
  10391. common: {
  10392. diffuse: {
  10393. value: new Color(0xeeeeee)
  10394. },
  10395. opacity: {
  10396. value: 1.0
  10397. },
  10398. map: {
  10399. value: null
  10400. },
  10401. uvTransform: {
  10402. value: new Matrix3()
  10403. },
  10404. alphaMap: {
  10405. value: null
  10406. }
  10407. },
  10408. specularmap: {
  10409. specularMap: {
  10410. value: null
  10411. }
  10412. },
  10413. envmap: {
  10414. envMap: {
  10415. value: null
  10416. },
  10417. flipEnvMap: {
  10418. value: -1
  10419. },
  10420. reflectivity: {
  10421. value: 1.0
  10422. },
  10423. refractionRatio: {
  10424. value: 0.98
  10425. },
  10426. maxMipLevel: {
  10427. value: 0
  10428. }
  10429. },
  10430. aomap: {
  10431. aoMap: {
  10432. value: null
  10433. },
  10434. aoMapIntensity: {
  10435. value: 1
  10436. }
  10437. },
  10438. lightmap: {
  10439. lightMap: {
  10440. value: null
  10441. },
  10442. lightMapIntensity: {
  10443. value: 1
  10444. }
  10445. },
  10446. emissivemap: {
  10447. emissiveMap: {
  10448. value: null
  10449. }
  10450. },
  10451. bumpmap: {
  10452. bumpMap: {
  10453. value: null
  10454. },
  10455. bumpScale: {
  10456. value: 1
  10457. }
  10458. },
  10459. normalmap: {
  10460. normalMap: {
  10461. value: null
  10462. },
  10463. normalScale: {
  10464. value: new Vector2(1, 1)
  10465. }
  10466. },
  10467. displacementmap: {
  10468. displacementMap: {
  10469. value: null
  10470. },
  10471. displacementScale: {
  10472. value: 1
  10473. },
  10474. displacementBias: {
  10475. value: 0
  10476. }
  10477. },
  10478. roughnessmap: {
  10479. roughnessMap: {
  10480. value: null
  10481. }
  10482. },
  10483. metalnessmap: {
  10484. metalnessMap: {
  10485. value: null
  10486. }
  10487. },
  10488. gradientmap: {
  10489. gradientMap: {
  10490. value: null
  10491. }
  10492. },
  10493. fog: {
  10494. fogDensity: {
  10495. value: 0.00025
  10496. },
  10497. fogNear: {
  10498. value: 1
  10499. },
  10500. fogFar: {
  10501. value: 2000
  10502. },
  10503. fogColor: {
  10504. value: new Color(0xffffff)
  10505. }
  10506. },
  10507. lights: {
  10508. ambientLightColor: {
  10509. value: []
  10510. },
  10511. lightProbe: {
  10512. value: []
  10513. },
  10514. directionalLights: {
  10515. value: [],
  10516. properties: {
  10517. direction: {},
  10518. color: {},
  10519. shadow: {},
  10520. shadowBias: {},
  10521. shadowRadius: {},
  10522. shadowMapSize: {}
  10523. }
  10524. },
  10525. directionalShadowMap: {
  10526. value: []
  10527. },
  10528. directionalShadowMatrix: {
  10529. value: []
  10530. },
  10531. spotLights: {
  10532. value: [],
  10533. properties: {
  10534. color: {},
  10535. position: {},
  10536. direction: {},
  10537. distance: {},
  10538. coneCos: {},
  10539. penumbraCos: {},
  10540. decay: {},
  10541. shadow: {},
  10542. shadowBias: {},
  10543. shadowRadius: {},
  10544. shadowMapSize: {}
  10545. }
  10546. },
  10547. spotShadowMap: {
  10548. value: []
  10549. },
  10550. spotShadowMatrix: {
  10551. value: []
  10552. },
  10553. pointLights: {
  10554. value: [],
  10555. properties: {
  10556. color: {},
  10557. position: {},
  10558. decay: {},
  10559. distance: {},
  10560. shadow: {},
  10561. shadowBias: {},
  10562. shadowRadius: {},
  10563. shadowMapSize: {},
  10564. shadowCameraNear: {},
  10565. shadowCameraFar: {}
  10566. }
  10567. },
  10568. pointShadowMap: {
  10569. value: []
  10570. },
  10571. pointShadowMatrix: {
  10572. value: []
  10573. },
  10574. hemisphereLights: {
  10575. value: [],
  10576. properties: {
  10577. direction: {},
  10578. skyColor: {},
  10579. groundColor: {}
  10580. }
  10581. },
  10582. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  10583. rectAreaLights: {
  10584. value: [],
  10585. properties: {
  10586. color: {},
  10587. position: {},
  10588. width: {},
  10589. height: {}
  10590. }
  10591. }
  10592. },
  10593. points: {
  10594. diffuse: {
  10595. value: new Color(0xeeeeee)
  10596. },
  10597. opacity: {
  10598. value: 1.0
  10599. },
  10600. size: {
  10601. value: 1.0
  10602. },
  10603. scale: {
  10604. value: 1.0
  10605. },
  10606. map: {
  10607. value: null
  10608. },
  10609. uvTransform: {
  10610. value: new Matrix3()
  10611. }
  10612. },
  10613. sprite: {
  10614. diffuse: {
  10615. value: new Color(0xeeeeee)
  10616. },
  10617. opacity: {
  10618. value: 1.0
  10619. },
  10620. center: {
  10621. value: new Vector2(0.5, 0.5)
  10622. },
  10623. rotation: {
  10624. value: 0.0
  10625. },
  10626. map: {
  10627. value: null
  10628. },
  10629. uvTransform: {
  10630. value: new Matrix3()
  10631. }
  10632. }
  10633. };
  10634. /**
  10635. * @author alteredq / http://alteredqualia.com/
  10636. * @author mrdoob / http://mrdoob.com/
  10637. * @author mikael emtinger / http://gomo.se/
  10638. */
  10639. exports.UniformsLib = UniformsLib;
  10640. var ShaderLib = {
  10641. basic: {
  10642. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  10643. vertexShader: ShaderChunk.meshbasic_vert,
  10644. fragmentShader: ShaderChunk.meshbasic_frag
  10645. },
  10646. lambert: {
  10647. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
  10648. emissive: {
  10649. value: new Color(0x000000)
  10650. }
  10651. }]),
  10652. vertexShader: ShaderChunk.meshlambert_vert,
  10653. fragmentShader: ShaderChunk.meshlambert_frag
  10654. },
  10655. phong: {
  10656. 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, {
  10657. emissive: {
  10658. value: new Color(0x000000)
  10659. },
  10660. specular: {
  10661. value: new Color(0x111111)
  10662. },
  10663. shininess: {
  10664. value: 30
  10665. }
  10666. }]),
  10667. vertexShader: ShaderChunk.meshphong_vert,
  10668. fragmentShader: ShaderChunk.meshphong_frag
  10669. },
  10670. standard: {
  10671. 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, {
  10672. emissive: {
  10673. value: new Color(0x000000)
  10674. },
  10675. roughness: {
  10676. value: 0.5
  10677. },
  10678. metalness: {
  10679. value: 0.5
  10680. },
  10681. envMapIntensity: {
  10682. value: 1
  10683. } // temporary
  10684. }]),
  10685. vertexShader: ShaderChunk.meshphysical_vert,
  10686. fragmentShader: ShaderChunk.meshphysical_frag
  10687. },
  10688. matcap: {
  10689. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  10690. matcap: {
  10691. value: null
  10692. }
  10693. }]),
  10694. vertexShader: ShaderChunk.meshmatcap_vert,
  10695. fragmentShader: ShaderChunk.meshmatcap_frag
  10696. },
  10697. points: {
  10698. uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  10699. vertexShader: ShaderChunk.points_vert,
  10700. fragmentShader: ShaderChunk.points_frag
  10701. },
  10702. dashed: {
  10703. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  10704. scale: {
  10705. value: 1
  10706. },
  10707. dashSize: {
  10708. value: 1
  10709. },
  10710. totalSize: {
  10711. value: 2
  10712. }
  10713. }]),
  10714. vertexShader: ShaderChunk.linedashed_vert,
  10715. fragmentShader: ShaderChunk.linedashed_frag
  10716. },
  10717. depth: {
  10718. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  10719. vertexShader: ShaderChunk.depth_vert,
  10720. fragmentShader: ShaderChunk.depth_frag
  10721. },
  10722. normal: {
  10723. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  10724. opacity: {
  10725. value: 1.0
  10726. }
  10727. }]),
  10728. vertexShader: ShaderChunk.normal_vert,
  10729. fragmentShader: ShaderChunk.normal_frag
  10730. },
  10731. sprite: {
  10732. uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  10733. vertexShader: ShaderChunk.sprite_vert,
  10734. fragmentShader: ShaderChunk.sprite_frag
  10735. },
  10736. background: {
  10737. uniforms: {
  10738. uvTransform: {
  10739. value: new Matrix3()
  10740. },
  10741. t2D: {
  10742. value: null
  10743. }
  10744. },
  10745. vertexShader: ShaderChunk.background_vert,
  10746. fragmentShader: ShaderChunk.background_frag
  10747. },
  10748. /* -------------------------------------------------------------------------
  10749. // Cube map shader
  10750. ------------------------------------------------------------------------- */
  10751. cube: {
  10752. uniforms: {
  10753. tCube: {
  10754. value: null
  10755. },
  10756. tFlip: {
  10757. value: -1
  10758. },
  10759. opacity: {
  10760. value: 1.0
  10761. }
  10762. },
  10763. vertexShader: ShaderChunk.cube_vert,
  10764. fragmentShader: ShaderChunk.cube_frag
  10765. },
  10766. equirect: {
  10767. uniforms: {
  10768. tEquirect: {
  10769. value: null
  10770. }
  10771. },
  10772. vertexShader: ShaderChunk.equirect_vert,
  10773. fragmentShader: ShaderChunk.equirect_frag
  10774. },
  10775. distanceRGBA: {
  10776. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  10777. referencePosition: {
  10778. value: new Vector3()
  10779. },
  10780. nearDistance: {
  10781. value: 1
  10782. },
  10783. farDistance: {
  10784. value: 1000
  10785. }
  10786. }]),
  10787. vertexShader: ShaderChunk.distanceRGBA_vert,
  10788. fragmentShader: ShaderChunk.distanceRGBA_frag
  10789. },
  10790. shadow: {
  10791. uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  10792. color: {
  10793. value: new Color(0x00000)
  10794. },
  10795. opacity: {
  10796. value: 1.0
  10797. }
  10798. }]),
  10799. vertexShader: ShaderChunk.shadow_vert,
  10800. fragmentShader: ShaderChunk.shadow_frag
  10801. }
  10802. };
  10803. exports.ShaderLib = ShaderLib;
  10804. ShaderLib.physical = {
  10805. uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
  10806. transparency: {
  10807. value: 0
  10808. },
  10809. clearcoat: {
  10810. value: 0
  10811. },
  10812. clearcoatRoughness: {
  10813. value: 0
  10814. },
  10815. sheen: {
  10816. value: new Color(0x000000)
  10817. },
  10818. clearcoatNormalScale: {
  10819. value: new Vector2(1, 1)
  10820. },
  10821. clearcoatNormalMap: {
  10822. value: null
  10823. }
  10824. }]),
  10825. vertexShader: ShaderChunk.meshphysical_vert,
  10826. fragmentShader: ShaderChunk.meshphysical_frag
  10827. };
  10828. /**
  10829. * @author mrdoob / http://mrdoob.com/
  10830. */
  10831. function WebGLAnimation() {
  10832. var context = null;
  10833. var isAnimating = false;
  10834. var animationLoop = null;
  10835. function onAnimationFrame(time, frame) {
  10836. if (isAnimating === false) return;
  10837. animationLoop(time, frame);
  10838. context.requestAnimationFrame(onAnimationFrame);
  10839. }
  10840. return {
  10841. start: function () {
  10842. if (isAnimating === true) return;
  10843. if (animationLoop === null) return;
  10844. context.requestAnimationFrame(onAnimationFrame);
  10845. isAnimating = true;
  10846. },
  10847. stop: function () {
  10848. isAnimating = false;
  10849. },
  10850. setAnimationLoop: function (callback) {
  10851. animationLoop = callback;
  10852. },
  10853. setContext: function (value) {
  10854. context = value;
  10855. }
  10856. };
  10857. }
  10858. /**
  10859. * @author mrdoob / http://mrdoob.com/
  10860. */
  10861. function WebGLAttributes(gl) {
  10862. var buffers = new WeakMap();
  10863. function createBuffer(attribute, bufferType) {
  10864. var array = attribute.array;
  10865. var usage = attribute.dynamic ? 35048 : 35044;
  10866. var buffer = gl.createBuffer();
  10867. gl.bindBuffer(bufferType, buffer);
  10868. gl.bufferData(bufferType, array, usage);
  10869. attribute.onUploadCallback();
  10870. var type = 5126;
  10871. if (array instanceof Float32Array) {
  10872. type = 5126;
  10873. } else if (array instanceof Float64Array) {
  10874. console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
  10875. } else if (array instanceof Uint16Array) {
  10876. type = 5123;
  10877. } else if (array instanceof Int16Array) {
  10878. type = 5122;
  10879. } else if (array instanceof Uint32Array) {
  10880. type = 5125;
  10881. } else if (array instanceof Int32Array) {
  10882. type = 5124;
  10883. } else if (array instanceof Int8Array) {
  10884. type = 5120;
  10885. } else if (array instanceof Uint8Array) {
  10886. type = 5121;
  10887. }
  10888. return {
  10889. buffer: buffer,
  10890. type: type,
  10891. bytesPerElement: array.BYTES_PER_ELEMENT,
  10892. version: attribute.version
  10893. };
  10894. }
  10895. function updateBuffer(buffer, attribute, bufferType) {
  10896. var array = attribute.array;
  10897. var updateRange = attribute.updateRange;
  10898. gl.bindBuffer(bufferType, buffer);
  10899. if (attribute.dynamic === false) {
  10900. gl.bufferData(bufferType, array, 35044);
  10901. } else if (updateRange.count === -1) {
  10902. // Not using update ranges
  10903. gl.bufferSubData(bufferType, 0, array);
  10904. } else if (updateRange.count === 0) {
  10905. 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.');
  10906. } else {
  10907. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  10908. updateRange.count = -1; // reset range
  10909. }
  10910. } //
  10911. function get(attribute) {
  10912. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  10913. return buffers.get(attribute);
  10914. }
  10915. function remove(attribute) {
  10916. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  10917. var data = buffers.get(attribute);
  10918. if (data) {
  10919. gl.deleteBuffer(data.buffer);
  10920. buffers.delete(attribute);
  10921. }
  10922. }
  10923. function update(attribute, bufferType) {
  10924. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  10925. var data = buffers.get(attribute);
  10926. if (data === undefined) {
  10927. buffers.set(attribute, createBuffer(attribute, bufferType));
  10928. } else if (data.version < attribute.version) {
  10929. updateBuffer(data.buffer, attribute, bufferType);
  10930. data.version = attribute.version;
  10931. }
  10932. }
  10933. return {
  10934. get: get,
  10935. remove: remove,
  10936. update: update
  10937. };
  10938. }
  10939. /**
  10940. * @author mrdoob / http://mrdoob.com/
  10941. * @author Mugen87 / https://github.com/Mugen87
  10942. */
  10943. // PlaneGeometry
  10944. function PlaneGeometry(width, height, widthSegments, heightSegments) {
  10945. Geometry.call(this);
  10946. this.type = 'PlaneGeometry';
  10947. this.parameters = {
  10948. width: width,
  10949. height: height,
  10950. widthSegments: widthSegments,
  10951. heightSegments: heightSegments
  10952. };
  10953. this.fromBufferGeometry(new PlaneBufferGeometry(width, height, widthSegments, heightSegments));
  10954. this.mergeVertices();
  10955. }
  10956. PlaneGeometry.prototype = Object.create(Geometry.prototype);
  10957. PlaneGeometry.prototype.constructor = PlaneGeometry; // PlaneBufferGeometry
  10958. function PlaneBufferGeometry(width, height, widthSegments, heightSegments) {
  10959. BufferGeometry.call(this);
  10960. this.type = 'PlaneBufferGeometry';
  10961. this.parameters = {
  10962. width: width,
  10963. height: height,
  10964. widthSegments: widthSegments,
  10965. heightSegments: heightSegments
  10966. };
  10967. width = width || 1;
  10968. height = height || 1;
  10969. var width_half = width / 2;
  10970. var height_half = height / 2;
  10971. var gridX = Math.floor(widthSegments) || 1;
  10972. var gridY = Math.floor(heightSegments) || 1;
  10973. var gridX1 = gridX + 1;
  10974. var gridY1 = gridY + 1;
  10975. var segment_width = width / gridX;
  10976. var segment_height = height / gridY;
  10977. var ix, iy; // buffers
  10978. var indices = [];
  10979. var vertices = [];
  10980. var normals = [];
  10981. var uvs = []; // generate vertices, normals and uvs
  10982. for (iy = 0; iy < gridY1; iy++) {
  10983. var y = iy * segment_height - height_half;
  10984. for (ix = 0; ix < gridX1; ix++) {
  10985. var x = ix * segment_width - width_half;
  10986. vertices.push(x, -y, 0);
  10987. normals.push(0, 0, 1);
  10988. uvs.push(ix / gridX);
  10989. uvs.push(1 - iy / gridY);
  10990. }
  10991. } // indices
  10992. for (iy = 0; iy < gridY; iy++) {
  10993. for (ix = 0; ix < gridX; ix++) {
  10994. var a = ix + gridX1 * iy;
  10995. var b = ix + gridX1 * (iy + 1);
  10996. var c = ix + 1 + gridX1 * (iy + 1);
  10997. var d = ix + 1 + gridX1 * iy; // faces
  10998. indices.push(a, b, d);
  10999. indices.push(b, c, d);
  11000. }
  11001. } // build geometry
  11002. this.setIndex(indices);
  11003. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  11004. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  11005. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  11006. }
  11007. PlaneBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  11008. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  11009. /**
  11010. * @author mrdoob / http://mrdoob.com/
  11011. */
  11012. function WebGLBackground(renderer, state, objects, premultipliedAlpha) {
  11013. var clearColor = new Color(0x000000);
  11014. var clearAlpha = 0;
  11015. var planeMesh;
  11016. var boxMesh; // Store the current background texture and its `version`
  11017. // so we can recompile the material accordingly.
  11018. var currentBackground = null;
  11019. var currentBackgroundVersion = 0;
  11020. function render(renderList, scene, camera, forceClear) {
  11021. var background = scene.background; // Ignore background in AR
  11022. // TODO: Reconsider this.
  11023. var vr = renderer.vr;
  11024. var session = vr.getSession && vr.getSession();
  11025. if (session && session.environmentBlendMode === 'additive') {
  11026. background = null;
  11027. }
  11028. if (background === null) {
  11029. setClear(clearColor, clearAlpha);
  11030. currentBackground = null;
  11031. currentBackgroundVersion = 0;
  11032. } else if (background && background.isColor) {
  11033. setClear(background, 1);
  11034. forceClear = true;
  11035. currentBackground = null;
  11036. currentBackgroundVersion = 0;
  11037. }
  11038. if (renderer.autoClear || forceClear) {
  11039. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  11040. }
  11041. if (background && (background.isCubeTexture || background.isWebGLRenderTargetCube)) {
  11042. if (boxMesh === undefined) {
  11043. boxMesh = new Mesh(new BoxBufferGeometry(1, 1, 1), new ShaderMaterial({
  11044. type: 'BackgroundCubeMaterial',
  11045. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  11046. vertexShader: ShaderLib.cube.vertexShader,
  11047. fragmentShader: ShaderLib.cube.fragmentShader,
  11048. side: BackSide,
  11049. depthTest: false,
  11050. depthWrite: false,
  11051. fog: false
  11052. }));
  11053. boxMesh.geometry.removeAttribute('normal');
  11054. boxMesh.geometry.removeAttribute('uv');
  11055. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  11056. this.matrixWorld.copyPosition(camera.matrixWorld);
  11057. }; // enable code injection for non-built-in material
  11058. Object.defineProperty(boxMesh.material, 'map', {
  11059. get: function () {
  11060. return this.uniforms.tCube.value;
  11061. }
  11062. });
  11063. objects.update(boxMesh);
  11064. }
  11065. var texture = background.isWebGLRenderTargetCube ? background.texture : background;
  11066. boxMesh.material.uniforms.tCube.value = texture;
  11067. boxMesh.material.uniforms.tFlip.value = background.isWebGLRenderTargetCube ? 1 : -1;
  11068. if (currentBackground !== background || currentBackgroundVersion !== texture.version) {
  11069. boxMesh.material.needsUpdate = true;
  11070. currentBackground = background;
  11071. currentBackgroundVersion = texture.version;
  11072. } // push to the pre-sorted opaque render list
  11073. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  11074. } else if (background && background.isTexture) {
  11075. if (planeMesh === undefined) {
  11076. planeMesh = new Mesh(new PlaneBufferGeometry(2, 2), new ShaderMaterial({
  11077. type: 'BackgroundMaterial',
  11078. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  11079. vertexShader: ShaderLib.background.vertexShader,
  11080. fragmentShader: ShaderLib.background.fragmentShader,
  11081. side: FrontSide,
  11082. depthTest: false,
  11083. depthWrite: false,
  11084. fog: false
  11085. }));
  11086. planeMesh.geometry.removeAttribute('normal'); // enable code injection for non-built-in material
  11087. Object.defineProperty(planeMesh.material, 'map', {
  11088. get: function () {
  11089. return this.uniforms.t2D.value;
  11090. }
  11091. });
  11092. objects.update(planeMesh);
  11093. }
  11094. planeMesh.material.uniforms.t2D.value = background;
  11095. if (background.matrixAutoUpdate === true) {
  11096. background.updateMatrix();
  11097. }
  11098. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  11099. if (currentBackground !== background || currentBackgroundVersion !== background.version) {
  11100. planeMesh.material.needsUpdate = true;
  11101. currentBackground = background;
  11102. currentBackgroundVersion = background.version;
  11103. } // push to the pre-sorted opaque render list
  11104. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  11105. }
  11106. }
  11107. function setClear(color, alpha) {
  11108. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  11109. }
  11110. return {
  11111. getClearColor: function () {
  11112. return clearColor;
  11113. },
  11114. setClearColor: function (color, alpha) {
  11115. clearColor.set(color);
  11116. clearAlpha = alpha !== undefined ? alpha : 1;
  11117. setClear(clearColor, clearAlpha);
  11118. },
  11119. getClearAlpha: function () {
  11120. return clearAlpha;
  11121. },
  11122. setClearAlpha: function (alpha) {
  11123. clearAlpha = alpha;
  11124. setClear(clearColor, clearAlpha);
  11125. },
  11126. render: render
  11127. };
  11128. }
  11129. /**
  11130. * @author mrdoob / http://mrdoob.com/
  11131. */
  11132. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  11133. var mode;
  11134. function setMode(value) {
  11135. mode = value;
  11136. }
  11137. function render(start, count) {
  11138. gl.drawArrays(mode, start, count);
  11139. info.update(count, mode);
  11140. }
  11141. function renderInstances(geometry, start, count, primcount) {
  11142. if (primcount === 0) return;
  11143. var extension, methodName;
  11144. if (capabilities.isWebGL2) {
  11145. extension = gl;
  11146. methodName = 'drawArraysInstanced';
  11147. } else {
  11148. extension = extensions.get('ANGLE_instanced_arrays');
  11149. methodName = 'drawArraysInstancedANGLE';
  11150. if (extension === null) {
  11151. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  11152. return;
  11153. }
  11154. }
  11155. extension[methodName](mode, start, count, primcount);
  11156. info.update(count, mode, primcount);
  11157. } //
  11158. this.setMode = setMode;
  11159. this.render = render;
  11160. this.renderInstances = renderInstances;
  11161. }
  11162. /**
  11163. * @author mrdoob / http://mrdoob.com/
  11164. */
  11165. function WebGLCapabilities(gl, extensions, parameters) {
  11166. var maxAnisotropy;
  11167. function getMaxAnisotropy() {
  11168. if (maxAnisotropy !== undefined) return maxAnisotropy;
  11169. var extension = extensions.get('EXT_texture_filter_anisotropic');
  11170. if (extension !== null) {
  11171. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  11172. } else {
  11173. maxAnisotropy = 0;
  11174. }
  11175. return maxAnisotropy;
  11176. }
  11177. function getMaxPrecision(precision) {
  11178. if (precision === 'highp') {
  11179. if (gl.getShaderPrecisionFormat(35633, 36338).precision > 0 && gl.getShaderPrecisionFormat(35632, 36338).precision > 0) {
  11180. return 'highp';
  11181. }
  11182. precision = 'mediump';
  11183. }
  11184. if (precision === 'mediump') {
  11185. if (gl.getShaderPrecisionFormat(35633, 36337).precision > 0 && gl.getShaderPrecisionFormat(35632, 36337).precision > 0) {
  11186. return 'mediump';
  11187. }
  11188. }
  11189. return 'lowp';
  11190. }
  11191. var isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext;
  11192. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  11193. var maxPrecision = getMaxPrecision(precision);
  11194. if (maxPrecision !== precision) {
  11195. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  11196. precision = maxPrecision;
  11197. }
  11198. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  11199. var maxTextures = gl.getParameter(34930);
  11200. var maxVertexTextures = gl.getParameter(35660);
  11201. var maxTextureSize = gl.getParameter(3379);
  11202. var maxCubemapSize = gl.getParameter(34076);
  11203. var maxAttributes = gl.getParameter(34921);
  11204. var maxVertexUniforms = gl.getParameter(36347);
  11205. var maxVaryings = gl.getParameter(36348);
  11206. var maxFragmentUniforms = gl.getParameter(36349);
  11207. var vertexTextures = maxVertexTextures > 0;
  11208. var floatFragmentTextures = isWebGL2 || !!extensions.get('OES_texture_float');
  11209. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  11210. var maxSamples = isWebGL2 ? gl.getParameter(36183) : 0;
  11211. return {
  11212. isWebGL2: isWebGL2,
  11213. getMaxAnisotropy: getMaxAnisotropy,
  11214. getMaxPrecision: getMaxPrecision,
  11215. precision: precision,
  11216. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11217. maxTextures: maxTextures,
  11218. maxVertexTextures: maxVertexTextures,
  11219. maxTextureSize: maxTextureSize,
  11220. maxCubemapSize: maxCubemapSize,
  11221. maxAttributes: maxAttributes,
  11222. maxVertexUniforms: maxVertexUniforms,
  11223. maxVaryings: maxVaryings,
  11224. maxFragmentUniforms: maxFragmentUniforms,
  11225. vertexTextures: vertexTextures,
  11226. floatFragmentTextures: floatFragmentTextures,
  11227. floatVertexTextures: floatVertexTextures,
  11228. maxSamples: maxSamples
  11229. };
  11230. }
  11231. /**
  11232. * @author tschw
  11233. */
  11234. function WebGLClipping() {
  11235. var scope = this,
  11236. globalState = null,
  11237. numGlobalPlanes = 0,
  11238. localClippingEnabled = false,
  11239. renderingShadows = false,
  11240. plane = new Plane(),
  11241. viewNormalMatrix = new Matrix3(),
  11242. uniform = {
  11243. value: null,
  11244. needsUpdate: false
  11245. };
  11246. this.uniform = uniform;
  11247. this.numPlanes = 0;
  11248. this.numIntersection = 0;
  11249. this.init = function (planes, enableLocalClipping, camera) {
  11250. var enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  11251. // run another frame in order to reset the state:
  11252. numGlobalPlanes !== 0 || localClippingEnabled;
  11253. localClippingEnabled = enableLocalClipping;
  11254. globalState = projectPlanes(planes, camera, 0);
  11255. numGlobalPlanes = planes.length;
  11256. return enabled;
  11257. };
  11258. this.beginShadows = function () {
  11259. renderingShadows = true;
  11260. projectPlanes(null);
  11261. };
  11262. this.endShadows = function () {
  11263. renderingShadows = false;
  11264. resetGlobalState();
  11265. };
  11266. this.setState = function (planes, clipIntersection, clipShadows, camera, cache, fromCache) {
  11267. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  11268. // there's no local clipping
  11269. if (renderingShadows) {
  11270. // there's no global clipping
  11271. projectPlanes(null);
  11272. } else {
  11273. resetGlobalState();
  11274. }
  11275. } else {
  11276. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  11277. lGlobal = nGlobal * 4,
  11278. dstArray = cache.clippingState || null;
  11279. uniform.value = dstArray; // ensure unique state
  11280. dstArray = projectPlanes(planes, camera, lGlobal, fromCache);
  11281. for (var i = 0; i !== lGlobal; ++i) {
  11282. dstArray[i] = globalState[i];
  11283. }
  11284. cache.clippingState = dstArray;
  11285. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  11286. this.numPlanes += nGlobal;
  11287. }
  11288. };
  11289. function resetGlobalState() {
  11290. if (uniform.value !== globalState) {
  11291. uniform.value = globalState;
  11292. uniform.needsUpdate = numGlobalPlanes > 0;
  11293. }
  11294. scope.numPlanes = numGlobalPlanes;
  11295. scope.numIntersection = 0;
  11296. }
  11297. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  11298. var nPlanes = planes !== null ? planes.length : 0,
  11299. dstArray = null;
  11300. if (nPlanes !== 0) {
  11301. dstArray = uniform.value;
  11302. if (skipTransform !== true || dstArray === null) {
  11303. var flatSize = dstOffset + nPlanes * 4,
  11304. viewMatrix = camera.matrixWorldInverse;
  11305. viewNormalMatrix.getNormalMatrix(viewMatrix);
  11306. if (dstArray === null || dstArray.length < flatSize) {
  11307. dstArray = new Float32Array(flatSize);
  11308. }
  11309. for (var i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  11310. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  11311. plane.normal.toArray(dstArray, i4);
  11312. dstArray[i4 + 3] = plane.constant;
  11313. }
  11314. }
  11315. uniform.value = dstArray;
  11316. uniform.needsUpdate = true;
  11317. }
  11318. scope.numPlanes = nPlanes;
  11319. return dstArray;
  11320. }
  11321. }
  11322. /**
  11323. * @author mrdoob / http://mrdoob.com/
  11324. */
  11325. function WebGLExtensions(gl) {
  11326. var extensions = {};
  11327. return {
  11328. get: function (name) {
  11329. if (extensions[name] !== undefined) {
  11330. return extensions[name];
  11331. }
  11332. var extension;
  11333. switch (name) {
  11334. case 'WEBGL_depth_texture':
  11335. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  11336. break;
  11337. case 'EXT_texture_filter_anisotropic':
  11338. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  11339. break;
  11340. case 'WEBGL_compressed_texture_s3tc':
  11341. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11342. break;
  11343. case 'WEBGL_compressed_texture_pvrtc':
  11344. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11345. break;
  11346. default:
  11347. extension = gl.getExtension(name);
  11348. }
  11349. if (extension === null) {
  11350. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  11351. }
  11352. extensions[name] = extension;
  11353. return extension;
  11354. }
  11355. };
  11356. }
  11357. /**
  11358. * @author mrdoob / http://mrdoob.com/
  11359. */
  11360. function WebGLGeometries(gl, attributes, info) {
  11361. var geometries = new WeakMap();
  11362. var wireframeAttributes = new WeakMap();
  11363. function onGeometryDispose(event) {
  11364. var geometry = event.target;
  11365. var buffergeometry = geometries.get(geometry);
  11366. if (buffergeometry.index !== null) {
  11367. attributes.remove(buffergeometry.index);
  11368. }
  11369. for (var name in buffergeometry.attributes) {
  11370. attributes.remove(buffergeometry.attributes[name]);
  11371. }
  11372. geometry.removeEventListener('dispose', onGeometryDispose);
  11373. geometries.delete(geometry);
  11374. var attribute = wireframeAttributes.get(buffergeometry);
  11375. if (attribute) {
  11376. attributes.remove(attribute);
  11377. wireframeAttributes.delete(buffergeometry);
  11378. } //
  11379. info.memory.geometries--;
  11380. }
  11381. function get(object, geometry) {
  11382. var buffergeometry = geometries.get(geometry);
  11383. if (buffergeometry) return buffergeometry;
  11384. geometry.addEventListener('dispose', onGeometryDispose);
  11385. if (geometry.isBufferGeometry) {
  11386. buffergeometry = geometry;
  11387. } else if (geometry.isGeometry) {
  11388. if (geometry._bufferGeometry === undefined) {
  11389. geometry._bufferGeometry = new BufferGeometry().setFromObject(object);
  11390. }
  11391. buffergeometry = geometry._bufferGeometry;
  11392. }
  11393. geometries.set(geometry, buffergeometry);
  11394. info.memory.geometries++;
  11395. return buffergeometry;
  11396. }
  11397. function update(geometry) {
  11398. var index = geometry.index;
  11399. var geometryAttributes = geometry.attributes;
  11400. if (index !== null) {
  11401. attributes.update(index, 34963);
  11402. }
  11403. for (var name in geometryAttributes) {
  11404. attributes.update(geometryAttributes[name], 34962);
  11405. } // morph targets
  11406. var morphAttributes = geometry.morphAttributes;
  11407. for (var name in morphAttributes) {
  11408. var array = morphAttributes[name];
  11409. for (var i = 0, l = array.length; i < l; i++) {
  11410. attributes.update(array[i], 34962);
  11411. }
  11412. }
  11413. }
  11414. function updateWireframeAttribute(geometry) {
  11415. var indices = [];
  11416. var geometryIndex = geometry.index;
  11417. var geometryPosition = geometry.attributes.position;
  11418. var version = 0;
  11419. if (geometryIndex !== null) {
  11420. var array = geometryIndex.array;
  11421. version = geometryIndex.version;
  11422. for (var i = 0, l = array.length; i < l; i += 3) {
  11423. var a = array[i + 0];
  11424. var b = array[i + 1];
  11425. var c = array[i + 2];
  11426. indices.push(a, b, b, c, c, a);
  11427. }
  11428. } else {
  11429. var array = geometryPosition.array;
  11430. version = geometryPosition.version;
  11431. for (var i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  11432. var a = i + 0;
  11433. var b = i + 1;
  11434. var c = i + 2;
  11435. indices.push(a, b, b, c, c, a);
  11436. }
  11437. }
  11438. var attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  11439. attribute.version = version;
  11440. attributes.update(attribute, 34963); //
  11441. var previousAttribute = wireframeAttributes.get(geometry);
  11442. if (previousAttribute) attributes.remove(previousAttribute); //
  11443. wireframeAttributes.set(geometry, attribute);
  11444. }
  11445. function getWireframeAttribute(geometry) {
  11446. var currentAttribute = wireframeAttributes.get(geometry);
  11447. if (currentAttribute) {
  11448. var geometryIndex = geometry.index;
  11449. if (geometryIndex !== null) {
  11450. // if the attribute is obsolete, create a new one
  11451. if (currentAttribute.version < geometryIndex.version) {
  11452. updateWireframeAttribute(geometry);
  11453. }
  11454. }
  11455. } else {
  11456. updateWireframeAttribute(geometry);
  11457. }
  11458. return wireframeAttributes.get(geometry);
  11459. }
  11460. return {
  11461. get: get,
  11462. update: update,
  11463. getWireframeAttribute: getWireframeAttribute
  11464. };
  11465. }
  11466. /**
  11467. * @author mrdoob / http://mrdoob.com/
  11468. */
  11469. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  11470. var mode;
  11471. function setMode(value) {
  11472. mode = value;
  11473. }
  11474. var type, bytesPerElement;
  11475. function setIndex(value) {
  11476. type = value.type;
  11477. bytesPerElement = value.bytesPerElement;
  11478. }
  11479. function render(start, count) {
  11480. gl.drawElements(mode, count, type, start * bytesPerElement);
  11481. info.update(count, mode);
  11482. }
  11483. function renderInstances(geometry, start, count, primcount) {
  11484. if (primcount === 0) return;
  11485. var extension, methodName;
  11486. if (capabilities.isWebGL2) {
  11487. extension = gl;
  11488. methodName = 'drawElementsInstanced';
  11489. } else {
  11490. extension = extensions.get('ANGLE_instanced_arrays');
  11491. methodName = 'drawElementsInstancedANGLE';
  11492. if (extension === null) {
  11493. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  11494. return;
  11495. }
  11496. }
  11497. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  11498. info.update(count, mode, primcount);
  11499. } //
  11500. this.setMode = setMode;
  11501. this.setIndex = setIndex;
  11502. this.render = render;
  11503. this.renderInstances = renderInstances;
  11504. }
  11505. /**
  11506. * @author Mugen87 / https://github.com/Mugen87
  11507. */
  11508. function WebGLInfo(gl) {
  11509. var memory = {
  11510. geometries: 0,
  11511. textures: 0
  11512. };
  11513. var render = {
  11514. frame: 0,
  11515. calls: 0,
  11516. triangles: 0,
  11517. points: 0,
  11518. lines: 0
  11519. };
  11520. function update(count, mode, instanceCount) {
  11521. instanceCount = instanceCount || 1;
  11522. render.calls++;
  11523. switch (mode) {
  11524. case 4:
  11525. render.triangles += instanceCount * (count / 3);
  11526. break;
  11527. case 5:
  11528. case 6:
  11529. render.triangles += instanceCount * (count - 2);
  11530. break;
  11531. case 1:
  11532. render.lines += instanceCount * (count / 2);
  11533. break;
  11534. case 3:
  11535. render.lines += instanceCount * (count - 1);
  11536. break;
  11537. case 2:
  11538. render.lines += instanceCount * count;
  11539. break;
  11540. case 0:
  11541. render.points += instanceCount * count;
  11542. break;
  11543. default:
  11544. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  11545. break;
  11546. }
  11547. }
  11548. function reset() {
  11549. render.frame++;
  11550. render.calls = 0;
  11551. render.triangles = 0;
  11552. render.points = 0;
  11553. render.lines = 0;
  11554. }
  11555. return {
  11556. memory: memory,
  11557. render: render,
  11558. programs: null,
  11559. autoReset: true,
  11560. reset: reset,
  11561. update: update
  11562. };
  11563. }
  11564. /**
  11565. * @author mrdoob / http://mrdoob.com/
  11566. */
  11567. function absNumericalSort(a, b) {
  11568. return Math.abs(b[1]) - Math.abs(a[1]);
  11569. }
  11570. function WebGLMorphtargets(gl) {
  11571. var influencesList = {};
  11572. var morphInfluences = new Float32Array(8);
  11573. function update(object, geometry, material, program) {
  11574. var objectInfluences = object.morphTargetInfluences;
  11575. var length = objectInfluences.length;
  11576. var influences = influencesList[geometry.id];
  11577. if (influences === undefined) {
  11578. // initialise list
  11579. influences = [];
  11580. for (var i = 0; i < length; i++) {
  11581. influences[i] = [i, 0];
  11582. }
  11583. influencesList[geometry.id] = influences;
  11584. }
  11585. var morphTargets = material.morphTargets && geometry.morphAttributes.position;
  11586. var morphNormals = material.morphNormals && geometry.morphAttributes.normal; // Remove current morphAttributes
  11587. for (var i = 0; i < length; i++) {
  11588. var influence = influences[i];
  11589. if (influence[1] !== 0) {
  11590. if (morphTargets) geometry.removeAttribute('morphTarget' + i);
  11591. if (morphNormals) geometry.removeAttribute('morphNormal' + i);
  11592. }
  11593. } // Collect influences
  11594. for (var i = 0; i < length; i++) {
  11595. var influence = influences[i];
  11596. influence[0] = i;
  11597. influence[1] = objectInfluences[i];
  11598. }
  11599. influences.sort(absNumericalSort); // Add morphAttributes
  11600. for (var i = 0; i < 8; i++) {
  11601. var influence = influences[i];
  11602. if (influence) {
  11603. var index = influence[0];
  11604. var value = influence[1];
  11605. if (value) {
  11606. if (morphTargets) geometry.addAttribute('morphTarget' + i, morphTargets[index]);
  11607. if (morphNormals) geometry.addAttribute('morphNormal' + i, morphNormals[index]);
  11608. morphInfluences[i] = value;
  11609. continue;
  11610. }
  11611. }
  11612. morphInfluences[i] = 0;
  11613. }
  11614. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  11615. }
  11616. return {
  11617. update: update
  11618. };
  11619. }
  11620. /**
  11621. * @author mrdoob / http://mrdoob.com/
  11622. */
  11623. function WebGLObjects(gl, geometries, attributes, info) {
  11624. var updateList = {};
  11625. function update(object) {
  11626. var frame = info.render.frame;
  11627. var geometry = object.geometry;
  11628. var buffergeometry = geometries.get(object, geometry); // Update once per frame
  11629. if (updateList[buffergeometry.id] !== frame) {
  11630. if (geometry.isGeometry) {
  11631. buffergeometry.updateFromObject(object);
  11632. }
  11633. geometries.update(buffergeometry);
  11634. updateList[buffergeometry.id] = frame;
  11635. }
  11636. if (object.isInstancedMesh) {
  11637. attributes.update(object.instanceMatrix, 34962);
  11638. }
  11639. return buffergeometry;
  11640. }
  11641. function dispose() {
  11642. updateList = {};
  11643. }
  11644. return {
  11645. update: update,
  11646. dispose: dispose
  11647. };
  11648. }
  11649. /**
  11650. * @author mrdoob / http://mrdoob.com/
  11651. */
  11652. function CubeTexture(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  11653. images = images !== undefined ? images : [];
  11654. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  11655. format = format !== undefined ? format : RGBFormat;
  11656. Texture.call(this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  11657. this.flipY = false;
  11658. }
  11659. CubeTexture.prototype = Object.create(Texture.prototype);
  11660. CubeTexture.prototype.constructor = CubeTexture;
  11661. CubeTexture.prototype.isCubeTexture = true;
  11662. Object.defineProperty(CubeTexture.prototype, 'images', {
  11663. get: function () {
  11664. return this.image;
  11665. },
  11666. set: function (value) {
  11667. this.image = value;
  11668. }
  11669. });
  11670. /**
  11671. * @author Takahiro https://github.com/takahirox
  11672. */
  11673. function DataTexture2DArray(data, width, height, depth) {
  11674. Texture.call(this, null);
  11675. this.image = {
  11676. data: data || null,
  11677. width: width || 1,
  11678. height: height || 1,
  11679. depth: depth || 1
  11680. };
  11681. this.magFilter = NearestFilter;
  11682. this.minFilter = NearestFilter;
  11683. this.wrapR = ClampToEdgeWrapping;
  11684. this.generateMipmaps = false;
  11685. this.flipY = false;
  11686. this.needsUpdate = true;
  11687. }
  11688. DataTexture2DArray.prototype = Object.create(Texture.prototype);
  11689. DataTexture2DArray.prototype.constructor = DataTexture2DArray;
  11690. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  11691. /**
  11692. * @author Artur Trzesiok
  11693. */
  11694. function DataTexture3D(data, width, height, depth) {
  11695. // We're going to add .setXXX() methods for setting properties later.
  11696. // Users can still set in DataTexture3D directly.
  11697. //
  11698. // var texture = new THREE.DataTexture3D( data, width, height, depth );
  11699. // texture.anisotropy = 16;
  11700. //
  11701. // See #14839
  11702. Texture.call(this, null);
  11703. this.image = {
  11704. data: data || null,
  11705. width: width || 1,
  11706. height: height || 1,
  11707. depth: depth || 1
  11708. };
  11709. this.magFilter = NearestFilter;
  11710. this.minFilter = NearestFilter;
  11711. this.wrapR = ClampToEdgeWrapping;
  11712. this.generateMipmaps = false;
  11713. this.flipY = false;
  11714. this.needsUpdate = true;
  11715. }
  11716. DataTexture3D.prototype = Object.create(Texture.prototype);
  11717. DataTexture3D.prototype.constructor = DataTexture3D;
  11718. DataTexture3D.prototype.isDataTexture3D = true;
  11719. /**
  11720. * @author tschw
  11721. * @author Mugen87 / https://github.com/Mugen87
  11722. * @author mrdoob / http://mrdoob.com/
  11723. *
  11724. * Uniforms of a program.
  11725. * Those form a tree structure with a special top-level container for the root,
  11726. * which you get by calling 'new WebGLUniforms( gl, program )'.
  11727. *
  11728. *
  11729. * Properties of inner nodes including the top-level container:
  11730. *
  11731. * .seq - array of nested uniforms
  11732. * .map - nested uniforms by name
  11733. *
  11734. *
  11735. * Methods of all nodes except the top-level container:
  11736. *
  11737. * .setValue( gl, value, [textures] )
  11738. *
  11739. * uploads a uniform value(s)
  11740. * the 'textures' parameter is needed for sampler uniforms
  11741. *
  11742. *
  11743. * Static methods of the top-level container (textures factorizations):
  11744. *
  11745. * .upload( gl, seq, values, textures )
  11746. *
  11747. * sets uniforms in 'seq' to 'values[id].value'
  11748. *
  11749. * .seqWithValue( seq, values ) : filteredSeq
  11750. *
  11751. * filters 'seq' entries with corresponding entry in values
  11752. *
  11753. *
  11754. * Methods of the top-level container (textures factorizations):
  11755. *
  11756. * .setValue( gl, name, value, textures )
  11757. *
  11758. * sets uniform with name 'name' to 'value'
  11759. *
  11760. * .setOptional( gl, obj, prop )
  11761. *
  11762. * like .set for an optional property of the object
  11763. *
  11764. */
  11765. var emptyTexture = new Texture();
  11766. var emptyTexture2dArray = new DataTexture2DArray();
  11767. var emptyTexture3d = new DataTexture3D();
  11768. var emptyCubeTexture = new CubeTexture(); // --- Utilities ---
  11769. // Array Caches (provide typed arrays for temporary by size)
  11770. var arrayCacheF32 = [];
  11771. var arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  11772. var mat4array = new Float32Array(16);
  11773. var mat3array = new Float32Array(9);
  11774. var mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  11775. function flatten(array, nBlocks, blockSize) {
  11776. var firstElem = array[0];
  11777. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  11778. // see http://jacksondunstan.com/articles/983
  11779. var n = nBlocks * blockSize,
  11780. r = arrayCacheF32[n];
  11781. if (r === undefined) {
  11782. r = new Float32Array(n);
  11783. arrayCacheF32[n] = r;
  11784. }
  11785. if (nBlocks !== 0) {
  11786. firstElem.toArray(r, 0);
  11787. for (var i = 1, offset = 0; i !== nBlocks; ++i) {
  11788. offset += blockSize;
  11789. array[i].toArray(r, offset);
  11790. }
  11791. }
  11792. return r;
  11793. }
  11794. function arraysEqual(a, b) {
  11795. if (a.length !== b.length) return false;
  11796. for (var i = 0, l = a.length; i < l; i++) {
  11797. if (a[i] !== b[i]) return false;
  11798. }
  11799. return true;
  11800. }
  11801. function copyArray(a, b) {
  11802. for (var i = 0, l = b.length; i < l; i++) {
  11803. a[i] = b[i];
  11804. }
  11805. } // Texture unit allocation
  11806. function allocTexUnits(textures, n) {
  11807. var r = arrayCacheI32[n];
  11808. if (r === undefined) {
  11809. r = new Int32Array(n);
  11810. arrayCacheI32[n] = r;
  11811. }
  11812. for (var i = 0; i !== n; ++i) r[i] = textures.allocateTextureUnit();
  11813. return r;
  11814. } // --- Setters ---
  11815. // Note: Defining these methods externally, because they come in a bunch
  11816. // and this way their names minify.
  11817. // Single scalar
  11818. function setValueV1f(gl, v) {
  11819. var cache = this.cache;
  11820. if (cache[0] === v) return;
  11821. gl.uniform1f(this.addr, v);
  11822. cache[0] = v;
  11823. } // Single float vector (from flat array or THREE.VectorN)
  11824. function setValueV2f(gl, v) {
  11825. var cache = this.cache;
  11826. if (v.x !== undefined) {
  11827. if (cache[0] !== v.x || cache[1] !== v.y) {
  11828. gl.uniform2f(this.addr, v.x, v.y);
  11829. cache[0] = v.x;
  11830. cache[1] = v.y;
  11831. }
  11832. } else {
  11833. if (arraysEqual(cache, v)) return;
  11834. gl.uniform2fv(this.addr, v);
  11835. copyArray(cache, v);
  11836. }
  11837. }
  11838. function setValueV3f(gl, v) {
  11839. var cache = this.cache;
  11840. if (v.x !== undefined) {
  11841. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  11842. gl.uniform3f(this.addr, v.x, v.y, v.z);
  11843. cache[0] = v.x;
  11844. cache[1] = v.y;
  11845. cache[2] = v.z;
  11846. }
  11847. } else if (v.r !== undefined) {
  11848. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  11849. gl.uniform3f(this.addr, v.r, v.g, v.b);
  11850. cache[0] = v.r;
  11851. cache[1] = v.g;
  11852. cache[2] = v.b;
  11853. }
  11854. } else {
  11855. if (arraysEqual(cache, v)) return;
  11856. gl.uniform3fv(this.addr, v);
  11857. copyArray(cache, v);
  11858. }
  11859. }
  11860. function setValueV4f(gl, v) {
  11861. var cache = this.cache;
  11862. if (v.x !== undefined) {
  11863. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  11864. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  11865. cache[0] = v.x;
  11866. cache[1] = v.y;
  11867. cache[2] = v.z;
  11868. cache[3] = v.w;
  11869. }
  11870. } else {
  11871. if (arraysEqual(cache, v)) return;
  11872. gl.uniform4fv(this.addr, v);
  11873. copyArray(cache, v);
  11874. }
  11875. } // Single matrix (from flat array or MatrixN)
  11876. function setValueM2(gl, v) {
  11877. var cache = this.cache;
  11878. var elements = v.elements;
  11879. if (elements === undefined) {
  11880. if (arraysEqual(cache, v)) return;
  11881. gl.uniformMatrix2fv(this.addr, false, v);
  11882. copyArray(cache, v);
  11883. } else {
  11884. if (arraysEqual(cache, elements)) return;
  11885. mat2array.set(elements);
  11886. gl.uniformMatrix2fv(this.addr, false, mat2array);
  11887. copyArray(cache, elements);
  11888. }
  11889. }
  11890. function setValueM3(gl, v) {
  11891. var cache = this.cache;
  11892. var elements = v.elements;
  11893. if (elements === undefined) {
  11894. if (arraysEqual(cache, v)) return;
  11895. gl.uniformMatrix3fv(this.addr, false, v);
  11896. copyArray(cache, v);
  11897. } else {
  11898. if (arraysEqual(cache, elements)) return;
  11899. mat3array.set(elements);
  11900. gl.uniformMatrix3fv(this.addr, false, mat3array);
  11901. copyArray(cache, elements);
  11902. }
  11903. }
  11904. function setValueM4(gl, v) {
  11905. var cache = this.cache;
  11906. var elements = v.elements;
  11907. if (elements === undefined) {
  11908. if (arraysEqual(cache, v)) return;
  11909. gl.uniformMatrix4fv(this.addr, false, v);
  11910. copyArray(cache, v);
  11911. } else {
  11912. if (arraysEqual(cache, elements)) return;
  11913. mat4array.set(elements);
  11914. gl.uniformMatrix4fv(this.addr, false, mat4array);
  11915. copyArray(cache, elements);
  11916. }
  11917. } // Single texture (2D / Cube)
  11918. function setValueT1(gl, v, textures) {
  11919. var cache = this.cache;
  11920. var unit = textures.allocateTextureUnit();
  11921. if (cache[0] !== unit) {
  11922. gl.uniform1i(this.addr, unit);
  11923. cache[0] = unit;
  11924. }
  11925. textures.safeSetTexture2D(v || emptyTexture, unit);
  11926. }
  11927. function setValueT2DArray1(gl, v, textures) {
  11928. var cache = this.cache;
  11929. var unit = textures.allocateTextureUnit();
  11930. if (cache[0] !== unit) {
  11931. gl.uniform1i(this.addr, unit);
  11932. cache[0] = unit;
  11933. }
  11934. textures.setTexture2DArray(v || emptyTexture2dArray, unit);
  11935. }
  11936. function setValueT3D1(gl, v, textures) {
  11937. var cache = this.cache;
  11938. var unit = textures.allocateTextureUnit();
  11939. if (cache[0] !== unit) {
  11940. gl.uniform1i(this.addr, unit);
  11941. cache[0] = unit;
  11942. }
  11943. textures.setTexture3D(v || emptyTexture3d, unit);
  11944. }
  11945. function setValueT6(gl, v, textures) {
  11946. var cache = this.cache;
  11947. var unit = textures.allocateTextureUnit();
  11948. if (cache[0] !== unit) {
  11949. gl.uniform1i(this.addr, unit);
  11950. cache[0] = unit;
  11951. }
  11952. textures.safeSetTextureCube(v || emptyCubeTexture, unit);
  11953. } // Integer / Boolean vectors or arrays thereof (always flat arrays)
  11954. function setValueV1i(gl, v) {
  11955. var cache = this.cache;
  11956. if (cache[0] === v) return;
  11957. gl.uniform1i(this.addr, v);
  11958. cache[0] = v;
  11959. }
  11960. function setValueV2i(gl, v) {
  11961. var cache = this.cache;
  11962. if (arraysEqual(cache, v)) return;
  11963. gl.uniform2iv(this.addr, v);
  11964. copyArray(cache, v);
  11965. }
  11966. function setValueV3i(gl, v) {
  11967. var cache = this.cache;
  11968. if (arraysEqual(cache, v)) return;
  11969. gl.uniform3iv(this.addr, v);
  11970. copyArray(cache, v);
  11971. }
  11972. function setValueV4i(gl, v) {
  11973. var cache = this.cache;
  11974. if (arraysEqual(cache, v)) return;
  11975. gl.uniform4iv(this.addr, v);
  11976. copyArray(cache, v);
  11977. } // Helper to pick the right setter for the singular case
  11978. function getSingularSetter(type) {
  11979. switch (type) {
  11980. case 0x1406:
  11981. return setValueV1f;
  11982. // FLOAT
  11983. case 0x8b50:
  11984. return setValueV2f;
  11985. // _VEC2
  11986. case 0x8b51:
  11987. return setValueV3f;
  11988. // _VEC3
  11989. case 0x8b52:
  11990. return setValueV4f;
  11991. // _VEC4
  11992. case 0x8b5a:
  11993. return setValueM2;
  11994. // _MAT2
  11995. case 0x8b5b:
  11996. return setValueM3;
  11997. // _MAT3
  11998. case 0x8b5c:
  11999. return setValueM4;
  12000. // _MAT4
  12001. case 0x8b5e:
  12002. case 0x8d66:
  12003. return setValueT1;
  12004. // SAMPLER_2D, SAMPLER_EXTERNAL_OES
  12005. case 0x8b5f:
  12006. return setValueT3D1;
  12007. // SAMPLER_3D
  12008. case 0x8b60:
  12009. return setValueT6;
  12010. // SAMPLER_CUBE
  12011. case 0x8DC1:
  12012. return setValueT2DArray1;
  12013. // SAMPLER_2D_ARRAY
  12014. case 0x1404:
  12015. case 0x8b56:
  12016. return setValueV1i;
  12017. // INT, BOOL
  12018. case 0x8b53:
  12019. case 0x8b57:
  12020. return setValueV2i;
  12021. // _VEC2
  12022. case 0x8b54:
  12023. case 0x8b58:
  12024. return setValueV3i;
  12025. // _VEC3
  12026. case 0x8b55:
  12027. case 0x8b59:
  12028. return setValueV4i;
  12029. // _VEC4
  12030. }
  12031. } // Array of scalars
  12032. function setValueV1fArray(gl, v) {
  12033. gl.uniform1fv(this.addr, v);
  12034. } // Integer / Boolean vectors or arrays thereof (always flat arrays)
  12035. function setValueV1iArray(gl, v) {
  12036. gl.uniform1iv(this.addr, v);
  12037. }
  12038. function setValueV2iArray(gl, v) {
  12039. gl.uniform2iv(this.addr, v);
  12040. }
  12041. function setValueV3iArray(gl, v) {
  12042. gl.uniform3iv(this.addr, v);
  12043. }
  12044. function setValueV4iArray(gl, v) {
  12045. gl.uniform4iv(this.addr, v);
  12046. } // Array of vectors (flat or from THREE classes)
  12047. function setValueV2fArray(gl, v) {
  12048. var data = flatten(v, this.size, 2);
  12049. gl.uniform2fv(this.addr, data);
  12050. }
  12051. function setValueV3fArray(gl, v) {
  12052. var data = flatten(v, this.size, 3);
  12053. gl.uniform3fv(this.addr, data);
  12054. }
  12055. function setValueV4fArray(gl, v) {
  12056. var data = flatten(v, this.size, 4);
  12057. gl.uniform4fv(this.addr, data);
  12058. } // Array of matrices (flat or from THREE clases)
  12059. function setValueM2Array(gl, v) {
  12060. var data = flatten(v, this.size, 4);
  12061. gl.uniformMatrix2fv(this.addr, false, data);
  12062. }
  12063. function setValueM3Array(gl, v) {
  12064. var data = flatten(v, this.size, 9);
  12065. gl.uniformMatrix3fv(this.addr, false, data);
  12066. }
  12067. function setValueM4Array(gl, v) {
  12068. var data = flatten(v, this.size, 16);
  12069. gl.uniformMatrix4fv(this.addr, false, data);
  12070. } // Array of textures (2D / Cube)
  12071. function setValueT1Array(gl, v, textures) {
  12072. var n = v.length;
  12073. var units = allocTexUnits(textures, n);
  12074. gl.uniform1iv(this.addr, units);
  12075. for (var i = 0; i !== n; ++i) {
  12076. textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
  12077. }
  12078. }
  12079. function setValueT6Array(gl, v, textures) {
  12080. var n = v.length;
  12081. var units = allocTexUnits(textures, n);
  12082. gl.uniform1iv(this.addr, units);
  12083. for (var i = 0; i !== n; ++i) {
  12084. textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
  12085. }
  12086. } // Helper to pick the right setter for a pure (bottom-level) array
  12087. function getPureArraySetter(type) {
  12088. switch (type) {
  12089. case 0x1406:
  12090. return setValueV1fArray;
  12091. // FLOAT
  12092. case 0x8b50:
  12093. return setValueV2fArray;
  12094. // _VEC2
  12095. case 0x8b51:
  12096. return setValueV3fArray;
  12097. // _VEC3
  12098. case 0x8b52:
  12099. return setValueV4fArray;
  12100. // _VEC4
  12101. case 0x8b5a:
  12102. return setValueM2Array;
  12103. // _MAT2
  12104. case 0x8b5b:
  12105. return setValueM3Array;
  12106. // _MAT3
  12107. case 0x8b5c:
  12108. return setValueM4Array;
  12109. // _MAT4
  12110. case 0x8b5e:
  12111. return setValueT1Array;
  12112. // SAMPLER_2D
  12113. case 0x8b60:
  12114. return setValueT6Array;
  12115. // SAMPLER_CUBE
  12116. case 0x1404:
  12117. case 0x8b56:
  12118. return setValueV1iArray;
  12119. // INT, BOOL
  12120. case 0x8b53:
  12121. case 0x8b57:
  12122. return setValueV2iArray;
  12123. // _VEC2
  12124. case 0x8b54:
  12125. case 0x8b58:
  12126. return setValueV3iArray;
  12127. // _VEC3
  12128. case 0x8b55:
  12129. case 0x8b59:
  12130. return setValueV4iArray;
  12131. // _VEC4
  12132. }
  12133. } // --- Uniform Classes ---
  12134. function SingleUniform(id, activeInfo, addr) {
  12135. this.id = id;
  12136. this.addr = addr;
  12137. this.cache = [];
  12138. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  12139. }
  12140. function PureArrayUniform(id, activeInfo, addr) {
  12141. this.id = id;
  12142. this.addr = addr;
  12143. this.cache = [];
  12144. this.size = activeInfo.size;
  12145. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  12146. }
  12147. PureArrayUniform.prototype.updateCache = function (data) {
  12148. var cache = this.cache;
  12149. if (data instanceof Float32Array && cache.length !== data.length) {
  12150. this.cache = new Float32Array(data.length);
  12151. }
  12152. copyArray(cache, data);
  12153. };
  12154. function StructuredUniform(id) {
  12155. this.id = id;
  12156. this.seq = [];
  12157. this.map = {};
  12158. }
  12159. StructuredUniform.prototype.setValue = function (gl, value, textures) {
  12160. var seq = this.seq;
  12161. for (var i = 0, n = seq.length; i !== n; ++i) {
  12162. var u = seq[i];
  12163. u.setValue(gl, value[u.id], textures);
  12164. }
  12165. }; // --- Top-level ---
  12166. // Parser - builds up the property tree from the path strings
  12167. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g; // extracts
  12168. // - the identifier (member name or array index)
  12169. // - followed by an optional right bracket (found when array index)
  12170. // - followed by an optional left bracket or dot (type of subscript)
  12171. //
  12172. // Note: These portions can be read in a non-overlapping fashion and
  12173. // allow straightforward parsing of the hierarchy that WebGL encodes
  12174. // in the uniform names.
  12175. function addUniform(container, uniformObject) {
  12176. container.seq.push(uniformObject);
  12177. container.map[uniformObject.id] = uniformObject;
  12178. }
  12179. function parseUniform(activeInfo, addr, container) {
  12180. var path = activeInfo.name,
  12181. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  12182. RePathPart.lastIndex = 0;
  12183. while (true) {
  12184. var match = RePathPart.exec(path),
  12185. matchEnd = RePathPart.lastIndex,
  12186. id = match[1],
  12187. idIsIndex = match[2] === ']',
  12188. subscript = match[3];
  12189. if (idIsIndex) id = id | 0; // convert to integer
  12190. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  12191. // bare name or "pure" bottom-level array "[0]" suffix
  12192. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  12193. break;
  12194. } else {
  12195. // step into inner node / create it in case it doesn't exist
  12196. var map = container.map,
  12197. next = map[id];
  12198. if (next === undefined) {
  12199. next = new StructuredUniform(id);
  12200. addUniform(container, next);
  12201. }
  12202. container = next;
  12203. }
  12204. }
  12205. } // Root Container
  12206. function WebGLUniforms(gl, program) {
  12207. this.seq = [];
  12208. this.map = {};
  12209. var n = gl.getProgramParameter(program, 35718);
  12210. for (var i = 0; i < n; ++i) {
  12211. var info = gl.getActiveUniform(program, i),
  12212. addr = gl.getUniformLocation(program, info.name);
  12213. parseUniform(info, addr, this);
  12214. }
  12215. }
  12216. WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
  12217. var u = this.map[name];
  12218. if (u !== undefined) u.setValue(gl, value, textures);
  12219. };
  12220. WebGLUniforms.prototype.setOptional = function (gl, object, name) {
  12221. var v = object[name];
  12222. if (v !== undefined) this.setValue(gl, name, v);
  12223. }; // Static interface
  12224. WebGLUniforms.upload = function (gl, seq, values, textures) {
  12225. for (var i = 0, n = seq.length; i !== n; ++i) {
  12226. var u = seq[i],
  12227. v = values[u.id];
  12228. if (v.needsUpdate !== false) {
  12229. // note: always updating when .needsUpdate is undefined
  12230. u.setValue(gl, v.value, textures);
  12231. }
  12232. }
  12233. };
  12234. WebGLUniforms.seqWithValue = function (seq, values) {
  12235. var r = [];
  12236. for (var i = 0, n = seq.length; i !== n; ++i) {
  12237. var u = seq[i];
  12238. if (u.id in values) r.push(u);
  12239. }
  12240. return r;
  12241. };
  12242. /**
  12243. * @author mrdoob / http://mrdoob.com/
  12244. */
  12245. function WebGLShader(gl, type, string) {
  12246. var shader = gl.createShader(type);
  12247. gl.shaderSource(shader, string);
  12248. gl.compileShader(shader);
  12249. return shader;
  12250. }
  12251. /**
  12252. * @author mrdoob / http://mrdoob.com/
  12253. */
  12254. var programIdCount = 0;
  12255. function addLineNumbers(string) {
  12256. var lines = string.split('\n');
  12257. for (var i = 0; i < lines.length; i++) {
  12258. lines[i] = i + 1 + ': ' + lines[i];
  12259. }
  12260. return lines.join('\n');
  12261. }
  12262. function getEncodingComponents(encoding) {
  12263. switch (encoding) {
  12264. case LinearEncoding:
  12265. return ['Linear', '( value )'];
  12266. case sRGBEncoding:
  12267. return ['sRGB', '( value )'];
  12268. case RGBEEncoding:
  12269. return ['RGBE', '( value )'];
  12270. case RGBM7Encoding:
  12271. return ['RGBM', '( value, 7.0 )'];
  12272. case RGBM16Encoding:
  12273. return ['RGBM', '( value, 16.0 )'];
  12274. case RGBDEncoding:
  12275. return ['RGBD', '( value, 256.0 )'];
  12276. case GammaEncoding:
  12277. return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
  12278. case LogLuvEncoding:
  12279. return ['LogLuv', '( value )'];
  12280. default:
  12281. throw new Error('unsupported encoding: ' + encoding);
  12282. }
  12283. }
  12284. function getShaderErrors(gl, shader, type) {
  12285. var status = gl.getShaderParameter(shader, 35713);
  12286. var log = gl.getShaderInfoLog(shader).trim();
  12287. if (status && log === '') return ''; // --enable-privileged-webgl-extension
  12288. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  12289. var source = gl.getShaderSource(shader);
  12290. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers(source);
  12291. }
  12292. function getTexelDecodingFunction(functionName, encoding) {
  12293. var components = getEncodingComponents(encoding);
  12294. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
  12295. }
  12296. function getTexelEncodingFunction(functionName, encoding) {
  12297. var components = getEncodingComponents(encoding);
  12298. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  12299. }
  12300. function getToneMappingFunction(functionName, toneMapping) {
  12301. var toneMappingName;
  12302. switch (toneMapping) {
  12303. case LinearToneMapping:
  12304. toneMappingName = 'Linear';
  12305. break;
  12306. case ReinhardToneMapping:
  12307. toneMappingName = 'Reinhard';
  12308. break;
  12309. case Uncharted2ToneMapping:
  12310. toneMappingName = 'Uncharted2';
  12311. break;
  12312. case CineonToneMapping:
  12313. toneMappingName = 'OptimizedCineon';
  12314. break;
  12315. case ACESFilmicToneMapping:
  12316. toneMappingName = 'ACESFilmic';
  12317. break;
  12318. default:
  12319. throw new Error('unsupported toneMapping: ' + toneMapping);
  12320. }
  12321. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  12322. }
  12323. function generateExtensions(extensions, parameters, rendererExtensions) {
  12324. extensions = extensions || {};
  12325. 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' : ''];
  12326. return chunks.filter(filterEmptyLine).join('\n');
  12327. }
  12328. function generateDefines(defines) {
  12329. var chunks = [];
  12330. for (var name in defines) {
  12331. var value = defines[name];
  12332. if (value === false) continue;
  12333. chunks.push('#define ' + name + ' ' + value);
  12334. }
  12335. return chunks.join('\n');
  12336. }
  12337. function fetchAttributeLocations(gl, program) {
  12338. var attributes = {};
  12339. var n = gl.getProgramParameter(program, 35721);
  12340. for (var i = 0; i < n; i++) {
  12341. var info = gl.getActiveAttrib(program, i);
  12342. var name = info.name; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  12343. attributes[name] = gl.getAttribLocation(program, name);
  12344. }
  12345. return attributes;
  12346. }
  12347. function filterEmptyLine(string) {
  12348. return string !== '';
  12349. }
  12350. function replaceLightNums(string, parameters) {
  12351. 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);
  12352. }
  12353. function replaceClippingPlaneNums(string, parameters) {
  12354. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  12355. } // Resolve Includes
  12356. var includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  12357. function resolveIncludes(string) {
  12358. return string.replace(includePattern, includeReplacer);
  12359. }
  12360. function includeReplacer(match, include) {
  12361. var string = ShaderChunk[include];
  12362. if (string === undefined) {
  12363. throw new Error('Can not resolve #include <' + include + '>');
  12364. }
  12365. return resolveIncludes(string);
  12366. } // Unroll Loops
  12367. var loopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  12368. function unrollLoops(string) {
  12369. return string.replace(loopPattern, loopReplacer);
  12370. }
  12371. function loopReplacer(match, start, end, snippet) {
  12372. var string = '';
  12373. for (var i = parseInt(start); i < parseInt(end); i++) {
  12374. string += snippet.replace(/\[ i \]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  12375. }
  12376. return string;
  12377. } //
  12378. function generatePrecision(parameters) {
  12379. var precisionstring = "precision " + parameters.precision + " float;\nprecision " + parameters.precision + " int;";
  12380. if (parameters.precision === "highp") {
  12381. precisionstring += "\n#define HIGH_PRECISION";
  12382. } else if (parameters.precision === "mediump") {
  12383. precisionstring += "\n#define MEDIUM_PRECISION";
  12384. } else if (parameters.precision === "lowp") {
  12385. precisionstring += "\n#define LOW_PRECISION";
  12386. }
  12387. return precisionstring;
  12388. }
  12389. function generateShadowMapTypeDefine(parameters) {
  12390. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  12391. if (parameters.shadowMapType === PCFShadowMap) {
  12392. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  12393. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  12394. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  12395. } else if (parameters.shadowMapType === VSMShadowMap) {
  12396. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  12397. }
  12398. return shadowMapTypeDefine;
  12399. }
  12400. function generateEnvMapTypeDefine(parameters, material) {
  12401. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  12402. if (parameters.envMap) {
  12403. switch (material.envMap.mapping) {
  12404. case CubeReflectionMapping:
  12405. case CubeRefractionMapping:
  12406. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  12407. break;
  12408. case CubeUVReflectionMapping:
  12409. case CubeUVRefractionMapping:
  12410. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  12411. break;
  12412. case EquirectangularReflectionMapping:
  12413. case EquirectangularRefractionMapping:
  12414. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  12415. break;
  12416. case SphericalReflectionMapping:
  12417. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  12418. break;
  12419. }
  12420. }
  12421. return envMapTypeDefine;
  12422. }
  12423. function generateEnvMapModeDefine(parameters, material) {
  12424. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  12425. if (parameters.envMap) {
  12426. switch (material.envMap.mapping) {
  12427. case CubeRefractionMapping:
  12428. case EquirectangularRefractionMapping:
  12429. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  12430. break;
  12431. }
  12432. }
  12433. return envMapModeDefine;
  12434. }
  12435. function generateEnvMapBlendingDefine(parameters, material) {
  12436. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  12437. if (parameters.envMap) {
  12438. switch (material.combine) {
  12439. case MultiplyOperation:
  12440. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  12441. break;
  12442. case MixOperation:
  12443. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  12444. break;
  12445. case AddOperation:
  12446. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  12447. break;
  12448. }
  12449. }
  12450. return envMapBlendingDefine;
  12451. }
  12452. function WebGLProgram(renderer, extensions, code, material, shader, parameters) {
  12453. var gl = renderer.getContext();
  12454. var defines = material.defines;
  12455. var vertexShader = shader.vertexShader;
  12456. var fragmentShader = shader.fragmentShader;
  12457. var shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  12458. var envMapTypeDefine = generateEnvMapTypeDefine(parameters, material);
  12459. var envMapModeDefine = generateEnvMapModeDefine(parameters, material);
  12460. var envMapBlendingDefine = generateEnvMapBlendingDefine(parameters, material);
  12461. var gammaFactorDefine = renderer.gammaFactor > 0 ? renderer.gammaFactor : 1.0;
  12462. var customExtensions = parameters.isWebGL2 ? '' : generateExtensions(material.extensions, parameters, extensions);
  12463. var customDefines = generateDefines(defines);
  12464. var program = gl.createProgram();
  12465. var prefixVertex, prefixFragment;
  12466. var renderTarget = renderer.getRenderTarget();
  12467. var numMultiviewViews = renderTarget && renderTarget.isWebGLMultiviewRenderTarget ? renderTarget.numViews : 0;
  12468. if (material.isRawShaderMaterial) {
  12469. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  12470. if (prefixVertex.length > 0) {
  12471. prefixVertex += '\n';
  12472. }
  12473. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  12474. if (prefixFragment.length > 0) {
  12475. prefixFragment += '\n';
  12476. }
  12477. } else {
  12478. 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');
  12479. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + shader.name, customDefines, parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + (parameters.alphaTest % 1 ? '' : '.0') : '', // add '.0' if integer
  12480. '#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
  12481. 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
  12482. 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');
  12483. }
  12484. vertexShader = resolveIncludes(vertexShader);
  12485. vertexShader = replaceLightNums(vertexShader, parameters);
  12486. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  12487. fragmentShader = resolveIncludes(fragmentShader);
  12488. fragmentShader = replaceLightNums(fragmentShader, parameters);
  12489. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  12490. vertexShader = unrollLoops(vertexShader);
  12491. fragmentShader = unrollLoops(fragmentShader);
  12492. if (parameters.isWebGL2 && !material.isRawShaderMaterial) {
  12493. var isGLSL3ShaderMaterial = false;
  12494. var versionRegex = /^\s*#version\s+300\s+es\s*\n/;
  12495. if (material.isShaderMaterial && vertexShader.match(versionRegex) !== null && fragmentShader.match(versionRegex) !== null) {
  12496. isGLSL3ShaderMaterial = true;
  12497. vertexShader = vertexShader.replace(versionRegex, '');
  12498. fragmentShader = fragmentShader.replace(versionRegex, '');
  12499. } // GLSL 3.0 conversion
  12500. prefixVertex = ['#version 300 es\n', '#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  12501. 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
  12502. if (numMultiviewViews > 0) {
  12503. 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'));
  12504. 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'));
  12505. prefixFragment = prefixFragment.replace('#version 300 es\n', ['#version 300 es\n', '#extension GL_OVR_multiview2 : require', '#define VIEW_ID gl_ViewID_OVR'].join('\n'));
  12506. prefixFragment = prefixFragment.replace('uniform mat4 viewMatrix;', ['uniform mat4 viewMatrices[' + numMultiviewViews + '];', '#define viewMatrix viewMatrices[VIEW_ID]'].join('\n'));
  12507. }
  12508. }
  12509. var vertexGlsl = prefixVertex + vertexShader;
  12510. var fragmentGlsl = prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  12511. // console.log( '*FRAGMENT*', fragmentGlsl );
  12512. var glVertexShader = WebGLShader(gl, 35633, vertexGlsl);
  12513. var glFragmentShader = WebGLShader(gl, 35632, fragmentGlsl);
  12514. gl.attachShader(program, glVertexShader);
  12515. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  12516. if (material.index0AttributeName !== undefined) {
  12517. gl.bindAttribLocation(program, 0, material.index0AttributeName);
  12518. } else if (parameters.morphTargets === true) {
  12519. // programs with morphTargets displace position out of attribute 0
  12520. gl.bindAttribLocation(program, 0, 'position');
  12521. }
  12522. gl.linkProgram(program); // check for link errors
  12523. if (renderer.debug.checkShaderErrors) {
  12524. var programLog = gl.getProgramInfoLog(program).trim();
  12525. var vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  12526. var fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  12527. var runnable = true;
  12528. var haveDiagnostics = true;
  12529. if (gl.getProgramParameter(program, 35714) === false) {
  12530. runnable = false;
  12531. var vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  12532. var fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  12533. console.error('THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter(program, 35715), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors);
  12534. } else if (programLog !== '') {
  12535. console.warn('THREE.WebGLProgram: gl.getProgramInfoLog()', programLog);
  12536. } else if (vertexLog === '' || fragmentLog === '') {
  12537. haveDiagnostics = false;
  12538. }
  12539. if (haveDiagnostics) {
  12540. this.diagnostics = {
  12541. runnable: runnable,
  12542. material: material,
  12543. programLog: programLog,
  12544. vertexShader: {
  12545. log: vertexLog,
  12546. prefix: prefixVertex
  12547. },
  12548. fragmentShader: {
  12549. log: fragmentLog,
  12550. prefix: prefixFragment
  12551. }
  12552. };
  12553. }
  12554. } // clean up
  12555. gl.deleteShader(glVertexShader);
  12556. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  12557. var cachedUniforms;
  12558. this.getUniforms = function () {
  12559. if (cachedUniforms === undefined) {
  12560. cachedUniforms = new WebGLUniforms(gl, program);
  12561. }
  12562. return cachedUniforms;
  12563. }; // set up caching for attribute locations
  12564. var cachedAttributes;
  12565. this.getAttributes = function () {
  12566. if (cachedAttributes === undefined) {
  12567. cachedAttributes = fetchAttributeLocations(gl, program);
  12568. }
  12569. return cachedAttributes;
  12570. }; // free resource
  12571. this.destroy = function () {
  12572. gl.deleteProgram(program);
  12573. this.program = undefined;
  12574. }; //
  12575. this.name = shader.name;
  12576. this.id = programIdCount++;
  12577. this.code = code;
  12578. this.usedTimes = 1;
  12579. this.program = program;
  12580. this.vertexShader = glVertexShader;
  12581. this.fragmentShader = glFragmentShader;
  12582. this.numMultiviewViews = numMultiviewViews;
  12583. return this;
  12584. }
  12585. /**
  12586. * @author mrdoob / http://mrdoob.com/
  12587. */
  12588. function WebGLPrograms(renderer, extensions, capabilities) {
  12589. var programs = [];
  12590. var shaderIDs = {
  12591. MeshDepthMaterial: 'depth',
  12592. MeshDistanceMaterial: 'distanceRGBA',
  12593. MeshNormalMaterial: 'normal',
  12594. MeshBasicMaterial: 'basic',
  12595. MeshLambertMaterial: 'lambert',
  12596. MeshPhongMaterial: 'phong',
  12597. MeshToonMaterial: 'phong',
  12598. MeshStandardMaterial: 'physical',
  12599. MeshPhysicalMaterial: 'physical',
  12600. MeshMatcapMaterial: 'matcap',
  12601. LineBasicMaterial: 'basic',
  12602. LineDashedMaterial: 'dashed',
  12603. PointsMaterial: 'points',
  12604. ShadowMaterial: 'shadow',
  12605. SpriteMaterial: 'sprite'
  12606. };
  12607. 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"];
  12608. function allocateBones(object) {
  12609. var skeleton = object.skeleton;
  12610. var bones = skeleton.bones;
  12611. if (capabilities.floatVertexTextures) {
  12612. return 1024;
  12613. } else {
  12614. // default for when object is not specified
  12615. // ( for example when prebuilding shader to be used with multiple objects )
  12616. //
  12617. // - leave some extra space for other uniforms
  12618. // - limit here is ANGLE's 254 max uniform vectors
  12619. // (up to 54 should be safe)
  12620. var nVertexUniforms = capabilities.maxVertexUniforms;
  12621. var nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
  12622. var maxBones = Math.min(nVertexMatrices, bones.length);
  12623. if (maxBones < bones.length) {
  12624. console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
  12625. return 0;
  12626. }
  12627. return maxBones;
  12628. }
  12629. }
  12630. function getTextureEncodingFromMap(map, gammaOverrideLinear) {
  12631. var encoding;
  12632. if (!map) {
  12633. encoding = LinearEncoding;
  12634. } else if (map.isTexture) {
  12635. encoding = map.encoding;
  12636. } else if (map.isWebGLRenderTarget) {
  12637. console.warn("THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead.");
  12638. encoding = map.texture.encoding;
  12639. } // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  12640. if (encoding === LinearEncoding && gammaOverrideLinear) {
  12641. encoding = GammaEncoding;
  12642. }
  12643. return encoding;
  12644. }
  12645. this.getParameters = function (material, lights, shadows, fog, nClipPlanes, nClipIntersection, object) {
  12646. var shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  12647. // (not to blow over maxLights budget)
  12648. var maxBones = object.isSkinnedMesh ? allocateBones(object) : 0;
  12649. var precision = capabilities.precision;
  12650. if (material.precision !== null) {
  12651. precision = capabilities.getMaxPrecision(material.precision);
  12652. if (precision !== material.precision) {
  12653. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  12654. }
  12655. }
  12656. var currentRenderTarget = renderer.getRenderTarget();
  12657. var parameters = {
  12658. isWebGL2: capabilities.isWebGL2,
  12659. shaderID: shaderID,
  12660. precision: precision,
  12661. instancing: object.isInstancedMesh === true,
  12662. supportsVertexTextures: capabilities.vertexTextures,
  12663. outputEncoding: getTextureEncodingFromMap(!currentRenderTarget ? null : currentRenderTarget.texture, renderer.gammaOutput),
  12664. map: !!material.map,
  12665. mapEncoding: getTextureEncodingFromMap(material.map, renderer.gammaInput),
  12666. matcap: !!material.matcap,
  12667. matcapEncoding: getTextureEncodingFromMap(material.matcap, renderer.gammaInput),
  12668. envMap: !!material.envMap,
  12669. envMapMode: material.envMap && material.envMap.mapping,
  12670. envMapEncoding: getTextureEncodingFromMap(material.envMap, renderer.gammaInput),
  12671. envMapCubeUV: !!material.envMap && (material.envMap.mapping === CubeUVReflectionMapping || material.envMap.mapping === CubeUVRefractionMapping),
  12672. lightMap: !!material.lightMap,
  12673. aoMap: !!material.aoMap,
  12674. emissiveMap: !!material.emissiveMap,
  12675. emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap, renderer.gammaInput),
  12676. bumpMap: !!material.bumpMap,
  12677. normalMap: !!material.normalMap,
  12678. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  12679. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  12680. clearcoatNormalMap: !!material.clearcoatNormalMap,
  12681. displacementMap: !!material.displacementMap,
  12682. roughnessMap: !!material.roughnessMap,
  12683. metalnessMap: !!material.metalnessMap,
  12684. specularMap: !!material.specularMap,
  12685. alphaMap: !!material.alphaMap,
  12686. gradientMap: !!material.gradientMap,
  12687. sheen: !!material.sheen,
  12688. combine: material.combine,
  12689. vertexTangents: material.normalMap && material.vertexTangents,
  12690. vertexColors: material.vertexColors,
  12691. vertexUvs: !!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap,
  12692. fog: !!fog,
  12693. useFog: material.fog,
  12694. fogExp2: fog && fog.isFogExp2,
  12695. flatShading: material.flatShading,
  12696. sizeAttenuation: material.sizeAttenuation,
  12697. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  12698. skinning: material.skinning && maxBones > 0,
  12699. maxBones: maxBones,
  12700. useVertexTexture: capabilities.floatVertexTextures,
  12701. morphTargets: material.morphTargets,
  12702. morphNormals: material.morphNormals,
  12703. maxMorphTargets: renderer.maxMorphTargets,
  12704. maxMorphNormals: renderer.maxMorphNormals,
  12705. numDirLights: lights.directional.length,
  12706. numPointLights: lights.point.length,
  12707. numSpotLights: lights.spot.length,
  12708. numRectAreaLights: lights.rectArea.length,
  12709. numHemiLights: lights.hemi.length,
  12710. numDirLightShadows: lights.directionalShadowMap.length,
  12711. numPointLightShadows: lights.pointShadowMap.length,
  12712. numSpotLightShadows: lights.spotShadowMap.length,
  12713. numClippingPlanes: nClipPlanes,
  12714. numClipIntersection: nClipIntersection,
  12715. dithering: material.dithering,
  12716. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  12717. shadowMapType: renderer.shadowMap.type,
  12718. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  12719. physicallyCorrectLights: renderer.physicallyCorrectLights,
  12720. premultipliedAlpha: material.premultipliedAlpha,
  12721. alphaTest: material.alphaTest,
  12722. doubleSided: material.side === DoubleSide,
  12723. flipSided: material.side === BackSide,
  12724. depthPacking: material.depthPacking !== undefined ? material.depthPacking : false
  12725. };
  12726. return parameters;
  12727. };
  12728. this.getProgramCode = function (material, parameters) {
  12729. var array = [];
  12730. if (parameters.shaderID) {
  12731. array.push(parameters.shaderID);
  12732. } else {
  12733. array.push(material.fragmentShader);
  12734. array.push(material.vertexShader);
  12735. }
  12736. if (material.defines !== undefined) {
  12737. for (var name in material.defines) {
  12738. array.push(name);
  12739. array.push(material.defines[name]);
  12740. }
  12741. }
  12742. for (var i = 0; i < parameterNames.length; i++) {
  12743. array.push(parameters[parameterNames[i]]);
  12744. }
  12745. array.push(material.onBeforeCompile.toString());
  12746. array.push(renderer.gammaOutput);
  12747. array.push(renderer.gammaFactor);
  12748. return array.join();
  12749. };
  12750. this.acquireProgram = function (material, shader, parameters, code) {
  12751. var program; // Check if code has been already compiled
  12752. for (var p = 0, pl = programs.length; p < pl; p++) {
  12753. var programInfo = programs[p];
  12754. if (programInfo.code === code) {
  12755. program = programInfo;
  12756. ++program.usedTimes;
  12757. break;
  12758. }
  12759. }
  12760. if (program === undefined) {
  12761. program = new WebGLProgram(renderer, extensions, code, material, shader, parameters);
  12762. programs.push(program);
  12763. }
  12764. return program;
  12765. };
  12766. this.releaseProgram = function (program) {
  12767. if (--program.usedTimes === 0) {
  12768. // Remove from unordered set
  12769. var i = programs.indexOf(program);
  12770. programs[i] = programs[programs.length - 1];
  12771. programs.pop(); // Free WebGL resources
  12772. program.destroy();
  12773. }
  12774. }; // Exposed for resource monitoring & error feedback via renderer.info:
  12775. this.programs = programs;
  12776. }
  12777. /**
  12778. * @author fordacious / fordacious.github.io
  12779. */
  12780. function WebGLProperties() {
  12781. var properties = new WeakMap();
  12782. function get(object) {
  12783. var map = properties.get(object);
  12784. if (map === undefined) {
  12785. map = {};
  12786. properties.set(object, map);
  12787. }
  12788. return map;
  12789. }
  12790. function remove(object) {
  12791. properties.delete(object);
  12792. }
  12793. function update(object, key, value) {
  12794. properties.get(object)[key] = value;
  12795. }
  12796. function dispose() {
  12797. properties = new WeakMap();
  12798. }
  12799. return {
  12800. get: get,
  12801. remove: remove,
  12802. update: update,
  12803. dispose: dispose
  12804. };
  12805. }
  12806. /**
  12807. * @author mrdoob / http://mrdoob.com/
  12808. */
  12809. function painterSortStable(a, b) {
  12810. if (a.groupOrder !== b.groupOrder) {
  12811. return a.groupOrder - b.groupOrder;
  12812. } else if (a.renderOrder !== b.renderOrder) {
  12813. return a.renderOrder - b.renderOrder;
  12814. } else if (a.program !== b.program) {
  12815. return a.program.id - b.program.id;
  12816. } else if (a.material.id !== b.material.id) {
  12817. return a.material.id - b.material.id;
  12818. } else if (a.z !== b.z) {
  12819. return a.z - b.z;
  12820. } else {
  12821. return a.id - b.id;
  12822. }
  12823. }
  12824. function reversePainterSortStable(a, b) {
  12825. if (a.groupOrder !== b.groupOrder) {
  12826. return a.groupOrder - b.groupOrder;
  12827. } else if (a.renderOrder !== b.renderOrder) {
  12828. return a.renderOrder - b.renderOrder;
  12829. } else if (a.z !== b.z) {
  12830. return b.z - a.z;
  12831. } else {
  12832. return a.id - b.id;
  12833. }
  12834. }
  12835. function WebGLRenderList() {
  12836. var renderItems = [];
  12837. var renderItemsIndex = 0;
  12838. var opaque = [];
  12839. var transparent = [];
  12840. var defaultProgram = {
  12841. id: -1
  12842. };
  12843. function init() {
  12844. renderItemsIndex = 0;
  12845. opaque.length = 0;
  12846. transparent.length = 0;
  12847. }
  12848. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  12849. var renderItem = renderItems[renderItemsIndex];
  12850. if (renderItem === undefined) {
  12851. renderItem = {
  12852. id: object.id,
  12853. object: object,
  12854. geometry: geometry,
  12855. material: material,
  12856. program: material.program || defaultProgram,
  12857. groupOrder: groupOrder,
  12858. renderOrder: object.renderOrder,
  12859. z: z,
  12860. group: group
  12861. };
  12862. renderItems[renderItemsIndex] = renderItem;
  12863. } else {
  12864. renderItem.id = object.id;
  12865. renderItem.object = object;
  12866. renderItem.geometry = geometry;
  12867. renderItem.material = material;
  12868. renderItem.program = material.program || defaultProgram;
  12869. renderItem.groupOrder = groupOrder;
  12870. renderItem.renderOrder = object.renderOrder;
  12871. renderItem.z = z;
  12872. renderItem.group = group;
  12873. }
  12874. renderItemsIndex++;
  12875. return renderItem;
  12876. }
  12877. function push(object, geometry, material, groupOrder, z, group) {
  12878. var renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12879. (material.transparent === true ? transparent : opaque).push(renderItem);
  12880. }
  12881. function unshift(object, geometry, material, groupOrder, z, group) {
  12882. var renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12883. (material.transparent === true ? transparent : opaque).unshift(renderItem);
  12884. }
  12885. function sort() {
  12886. if (opaque.length > 1) opaque.sort(painterSortStable);
  12887. if (transparent.length > 1) transparent.sort(reversePainterSortStable);
  12888. }
  12889. return {
  12890. opaque: opaque,
  12891. transparent: transparent,
  12892. init: init,
  12893. push: push,
  12894. unshift: unshift,
  12895. sort: sort
  12896. };
  12897. }
  12898. function WebGLRenderLists() {
  12899. var lists = new WeakMap();
  12900. function onSceneDispose(event) {
  12901. var scene = event.target;
  12902. scene.removeEventListener('dispose', onSceneDispose);
  12903. lists.delete(scene);
  12904. }
  12905. function get(scene, camera) {
  12906. var cameras = lists.get(scene);
  12907. var list;
  12908. if (cameras === undefined) {
  12909. list = new WebGLRenderList();
  12910. lists.set(scene, new WeakMap());
  12911. lists.get(scene).set(camera, list);
  12912. scene.addEventListener('dispose', onSceneDispose);
  12913. } else {
  12914. list = cameras.get(camera);
  12915. if (list === undefined) {
  12916. list = new WebGLRenderList();
  12917. cameras.set(camera, list);
  12918. }
  12919. }
  12920. return list;
  12921. }
  12922. function dispose() {
  12923. lists = new WeakMap();
  12924. }
  12925. return {
  12926. get: get,
  12927. dispose: dispose
  12928. };
  12929. }
  12930. /**
  12931. * @author mrdoob / http://mrdoob.com/
  12932. */
  12933. function UniformsCache() {
  12934. var lights = {};
  12935. return {
  12936. get: function (light) {
  12937. if (lights[light.id] !== undefined) {
  12938. return lights[light.id];
  12939. }
  12940. var uniforms;
  12941. switch (light.type) {
  12942. case 'DirectionalLight':
  12943. uniforms = {
  12944. direction: new Vector3(),
  12945. color: new Color(),
  12946. shadow: false,
  12947. shadowBias: 0,
  12948. shadowRadius: 1,
  12949. shadowMapSize: new Vector2()
  12950. };
  12951. break;
  12952. case 'SpotLight':
  12953. uniforms = {
  12954. position: new Vector3(),
  12955. direction: new Vector3(),
  12956. color: new Color(),
  12957. distance: 0,
  12958. coneCos: 0,
  12959. penumbraCos: 0,
  12960. decay: 0,
  12961. shadow: false,
  12962. shadowBias: 0,
  12963. shadowRadius: 1,
  12964. shadowMapSize: new Vector2()
  12965. };
  12966. break;
  12967. case 'PointLight':
  12968. uniforms = {
  12969. position: new Vector3(),
  12970. color: new Color(),
  12971. distance: 0,
  12972. decay: 0,
  12973. shadow: false,
  12974. shadowBias: 0,
  12975. shadowRadius: 1,
  12976. shadowMapSize: new Vector2(),
  12977. shadowCameraNear: 1,
  12978. shadowCameraFar: 1000
  12979. };
  12980. break;
  12981. case 'HemisphereLight':
  12982. uniforms = {
  12983. direction: new Vector3(),
  12984. skyColor: new Color(),
  12985. groundColor: new Color()
  12986. };
  12987. break;
  12988. case 'RectAreaLight':
  12989. uniforms = {
  12990. color: new Color(),
  12991. position: new Vector3(),
  12992. halfWidth: new Vector3(),
  12993. halfHeight: new Vector3() // TODO (abelnation): set RectAreaLight shadow uniforms
  12994. };
  12995. break;
  12996. }
  12997. lights[light.id] = uniforms;
  12998. return uniforms;
  12999. }
  13000. };
  13001. }
  13002. var nextVersion = 0;
  13003. function shadowCastingLightsFirst(lightA, lightB) {
  13004. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  13005. }
  13006. function WebGLLights() {
  13007. var cache = new UniformsCache();
  13008. var state = {
  13009. version: 0,
  13010. hash: {
  13011. directionalLength: -1,
  13012. pointLength: -1,
  13013. spotLength: -1,
  13014. rectAreaLength: -1,
  13015. hemiLength: -1,
  13016. numDirectionalShadows: -1,
  13017. numPointShadows: -1,
  13018. numSpotShadows: -1
  13019. },
  13020. ambient: [0, 0, 0],
  13021. probe: [],
  13022. directional: [],
  13023. directionalShadowMap: [],
  13024. directionalShadowMatrix: [],
  13025. spot: [],
  13026. spotShadowMap: [],
  13027. spotShadowMatrix: [],
  13028. rectArea: [],
  13029. point: [],
  13030. pointShadowMap: [],
  13031. pointShadowMatrix: [],
  13032. hemi: [],
  13033. numDirectionalShadows: -1,
  13034. numPointShadows: -1,
  13035. numSpotShadows: -1
  13036. };
  13037. for (var i = 0; i < 9; i++) state.probe.push(new Vector3());
  13038. var vector3 = new Vector3();
  13039. var matrix4 = new Matrix4();
  13040. var matrix42 = new Matrix4();
  13041. function setup(lights, shadows, camera) {
  13042. var r = 0,
  13043. g = 0,
  13044. b = 0;
  13045. for (var i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  13046. var directionalLength = 0;
  13047. var pointLength = 0;
  13048. var spotLength = 0;
  13049. var rectAreaLength = 0;
  13050. var hemiLength = 0;
  13051. var numDirectionalShadows = 0;
  13052. var numPointShadows = 0;
  13053. var numSpotShadows = 0;
  13054. var viewMatrix = camera.matrixWorldInverse;
  13055. lights.sort(shadowCastingLightsFirst);
  13056. for (var i = 0, l = lights.length; i < l; i++) {
  13057. var light = lights[i];
  13058. var color = light.color;
  13059. var intensity = light.intensity;
  13060. var distance = light.distance;
  13061. var shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  13062. if (light.isAmbientLight) {
  13063. r += color.r * intensity;
  13064. g += color.g * intensity;
  13065. b += color.b * intensity;
  13066. } else if (light.isLightProbe) {
  13067. for (var j = 0; j < 9; j++) {
  13068. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  13069. }
  13070. } else if (light.isDirectionalLight) {
  13071. var uniforms = cache.get(light);
  13072. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  13073. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  13074. vector3.setFromMatrixPosition(light.target.matrixWorld);
  13075. uniforms.direction.sub(vector3);
  13076. uniforms.direction.transformDirection(viewMatrix);
  13077. uniforms.shadow = light.castShadow;
  13078. if (light.castShadow) {
  13079. var shadow = light.shadow;
  13080. uniforms.shadowBias = shadow.bias;
  13081. uniforms.shadowRadius = shadow.radius;
  13082. uniforms.shadowMapSize = shadow.mapSize;
  13083. state.directionalShadowMap[directionalLength] = shadowMap;
  13084. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  13085. numDirectionalShadows++;
  13086. }
  13087. state.directional[directionalLength] = uniforms;
  13088. directionalLength++;
  13089. } else if (light.isSpotLight) {
  13090. var uniforms = cache.get(light);
  13091. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  13092. uniforms.position.applyMatrix4(viewMatrix);
  13093. uniforms.color.copy(color).multiplyScalar(intensity);
  13094. uniforms.distance = distance;
  13095. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  13096. vector3.setFromMatrixPosition(light.target.matrixWorld);
  13097. uniforms.direction.sub(vector3);
  13098. uniforms.direction.transformDirection(viewMatrix);
  13099. uniforms.coneCos = Math.cos(light.angle);
  13100. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  13101. uniforms.decay = light.decay;
  13102. uniforms.shadow = light.castShadow;
  13103. if (light.castShadow) {
  13104. var shadow = light.shadow;
  13105. uniforms.shadowBias = shadow.bias;
  13106. uniforms.shadowRadius = shadow.radius;
  13107. uniforms.shadowMapSize = shadow.mapSize;
  13108. state.spotShadowMap[spotLength] = shadowMap;
  13109. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  13110. numSpotShadows++;
  13111. }
  13112. state.spot[spotLength] = uniforms;
  13113. spotLength++;
  13114. } else if (light.isRectAreaLight) {
  13115. var uniforms = cache.get(light); // (a) intensity is the total visible light emitted
  13116. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  13117. // (b) intensity is the brightness of the light
  13118. uniforms.color.copy(color).multiplyScalar(intensity);
  13119. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  13120. uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  13121. matrix42.identity();
  13122. matrix4.copy(light.matrixWorld);
  13123. matrix4.premultiply(viewMatrix);
  13124. matrix42.extractRotation(matrix4);
  13125. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  13126. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  13127. uniforms.halfWidth.applyMatrix4(matrix42);
  13128. uniforms.halfHeight.applyMatrix4(matrix42); // TODO (abelnation): RectAreaLight distance?
  13129. // uniforms.distance = distance;
  13130. state.rectArea[rectAreaLength] = uniforms;
  13131. rectAreaLength++;
  13132. } else if (light.isPointLight) {
  13133. var uniforms = cache.get(light);
  13134. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  13135. uniforms.position.applyMatrix4(viewMatrix);
  13136. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  13137. uniforms.distance = light.distance;
  13138. uniforms.decay = light.decay;
  13139. uniforms.shadow = light.castShadow;
  13140. if (light.castShadow) {
  13141. var shadow = light.shadow;
  13142. uniforms.shadowBias = shadow.bias;
  13143. uniforms.shadowRadius = shadow.radius;
  13144. uniforms.shadowMapSize = shadow.mapSize;
  13145. uniforms.shadowCameraNear = shadow.camera.near;
  13146. uniforms.shadowCameraFar = shadow.camera.far;
  13147. state.pointShadowMap[pointLength] = shadowMap;
  13148. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  13149. numPointShadows++;
  13150. }
  13151. state.point[pointLength] = uniforms;
  13152. pointLength++;
  13153. } else if (light.isHemisphereLight) {
  13154. var uniforms = cache.get(light);
  13155. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  13156. uniforms.direction.transformDirection(viewMatrix);
  13157. uniforms.direction.normalize();
  13158. uniforms.skyColor.copy(light.color).multiplyScalar(intensity);
  13159. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity);
  13160. state.hemi[hemiLength] = uniforms;
  13161. hemiLength++;
  13162. }
  13163. }
  13164. state.ambient[0] = r;
  13165. state.ambient[1] = g;
  13166. state.ambient[2] = b;
  13167. var hash = state.hash;
  13168. 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) {
  13169. state.directional.length = directionalLength;
  13170. state.spot.length = spotLength;
  13171. state.rectArea.length = rectAreaLength;
  13172. state.point.length = pointLength;
  13173. state.hemi.length = hemiLength;
  13174. state.directionalShadowMap.length = numDirectionalShadows;
  13175. state.pointShadowMap.length = numPointShadows;
  13176. state.spotShadowMap.length = numSpotShadows;
  13177. state.directionalShadowMatrix.length = numDirectionalShadows;
  13178. state.pointShadowMatrix.length = numPointShadows;
  13179. state.spotShadowMatrix.length = numSpotShadows;
  13180. hash.directionalLength = directionalLength;
  13181. hash.pointLength = pointLength;
  13182. hash.spotLength = spotLength;
  13183. hash.rectAreaLength = rectAreaLength;
  13184. hash.hemiLength = hemiLength;
  13185. hash.numDirectionalShadows = numDirectionalShadows;
  13186. hash.numPointShadows = numPointShadows;
  13187. hash.numSpotShadows = numSpotShadows;
  13188. state.version = nextVersion++;
  13189. }
  13190. }
  13191. return {
  13192. setup: setup,
  13193. state: state
  13194. };
  13195. }
  13196. /**
  13197. * @author Mugen87 / https://github.com/Mugen87
  13198. */
  13199. function WebGLRenderState() {
  13200. var lights = new WebGLLights();
  13201. var lightsArray = [];
  13202. var shadowsArray = [];
  13203. function init() {
  13204. lightsArray.length = 0;
  13205. shadowsArray.length = 0;
  13206. }
  13207. function pushLight(light) {
  13208. lightsArray.push(light);
  13209. }
  13210. function pushShadow(shadowLight) {
  13211. shadowsArray.push(shadowLight);
  13212. }
  13213. function setupLights(camera) {
  13214. lights.setup(lightsArray, shadowsArray, camera);
  13215. }
  13216. var state = {
  13217. lightsArray: lightsArray,
  13218. shadowsArray: shadowsArray,
  13219. lights: lights
  13220. };
  13221. return {
  13222. init: init,
  13223. state: state,
  13224. setupLights: setupLights,
  13225. pushLight: pushLight,
  13226. pushShadow: pushShadow
  13227. };
  13228. }
  13229. function WebGLRenderStates() {
  13230. var renderStates = new WeakMap();
  13231. function onSceneDispose(event) {
  13232. var scene = event.target;
  13233. scene.removeEventListener('dispose', onSceneDispose);
  13234. renderStates.delete(scene);
  13235. }
  13236. function get(scene, camera) {
  13237. var renderState;
  13238. if (renderStates.has(scene) === false) {
  13239. renderState = new WebGLRenderState();
  13240. renderStates.set(scene, new WeakMap());
  13241. renderStates.get(scene).set(camera, renderState);
  13242. scene.addEventListener('dispose', onSceneDispose);
  13243. } else {
  13244. if (renderStates.get(scene).has(camera) === false) {
  13245. renderState = new WebGLRenderState();
  13246. renderStates.get(scene).set(camera, renderState);
  13247. } else {
  13248. renderState = renderStates.get(scene).get(camera);
  13249. }
  13250. }
  13251. return renderState;
  13252. }
  13253. function dispose() {
  13254. renderStates = new WeakMap();
  13255. }
  13256. return {
  13257. get: get,
  13258. dispose: dispose
  13259. };
  13260. }
  13261. /**
  13262. * @author mrdoob / http://mrdoob.com/
  13263. * @author alteredq / http://alteredqualia.com/
  13264. * @author bhouston / https://clara.io
  13265. * @author WestLangley / http://github.com/WestLangley
  13266. *
  13267. * parameters = {
  13268. *
  13269. * opacity: <float>,
  13270. *
  13271. * map: new THREE.Texture( <Image> ),
  13272. *
  13273. * alphaMap: new THREE.Texture( <Image> ),
  13274. *
  13275. * displacementMap: new THREE.Texture( <Image> ),
  13276. * displacementScale: <float>,
  13277. * displacementBias: <float>,
  13278. *
  13279. * wireframe: <boolean>,
  13280. * wireframeLinewidth: <float>
  13281. * }
  13282. */
  13283. function MeshDepthMaterial(parameters) {
  13284. Material.call(this);
  13285. this.type = 'MeshDepthMaterial';
  13286. this.depthPacking = BasicDepthPacking;
  13287. this.skinning = false;
  13288. this.morphTargets = false;
  13289. this.map = null;
  13290. this.alphaMap = null;
  13291. this.displacementMap = null;
  13292. this.displacementScale = 1;
  13293. this.displacementBias = 0;
  13294. this.wireframe = false;
  13295. this.wireframeLinewidth = 1;
  13296. this.fog = false;
  13297. this.setValues(parameters);
  13298. }
  13299. MeshDepthMaterial.prototype = Object.create(Material.prototype);
  13300. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  13301. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  13302. MeshDepthMaterial.prototype.copy = function (source) {
  13303. Material.prototype.copy.call(this, source);
  13304. this.depthPacking = source.depthPacking;
  13305. this.skinning = source.skinning;
  13306. this.morphTargets = source.morphTargets;
  13307. this.map = source.map;
  13308. this.alphaMap = source.alphaMap;
  13309. this.displacementMap = source.displacementMap;
  13310. this.displacementScale = source.displacementScale;
  13311. this.displacementBias = source.displacementBias;
  13312. this.wireframe = source.wireframe;
  13313. this.wireframeLinewidth = source.wireframeLinewidth;
  13314. return this;
  13315. };
  13316. /**
  13317. * @author WestLangley / http://github.com/WestLangley
  13318. *
  13319. * parameters = {
  13320. *
  13321. * referencePosition: <float>,
  13322. * nearDistance: <float>,
  13323. * farDistance: <float>,
  13324. *
  13325. * skinning: <bool>,
  13326. * morphTargets: <bool>,
  13327. *
  13328. * map: new THREE.Texture( <Image> ),
  13329. *
  13330. * alphaMap: new THREE.Texture( <Image> ),
  13331. *
  13332. * displacementMap: new THREE.Texture( <Image> ),
  13333. * displacementScale: <float>,
  13334. * displacementBias: <float>
  13335. *
  13336. * }
  13337. */
  13338. function MeshDistanceMaterial(parameters) {
  13339. Material.call(this);
  13340. this.type = 'MeshDistanceMaterial';
  13341. this.referencePosition = new Vector3();
  13342. this.nearDistance = 1;
  13343. this.farDistance = 1000;
  13344. this.skinning = false;
  13345. this.morphTargets = false;
  13346. this.map = null;
  13347. this.alphaMap = null;
  13348. this.displacementMap = null;
  13349. this.displacementScale = 1;
  13350. this.displacementBias = 0;
  13351. this.fog = false;
  13352. this.setValues(parameters);
  13353. }
  13354. MeshDistanceMaterial.prototype = Object.create(Material.prototype);
  13355. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  13356. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  13357. MeshDistanceMaterial.prototype.copy = function (source) {
  13358. Material.prototype.copy.call(this, source);
  13359. this.referencePosition.copy(source.referencePosition);
  13360. this.nearDistance = source.nearDistance;
  13361. this.farDistance = source.farDistance;
  13362. this.skinning = source.skinning;
  13363. this.morphTargets = source.morphTargets;
  13364. this.map = source.map;
  13365. this.alphaMap = source.alphaMap;
  13366. this.displacementMap = source.displacementMap;
  13367. this.displacementScale = source.displacementScale;
  13368. this.displacementBias = source.displacementBias;
  13369. return this;
  13370. };
  13371. 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}";
  13372. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  13373. /**
  13374. * @author alteredq / http://alteredqualia.com/
  13375. * @author mrdoob / http://mrdoob.com/
  13376. */
  13377. function WebGLShadowMap(_renderer, _objects, maxTextureSize) {
  13378. var _frustum = new Frustum(),
  13379. _shadowMapSize = new Vector2(),
  13380. _viewportSize = new Vector2(),
  13381. _viewport = new Vector4(),
  13382. _MorphingFlag = 1,
  13383. _SkinningFlag = 2,
  13384. _NumberOfMaterialVariants = (_MorphingFlag | _SkinningFlag) + 1,
  13385. _depthMaterials = new Array(_NumberOfMaterialVariants),
  13386. _distanceMaterials = new Array(_NumberOfMaterialVariants),
  13387. _materialCache = {};
  13388. var shadowSide = {
  13389. 0: BackSide,
  13390. 1: FrontSide,
  13391. 2: DoubleSide
  13392. };
  13393. var shadowMaterialVertical = new ShaderMaterial({
  13394. defines: {
  13395. SAMPLE_RATE: 2.0 / 8.0,
  13396. HALF_SAMPLE_RATE: 1.0 / 8.0
  13397. },
  13398. uniforms: {
  13399. shadow_pass: {
  13400. value: null
  13401. },
  13402. resolution: {
  13403. value: new Vector2()
  13404. },
  13405. radius: {
  13406. value: 4.0
  13407. }
  13408. },
  13409. vertexShader: vsm_vert,
  13410. fragmentShader: vsm_frag
  13411. });
  13412. var shadowMaterialHorizonal = shadowMaterialVertical.clone();
  13413. shadowMaterialHorizonal.defines.HORIZONAL_PASS = 1;
  13414. var fullScreenTri = new BufferGeometry();
  13415. fullScreenTri.addAttribute("position", new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  13416. var fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical); // init
  13417. for (var i = 0; i !== _NumberOfMaterialVariants; ++i) {
  13418. var useMorphing = (i & _MorphingFlag) !== 0;
  13419. var useSkinning = (i & _SkinningFlag) !== 0;
  13420. var depthMaterial = new MeshDepthMaterial({
  13421. depthPacking: RGBADepthPacking,
  13422. morphTargets: useMorphing,
  13423. skinning: useSkinning
  13424. });
  13425. _depthMaterials[i] = depthMaterial;
  13426. var distanceMaterial = new MeshDistanceMaterial({
  13427. morphTargets: useMorphing,
  13428. skinning: useSkinning
  13429. });
  13430. _distanceMaterials[i] = distanceMaterial;
  13431. }
  13432. var scope = this;
  13433. this.enabled = false;
  13434. this.autoUpdate = true;
  13435. this.needsUpdate = false;
  13436. this.type = PCFShadowMap;
  13437. this.render = function (lights, scene, camera) {
  13438. if (scope.enabled === false) return;
  13439. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  13440. if (lights.length === 0) return;
  13441. var currentRenderTarget = _renderer.getRenderTarget();
  13442. var activeCubeFace = _renderer.getActiveCubeFace();
  13443. var activeMipmapLevel = _renderer.getActiveMipmapLevel();
  13444. var _state = _renderer.state; // Set GL state for depth map.
  13445. _state.setBlending(NoBlending);
  13446. _state.buffers.color.setClear(1, 1, 1, 1);
  13447. _state.buffers.depth.setTest(true);
  13448. _state.setScissorTest(false); // render depth map
  13449. for (var i = 0, il = lights.length; i < il; i++) {
  13450. var light = lights[i];
  13451. var shadow = light.shadow;
  13452. if (shadow === undefined) {
  13453. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  13454. continue;
  13455. }
  13456. _shadowMapSize.copy(shadow.mapSize);
  13457. var shadowFrameExtents = shadow.getFrameExtents();
  13458. _shadowMapSize.multiply(shadowFrameExtents);
  13459. _viewportSize.copy(shadow.mapSize);
  13460. if (_shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize) {
  13461. console.warn('THREE.WebGLShadowMap:', light, 'has shadow exceeding max texture size, reducing');
  13462. if (_shadowMapSize.x > maxTextureSize) {
  13463. _viewportSize.x = Math.floor(maxTextureSize / shadowFrameExtents.x);
  13464. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  13465. shadow.mapSize.x = _viewportSize.x;
  13466. }
  13467. if (_shadowMapSize.y > maxTextureSize) {
  13468. _viewportSize.y = Math.floor(maxTextureSize / shadowFrameExtents.y);
  13469. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  13470. shadow.mapSize.y = _viewportSize.y;
  13471. }
  13472. }
  13473. if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
  13474. var pars = {
  13475. minFilter: LinearFilter,
  13476. magFilter: LinearFilter,
  13477. format: RGBAFormat
  13478. };
  13479. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  13480. shadow.map.texture.name = light.name + ".shadowMap";
  13481. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  13482. shadow.camera.updateProjectionMatrix();
  13483. }
  13484. if (shadow.map === null) {
  13485. var pars = {
  13486. minFilter: NearestFilter,
  13487. magFilter: NearestFilter,
  13488. format: RGBAFormat
  13489. };
  13490. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  13491. shadow.map.texture.name = light.name + ".shadowMap";
  13492. shadow.camera.updateProjectionMatrix();
  13493. }
  13494. _renderer.setRenderTarget(shadow.map);
  13495. _renderer.clear();
  13496. var viewportCount = shadow.getViewportCount();
  13497. for (var vp = 0; vp < viewportCount; vp++) {
  13498. var viewport = shadow.getViewport(vp);
  13499. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  13500. _state.viewport(_viewport);
  13501. shadow.updateMatrices(light, camera, vp);
  13502. _frustum = shadow.getFrustum();
  13503. renderObject(scene, camera, shadow.camera, light, this.type);
  13504. } // do blur pass for VSM
  13505. if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
  13506. VSMPass(shadow, camera);
  13507. }
  13508. }
  13509. scope.needsUpdate = false;
  13510. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  13511. };
  13512. function VSMPass(shadow, camera) {
  13513. var geometry = _objects.update(fullScreenMesh); // vertical pass
  13514. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  13515. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  13516. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  13517. _renderer.setRenderTarget(shadow.mapPass);
  13518. _renderer.clear();
  13519. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizonal pass
  13520. shadowMaterialHorizonal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  13521. shadowMaterialHorizonal.uniforms.resolution.value = shadow.mapSize;
  13522. shadowMaterialHorizonal.uniforms.radius.value = shadow.radius;
  13523. _renderer.setRenderTarget(shadow.map);
  13524. _renderer.clear();
  13525. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizonal, fullScreenMesh, null);
  13526. }
  13527. function getDepthMaterial(object, material, light, shadowCameraNear, shadowCameraFar, type) {
  13528. var geometry = object.geometry;
  13529. var result = null;
  13530. var materialVariants = _depthMaterials;
  13531. var customMaterial = object.customDepthMaterial;
  13532. if (light.isPointLight) {
  13533. materialVariants = _distanceMaterials;
  13534. customMaterial = object.customDistanceMaterial;
  13535. }
  13536. if (!customMaterial) {
  13537. var useMorphing = false;
  13538. if (material.morphTargets) {
  13539. if (geometry && geometry.isBufferGeometry) {
  13540. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  13541. } else if (geometry && geometry.isGeometry) {
  13542. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  13543. }
  13544. }
  13545. if (object.isSkinnedMesh && material.skinning === false) {
  13546. console.warn('THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object);
  13547. }
  13548. var useSkinning = object.isSkinnedMesh && material.skinning;
  13549. var variantIndex = 0;
  13550. if (useMorphing) variantIndex |= _MorphingFlag;
  13551. if (useSkinning) variantIndex |= _SkinningFlag;
  13552. result = materialVariants[variantIndex];
  13553. } else {
  13554. result = customMaterial;
  13555. }
  13556. if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0) {
  13557. // in this case we need a unique material instance reflecting the
  13558. // appropriate state
  13559. var keyA = result.uuid,
  13560. keyB = material.uuid;
  13561. var materialsForVariant = _materialCache[keyA];
  13562. if (materialsForVariant === undefined) {
  13563. materialsForVariant = {};
  13564. _materialCache[keyA] = materialsForVariant;
  13565. }
  13566. var cachedMaterial = materialsForVariant[keyB];
  13567. if (cachedMaterial === undefined) {
  13568. cachedMaterial = result.clone();
  13569. materialsForVariant[keyB] = cachedMaterial;
  13570. }
  13571. result = cachedMaterial;
  13572. }
  13573. result.visible = material.visible;
  13574. result.wireframe = material.wireframe;
  13575. if (type === VSMShadowMap) {
  13576. result.side = material.shadowSide != null ? material.shadowSide : material.side;
  13577. } else {
  13578. result.side = material.shadowSide != null ? material.shadowSide : shadowSide[material.side];
  13579. }
  13580. result.clipShadows = material.clipShadows;
  13581. result.clippingPlanes = material.clippingPlanes;
  13582. result.clipIntersection = material.clipIntersection;
  13583. result.wireframeLinewidth = material.wireframeLinewidth;
  13584. result.linewidth = material.linewidth;
  13585. if (light.isPointLight && result.isMeshDistanceMaterial) {
  13586. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  13587. result.nearDistance = shadowCameraNear;
  13588. result.farDistance = shadowCameraFar;
  13589. }
  13590. return result;
  13591. }
  13592. function renderObject(object, camera, shadowCamera, light, type) {
  13593. if (object.visible === false) return;
  13594. var visible = object.layers.test(camera.layers);
  13595. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  13596. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  13597. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  13598. var geometry = _objects.update(object);
  13599. var material = object.material;
  13600. if (Array.isArray(material)) {
  13601. var groups = geometry.groups;
  13602. for (var k = 0, kl = groups.length; k < kl; k++) {
  13603. var group = groups[k];
  13604. var groupMaterial = material[group.materialIndex];
  13605. if (groupMaterial && groupMaterial.visible) {
  13606. var depthMaterial = getDepthMaterial(object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  13607. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  13608. }
  13609. }
  13610. } else if (material.visible) {
  13611. var depthMaterial = getDepthMaterial(object, material, light, shadowCamera.near, shadowCamera.far, type);
  13612. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  13613. }
  13614. }
  13615. }
  13616. var children = object.children;
  13617. for (var i = 0, l = children.length; i < l; i++) {
  13618. renderObject(children[i], camera, shadowCamera, light, type);
  13619. }
  13620. }
  13621. }
  13622. /**
  13623. * @author mrdoob / http://mrdoob.com/
  13624. */
  13625. function WebGLState(gl, extensions, utils, capabilities) {
  13626. function ColorBuffer() {
  13627. var locked = false;
  13628. var color = new Vector4();
  13629. var currentColorMask = null;
  13630. var currentColorClear = new Vector4(0, 0, 0, 0);
  13631. return {
  13632. setMask: function (colorMask) {
  13633. if (currentColorMask !== colorMask && !locked) {
  13634. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  13635. currentColorMask = colorMask;
  13636. }
  13637. },
  13638. setLocked: function (lock) {
  13639. locked = lock;
  13640. },
  13641. setClear: function (r, g, b, a, premultipliedAlpha) {
  13642. if (premultipliedAlpha === true) {
  13643. r *= a;
  13644. g *= a;
  13645. b *= a;
  13646. }
  13647. color.set(r, g, b, a);
  13648. if (currentColorClear.equals(color) === false) {
  13649. gl.clearColor(r, g, b, a);
  13650. currentColorClear.copy(color);
  13651. }
  13652. },
  13653. reset: function () {
  13654. locked = false;
  13655. currentColorMask = null;
  13656. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  13657. }
  13658. };
  13659. }
  13660. function DepthBuffer() {
  13661. var locked = false;
  13662. var currentDepthMask = null;
  13663. var currentDepthFunc = null;
  13664. var currentDepthClear = null;
  13665. return {
  13666. setTest: function (depthTest) {
  13667. if (depthTest) {
  13668. enable(2929);
  13669. } else {
  13670. disable(2929);
  13671. }
  13672. },
  13673. setMask: function (depthMask) {
  13674. if (currentDepthMask !== depthMask && !locked) {
  13675. gl.depthMask(depthMask);
  13676. currentDepthMask = depthMask;
  13677. }
  13678. },
  13679. setFunc: function (depthFunc) {
  13680. if (currentDepthFunc !== depthFunc) {
  13681. if (depthFunc) {
  13682. switch (depthFunc) {
  13683. case NeverDepth:
  13684. gl.depthFunc(512);
  13685. break;
  13686. case AlwaysDepth:
  13687. gl.depthFunc(519);
  13688. break;
  13689. case LessDepth:
  13690. gl.depthFunc(513);
  13691. break;
  13692. case LessEqualDepth:
  13693. gl.depthFunc(515);
  13694. break;
  13695. case EqualDepth:
  13696. gl.depthFunc(514);
  13697. break;
  13698. case GreaterEqualDepth:
  13699. gl.depthFunc(518);
  13700. break;
  13701. case GreaterDepth:
  13702. gl.depthFunc(516);
  13703. break;
  13704. case NotEqualDepth:
  13705. gl.depthFunc(517);
  13706. break;
  13707. default:
  13708. gl.depthFunc(515);
  13709. }
  13710. } else {
  13711. gl.depthFunc(515);
  13712. }
  13713. currentDepthFunc = depthFunc;
  13714. }
  13715. },
  13716. setLocked: function (lock) {
  13717. locked = lock;
  13718. },
  13719. setClear: function (depth) {
  13720. if (currentDepthClear !== depth) {
  13721. gl.clearDepth(depth);
  13722. currentDepthClear = depth;
  13723. }
  13724. },
  13725. reset: function () {
  13726. locked = false;
  13727. currentDepthMask = null;
  13728. currentDepthFunc = null;
  13729. currentDepthClear = null;
  13730. }
  13731. };
  13732. }
  13733. function StencilBuffer() {
  13734. var locked = false;
  13735. var currentStencilMask = null;
  13736. var currentStencilFunc = null;
  13737. var currentStencilRef = null;
  13738. var currentStencilFuncMask = null;
  13739. var currentStencilFail = null;
  13740. var currentStencilZFail = null;
  13741. var currentStencilZPass = null;
  13742. var currentStencilClear = null;
  13743. return {
  13744. setTest: function (stencilTest) {
  13745. if (!locked) {
  13746. if (stencilTest) {
  13747. enable(2960);
  13748. } else {
  13749. disable(2960);
  13750. }
  13751. }
  13752. },
  13753. setMask: function (stencilMask) {
  13754. if (currentStencilMask !== stencilMask && !locked) {
  13755. gl.stencilMask(stencilMask);
  13756. currentStencilMask = stencilMask;
  13757. }
  13758. },
  13759. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  13760. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  13761. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  13762. currentStencilFunc = stencilFunc;
  13763. currentStencilRef = stencilRef;
  13764. currentStencilFuncMask = stencilMask;
  13765. }
  13766. },
  13767. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  13768. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  13769. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  13770. currentStencilFail = stencilFail;
  13771. currentStencilZFail = stencilZFail;
  13772. currentStencilZPass = stencilZPass;
  13773. }
  13774. },
  13775. setLocked: function (lock) {
  13776. locked = lock;
  13777. },
  13778. setClear: function (stencil) {
  13779. if (currentStencilClear !== stencil) {
  13780. gl.clearStencil(stencil);
  13781. currentStencilClear = stencil;
  13782. }
  13783. },
  13784. reset: function () {
  13785. locked = false;
  13786. currentStencilMask = null;
  13787. currentStencilFunc = null;
  13788. currentStencilRef = null;
  13789. currentStencilFuncMask = null;
  13790. currentStencilFail = null;
  13791. currentStencilZFail = null;
  13792. currentStencilZPass = null;
  13793. currentStencilClear = null;
  13794. }
  13795. };
  13796. } //
  13797. var colorBuffer = new ColorBuffer();
  13798. var depthBuffer = new DepthBuffer();
  13799. var stencilBuffer = new StencilBuffer();
  13800. var maxVertexAttributes = gl.getParameter(34921);
  13801. var newAttributes = new Uint8Array(maxVertexAttributes);
  13802. var enabledAttributes = new Uint8Array(maxVertexAttributes);
  13803. var attributeDivisors = new Uint8Array(maxVertexAttributes);
  13804. var enabledCapabilities = {};
  13805. var compressedTextureFormats = null;
  13806. var currentProgram = null;
  13807. var currentBlendingEnabled = null;
  13808. var currentBlending = null;
  13809. var currentBlendEquation = null;
  13810. var currentBlendSrc = null;
  13811. var currentBlendDst = null;
  13812. var currentBlendEquationAlpha = null;
  13813. var currentBlendSrcAlpha = null;
  13814. var currentBlendDstAlpha = null;
  13815. var currentPremultipledAlpha = false;
  13816. var currentFlipSided = null;
  13817. var currentCullFace = null;
  13818. var currentLineWidth = null;
  13819. var currentPolygonOffsetFactor = null;
  13820. var currentPolygonOffsetUnits = null;
  13821. var maxTextures = gl.getParameter(35661);
  13822. var lineWidthAvailable = false;
  13823. var version = 0;
  13824. var glVersion = gl.getParameter(7938);
  13825. if (glVersion.indexOf('WebGL') !== -1) {
  13826. version = parseFloat(/^WebGL\ ([0-9])/.exec(glVersion)[1]);
  13827. lineWidthAvailable = version >= 1.0;
  13828. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  13829. version = parseFloat(/^OpenGL\ ES\ ([0-9])/.exec(glVersion)[1]);
  13830. lineWidthAvailable = version >= 2.0;
  13831. }
  13832. var currentTextureSlot = null;
  13833. var currentBoundTextures = {};
  13834. var currentScissor = new Vector4();
  13835. var currentViewport = new Vector4();
  13836. function createTexture(type, target, count) {
  13837. var data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  13838. var texture = gl.createTexture();
  13839. gl.bindTexture(type, texture);
  13840. gl.texParameteri(type, 10241, 9728);
  13841. gl.texParameteri(type, 10240, 9728);
  13842. for (var i = 0; i < count; i++) {
  13843. gl.texImage2D(target + i, 0, 6408, 1, 1, 0, 6408, 5121, data);
  13844. }
  13845. return texture;
  13846. }
  13847. var emptyTextures = {};
  13848. emptyTextures[3553] = createTexture(3553, 3553, 1);
  13849. emptyTextures[34067] = createTexture(34067, 34069, 6); // init
  13850. colorBuffer.setClear(0, 0, 0, 1);
  13851. depthBuffer.setClear(1);
  13852. stencilBuffer.setClear(0);
  13853. enable(2929);
  13854. depthBuffer.setFunc(LessEqualDepth);
  13855. setFlipSided(false);
  13856. setCullFace(CullFaceBack);
  13857. enable(2884);
  13858. setBlending(NoBlending); //
  13859. function initAttributes() {
  13860. for (var i = 0, l = newAttributes.length; i < l; i++) {
  13861. newAttributes[i] = 0;
  13862. }
  13863. }
  13864. function enableAttribute(attribute) {
  13865. enableAttributeAndDivisor(attribute, 0);
  13866. }
  13867. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  13868. newAttributes[attribute] = 1;
  13869. if (enabledAttributes[attribute] === 0) {
  13870. gl.enableVertexAttribArray(attribute);
  13871. enabledAttributes[attribute] = 1;
  13872. }
  13873. if (attributeDivisors[attribute] !== meshPerAttribute) {
  13874. var extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  13875. extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  13876. attributeDivisors[attribute] = meshPerAttribute;
  13877. }
  13878. }
  13879. function disableUnusedAttributes() {
  13880. for (var i = 0, l = enabledAttributes.length; i !== l; ++i) {
  13881. if (enabledAttributes[i] !== newAttributes[i]) {
  13882. gl.disableVertexAttribArray(i);
  13883. enabledAttributes[i] = 0;
  13884. }
  13885. }
  13886. }
  13887. function enable(id) {
  13888. if (enabledCapabilities[id] !== true) {
  13889. gl.enable(id);
  13890. enabledCapabilities[id] = true;
  13891. }
  13892. }
  13893. function disable(id) {
  13894. if (enabledCapabilities[id] !== false) {
  13895. gl.disable(id);
  13896. enabledCapabilities[id] = false;
  13897. }
  13898. }
  13899. function getCompressedTextureFormats() {
  13900. if (compressedTextureFormats === null) {
  13901. compressedTextureFormats = [];
  13902. 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')) {
  13903. var formats = gl.getParameter(34467);
  13904. for (var i = 0; i < formats.length; i++) {
  13905. compressedTextureFormats.push(formats[i]);
  13906. }
  13907. }
  13908. }
  13909. return compressedTextureFormats;
  13910. }
  13911. function useProgram(program) {
  13912. if (currentProgram !== program) {
  13913. gl.useProgram(program);
  13914. currentProgram = program;
  13915. return true;
  13916. }
  13917. return false;
  13918. }
  13919. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  13920. if (blending === NoBlending) {
  13921. if (currentBlendingEnabled) {
  13922. disable(3042);
  13923. currentBlendingEnabled = false;
  13924. }
  13925. return;
  13926. }
  13927. if (!currentBlendingEnabled) {
  13928. enable(3042);
  13929. currentBlendingEnabled = true;
  13930. }
  13931. if (blending !== CustomBlending) {
  13932. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  13933. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  13934. gl.blendEquation(32774);
  13935. currentBlendEquation = AddEquation;
  13936. currentBlendEquationAlpha = AddEquation;
  13937. }
  13938. if (premultipliedAlpha) {
  13939. switch (blending) {
  13940. case NormalBlending:
  13941. gl.blendFuncSeparate(1, 771, 1, 771);
  13942. break;
  13943. case AdditiveBlending:
  13944. gl.blendFunc(1, 1);
  13945. break;
  13946. case SubtractiveBlending:
  13947. gl.blendFuncSeparate(0, 0, 769, 771);
  13948. break;
  13949. case MultiplyBlending:
  13950. gl.blendFuncSeparate(0, 768, 0, 770);
  13951. break;
  13952. default:
  13953. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13954. break;
  13955. }
  13956. } else {
  13957. switch (blending) {
  13958. case NormalBlending:
  13959. gl.blendFuncSeparate(770, 771, 1, 771);
  13960. break;
  13961. case AdditiveBlending:
  13962. gl.blendFunc(770, 1);
  13963. break;
  13964. case SubtractiveBlending:
  13965. gl.blendFunc(0, 769);
  13966. break;
  13967. case MultiplyBlending:
  13968. gl.blendFunc(0, 768);
  13969. break;
  13970. default:
  13971. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13972. break;
  13973. }
  13974. }
  13975. currentBlendSrc = null;
  13976. currentBlendDst = null;
  13977. currentBlendSrcAlpha = null;
  13978. currentBlendDstAlpha = null;
  13979. currentBlending = blending;
  13980. currentPremultipledAlpha = premultipliedAlpha;
  13981. }
  13982. return;
  13983. } // custom blending
  13984. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13985. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13986. blendDstAlpha = blendDstAlpha || blendDst;
  13987. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  13988. gl.blendEquationSeparate(utils.convert(blendEquation), utils.convert(blendEquationAlpha));
  13989. currentBlendEquation = blendEquation;
  13990. currentBlendEquationAlpha = blendEquationAlpha;
  13991. }
  13992. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  13993. gl.blendFuncSeparate(utils.convert(blendSrc), utils.convert(blendDst), utils.convert(blendSrcAlpha), utils.convert(blendDstAlpha));
  13994. currentBlendSrc = blendSrc;
  13995. currentBlendDst = blendDst;
  13996. currentBlendSrcAlpha = blendSrcAlpha;
  13997. currentBlendDstAlpha = blendDstAlpha;
  13998. }
  13999. currentBlending = blending;
  14000. currentPremultipledAlpha = null;
  14001. }
  14002. function setMaterial(material, frontFaceCW) {
  14003. material.side === DoubleSide ? disable(2884) : enable(2884);
  14004. var flipSided = material.side === BackSide;
  14005. if (frontFaceCW) flipSided = !flipSided;
  14006. setFlipSided(flipSided);
  14007. 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);
  14008. depthBuffer.setFunc(material.depthFunc);
  14009. depthBuffer.setTest(material.depthTest);
  14010. depthBuffer.setMask(material.depthWrite);
  14011. colorBuffer.setMask(material.colorWrite);
  14012. var stencilWrite = material.stencilWrite;
  14013. stencilBuffer.setTest(stencilWrite);
  14014. if (stencilWrite) {
  14015. stencilBuffer.setMask(material.stencilWriteMask);
  14016. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  14017. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  14018. }
  14019. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  14020. } //
  14021. function setFlipSided(flipSided) {
  14022. if (currentFlipSided !== flipSided) {
  14023. if (flipSided) {
  14024. gl.frontFace(2304);
  14025. } else {
  14026. gl.frontFace(2305);
  14027. }
  14028. currentFlipSided = flipSided;
  14029. }
  14030. }
  14031. function setCullFace(cullFace) {
  14032. if (cullFace !== CullFaceNone) {
  14033. enable(2884);
  14034. if (cullFace !== currentCullFace) {
  14035. if (cullFace === CullFaceBack) {
  14036. gl.cullFace(1029);
  14037. } else if (cullFace === CullFaceFront) {
  14038. gl.cullFace(1028);
  14039. } else {
  14040. gl.cullFace(1032);
  14041. }
  14042. }
  14043. } else {
  14044. disable(2884);
  14045. }
  14046. currentCullFace = cullFace;
  14047. }
  14048. function setLineWidth(width) {
  14049. if (width !== currentLineWidth) {
  14050. if (lineWidthAvailable) gl.lineWidth(width);
  14051. currentLineWidth = width;
  14052. }
  14053. }
  14054. function setPolygonOffset(polygonOffset, factor, units) {
  14055. if (polygonOffset) {
  14056. enable(32823);
  14057. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  14058. gl.polygonOffset(factor, units);
  14059. currentPolygonOffsetFactor = factor;
  14060. currentPolygonOffsetUnits = units;
  14061. }
  14062. } else {
  14063. disable(32823);
  14064. }
  14065. }
  14066. function setScissorTest(scissorTest) {
  14067. if (scissorTest) {
  14068. enable(3089);
  14069. } else {
  14070. disable(3089);
  14071. }
  14072. } // texture
  14073. function activeTexture(webglSlot) {
  14074. if (webglSlot === undefined) webglSlot = 33984 + maxTextures - 1;
  14075. if (currentTextureSlot !== webglSlot) {
  14076. gl.activeTexture(webglSlot);
  14077. currentTextureSlot = webglSlot;
  14078. }
  14079. }
  14080. function bindTexture(webglType, webglTexture) {
  14081. if (currentTextureSlot === null) {
  14082. activeTexture();
  14083. }
  14084. var boundTexture = currentBoundTextures[currentTextureSlot];
  14085. if (boundTexture === undefined) {
  14086. boundTexture = {
  14087. type: undefined,
  14088. texture: undefined
  14089. };
  14090. currentBoundTextures[currentTextureSlot] = boundTexture;
  14091. }
  14092. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  14093. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  14094. boundTexture.type = webglType;
  14095. boundTexture.texture = webglTexture;
  14096. }
  14097. }
  14098. function compressedTexImage2D() {
  14099. try {
  14100. gl.compressedTexImage2D.apply(gl, arguments);
  14101. } catch (error) {
  14102. console.error('THREE.WebGLState:', error);
  14103. }
  14104. }
  14105. function texImage2D() {
  14106. try {
  14107. gl.texImage2D.apply(gl, arguments);
  14108. } catch (error) {
  14109. console.error('THREE.WebGLState:', error);
  14110. }
  14111. }
  14112. function texImage3D() {
  14113. try {
  14114. gl.texImage3D.apply(gl, arguments);
  14115. } catch (error) {
  14116. console.error('THREE.WebGLState:', error);
  14117. }
  14118. } //
  14119. function scissor(scissor) {
  14120. if (currentScissor.equals(scissor) === false) {
  14121. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  14122. currentScissor.copy(scissor);
  14123. }
  14124. }
  14125. function viewport(viewport) {
  14126. if (currentViewport.equals(viewport) === false) {
  14127. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  14128. currentViewport.copy(viewport);
  14129. }
  14130. } //
  14131. function reset() {
  14132. for (var i = 0; i < enabledAttributes.length; i++) {
  14133. if (enabledAttributes[i] === 1) {
  14134. gl.disableVertexAttribArray(i);
  14135. enabledAttributes[i] = 0;
  14136. }
  14137. }
  14138. enabledCapabilities = {};
  14139. compressedTextureFormats = null;
  14140. currentTextureSlot = null;
  14141. currentBoundTextures = {};
  14142. currentProgram = null;
  14143. currentBlending = null;
  14144. currentFlipSided = null;
  14145. currentCullFace = null;
  14146. colorBuffer.reset();
  14147. depthBuffer.reset();
  14148. stencilBuffer.reset();
  14149. }
  14150. return {
  14151. buffers: {
  14152. color: colorBuffer,
  14153. depth: depthBuffer,
  14154. stencil: stencilBuffer
  14155. },
  14156. initAttributes: initAttributes,
  14157. enableAttribute: enableAttribute,
  14158. enableAttributeAndDivisor: enableAttributeAndDivisor,
  14159. disableUnusedAttributes: disableUnusedAttributes,
  14160. enable: enable,
  14161. disable: disable,
  14162. getCompressedTextureFormats: getCompressedTextureFormats,
  14163. useProgram: useProgram,
  14164. setBlending: setBlending,
  14165. setMaterial: setMaterial,
  14166. setFlipSided: setFlipSided,
  14167. setCullFace: setCullFace,
  14168. setLineWidth: setLineWidth,
  14169. setPolygonOffset: setPolygonOffset,
  14170. setScissorTest: setScissorTest,
  14171. activeTexture: activeTexture,
  14172. bindTexture: bindTexture,
  14173. compressedTexImage2D: compressedTexImage2D,
  14174. texImage2D: texImage2D,
  14175. texImage3D: texImage3D,
  14176. scissor: scissor,
  14177. viewport: viewport,
  14178. reset: reset
  14179. };
  14180. }
  14181. /**
  14182. * @author mrdoob / http://mrdoob.com/
  14183. */
  14184. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  14185. var _videoTextures = new WeakMap();
  14186. var _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  14187. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  14188. var useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext("2d") !== null;
  14189. function createCanvas(width, height) {
  14190. // Use OffscreenCanvas when available. Specially needed in web workers
  14191. return useOffscreenCanvas ? new OffscreenCanvas(width, height) : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  14192. }
  14193. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  14194. var scale = 1; // handle case if texture exceeds max size
  14195. if (image.width > maxSize || image.height > maxSize) {
  14196. scale = maxSize / Math.max(image.width, image.height);
  14197. } // only perform resize if necessary
  14198. if (scale < 1 || needsPowerOfTwo === true) {
  14199. // only perform resize for certain image types
  14200. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  14201. var floor = needsPowerOfTwo ? _Math.floorPowerOfTwo : Math.floor;
  14202. var width = floor(scale * image.width);
  14203. var height = floor(scale * image.height);
  14204. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  14205. var canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  14206. canvas.width = width;
  14207. canvas.height = height;
  14208. var context = canvas.getContext('2d');
  14209. context.drawImage(image, 0, 0, width, height);
  14210. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  14211. return canvas;
  14212. } else {
  14213. if ('data' in image) {
  14214. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  14215. }
  14216. return image;
  14217. }
  14218. }
  14219. return image;
  14220. }
  14221. function isPowerOfTwo(image) {
  14222. return _Math.isPowerOfTwo(image.width) && _Math.isPowerOfTwo(image.height);
  14223. }
  14224. function textureNeedsPowerOfTwo(texture) {
  14225. if (capabilities.isWebGL2) return false;
  14226. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  14227. }
  14228. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  14229. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  14230. }
  14231. function generateMipmap(target, texture, width, height) {
  14232. _gl.generateMipmap(target);
  14233. var textureProperties = properties.get(texture); // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
  14234. textureProperties.__maxMipLevel = Math.log(Math.max(width, height)) * Math.LOG2E;
  14235. }
  14236. function getInternalFormat(glFormat, glType) {
  14237. if (!capabilities.isWebGL2) return glFormat;
  14238. var internalFormat = glFormat;
  14239. if (glFormat === 6403) {
  14240. if (glType === 5126) internalFormat = 33326;
  14241. if (glType === 5131) internalFormat = 33325;
  14242. if (glType === 5121) internalFormat = 33321;
  14243. }
  14244. if (glFormat === 6407) {
  14245. if (glType === 5126) internalFormat = 34837;
  14246. if (glType === 5131) internalFormat = 34843;
  14247. if (glType === 5121) internalFormat = 32849;
  14248. }
  14249. if (glFormat === 6408) {
  14250. if (glType === 5126) internalFormat = 34836;
  14251. if (glType === 5131) internalFormat = 34842;
  14252. if (glType === 5121) internalFormat = 32856;
  14253. }
  14254. if (internalFormat === 33325 || internalFormat === 33326 || internalFormat === 34842 || internalFormat === 34836) {
  14255. extensions.get('EXT_color_buffer_float');
  14256. } else if (internalFormat === 34843 || internalFormat === 34837) {
  14257. console.warn('THREE.WebGLRenderer: Floating point textures with RGB format not supported. Please use RGBA instead.');
  14258. }
  14259. return internalFormat;
  14260. } // Fallback filters for non-power-of-2 textures
  14261. function filterFallback(f) {
  14262. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  14263. return 9728;
  14264. }
  14265. return 9729;
  14266. } //
  14267. function onTextureDispose(event) {
  14268. var texture = event.target;
  14269. texture.removeEventListener('dispose', onTextureDispose);
  14270. deallocateTexture(texture);
  14271. if (texture.isVideoTexture) {
  14272. _videoTextures.delete(texture);
  14273. }
  14274. info.memory.textures--;
  14275. }
  14276. function onRenderTargetDispose(event) {
  14277. var renderTarget = event.target;
  14278. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  14279. deallocateRenderTarget(renderTarget);
  14280. info.memory.textures--;
  14281. } //
  14282. function deallocateTexture(texture) {
  14283. var textureProperties = properties.get(texture);
  14284. if (textureProperties.__webglInit === undefined) return;
  14285. _gl.deleteTexture(textureProperties.__webglTexture);
  14286. properties.remove(texture);
  14287. }
  14288. function deallocateRenderTarget(renderTarget) {
  14289. var renderTargetProperties = properties.get(renderTarget);
  14290. var textureProperties = properties.get(renderTarget.texture);
  14291. if (!renderTarget) return;
  14292. if (textureProperties.__webglTexture !== undefined) {
  14293. _gl.deleteTexture(textureProperties.__webglTexture);
  14294. }
  14295. if (renderTarget.depthTexture) {
  14296. renderTarget.depthTexture.dispose();
  14297. }
  14298. if (renderTarget.isWebGLRenderTargetCube) {
  14299. for (var i = 0; i < 6; i++) {
  14300. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  14301. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  14302. }
  14303. } else {
  14304. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  14305. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  14306. }
  14307. if (renderTarget.isWebGLMultiviewRenderTarget) {
  14308. _gl.deleteTexture(renderTargetProperties.__webglColorTexture);
  14309. _gl.deleteTexture(renderTargetProperties.__webglDepthStencilTexture);
  14310. info.memory.textures -= 2;
  14311. for (var i = 0, il = renderTargetProperties.__webglViewFramebuffers.length; i < il; i++) {
  14312. _gl.deleteFramebuffer(renderTargetProperties.__webglViewFramebuffers[i]);
  14313. }
  14314. }
  14315. properties.remove(renderTarget.texture);
  14316. properties.remove(renderTarget);
  14317. } //
  14318. var textureUnits = 0;
  14319. function resetTextureUnits() {
  14320. textureUnits = 0;
  14321. }
  14322. function allocateTextureUnit() {
  14323. var textureUnit = textureUnits;
  14324. if (textureUnit >= capabilities.maxTextures) {
  14325. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures);
  14326. }
  14327. textureUnits += 1;
  14328. return textureUnit;
  14329. } //
  14330. function setTexture2D(texture, slot) {
  14331. var textureProperties = properties.get(texture);
  14332. if (texture.isVideoTexture) updateVideoTexture(texture);
  14333. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  14334. var image = texture.image;
  14335. if (image === undefined) {
  14336. console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
  14337. } else if (image.complete === false) {
  14338. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  14339. } else {
  14340. uploadTexture(textureProperties, texture, slot);
  14341. return;
  14342. }
  14343. }
  14344. state.activeTexture(33984 + slot);
  14345. state.bindTexture(3553, textureProperties.__webglTexture);
  14346. }
  14347. function setTexture2DArray(texture, slot) {
  14348. var textureProperties = properties.get(texture);
  14349. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  14350. uploadTexture(textureProperties, texture, slot);
  14351. return;
  14352. }
  14353. state.activeTexture(33984 + slot);
  14354. state.bindTexture(35866, textureProperties.__webglTexture);
  14355. }
  14356. function setTexture3D(texture, slot) {
  14357. var textureProperties = properties.get(texture);
  14358. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  14359. uploadTexture(textureProperties, texture, slot);
  14360. return;
  14361. }
  14362. state.activeTexture(33984 + slot);
  14363. state.bindTexture(32879, textureProperties.__webglTexture);
  14364. }
  14365. function setTextureCube(texture, slot) {
  14366. if (texture.image.length !== 6) return;
  14367. var textureProperties = properties.get(texture);
  14368. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  14369. initTexture(textureProperties, texture);
  14370. state.activeTexture(33984 + slot);
  14371. state.bindTexture(34067, textureProperties.__webglTexture);
  14372. _gl.pixelStorei(37440, texture.flipY);
  14373. var isCompressed = texture && texture.isCompressedTexture;
  14374. var isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  14375. var cubeImage = [];
  14376. for (var i = 0; i < 6; i++) {
  14377. if (!isCompressed && !isDataTexture) {
  14378. cubeImage[i] = resizeImage(texture.image[i], false, true, capabilities.maxCubemapSize);
  14379. } else {
  14380. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  14381. }
  14382. }
  14383. var image = cubeImage[0],
  14384. supportsMips = isPowerOfTwo(image) || capabilities.isWebGL2,
  14385. glFormat = utils.convert(texture.format),
  14386. glType = utils.convert(texture.type),
  14387. glInternalFormat = getInternalFormat(glFormat, glType);
  14388. setTextureParameters(34067, texture, supportsMips);
  14389. var mipmaps;
  14390. if (isCompressed) {
  14391. for (var i = 0; i < 6; i++) {
  14392. mipmaps = cubeImage[i].mipmaps;
  14393. for (var j = 0; j < mipmaps.length; j++) {
  14394. var mipmap = mipmaps[j];
  14395. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  14396. if (state.getCompressedTextureFormats().indexOf(glFormat) > -1) {
  14397. state.compressedTexImage2D(34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  14398. } else {
  14399. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  14400. }
  14401. } else {
  14402. state.texImage2D(34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  14403. }
  14404. }
  14405. }
  14406. textureProperties.__maxMipLevel = mipmaps.length - 1;
  14407. } else {
  14408. mipmaps = texture.mipmaps;
  14409. for (var i = 0; i < 6; i++) {
  14410. if (isDataTexture) {
  14411. state.texImage2D(34069 + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  14412. for (var j = 0; j < mipmaps.length; j++) {
  14413. var mipmap = mipmaps[j];
  14414. var mipmapImage = mipmap.image[i].image;
  14415. state.texImage2D(34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  14416. }
  14417. } else {
  14418. state.texImage2D(34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  14419. for (var j = 0; j < mipmaps.length; j++) {
  14420. var mipmap = mipmaps[j];
  14421. state.texImage2D(34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  14422. }
  14423. }
  14424. }
  14425. textureProperties.__maxMipLevel = mipmaps.length;
  14426. }
  14427. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14428. // We assume images for cube map have the same size.
  14429. generateMipmap(34067, texture, image.width, image.height);
  14430. }
  14431. textureProperties.__version = texture.version;
  14432. if (texture.onUpdate) texture.onUpdate(texture);
  14433. } else {
  14434. state.activeTexture(33984 + slot);
  14435. state.bindTexture(34067, textureProperties.__webglTexture);
  14436. }
  14437. }
  14438. function setTextureCubeDynamic(texture, slot) {
  14439. state.activeTexture(33984 + slot);
  14440. state.bindTexture(34067, properties.get(texture).__webglTexture);
  14441. }
  14442. function setTextureParameters(textureType, texture, supportsMips) {
  14443. var extension;
  14444. if (supportsMips) {
  14445. _gl.texParameteri(textureType, 10242, utils.convert(texture.wrapS));
  14446. _gl.texParameteri(textureType, 10243, utils.convert(texture.wrapT));
  14447. if (textureType === 32879 || textureType === 35866) {
  14448. _gl.texParameteri(textureType, 32882, utils.convert(texture.wrapR));
  14449. }
  14450. _gl.texParameteri(textureType, 10240, utils.convert(texture.magFilter));
  14451. _gl.texParameteri(textureType, 10241, utils.convert(texture.minFilter));
  14452. } else {
  14453. _gl.texParameteri(textureType, 10242, 33071);
  14454. _gl.texParameteri(textureType, 10243, 33071);
  14455. if (textureType === 32879 || textureType === 35866) {
  14456. _gl.texParameteri(textureType, 32882, 33071);
  14457. }
  14458. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  14459. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  14460. }
  14461. _gl.texParameteri(textureType, 10240, filterFallback(texture.magFilter));
  14462. _gl.texParameteri(textureType, 10241, filterFallback(texture.minFilter));
  14463. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  14464. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  14465. }
  14466. }
  14467. extension = extensions.get('EXT_texture_filter_anisotropic');
  14468. if (extension) {
  14469. if (texture.type === FloatType && extensions.get('OES_texture_float_linear') === null) return;
  14470. if (texture.type === HalfFloatType && (capabilities.isWebGL2 || extensions.get('OES_texture_half_float_linear')) === null) return;
  14471. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  14472. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  14473. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  14474. }
  14475. }
  14476. }
  14477. function initTexture(textureProperties, texture) {
  14478. if (textureProperties.__webglInit === undefined) {
  14479. textureProperties.__webglInit = true;
  14480. texture.addEventListener('dispose', onTextureDispose);
  14481. textureProperties.__webglTexture = _gl.createTexture();
  14482. info.memory.textures++;
  14483. }
  14484. }
  14485. function uploadTexture(textureProperties, texture, slot) {
  14486. var textureType = 3553;
  14487. if (texture.isDataTexture2DArray) textureType = 35866;
  14488. if (texture.isDataTexture3D) textureType = 32879;
  14489. initTexture(textureProperties, texture);
  14490. state.activeTexture(33984 + slot);
  14491. state.bindTexture(textureType, textureProperties.__webglTexture);
  14492. _gl.pixelStorei(37440, texture.flipY);
  14493. _gl.pixelStorei(37441, texture.premultiplyAlpha);
  14494. _gl.pixelStorei(3317, texture.unpackAlignment);
  14495. var needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo(texture.image) === false;
  14496. var image = resizeImage(texture.image, needsPowerOfTwo, false, capabilities.maxTextureSize);
  14497. var supportsMips = isPowerOfTwo(image) || capabilities.isWebGL2,
  14498. glFormat = utils.convert(texture.format),
  14499. glType = utils.convert(texture.type),
  14500. glInternalFormat = getInternalFormat(glFormat, glType);
  14501. setTextureParameters(textureType, texture, supportsMips);
  14502. var mipmap,
  14503. mipmaps = texture.mipmaps;
  14504. if (texture.isDepthTexture) {
  14505. // populate depth texture with dummy data
  14506. glInternalFormat = 6402;
  14507. if (texture.type === FloatType) {
  14508. if (!capabilities.isWebGL2) throw new Error('Float Depth Texture only supported in WebGL2.0');
  14509. glInternalFormat = 36012;
  14510. } else if (capabilities.isWebGL2) {
  14511. // WebGL 2.0 requires signed internalformat for glTexImage2D
  14512. glInternalFormat = 33189;
  14513. }
  14514. if (texture.format === DepthFormat && glInternalFormat === 6402) {
  14515. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14516. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  14517. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14518. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  14519. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  14520. texture.type = UnsignedShortType;
  14521. glType = utils.convert(texture.type);
  14522. }
  14523. } // Depth stencil textures need the DEPTH_STENCIL internal format
  14524. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14525. if (texture.format === DepthStencilFormat) {
  14526. glInternalFormat = 34041; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14527. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  14528. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14529. if (texture.type !== UnsignedInt248Type) {
  14530. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  14531. texture.type = UnsignedInt248Type;
  14532. glType = utils.convert(texture.type);
  14533. }
  14534. }
  14535. state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  14536. } else if (texture.isDataTexture) {
  14537. // use manually created mipmaps if available
  14538. // if there are no manual mipmaps
  14539. // set 0 level mipmap and then use GL to generate other mipmap levels
  14540. if (mipmaps.length > 0 && supportsMips) {
  14541. for (var i = 0, il = mipmaps.length; i < il; i++) {
  14542. mipmap = mipmaps[i];
  14543. state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  14544. }
  14545. texture.generateMipmaps = false;
  14546. textureProperties.__maxMipLevel = mipmaps.length - 1;
  14547. } else {
  14548. state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  14549. textureProperties.__maxMipLevel = 0;
  14550. }
  14551. } else if (texture.isCompressedTexture) {
  14552. for (var i = 0, il = mipmaps.length; i < il; i++) {
  14553. mipmap = mipmaps[i];
  14554. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  14555. if (state.getCompressedTextureFormats().indexOf(glFormat) > -1) {
  14556. state.compressedTexImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  14557. } else {
  14558. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  14559. }
  14560. } else {
  14561. state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  14562. }
  14563. }
  14564. textureProperties.__maxMipLevel = mipmaps.length - 1;
  14565. } else if (texture.isDataTexture2DArray) {
  14566. state.texImage3D(35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  14567. textureProperties.__maxMipLevel = 0;
  14568. } else if (texture.isDataTexture3D) {
  14569. state.texImage3D(32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  14570. textureProperties.__maxMipLevel = 0;
  14571. } else {
  14572. // regular Texture (image, video, canvas)
  14573. // use manually created mipmaps if available
  14574. // if there are no manual mipmaps
  14575. // set 0 level mipmap and then use GL to generate other mipmap levels
  14576. if (mipmaps.length > 0 && supportsMips) {
  14577. for (var i = 0, il = mipmaps.length; i < il; i++) {
  14578. mipmap = mipmaps[i];
  14579. state.texImage2D(3553, i, glInternalFormat, glFormat, glType, mipmap);
  14580. }
  14581. texture.generateMipmaps = false;
  14582. textureProperties.__maxMipLevel = mipmaps.length - 1;
  14583. } else {
  14584. state.texImage2D(3553, 0, glInternalFormat, glFormat, glType, image);
  14585. textureProperties.__maxMipLevel = 0;
  14586. }
  14587. }
  14588. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14589. generateMipmap(3553, texture, image.width, image.height);
  14590. }
  14591. textureProperties.__version = texture.version;
  14592. if (texture.onUpdate) texture.onUpdate(texture);
  14593. } // Render targets
  14594. // Setup storage for target texture and bind it to correct framebuffer
  14595. function setupFrameBufferTexture(framebuffer, renderTarget, attachment, textureTarget) {
  14596. var glFormat = utils.convert(renderTarget.texture.format);
  14597. var glType = utils.convert(renderTarget.texture.type);
  14598. var glInternalFormat = getInternalFormat(glFormat, glType);
  14599. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  14600. _gl.bindFramebuffer(36160, framebuffer);
  14601. _gl.framebufferTexture2D(36160, attachment, textureTarget, properties.get(renderTarget.texture).__webglTexture, 0);
  14602. _gl.bindFramebuffer(36160, null);
  14603. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14604. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  14605. _gl.bindRenderbuffer(36161, renderbuffer);
  14606. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  14607. if (isMultisample) {
  14608. var samples = getRenderTargetSamples(renderTarget);
  14609. _gl.renderbufferStorageMultisample(36161, samples, 33189, renderTarget.width, renderTarget.height);
  14610. } else {
  14611. _gl.renderbufferStorage(36161, 33189, renderTarget.width, renderTarget.height);
  14612. }
  14613. _gl.framebufferRenderbuffer(36160, 36096, 36161, renderbuffer);
  14614. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  14615. if (isMultisample) {
  14616. var samples = getRenderTargetSamples(renderTarget);
  14617. _gl.renderbufferStorageMultisample(36161, samples, 35056, renderTarget.width, renderTarget.height);
  14618. } else {
  14619. _gl.renderbufferStorage(36161, 34041, renderTarget.width, renderTarget.height);
  14620. }
  14621. _gl.framebufferRenderbuffer(36160, 33306, 36161, renderbuffer);
  14622. } else {
  14623. var glFormat = utils.convert(renderTarget.texture.format);
  14624. var glType = utils.convert(renderTarget.texture.type);
  14625. var glInternalFormat = getInternalFormat(glFormat, glType);
  14626. if (isMultisample) {
  14627. var samples = getRenderTargetSamples(renderTarget);
  14628. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14629. } else {
  14630. _gl.renderbufferStorage(36161, glInternalFormat, renderTarget.width, renderTarget.height);
  14631. }
  14632. }
  14633. _gl.bindRenderbuffer(36161, null);
  14634. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  14635. function setupDepthTexture(framebuffer, renderTarget) {
  14636. var isCube = renderTarget && renderTarget.isWebGLRenderTargetCube;
  14637. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  14638. _gl.bindFramebuffer(36160, framebuffer);
  14639. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  14640. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  14641. } // upload an empty depth texture with framebuffer size
  14642. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  14643. renderTarget.depthTexture.image.width = renderTarget.width;
  14644. renderTarget.depthTexture.image.height = renderTarget.height;
  14645. renderTarget.depthTexture.needsUpdate = true;
  14646. }
  14647. setTexture2D(renderTarget.depthTexture, 0);
  14648. var webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  14649. if (renderTarget.depthTexture.format === DepthFormat) {
  14650. _gl.framebufferTexture2D(36160, 36096, 3553, webglDepthTexture, 0);
  14651. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  14652. _gl.framebufferTexture2D(36160, 33306, 3553, webglDepthTexture, 0);
  14653. } else {
  14654. throw new Error('Unknown depthTexture format');
  14655. }
  14656. } // Setup GL resources for a non-texture depth buffer
  14657. function setupDepthRenderbuffer(renderTarget) {
  14658. var renderTargetProperties = properties.get(renderTarget);
  14659. var isCube = renderTarget.isWebGLRenderTargetCube === true;
  14660. if (renderTarget.depthTexture) {
  14661. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  14662. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  14663. } else {
  14664. if (isCube) {
  14665. renderTargetProperties.__webglDepthbuffer = [];
  14666. for (var i = 0; i < 6; i++) {
  14667. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer[i]);
  14668. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  14669. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget);
  14670. }
  14671. } else {
  14672. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer);
  14673. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14674. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget);
  14675. }
  14676. }
  14677. _gl.bindFramebuffer(36160, null);
  14678. } // Set up GL resources for the render target
  14679. function setupRenderTarget(renderTarget) {
  14680. var renderTargetProperties = properties.get(renderTarget);
  14681. var textureProperties = properties.get(renderTarget.texture);
  14682. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  14683. textureProperties.__webglTexture = _gl.createTexture();
  14684. info.memory.textures++;
  14685. var isCube = renderTarget.isWebGLRenderTargetCube === true;
  14686. var isMultisample = renderTarget.isWebGLMultisampleRenderTarget === true;
  14687. var isMultiview = renderTarget.isWebGLMultiviewRenderTarget === true;
  14688. var supportsMips = isPowerOfTwo(renderTarget) || capabilities.isWebGL2; // Setup framebuffer
  14689. if (isCube) {
  14690. renderTargetProperties.__webglFramebuffer = [];
  14691. for (var i = 0; i < 6; i++) {
  14692. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  14693. }
  14694. } else {
  14695. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  14696. if (isMultisample) {
  14697. if (capabilities.isWebGL2) {
  14698. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  14699. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  14700. _gl.bindRenderbuffer(36161, renderTargetProperties.__webglColorRenderbuffer);
  14701. var glFormat = utils.convert(renderTarget.texture.format);
  14702. var glType = utils.convert(renderTarget.texture.type);
  14703. var glInternalFormat = getInternalFormat(glFormat, glType);
  14704. var samples = getRenderTargetSamples(renderTarget);
  14705. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14706. _gl.bindFramebuffer(36160, renderTargetProperties.__webglMultisampledFramebuffer);
  14707. _gl.framebufferRenderbuffer(36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer);
  14708. _gl.bindRenderbuffer(36161, null);
  14709. if (renderTarget.depthBuffer) {
  14710. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14711. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  14712. }
  14713. _gl.bindFramebuffer(36160, null);
  14714. } else {
  14715. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  14716. }
  14717. } else if (isMultiview) {
  14718. var width = renderTarget.width;
  14719. var height = renderTarget.height;
  14720. var numViews = renderTarget.numViews;
  14721. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer);
  14722. var ext = extensions.get('OVR_multiview2');
  14723. info.memory.textures += 2;
  14724. var colorTexture = _gl.createTexture();
  14725. _gl.bindTexture(35866, colorTexture);
  14726. _gl.texParameteri(35866, 10240, 9728);
  14727. _gl.texParameteri(35866, 10241, 9728);
  14728. _gl.texImage3D(35866, 0, 32856, width, height, numViews, 0, 6408, 5121, null);
  14729. ext.framebufferTextureMultiviewOVR(36160, 36064, colorTexture, 0, 0, numViews);
  14730. var depthStencilTexture = _gl.createTexture();
  14731. _gl.bindTexture(35866, depthStencilTexture);
  14732. _gl.texParameteri(35866, 10240, 9728);
  14733. _gl.texParameteri(35866, 10241, 9728);
  14734. _gl.texImage3D(35866, 0, 35056, width, height, numViews, 0, 34041, 34042, null);
  14735. ext.framebufferTextureMultiviewOVR(36160, 33306, depthStencilTexture, 0, 0, numViews);
  14736. var viewFramebuffers = new Array(numViews);
  14737. for (var i = 0; i < numViews; ++i) {
  14738. viewFramebuffers[i] = _gl.createFramebuffer();
  14739. _gl.bindFramebuffer(36160, viewFramebuffers[i]);
  14740. _gl.framebufferTextureLayer(36160, 36064, colorTexture, 0, i);
  14741. }
  14742. renderTargetProperties.__webglColorTexture = colorTexture;
  14743. renderTargetProperties.__webglDepthStencilTexture = depthStencilTexture;
  14744. renderTargetProperties.__webglViewFramebuffers = viewFramebuffers;
  14745. _gl.bindFramebuffer(36160, null);
  14746. _gl.bindTexture(35866, null);
  14747. }
  14748. } // Setup color buffer
  14749. if (isCube) {
  14750. state.bindTexture(34067, textureProperties.__webglTexture);
  14751. setTextureParameters(34067, renderTarget.texture, supportsMips);
  14752. for (var i = 0; i < 6; i++) {
  14753. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, 36064, 34069 + i);
  14754. }
  14755. if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
  14756. generateMipmap(34067, renderTarget.texture, renderTarget.width, renderTarget.height);
  14757. }
  14758. state.bindTexture(34067, null);
  14759. } else if (!isMultiview) {
  14760. state.bindTexture(3553, textureProperties.__webglTexture);
  14761. setTextureParameters(3553, renderTarget.texture, supportsMips);
  14762. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553);
  14763. if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
  14764. generateMipmap(3553, renderTarget.texture, renderTarget.width, renderTarget.height);
  14765. }
  14766. state.bindTexture(3553, null);
  14767. } // Setup depth and stencil buffers
  14768. if (renderTarget.depthBuffer) {
  14769. setupDepthRenderbuffer(renderTarget);
  14770. }
  14771. }
  14772. function updateRenderTargetMipmap(renderTarget) {
  14773. var texture = renderTarget.texture;
  14774. var supportsMips = isPowerOfTwo(renderTarget) || capabilities.isWebGL2;
  14775. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14776. var target = renderTarget.isWebGLRenderTargetCube ? 34067 : 3553;
  14777. var webglTexture = properties.get(texture).__webglTexture;
  14778. state.bindTexture(target, webglTexture);
  14779. generateMipmap(target, texture, renderTarget.width, renderTarget.height);
  14780. state.bindTexture(target, null);
  14781. }
  14782. }
  14783. function updateMultisampleRenderTarget(renderTarget) {
  14784. if (renderTarget.isWebGLMultisampleRenderTarget) {
  14785. if (capabilities.isWebGL2) {
  14786. var renderTargetProperties = properties.get(renderTarget);
  14787. _gl.bindFramebuffer(36008, renderTargetProperties.__webglMultisampledFramebuffer);
  14788. _gl.bindFramebuffer(36009, renderTargetProperties.__webglFramebuffer);
  14789. var width = renderTarget.width;
  14790. var height = renderTarget.height;
  14791. var mask = 16384;
  14792. if (renderTarget.depthBuffer) mask |= 256;
  14793. if (renderTarget.stencilBuffer) mask |= 1024;
  14794. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, 9728);
  14795. } else {
  14796. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  14797. }
  14798. }
  14799. }
  14800. function getRenderTargetSamples(renderTarget) {
  14801. return capabilities.isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ? Math.min(capabilities.maxSamples, renderTarget.samples) : 0;
  14802. }
  14803. function updateVideoTexture(texture) {
  14804. var frame = info.render.frame; // Check the last frame we updated the VideoTexture
  14805. if (_videoTextures.get(texture) !== frame) {
  14806. _videoTextures.set(texture, frame);
  14807. texture.update();
  14808. }
  14809. } // backwards compatibility
  14810. var warnedTexture2D = false;
  14811. var warnedTextureCube = false;
  14812. function safeSetTexture2D(texture, slot) {
  14813. if (texture && texture.isWebGLRenderTarget) {
  14814. if (warnedTexture2D === false) {
  14815. console.warn("THREE.WebGLTextures.safeSetTexture2D: don't use render targets as textures. Use their .texture property instead.");
  14816. warnedTexture2D = true;
  14817. }
  14818. texture = texture.texture;
  14819. }
  14820. setTexture2D(texture, slot);
  14821. }
  14822. function safeSetTextureCube(texture, slot) {
  14823. if (texture && texture.isWebGLRenderTargetCube) {
  14824. if (warnedTextureCube === false) {
  14825. console.warn("THREE.WebGLTextures.safeSetTextureCube: don't use cube render targets as textures. Use their .texture property instead.");
  14826. warnedTextureCube = true;
  14827. }
  14828. texture = texture.texture;
  14829. } // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  14830. // TODO: unify these code paths
  14831. if (texture && texture.isCubeTexture || Array.isArray(texture.image) && texture.image.length === 6) {
  14832. // CompressedTexture can have Array in image :/
  14833. // this function alone should take care of cube textures
  14834. setTextureCube(texture, slot);
  14835. } else {
  14836. // assumed: texture property of THREE.WebGLRenderTargetCube
  14837. setTextureCubeDynamic(texture, slot);
  14838. }
  14839. } //
  14840. this.allocateTextureUnit = allocateTextureUnit;
  14841. this.resetTextureUnits = resetTextureUnits;
  14842. this.setTexture2D = setTexture2D;
  14843. this.setTexture2DArray = setTexture2DArray;
  14844. this.setTexture3D = setTexture3D;
  14845. this.setTextureCube = setTextureCube;
  14846. this.setTextureCubeDynamic = setTextureCubeDynamic;
  14847. this.setupRenderTarget = setupRenderTarget;
  14848. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14849. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14850. this.safeSetTexture2D = safeSetTexture2D;
  14851. this.safeSetTextureCube = safeSetTextureCube;
  14852. }
  14853. /**
  14854. * @author thespite / http://www.twitter.com/thespite
  14855. */
  14856. function WebGLUtils(gl, extensions, capabilities) {
  14857. function convert(p) {
  14858. var extension;
  14859. if (p === RepeatWrapping) return 10497;
  14860. if (p === ClampToEdgeWrapping) return 33071;
  14861. if (p === MirroredRepeatWrapping) return 33648;
  14862. if (p === NearestFilter) return 9728;
  14863. if (p === NearestMipmapNearestFilter) return 9984;
  14864. if (p === NearestMipmapLinearFilter) return 9986;
  14865. if (p === LinearFilter) return 9729;
  14866. if (p === LinearMipmapNearestFilter) return 9985;
  14867. if (p === LinearMipmapLinearFilter) return 9987;
  14868. if (p === UnsignedByteType) return 5121;
  14869. if (p === UnsignedShort4444Type) return 32819;
  14870. if (p === UnsignedShort5551Type) return 32820;
  14871. if (p === UnsignedShort565Type) return 33635;
  14872. if (p === ByteType) return 5120;
  14873. if (p === ShortType) return 5122;
  14874. if (p === UnsignedShortType) return 5123;
  14875. if (p === IntType) return 5124;
  14876. if (p === UnsignedIntType) return 5125;
  14877. if (p === FloatType) return 5126;
  14878. if (p === HalfFloatType) {
  14879. if (capabilities.isWebGL2) return 5131;
  14880. extension = extensions.get('OES_texture_half_float');
  14881. if (extension !== null) return extension.HALF_FLOAT_OES;
  14882. }
  14883. if (p === AlphaFormat) return 6406;
  14884. if (p === RGBFormat) return 6407;
  14885. if (p === RGBAFormat) return 6408;
  14886. if (p === LuminanceFormat) return 6409;
  14887. if (p === LuminanceAlphaFormat) return 6410;
  14888. if (p === DepthFormat) return 6402;
  14889. if (p === DepthStencilFormat) return 34041;
  14890. if (p === RedFormat) return 6403;
  14891. if (p === AddEquation) return 32774;
  14892. if (p === SubtractEquation) return 32778;
  14893. if (p === ReverseSubtractEquation) return 32779;
  14894. if (p === ZeroFactor) return 0;
  14895. if (p === OneFactor) return 1;
  14896. if (p === SrcColorFactor) return 768;
  14897. if (p === OneMinusSrcColorFactor) return 769;
  14898. if (p === SrcAlphaFactor) return 770;
  14899. if (p === OneMinusSrcAlphaFactor) return 771;
  14900. if (p === DstAlphaFactor) return 772;
  14901. if (p === OneMinusDstAlphaFactor) return 773;
  14902. if (p === DstColorFactor) return 774;
  14903. if (p === OneMinusDstColorFactor) return 775;
  14904. if (p === SrcAlphaSaturateFactor) return 776;
  14905. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  14906. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  14907. if (extension !== null) {
  14908. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14909. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14910. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14911. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14912. }
  14913. }
  14914. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  14915. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  14916. if (extension !== null) {
  14917. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14918. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14919. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14920. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14921. }
  14922. }
  14923. if (p === RGB_ETC1_Format) {
  14924. extension = extensions.get('WEBGL_compressed_texture_etc1');
  14925. if (extension !== null) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  14926. }
  14927. 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) {
  14928. extension = extensions.get('WEBGL_compressed_texture_astc');
  14929. if (extension !== null) {
  14930. return p;
  14931. }
  14932. }
  14933. if (p === MinEquation || p === MaxEquation) {
  14934. if (capabilities.isWebGL2) {
  14935. if (p === MinEquation) return 32775;
  14936. if (p === MaxEquation) return 32776;
  14937. }
  14938. extension = extensions.get('EXT_blend_minmax');
  14939. if (extension !== null) {
  14940. if (p === MinEquation) return extension.MIN_EXT;
  14941. if (p === MaxEquation) return extension.MAX_EXT;
  14942. }
  14943. }
  14944. if (p === UnsignedInt248Type) {
  14945. if (capabilities.isWebGL2) return 34042;
  14946. extension = extensions.get('WEBGL_depth_texture');
  14947. if (extension !== null) return extension.UNSIGNED_INT_24_8_WEBGL;
  14948. }
  14949. return 0;
  14950. }
  14951. return {
  14952. convert: convert
  14953. };
  14954. }
  14955. /**
  14956. * @author fernandojsg / http://fernandojsg.com
  14957. * @author Takahiro https://github.com/takahirox
  14958. */
  14959. function WebGLMultiviewRenderTarget(width, height, numViews, options) {
  14960. WebGLRenderTarget.call(this, width, height, options);
  14961. this.depthBuffer = false;
  14962. this.stencilBuffer = false;
  14963. this.numViews = numViews;
  14964. }
  14965. WebGLMultiviewRenderTarget.prototype = Object.assign(Object.create(WebGLRenderTarget.prototype), {
  14966. constructor: WebGLMultiviewRenderTarget,
  14967. isWebGLMultiviewRenderTarget: true,
  14968. copy: function (source) {
  14969. WebGLRenderTarget.prototype.copy.call(this, source);
  14970. this.numViews = source.numViews;
  14971. return this;
  14972. },
  14973. setNumViews: function (numViews) {
  14974. if (this.numViews !== numViews) {
  14975. this.numViews = numViews;
  14976. this.dispose();
  14977. }
  14978. return this;
  14979. }
  14980. });
  14981. /**
  14982. * @author fernandojsg / http://fernandojsg.com
  14983. * @author Takahiro https://github.com/takahirox
  14984. */
  14985. function WebGLMultiview(renderer, gl) {
  14986. var DEFAULT_NUMVIEWS = 2;
  14987. var extensions = renderer.extensions;
  14988. var properties = renderer.properties;
  14989. var renderTarget, currentRenderTarget;
  14990. var mat3, mat4, cameraArray, renderSize;
  14991. var available;
  14992. var maxNumViews = 0; //
  14993. function isAvailable() {
  14994. if (available === undefined) {
  14995. var extension = extensions.get('OVR_multiview2');
  14996. available = extension !== null && gl.getContextAttributes().antialias === false;
  14997. if (available) {
  14998. maxNumViews = gl.getParameter(extension.MAX_VIEWS_OVR);
  14999. renderTarget = new WebGLMultiviewRenderTarget(0, 0, DEFAULT_NUMVIEWS);
  15000. renderSize = new Vector2();
  15001. mat4 = [];
  15002. mat3 = [];
  15003. cameraArray = [];
  15004. for (var i = 0; i < maxNumViews; i++) {
  15005. mat4[i] = new Matrix4();
  15006. mat3[i] = new Matrix3();
  15007. }
  15008. }
  15009. }
  15010. return available;
  15011. }
  15012. function getCameraArray(camera) {
  15013. if (camera.isArrayCamera) return camera.cameras;
  15014. cameraArray[0] = camera;
  15015. return cameraArray;
  15016. }
  15017. function updateCameraProjectionMatricesUniform(camera, uniforms) {
  15018. var cameras = getCameraArray(camera);
  15019. for (var i = 0; i < cameras.length; i++) {
  15020. mat4[i].copy(cameras[i].projectionMatrix);
  15021. }
  15022. uniforms.setValue(gl, 'projectionMatrices', mat4);
  15023. }
  15024. function updateCameraViewMatricesUniform(camera, uniforms) {
  15025. var cameras = getCameraArray(camera);
  15026. for (var i = 0; i < cameras.length; i++) {
  15027. mat4[i].copy(cameras[i].matrixWorldInverse);
  15028. }
  15029. uniforms.setValue(gl, 'viewMatrices', mat4);
  15030. }
  15031. function updateObjectMatricesUniforms(object, camera, uniforms) {
  15032. var cameras = getCameraArray(camera);
  15033. for (var i = 0; i < cameras.length; i++) {
  15034. mat4[i].multiplyMatrices(cameras[i].matrixWorldInverse, object.matrixWorld);
  15035. mat3[i].getNormalMatrix(mat4[i]);
  15036. }
  15037. uniforms.setValue(gl, 'modelViewMatrices', mat4);
  15038. uniforms.setValue(gl, 'normalMatrices', mat3);
  15039. }
  15040. function isMultiviewCompatible(camera) {
  15041. if (camera.isArrayCamera === undefined) return true;
  15042. var cameras = camera.cameras;
  15043. if (cameras.length > maxNumViews) return false;
  15044. for (var i = 1, il = cameras.length; i < il; i++) {
  15045. if (cameras[0].viewport.z !== cameras[i].viewport.z || cameras[0].viewport.w !== cameras[i].viewport.w) return false;
  15046. }
  15047. return true;
  15048. }
  15049. function resizeRenderTarget(camera) {
  15050. if (currentRenderTarget) {
  15051. renderSize.set(currentRenderTarget.width, currentRenderTarget.height);
  15052. } else {
  15053. renderer.getDrawingBufferSize(renderSize);
  15054. }
  15055. if (camera.isArrayCamera) {
  15056. var viewport = camera.cameras[0].viewport;
  15057. renderTarget.setSize(viewport.z, viewport.w);
  15058. renderTarget.setNumViews(camera.cameras.length);
  15059. } else {
  15060. renderTarget.setSize(renderSize.x, renderSize.y);
  15061. renderTarget.setNumViews(DEFAULT_NUMVIEWS);
  15062. }
  15063. }
  15064. function attachCamera(camera) {
  15065. if (isMultiviewCompatible(camera) === false) return;
  15066. currentRenderTarget = renderer.getRenderTarget();
  15067. resizeRenderTarget(camera);
  15068. renderer.setRenderTarget(renderTarget);
  15069. }
  15070. function detachCamera(camera) {
  15071. if (renderTarget !== renderer.getRenderTarget()) return;
  15072. renderer.setRenderTarget(currentRenderTarget);
  15073. flush(camera);
  15074. }
  15075. function flush(camera) {
  15076. var srcRenderTarget = renderTarget;
  15077. var numViews = srcRenderTarget.numViews;
  15078. var srcFramebuffers = properties.get(srcRenderTarget).__webglViewFramebuffers;
  15079. var viewWidth = srcRenderTarget.width;
  15080. var viewHeight = srcRenderTarget.height;
  15081. if (camera.isArrayCamera) {
  15082. for (var i = 0; i < numViews; i++) {
  15083. var viewport = camera.cameras[i].viewport;
  15084. var x1 = viewport.x;
  15085. var y1 = viewport.y;
  15086. var x2 = x1 + viewport.z;
  15087. var y2 = y1 + viewport.w;
  15088. gl.bindFramebuffer(36008, srcFramebuffers[i]);
  15089. gl.blitFramebuffer(0, 0, viewWidth, viewHeight, x1, y1, x2, y2, 16384, 9728);
  15090. }
  15091. } else {
  15092. gl.bindFramebuffer(36008, srcFramebuffers[0]);
  15093. gl.blitFramebuffer(0, 0, viewWidth, viewHeight, 0, 0, renderSize.x, renderSize.y, 16384, 9728);
  15094. }
  15095. }
  15096. this.isAvailable = isAvailable;
  15097. this.attachCamera = attachCamera;
  15098. this.detachCamera = detachCamera;
  15099. this.updateCameraProjectionMatricesUniform = updateCameraProjectionMatricesUniform;
  15100. this.updateCameraViewMatricesUniform = updateCameraViewMatricesUniform;
  15101. this.updateObjectMatricesUniforms = updateObjectMatricesUniforms;
  15102. }
  15103. /**
  15104. * @author mrdoob / http://mrdoob.com/
  15105. */
  15106. function Group() {
  15107. Object3D.call(this);
  15108. this.type = 'Group';
  15109. }
  15110. Group.prototype = Object.assign(Object.create(Object3D.prototype), {
  15111. constructor: Group,
  15112. isGroup: true
  15113. });
  15114. /**
  15115. * @author mrdoob / http://mrdoob.com/
  15116. */
  15117. function ArrayCamera(array) {
  15118. PerspectiveCamera.call(this);
  15119. this.cameras = array || [];
  15120. }
  15121. ArrayCamera.prototype = Object.assign(Object.create(PerspectiveCamera.prototype), {
  15122. constructor: ArrayCamera,
  15123. isArrayCamera: true
  15124. });
  15125. /**
  15126. * @author jsantell / https://www.jsantell.com/
  15127. * @author mrdoob / http://mrdoob.com/
  15128. */
  15129. var cameraLPos = new Vector3();
  15130. var cameraRPos = new Vector3();
  15131. /**
  15132. * Assumes 2 cameras that are parallel and share an X-axis, and that
  15133. * the cameras' projection and world matrices have already been set.
  15134. * And that near and far planes are identical for both cameras.
  15135. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  15136. */
  15137. function setProjectionFromUnion(camera, cameraL, cameraR) {
  15138. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  15139. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  15140. var ipd = cameraLPos.distanceTo(cameraRPos);
  15141. var projL = cameraL.projectionMatrix.elements;
  15142. var projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  15143. // most likely identical top and bottom frustum extents.
  15144. // Use the left camera for these values.
  15145. var near = projL[14] / (projL[10] - 1);
  15146. var far = projL[14] / (projL[10] + 1);
  15147. var topFov = (projL[9] + 1) / projL[5];
  15148. var bottomFov = (projL[9] - 1) / projL[5];
  15149. var leftFov = (projL[8] - 1) / projL[0];
  15150. var rightFov = (projR[8] + 1) / projR[0];
  15151. var left = near * leftFov;
  15152. var right = near * rightFov; // Calculate the new camera's position offset from the
  15153. // left camera. xOffset should be roughly half `ipd`.
  15154. var zOffset = ipd / (-leftFov + rightFov);
  15155. var xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  15156. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  15157. camera.translateX(xOffset);
  15158. camera.translateZ(zOffset);
  15159. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  15160. camera.matrixWorldInverse.getInverse(camera.matrixWorld); // Find the union of the frustum values of the cameras and scale
  15161. // the values so that the near plane's position does not change in world space,
  15162. // although must now be relative to the new union camera.
  15163. var near2 = near + zOffset;
  15164. var far2 = far + zOffset;
  15165. var left2 = left - xOffset;
  15166. var right2 = right + (ipd - xOffset);
  15167. var top2 = topFov * far / far2 * near2;
  15168. var bottom2 = bottomFov * far / far2 * near2;
  15169. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  15170. }
  15171. /**
  15172. * @author mrdoob / http://mrdoob.com/
  15173. */
  15174. function WebVRManager(renderer) {
  15175. var renderWidth, renderHeight;
  15176. var scope = this;
  15177. var device = null;
  15178. var frameData = null;
  15179. var poseTarget = null;
  15180. var controllers = [];
  15181. var standingMatrix = new Matrix4();
  15182. var standingMatrixInverse = new Matrix4();
  15183. var framebufferScaleFactor = 1.0;
  15184. var referenceSpaceType = 'local-floor';
  15185. if (typeof window !== 'undefined' && 'VRFrameData' in window) {
  15186. frameData = new window.VRFrameData();
  15187. window.addEventListener('vrdisplaypresentchange', onVRDisplayPresentChange, false);
  15188. }
  15189. var matrixWorldInverse = new Matrix4();
  15190. var tempQuaternion = new Quaternion();
  15191. var tempPosition = new Vector3();
  15192. var cameraL = new PerspectiveCamera();
  15193. cameraL.viewport = new Vector4();
  15194. cameraL.layers.enable(1);
  15195. var cameraR = new PerspectiveCamera();
  15196. cameraR.viewport = new Vector4();
  15197. cameraR.layers.enable(2);
  15198. var cameraVR = new ArrayCamera([cameraL, cameraR]);
  15199. cameraVR.layers.enable(1);
  15200. cameraVR.layers.enable(2); //
  15201. function isPresenting() {
  15202. return device !== null && device.isPresenting === true;
  15203. }
  15204. var currentSize = new Vector2(),
  15205. currentPixelRatio;
  15206. function onVRDisplayPresentChange() {
  15207. if (isPresenting()) {
  15208. var eyeParameters = device.getEyeParameters('left');
  15209. renderWidth = 2 * eyeParameters.renderWidth * framebufferScaleFactor;
  15210. renderHeight = eyeParameters.renderHeight * framebufferScaleFactor;
  15211. currentPixelRatio = renderer.getPixelRatio();
  15212. renderer.getSize(currentSize);
  15213. renderer.setDrawingBufferSize(renderWidth, renderHeight, 1);
  15214. cameraL.viewport.set(0, 0, renderWidth / 2, renderHeight);
  15215. cameraR.viewport.set(renderWidth / 2, 0, renderWidth / 2, renderHeight);
  15216. animation.start();
  15217. scope.dispatchEvent({
  15218. type: 'sessionstart'
  15219. });
  15220. } else {
  15221. if (scope.enabled) {
  15222. renderer.setDrawingBufferSize(currentSize.width, currentSize.height, currentPixelRatio);
  15223. }
  15224. animation.stop();
  15225. scope.dispatchEvent({
  15226. type: 'sessionend'
  15227. });
  15228. }
  15229. } //
  15230. var triggers = [];
  15231. function findGamepad(id) {
  15232. var gamepads = navigator.getGamepads && navigator.getGamepads();
  15233. for (var i = 0, j = 0, l = gamepads.length; i < l; i++) {
  15234. var gamepad = gamepads[i];
  15235. 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'))) {
  15236. if (j === id) return gamepad;
  15237. j++;
  15238. }
  15239. }
  15240. }
  15241. function updateControllers() {
  15242. for (var i = 0; i < controllers.length; i++) {
  15243. var controller = controllers[i];
  15244. var gamepad = findGamepad(i);
  15245. if (gamepad !== undefined && gamepad.pose !== undefined) {
  15246. if (gamepad.pose === null) return; // Pose
  15247. var pose = gamepad.pose;
  15248. if (pose.hasPosition === false) controller.position.set(0.2, -0.6, -0.05);
  15249. if (pose.position !== null) controller.position.fromArray(pose.position);
  15250. if (pose.orientation !== null) controller.quaternion.fromArray(pose.orientation);
  15251. controller.matrix.compose(controller.position, controller.quaternion, controller.scale);
  15252. controller.matrix.premultiply(standingMatrix);
  15253. controller.matrix.decompose(controller.position, controller.quaternion, controller.scale);
  15254. controller.matrixWorldNeedsUpdate = true;
  15255. controller.visible = true; // Trigger
  15256. var buttonId = gamepad.id === 'Daydream Controller' ? 0 : 1;
  15257. if (triggers[i] === undefined) triggers[i] = false;
  15258. if (triggers[i] !== gamepad.buttons[buttonId].pressed) {
  15259. triggers[i] = gamepad.buttons[buttonId].pressed;
  15260. if (triggers[i] === true) {
  15261. controller.dispatchEvent({
  15262. type: 'selectstart'
  15263. });
  15264. } else {
  15265. controller.dispatchEvent({
  15266. type: 'selectend'
  15267. });
  15268. controller.dispatchEvent({
  15269. type: 'select'
  15270. });
  15271. }
  15272. }
  15273. } else {
  15274. controller.visible = false;
  15275. }
  15276. }
  15277. }
  15278. function updateViewportFromBounds(viewport, bounds) {
  15279. if (bounds !== null && bounds.length === 4) {
  15280. viewport.set(bounds[0] * renderWidth, bounds[1] * renderHeight, bounds[2] * renderWidth, bounds[3] * renderHeight);
  15281. }
  15282. } //
  15283. this.enabled = false;
  15284. this.getController = function (id) {
  15285. var controller = controllers[id];
  15286. if (controller === undefined) {
  15287. controller = new Group();
  15288. controller.matrixAutoUpdate = false;
  15289. controller.visible = false;
  15290. controllers[id] = controller;
  15291. }
  15292. return controller;
  15293. };
  15294. this.getDevice = function () {
  15295. return device;
  15296. };
  15297. this.setDevice = function (value) {
  15298. if (value !== undefined) device = value;
  15299. animation.setContext(value);
  15300. };
  15301. this.setFramebufferScaleFactor = function (value) {
  15302. framebufferScaleFactor = value;
  15303. };
  15304. this.setReferenceSpaceType = function (value) {
  15305. referenceSpaceType = value;
  15306. };
  15307. this.setPoseTarget = function (object) {
  15308. if (object !== undefined) poseTarget = object;
  15309. };
  15310. this.getCamera = function (camera) {
  15311. var userHeight = referenceSpaceType === 'local-floor' ? 1.6 : 0;
  15312. if (isPresenting() === false) {
  15313. camera.position.set(0, userHeight, 0);
  15314. camera.rotation.set(0, 0, 0);
  15315. return camera;
  15316. }
  15317. device.depthNear = camera.near;
  15318. device.depthFar = camera.far;
  15319. device.getFrameData(frameData); //
  15320. if (referenceSpaceType === 'local-floor') {
  15321. var stageParameters = device.stageParameters;
  15322. if (stageParameters) {
  15323. standingMatrix.fromArray(stageParameters.sittingToStandingTransform);
  15324. } else {
  15325. standingMatrix.makeTranslation(0, userHeight, 0);
  15326. }
  15327. }
  15328. var pose = frameData.pose;
  15329. var poseObject = poseTarget !== null ? poseTarget : camera; // We want to manipulate poseObject by its position and quaternion components since users may rely on them.
  15330. poseObject.matrix.copy(standingMatrix);
  15331. poseObject.matrix.decompose(poseObject.position, poseObject.quaternion, poseObject.scale);
  15332. if (pose.orientation !== null) {
  15333. tempQuaternion.fromArray(pose.orientation);
  15334. poseObject.quaternion.multiply(tempQuaternion);
  15335. }
  15336. if (pose.position !== null) {
  15337. tempQuaternion.setFromRotationMatrix(standingMatrix);
  15338. tempPosition.fromArray(pose.position);
  15339. tempPosition.applyQuaternion(tempQuaternion);
  15340. poseObject.position.add(tempPosition);
  15341. }
  15342. poseObject.updateMatrixWorld(); //
  15343. cameraL.near = camera.near;
  15344. cameraR.near = camera.near;
  15345. cameraL.far = camera.far;
  15346. cameraR.far = camera.far;
  15347. cameraL.matrixWorldInverse.fromArray(frameData.leftViewMatrix);
  15348. cameraR.matrixWorldInverse.fromArray(frameData.rightViewMatrix); // TODO (mrdoob) Double check this code
  15349. standingMatrixInverse.getInverse(standingMatrix);
  15350. if (referenceSpaceType === 'local-floor') {
  15351. cameraL.matrixWorldInverse.multiply(standingMatrixInverse);
  15352. cameraR.matrixWorldInverse.multiply(standingMatrixInverse);
  15353. }
  15354. var parent = poseObject.parent;
  15355. if (parent !== null) {
  15356. matrixWorldInverse.getInverse(parent.matrixWorld);
  15357. cameraL.matrixWorldInverse.multiply(matrixWorldInverse);
  15358. cameraR.matrixWorldInverse.multiply(matrixWorldInverse);
  15359. } // envMap and Mirror needs camera.matrixWorld
  15360. cameraL.matrixWorld.getInverse(cameraL.matrixWorldInverse);
  15361. cameraR.matrixWorld.getInverse(cameraR.matrixWorldInverse);
  15362. cameraL.projectionMatrix.fromArray(frameData.leftProjectionMatrix);
  15363. cameraR.projectionMatrix.fromArray(frameData.rightProjectionMatrix);
  15364. setProjectionFromUnion(cameraVR, cameraL, cameraR); //
  15365. var layers = device.getLayers();
  15366. if (layers.length) {
  15367. var layer = layers[0];
  15368. updateViewportFromBounds(cameraL.viewport, layer.leftBounds);
  15369. updateViewportFromBounds(cameraR.viewport, layer.rightBounds);
  15370. }
  15371. updateControllers();
  15372. return cameraVR;
  15373. };
  15374. this.getStandingMatrix = function () {
  15375. return standingMatrix;
  15376. };
  15377. this.isPresenting = isPresenting; // Animation Loop
  15378. var animation = new WebGLAnimation();
  15379. this.setAnimationLoop = function (callback) {
  15380. animation.setAnimationLoop(callback);
  15381. if (isPresenting()) animation.start();
  15382. };
  15383. this.submitFrame = function () {
  15384. if (isPresenting()) device.submitFrame();
  15385. };
  15386. this.dispose = function () {
  15387. if (typeof window !== 'undefined') {
  15388. window.removeEventListener('vrdisplaypresentchange', onVRDisplayPresentChange);
  15389. }
  15390. }; // DEPRECATED
  15391. this.setFrameOfReferenceType = function () {
  15392. console.warn('THREE.WebVRManager: setFrameOfReferenceType() has been deprecated.');
  15393. };
  15394. }
  15395. Object.assign(WebVRManager.prototype, EventDispatcher.prototype);
  15396. /**
  15397. * @author mrdoob / http://mrdoob.com/
  15398. */
  15399. function WebXRManager(renderer, gl) {
  15400. var scope = this;
  15401. var session = null; // var framebufferScaleFactor = 1.0;
  15402. var referenceSpace = null;
  15403. var referenceSpaceType = 'local-floor';
  15404. var pose = null;
  15405. var controllers = [];
  15406. var inputSources = [];
  15407. function isPresenting() {
  15408. return session !== null && referenceSpace !== null;
  15409. } //
  15410. var cameraL = new PerspectiveCamera();
  15411. cameraL.layers.enable(1);
  15412. cameraL.viewport = new Vector4();
  15413. var cameraR = new PerspectiveCamera();
  15414. cameraR.layers.enable(2);
  15415. cameraR.viewport = new Vector4();
  15416. var cameraVR = new ArrayCamera([cameraL, cameraR]);
  15417. cameraVR.layers.enable(1);
  15418. cameraVR.layers.enable(2); //
  15419. this.enabled = false;
  15420. this.getController = function (id) {
  15421. var controller = controllers[id];
  15422. if (controller === undefined) {
  15423. controller = new Group();
  15424. controller.matrixAutoUpdate = false;
  15425. controller.visible = false;
  15426. controllers[id] = controller;
  15427. }
  15428. return controller;
  15429. }; //
  15430. function onSessionEvent(event) {
  15431. for (var i = 0; i < controllers.length; i++) {
  15432. if (inputSources[i] === event.inputSource) {
  15433. controllers[i].dispatchEvent({
  15434. type: event.type
  15435. });
  15436. }
  15437. }
  15438. }
  15439. function onSessionEnd() {
  15440. renderer.setFramebuffer(null);
  15441. renderer.setRenderTarget(renderer.getRenderTarget()); // Hack #15830
  15442. animation.stop();
  15443. scope.dispatchEvent({
  15444. type: 'sessionend'
  15445. });
  15446. }
  15447. function onRequestReferenceSpace(value) {
  15448. referenceSpace = value;
  15449. animation.setContext(session);
  15450. animation.start();
  15451. scope.dispatchEvent({
  15452. type: 'sessionstart'
  15453. });
  15454. }
  15455. this.setFramebufferScaleFactor = function ()
  15456. /* value */
  15457. {// framebufferScaleFactor = value;
  15458. };
  15459. this.setReferenceSpaceType = function (value) {
  15460. referenceSpaceType = value;
  15461. };
  15462. this.getSession = function () {
  15463. return session;
  15464. };
  15465. this.setSession = function (value) {
  15466. session = value;
  15467. if (session !== null) {
  15468. session.addEventListener('select', onSessionEvent);
  15469. session.addEventListener('selectstart', onSessionEvent);
  15470. session.addEventListener('selectend', onSessionEvent);
  15471. session.addEventListener('end', onSessionEnd); // eslint-disable-next-line no-undef
  15472. session.updateRenderState({
  15473. baseLayer: new XRWebGLLayer(session, gl)
  15474. });
  15475. session.requestReferenceSpace(referenceSpaceType).then(onRequestReferenceSpace); //
  15476. inputSources = session.inputSources;
  15477. session.addEventListener('inputsourceschange', function () {
  15478. inputSources = session.inputSources;
  15479. console.log(inputSources);
  15480. for (var i = 0; i < controllers.length; i++) {
  15481. var controller = controllers[i];
  15482. controller.userData.inputSource = inputSources[i];
  15483. }
  15484. });
  15485. }
  15486. };
  15487. function updateCamera(camera, parent) {
  15488. if (parent === null) {
  15489. camera.matrixWorld.copy(camera.matrix);
  15490. } else {
  15491. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  15492. }
  15493. camera.matrixWorldInverse.getInverse(camera.matrixWorld);
  15494. }
  15495. this.getCamera = function (camera) {
  15496. if (isPresenting()) {
  15497. var parent = camera.parent;
  15498. var cameras = cameraVR.cameras;
  15499. updateCamera(cameraVR, parent);
  15500. for (var i = 0; i < cameras.length; i++) {
  15501. updateCamera(cameras[i], parent);
  15502. } // update camera and its children
  15503. camera.matrixWorld.copy(cameraVR.matrixWorld);
  15504. var children = camera.children;
  15505. for (var i = 0, l = children.length; i < l; i++) {
  15506. children[i].updateMatrixWorld(true);
  15507. }
  15508. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  15509. return cameraVR;
  15510. }
  15511. return camera;
  15512. };
  15513. this.isPresenting = isPresenting; // Animation Loop
  15514. var onAnimationFrameCallback = null;
  15515. function onAnimationFrame(time, frame) {
  15516. pose = frame.getViewerPose(referenceSpace);
  15517. if (pose !== null) {
  15518. var views = pose.views;
  15519. var baseLayer = session.renderState.baseLayer;
  15520. renderer.setFramebuffer(baseLayer.framebuffer);
  15521. for (var i = 0; i < views.length; i++) {
  15522. var view = views[i];
  15523. var viewport = baseLayer.getViewport(view);
  15524. var viewMatrix = view.transform.inverse.matrix;
  15525. var camera = cameraVR.cameras[i];
  15526. camera.matrix.fromArray(viewMatrix).getInverse(camera.matrix);
  15527. camera.projectionMatrix.fromArray(view.projectionMatrix);
  15528. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  15529. if (i === 0) {
  15530. cameraVR.matrix.copy(camera.matrix);
  15531. }
  15532. }
  15533. } //
  15534. for (var i = 0; i < controllers.length; i++) {
  15535. var controller = controllers[i];
  15536. var inputSource = inputSources[i];
  15537. if (inputSource) {
  15538. var inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  15539. if (inputPose !== null) {
  15540. controller.matrix.fromArray(inputPose.transform.matrix);
  15541. controller.matrix.decompose(controller.position, controller.rotation, controller.scale);
  15542. controller.visible = true;
  15543. continue;
  15544. }
  15545. }
  15546. controller.visible = false;
  15547. }
  15548. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  15549. }
  15550. var animation = new WebGLAnimation();
  15551. animation.setAnimationLoop(onAnimationFrame);
  15552. this.setAnimationLoop = function (callback) {
  15553. onAnimationFrameCallback = callback;
  15554. };
  15555. this.dispose = function () {}; // DEPRECATED
  15556. this.getStandingMatrix = function () {
  15557. console.warn('THREE.WebXRManager: getStandingMatrix() is no longer needed.');
  15558. return new Matrix4();
  15559. };
  15560. this.getDevice = function () {
  15561. console.warn('THREE.WebXRManager: getDevice() has been deprecated.');
  15562. };
  15563. this.setDevice = function () {
  15564. console.warn('THREE.WebXRManager: setDevice() has been deprecated.');
  15565. };
  15566. this.setFrameOfReferenceType = function () {
  15567. console.warn('THREE.WebXRManager: setFrameOfReferenceType() has been deprecated.');
  15568. };
  15569. this.submitFrame = function () {};
  15570. }
  15571. Object.assign(WebXRManager.prototype, EventDispatcher.prototype);
  15572. /**
  15573. * @author supereggbert / http://www.paulbrunt.co.uk/
  15574. * @author mrdoob / http://mrdoob.com/
  15575. * @author alteredq / http://alteredqualia.com/
  15576. * @author szimek / https://github.com/szimek/
  15577. * @author tschw
  15578. */
  15579. function WebGLRenderer(parameters) {
  15580. parameters = parameters || {};
  15581. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas'),
  15582. _context = parameters.context !== undefined ? parameters.context : null,
  15583. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  15584. _depth = parameters.depth !== undefined ? parameters.depth : true,
  15585. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  15586. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  15587. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  15588. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  15589. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  15590. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  15591. var currentRenderList = null;
  15592. var currentRenderState = null; // public properties
  15593. this.domElement = _canvas; // Debug configuration container
  15594. this.debug = {
  15595. /**
  15596. * Enables error checking and reporting when shader programs are being compiled
  15597. * @type {boolean}
  15598. */
  15599. checkShaderErrors: true
  15600. }; // clearing
  15601. this.autoClear = true;
  15602. this.autoClearColor = true;
  15603. this.autoClearDepth = true;
  15604. this.autoClearStencil = true; // scene graph
  15605. this.sortObjects = true; // user-defined clipping
  15606. this.clippingPlanes = [];
  15607. this.localClippingEnabled = false; // physically based shading
  15608. this.gammaFactor = 2.0; // for backwards compatibility
  15609. this.gammaInput = false;
  15610. this.gammaOutput = false; // physical lights
  15611. this.physicallyCorrectLights = false; // tone mapping
  15612. this.toneMapping = LinearToneMapping;
  15613. this.toneMappingExposure = 1.0;
  15614. this.toneMappingWhitePoint = 1.0; // morphs
  15615. this.maxMorphTargets = 8;
  15616. this.maxMorphNormals = 4; // internal properties
  15617. var _this = this,
  15618. _isContextLost = false,
  15619. // internal state cache
  15620. _framebuffer = null,
  15621. _currentActiveCubeFace = 0,
  15622. _currentActiveMipmapLevel = 0,
  15623. _currentRenderTarget = null,
  15624. _currentFramebuffer = null,
  15625. _currentMaterialId = -1,
  15626. // geometry and program caching
  15627. _currentGeometryProgram = {
  15628. geometry: null,
  15629. program: null,
  15630. wireframe: false
  15631. },
  15632. _currentCamera = null,
  15633. _currentArrayCamera = null,
  15634. _currentViewport = new Vector4(),
  15635. _currentScissor = new Vector4(),
  15636. _currentScissorTest = null,
  15637. //
  15638. _width = _canvas.width,
  15639. _height = _canvas.height,
  15640. _pixelRatio = 1,
  15641. _viewport = new Vector4(0, 0, _width, _height),
  15642. _scissor = new Vector4(0, 0, _width, _height),
  15643. _scissorTest = false,
  15644. // frustum
  15645. _frustum = new Frustum(),
  15646. // clipping
  15647. _clipping = new WebGLClipping(),
  15648. _clippingEnabled = false,
  15649. _localClippingEnabled = false,
  15650. // camera matrices cache
  15651. _projScreenMatrix = new Matrix4(),
  15652. _vector3 = new Vector3();
  15653. function getTargetPixelRatio() {
  15654. return _currentRenderTarget === null ? _pixelRatio : 1;
  15655. } // initialize
  15656. var _gl;
  15657. try {
  15658. var contextAttributes = {
  15659. alpha: _alpha,
  15660. depth: _depth,
  15661. stencil: _stencil,
  15662. antialias: _antialias,
  15663. premultipliedAlpha: _premultipliedAlpha,
  15664. preserveDrawingBuffer: _preserveDrawingBuffer,
  15665. powerPreference: _powerPreference,
  15666. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat,
  15667. xrCompatible: true
  15668. }; // event listeners must be registered before WebGL context is created, see #12753
  15669. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  15670. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  15671. _gl = _context || _canvas.getContext('webgl', contextAttributes) || _canvas.getContext('experimental-webgl', contextAttributes);
  15672. if (_gl === null) {
  15673. if (_canvas.getContext('webgl') !== null) {
  15674. throw new Error('Error creating WebGL context with your selected attributes.');
  15675. } else {
  15676. throw new Error('Error creating WebGL context.');
  15677. }
  15678. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  15679. if (_gl.getShaderPrecisionFormat === undefined) {
  15680. _gl.getShaderPrecisionFormat = function () {
  15681. return {
  15682. 'rangeMin': 1,
  15683. 'rangeMax': 1,
  15684. 'precision': 1
  15685. };
  15686. };
  15687. }
  15688. } catch (error) {
  15689. console.error('THREE.WebGLRenderer: ' + error.message);
  15690. throw error;
  15691. }
  15692. var extensions, capabilities, state, info;
  15693. var properties, textures, attributes, geometries, objects;
  15694. var programCache, renderLists, renderStates;
  15695. var background, morphtargets, bufferRenderer, indexedBufferRenderer;
  15696. var utils;
  15697. function initGLContext() {
  15698. extensions = new WebGLExtensions(_gl);
  15699. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  15700. if (capabilities.isWebGL2 === false) {
  15701. extensions.get('WEBGL_depth_texture');
  15702. extensions.get('OES_texture_float');
  15703. extensions.get('OES_texture_half_float');
  15704. extensions.get('OES_texture_half_float_linear');
  15705. extensions.get('OES_standard_derivatives');
  15706. extensions.get('OES_element_index_uint');
  15707. extensions.get('ANGLE_instanced_arrays');
  15708. }
  15709. extensions.get('OES_texture_float_linear');
  15710. utils = new WebGLUtils(_gl, extensions, capabilities);
  15711. state = new WebGLState(_gl, extensions, utils, capabilities);
  15712. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  15713. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  15714. info = new WebGLInfo(_gl);
  15715. properties = new WebGLProperties();
  15716. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  15717. attributes = new WebGLAttributes(_gl);
  15718. geometries = new WebGLGeometries(_gl, attributes, info);
  15719. objects = new WebGLObjects(_gl, geometries, attributes, info);
  15720. morphtargets = new WebGLMorphtargets(_gl);
  15721. programCache = new WebGLPrograms(_this, extensions, capabilities);
  15722. renderLists = new WebGLRenderLists();
  15723. renderStates = new WebGLRenderStates();
  15724. background = new WebGLBackground(_this, state, objects, _premultipliedAlpha);
  15725. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  15726. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  15727. info.programs = programCache.programs;
  15728. _this.capabilities = capabilities;
  15729. _this.extensions = extensions;
  15730. _this.properties = properties;
  15731. _this.renderLists = renderLists;
  15732. _this.state = state;
  15733. _this.info = info;
  15734. }
  15735. initGLContext(); // vr
  15736. var vr = typeof navigator !== 'undefined' && 'xr' in navigator && 'supportsSession' in navigator.xr ? new WebXRManager(_this, _gl) : new WebVRManager(_this);
  15737. this.vr = vr; // Multiview
  15738. var multiview = new WebGLMultiview(_this, _gl); // shadow map
  15739. var shadowMap = new WebGLShadowMap(_this, objects, capabilities.maxTextureSize);
  15740. this.shadowMap = shadowMap; // API
  15741. this.getContext = function () {
  15742. return _gl;
  15743. };
  15744. this.getContextAttributes = function () {
  15745. return _gl.getContextAttributes();
  15746. };
  15747. this.forceContextLoss = function () {
  15748. var extension = extensions.get('WEBGL_lose_context');
  15749. if (extension) extension.loseContext();
  15750. };
  15751. this.forceContextRestore = function () {
  15752. var extension = extensions.get('WEBGL_lose_context');
  15753. if (extension) extension.restoreContext();
  15754. };
  15755. this.getPixelRatio = function () {
  15756. return _pixelRatio;
  15757. };
  15758. this.setPixelRatio = function (value) {
  15759. if (value === undefined) return;
  15760. _pixelRatio = value;
  15761. this.setSize(_width, _height, false);
  15762. };
  15763. this.getSize = function (target) {
  15764. if (target === undefined) {
  15765. console.warn('WebGLRenderer: .getsize() now requires a Vector2 as an argument');
  15766. target = new Vector2();
  15767. }
  15768. return target.set(_width, _height);
  15769. };
  15770. this.setSize = function (width, height, updateStyle) {
  15771. if (vr.isPresenting()) {
  15772. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  15773. return;
  15774. }
  15775. _width = width;
  15776. _height = height;
  15777. _canvas.width = Math.floor(width * _pixelRatio);
  15778. _canvas.height = Math.floor(height * _pixelRatio);
  15779. if (updateStyle !== false) {
  15780. _canvas.style.width = width + 'px';
  15781. _canvas.style.height = height + 'px';
  15782. }
  15783. this.setViewport(0, 0, width, height);
  15784. };
  15785. this.getDrawingBufferSize = function (target) {
  15786. if (target === undefined) {
  15787. console.warn('WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument');
  15788. target = new Vector2();
  15789. }
  15790. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  15791. };
  15792. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  15793. _width = width;
  15794. _height = height;
  15795. _pixelRatio = pixelRatio;
  15796. _canvas.width = Math.floor(width * pixelRatio);
  15797. _canvas.height = Math.floor(height * pixelRatio);
  15798. this.setViewport(0, 0, width, height);
  15799. };
  15800. this.getCurrentViewport = function (target) {
  15801. if (target === undefined) {
  15802. console.warn('WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument');
  15803. target = new Vector4();
  15804. }
  15805. return target.copy(_currentViewport);
  15806. };
  15807. this.getViewport = function (target) {
  15808. return target.copy(_viewport);
  15809. };
  15810. this.setViewport = function (x, y, width, height) {
  15811. if (x.isVector4) {
  15812. _viewport.set(x.x, x.y, x.z, x.w);
  15813. } else {
  15814. _viewport.set(x, y, width, height);
  15815. }
  15816. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  15817. };
  15818. this.getScissor = function (target) {
  15819. return target.copy(_scissor);
  15820. };
  15821. this.setScissor = function (x, y, width, height) {
  15822. if (x.isVector4) {
  15823. _scissor.set(x.x, x.y, x.z, x.w);
  15824. } else {
  15825. _scissor.set(x, y, width, height);
  15826. }
  15827. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  15828. };
  15829. this.getScissorTest = function () {
  15830. return _scissorTest;
  15831. };
  15832. this.setScissorTest = function (boolean) {
  15833. state.setScissorTest(_scissorTest = boolean);
  15834. }; // Clearing
  15835. this.getClearColor = function () {
  15836. return background.getClearColor();
  15837. };
  15838. this.setClearColor = function () {
  15839. background.setClearColor.apply(background, arguments);
  15840. };
  15841. this.getClearAlpha = function () {
  15842. return background.getClearAlpha();
  15843. };
  15844. this.setClearAlpha = function () {
  15845. background.setClearAlpha.apply(background, arguments);
  15846. };
  15847. this.clear = function (color, depth, stencil) {
  15848. var bits = 0;
  15849. if (color === undefined || color) bits |= 16384;
  15850. if (depth === undefined || depth) bits |= 256;
  15851. if (stencil === undefined || stencil) bits |= 1024;
  15852. _gl.clear(bits);
  15853. };
  15854. this.clearColor = function () {
  15855. this.clear(true, false, false);
  15856. };
  15857. this.clearDepth = function () {
  15858. this.clear(false, true, false);
  15859. };
  15860. this.clearStencil = function () {
  15861. this.clear(false, false, true);
  15862. }; //
  15863. this.dispose = function () {
  15864. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  15865. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  15866. renderLists.dispose();
  15867. renderStates.dispose();
  15868. properties.dispose();
  15869. objects.dispose();
  15870. vr.dispose();
  15871. animation.stop();
  15872. }; // Events
  15873. function onContextLost(event) {
  15874. event.preventDefault();
  15875. console.log('THREE.WebGLRenderer: Context Lost.');
  15876. _isContextLost = true;
  15877. }
  15878. function onContextRestore()
  15879. /* event */
  15880. {
  15881. console.log('THREE.WebGLRenderer: Context Restored.');
  15882. _isContextLost = false;
  15883. initGLContext();
  15884. }
  15885. function onMaterialDispose(event) {
  15886. var material = event.target;
  15887. material.removeEventListener('dispose', onMaterialDispose);
  15888. deallocateMaterial(material);
  15889. } // Buffer deallocation
  15890. function deallocateMaterial(material) {
  15891. releaseMaterialProgramReference(material);
  15892. properties.remove(material);
  15893. }
  15894. function releaseMaterialProgramReference(material) {
  15895. var programInfo = properties.get(material).program;
  15896. material.program = undefined;
  15897. if (programInfo !== undefined) {
  15898. programCache.releaseProgram(programInfo);
  15899. }
  15900. } // Buffer rendering
  15901. function renderObjectImmediate(object, program) {
  15902. object.render(function (object) {
  15903. _this.renderBufferImmediate(object, program);
  15904. });
  15905. }
  15906. this.renderBufferImmediate = function (object, program) {
  15907. state.initAttributes();
  15908. var buffers = properties.get(object);
  15909. if (object.hasPositions && !buffers.position) buffers.position = _gl.createBuffer();
  15910. if (object.hasNormals && !buffers.normal) buffers.normal = _gl.createBuffer();
  15911. if (object.hasUvs && !buffers.uv) buffers.uv = _gl.createBuffer();
  15912. if (object.hasColors && !buffers.color) buffers.color = _gl.createBuffer();
  15913. var programAttributes = program.getAttributes();
  15914. if (object.hasPositions) {
  15915. _gl.bindBuffer(34962, buffers.position);
  15916. _gl.bufferData(34962, object.positionArray, 35048);
  15917. state.enableAttribute(programAttributes.position);
  15918. _gl.vertexAttribPointer(programAttributes.position, 3, 5126, false, 0, 0);
  15919. }
  15920. if (object.hasNormals) {
  15921. _gl.bindBuffer(34962, buffers.normal);
  15922. _gl.bufferData(34962, object.normalArray, 35048);
  15923. state.enableAttribute(programAttributes.normal);
  15924. _gl.vertexAttribPointer(programAttributes.normal, 3, 5126, false, 0, 0);
  15925. }
  15926. if (object.hasUvs) {
  15927. _gl.bindBuffer(34962, buffers.uv);
  15928. _gl.bufferData(34962, object.uvArray, 35048);
  15929. state.enableAttribute(programAttributes.uv);
  15930. _gl.vertexAttribPointer(programAttributes.uv, 2, 5126, false, 0, 0);
  15931. }
  15932. if (object.hasColors) {
  15933. _gl.bindBuffer(34962, buffers.color);
  15934. _gl.bufferData(34962, object.colorArray, 35048);
  15935. state.enableAttribute(programAttributes.color);
  15936. _gl.vertexAttribPointer(programAttributes.color, 3, 5126, false, 0, 0);
  15937. }
  15938. state.disableUnusedAttributes();
  15939. _gl.drawArrays(4, 0, object.count);
  15940. object.count = 0;
  15941. };
  15942. this.renderBufferDirect = function (camera, fog, geometry, material, object, group) {
  15943. var frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  15944. state.setMaterial(material, frontFaceCW);
  15945. var program = setProgram(camera, fog, material, object);
  15946. var updateBuffers = false;
  15947. if (_currentGeometryProgram.geometry !== geometry.id || _currentGeometryProgram.program !== program.id || _currentGeometryProgram.wireframe !== (material.wireframe === true)) {
  15948. _currentGeometryProgram.geometry = geometry.id;
  15949. _currentGeometryProgram.program = program.id;
  15950. _currentGeometryProgram.wireframe = material.wireframe === true;
  15951. updateBuffers = true;
  15952. }
  15953. if (object.morphTargetInfluences) {
  15954. morphtargets.update(object, geometry, material, program);
  15955. updateBuffers = true;
  15956. } //
  15957. var index = geometry.index;
  15958. var position = geometry.attributes.position;
  15959. var rangeFactor = 1;
  15960. if (material.wireframe === true) {
  15961. index = geometries.getWireframeAttribute(geometry);
  15962. rangeFactor = 2;
  15963. }
  15964. var attribute;
  15965. var renderer = bufferRenderer;
  15966. if (index !== null) {
  15967. attribute = attributes.get(index);
  15968. renderer = indexedBufferRenderer;
  15969. renderer.setIndex(attribute);
  15970. }
  15971. if (updateBuffers) {
  15972. setupVertexAttributes(object, geometry, material, program);
  15973. if (index !== null) {
  15974. _gl.bindBuffer(34963, attribute.buffer);
  15975. }
  15976. } //
  15977. var dataCount = Infinity;
  15978. if (index !== null) {
  15979. dataCount = index.count;
  15980. } else if (position !== undefined) {
  15981. dataCount = position.count;
  15982. }
  15983. var rangeStart = geometry.drawRange.start * rangeFactor;
  15984. var rangeCount = geometry.drawRange.count * rangeFactor;
  15985. var groupStart = group !== null ? group.start * rangeFactor : 0;
  15986. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  15987. var drawStart = Math.max(rangeStart, groupStart);
  15988. var drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  15989. var drawCount = Math.max(0, drawEnd - drawStart + 1);
  15990. if (drawCount === 0) return; //
  15991. if (object.isMesh) {
  15992. if (material.wireframe === true) {
  15993. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  15994. renderer.setMode(1);
  15995. } else {
  15996. switch (object.drawMode) {
  15997. case TrianglesDrawMode:
  15998. renderer.setMode(4);
  15999. break;
  16000. case TriangleStripDrawMode:
  16001. renderer.setMode(5);
  16002. break;
  16003. case TriangleFanDrawMode:
  16004. renderer.setMode(6);
  16005. break;
  16006. }
  16007. }
  16008. } else if (object.isLine) {
  16009. var lineWidth = material.linewidth;
  16010. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  16011. state.setLineWidth(lineWidth * getTargetPixelRatio());
  16012. if (object.isLineSegments) {
  16013. renderer.setMode(1);
  16014. } else if (object.isLineLoop) {
  16015. renderer.setMode(2);
  16016. } else {
  16017. renderer.setMode(3);
  16018. }
  16019. } else if (object.isPoints) {
  16020. renderer.setMode(0);
  16021. } else if (object.isSprite) {
  16022. renderer.setMode(4);
  16023. }
  16024. if (object.isInstancedMesh) {
  16025. renderer.renderInstances(geometry, drawStart, drawCount, object.count);
  16026. } else if (geometry.isInstancedBufferGeometry) {
  16027. renderer.renderInstances(geometry, drawStart, drawCount, geometry.maxInstancedCount);
  16028. } else {
  16029. renderer.render(drawStart, drawCount);
  16030. }
  16031. };
  16032. function setupVertexAttributes(object, geometry, material, program) {
  16033. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  16034. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  16035. }
  16036. state.initAttributes();
  16037. var geometryAttributes = geometry.attributes;
  16038. var programAttributes = program.getAttributes();
  16039. var materialDefaultAttributeValues = material.defaultAttributeValues;
  16040. for (var name in programAttributes) {
  16041. var programAttribute = programAttributes[name];
  16042. if (programAttribute >= 0) {
  16043. var geometryAttribute = geometryAttributes[name];
  16044. if (geometryAttribute !== undefined) {
  16045. var normalized = geometryAttribute.normalized;
  16046. var size = geometryAttribute.itemSize;
  16047. var attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  16048. if (attribute === undefined) continue;
  16049. var buffer = attribute.buffer;
  16050. var type = attribute.type;
  16051. var bytesPerElement = attribute.bytesPerElement;
  16052. if (geometryAttribute.isInterleavedBufferAttribute) {
  16053. var data = geometryAttribute.data;
  16054. var stride = data.stride;
  16055. var offset = geometryAttribute.offset;
  16056. if (data && data.isInstancedInterleavedBuffer) {
  16057. state.enableAttributeAndDivisor(programAttribute, data.meshPerAttribute);
  16058. if (geometry.maxInstancedCount === undefined) {
  16059. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  16060. }
  16061. } else {
  16062. state.enableAttribute(programAttribute);
  16063. }
  16064. _gl.bindBuffer(34962, buffer);
  16065. _gl.vertexAttribPointer(programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement);
  16066. } else {
  16067. if (geometryAttribute.isInstancedBufferAttribute) {
  16068. state.enableAttributeAndDivisor(programAttribute, geometryAttribute.meshPerAttribute);
  16069. if (geometry.maxInstancedCount === undefined) {
  16070. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  16071. }
  16072. } else {
  16073. state.enableAttribute(programAttribute);
  16074. }
  16075. _gl.bindBuffer(34962, buffer);
  16076. _gl.vertexAttribPointer(programAttribute, size, type, normalized, 0, 0);
  16077. }
  16078. } else if (name === 'instanceMatrix') {
  16079. var attribute = attributes.get(object.instanceMatrix); // TODO Attribute may not be available on context restore
  16080. if (attribute === undefined) continue;
  16081. var buffer = attribute.buffer;
  16082. var type = attribute.type;
  16083. state.enableAttributeAndDivisor(programAttribute + 0, 1);
  16084. state.enableAttributeAndDivisor(programAttribute + 1, 1);
  16085. state.enableAttributeAndDivisor(programAttribute + 2, 1);
  16086. state.enableAttributeAndDivisor(programAttribute + 3, 1);
  16087. _gl.bindBuffer(34962, buffer);
  16088. _gl.vertexAttribPointer(programAttribute + 0, 4, type, false, 64, 0);
  16089. _gl.vertexAttribPointer(programAttribute + 1, 4, type, false, 64, 16);
  16090. _gl.vertexAttribPointer(programAttribute + 2, 4, type, false, 64, 32);
  16091. _gl.vertexAttribPointer(programAttribute + 3, 4, type, false, 64, 48);
  16092. } else if (materialDefaultAttributeValues !== undefined) {
  16093. var value = materialDefaultAttributeValues[name];
  16094. if (value !== undefined) {
  16095. switch (value.length) {
  16096. case 2:
  16097. _gl.vertexAttrib2fv(programAttribute, value);
  16098. break;
  16099. case 3:
  16100. _gl.vertexAttrib3fv(programAttribute, value);
  16101. break;
  16102. case 4:
  16103. _gl.vertexAttrib4fv(programAttribute, value);
  16104. break;
  16105. default:
  16106. _gl.vertexAttrib1fv(programAttribute, value);
  16107. }
  16108. }
  16109. }
  16110. }
  16111. }
  16112. state.disableUnusedAttributes();
  16113. } // Compile
  16114. this.compile = function (scene, camera) {
  16115. currentRenderState = renderStates.get(scene, camera);
  16116. currentRenderState.init();
  16117. scene.traverse(function (object) {
  16118. if (object.isLight) {
  16119. currentRenderState.pushLight(object);
  16120. if (object.castShadow) {
  16121. currentRenderState.pushShadow(object);
  16122. }
  16123. }
  16124. });
  16125. currentRenderState.setupLights(camera);
  16126. scene.traverse(function (object) {
  16127. if (object.material) {
  16128. if (Array.isArray(object.material)) {
  16129. for (var i = 0; i < object.material.length; i++) {
  16130. initMaterial(object.material[i], scene.fog, object);
  16131. }
  16132. } else {
  16133. initMaterial(object.material, scene.fog, object);
  16134. }
  16135. }
  16136. });
  16137. }; // Animation Loop
  16138. var onAnimationFrameCallback = null;
  16139. function onAnimationFrame(time) {
  16140. if (vr.isPresenting()) return;
  16141. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  16142. }
  16143. var animation = new WebGLAnimation();
  16144. animation.setAnimationLoop(onAnimationFrame);
  16145. if (typeof window !== 'undefined') animation.setContext(window);
  16146. this.setAnimationLoop = function (callback) {
  16147. onAnimationFrameCallback = callback;
  16148. vr.setAnimationLoop(callback);
  16149. animation.start();
  16150. }; // Rendering
  16151. this.render = function (scene, camera) {
  16152. var renderTarget, forceClear;
  16153. if (arguments[2] !== undefined) {
  16154. console.warn('THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.');
  16155. renderTarget = arguments[2];
  16156. }
  16157. if (arguments[3] !== undefined) {
  16158. console.warn('THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.');
  16159. forceClear = arguments[3];
  16160. }
  16161. if (!(camera && camera.isCamera)) {
  16162. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  16163. return;
  16164. }
  16165. if (_isContextLost) return; // reset caching for this frame
  16166. _currentGeometryProgram.geometry = null;
  16167. _currentGeometryProgram.program = null;
  16168. _currentGeometryProgram.wireframe = false;
  16169. _currentMaterialId = -1;
  16170. _currentCamera = null; // update scene graph
  16171. if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  16172. if (camera.parent === null) camera.updateMatrixWorld();
  16173. if (vr.enabled) {
  16174. camera = vr.getCamera(camera);
  16175. } //
  16176. currentRenderState = renderStates.get(scene, camera);
  16177. currentRenderState.init();
  16178. scene.onBeforeRender(_this, scene, camera, renderTarget || _currentRenderTarget);
  16179. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  16180. _frustum.setFromMatrix(_projScreenMatrix);
  16181. _localClippingEnabled = this.localClippingEnabled;
  16182. _clippingEnabled = _clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  16183. currentRenderList = renderLists.get(scene, camera);
  16184. currentRenderList.init();
  16185. projectObject(scene, camera, 0, _this.sortObjects);
  16186. if (_this.sortObjects === true) {
  16187. currentRenderList.sort();
  16188. } //
  16189. if (_clippingEnabled) _clipping.beginShadows();
  16190. var shadowsArray = currentRenderState.state.shadowsArray;
  16191. shadowMap.render(shadowsArray, scene, camera);
  16192. currentRenderState.setupLights(camera);
  16193. if (_clippingEnabled) _clipping.endShadows(); //
  16194. if (this.info.autoReset) this.info.reset();
  16195. if (renderTarget !== undefined) {
  16196. this.setRenderTarget(renderTarget);
  16197. }
  16198. if (vr.enabled && multiview.isAvailable()) {
  16199. multiview.attachCamera(camera);
  16200. } //
  16201. background.render(currentRenderList, scene, camera, forceClear); // render scene
  16202. var opaqueObjects = currentRenderList.opaque;
  16203. var transparentObjects = currentRenderList.transparent;
  16204. if (scene.overrideMaterial) {
  16205. var overrideMaterial = scene.overrideMaterial;
  16206. if (opaqueObjects.length) renderObjects(opaqueObjects, scene, camera, overrideMaterial);
  16207. if (transparentObjects.length) renderObjects(transparentObjects, scene, camera, overrideMaterial);
  16208. } else {
  16209. // opaque pass (front-to-back order)
  16210. if (opaqueObjects.length) renderObjects(opaqueObjects, scene, camera); // transparent pass (back-to-front order)
  16211. if (transparentObjects.length) renderObjects(transparentObjects, scene, camera);
  16212. } //
  16213. scene.onAfterRender(_this, scene, camera); //
  16214. if (_currentRenderTarget !== null) {
  16215. // Generate mipmap if we're using any kind of mipmap filtering
  16216. textures.updateRenderTargetMipmap(_currentRenderTarget); // resolve multisample renderbuffers to a single-sample texture if necessary
  16217. textures.updateMultisampleRenderTarget(_currentRenderTarget);
  16218. } // Ensure depth buffer writing is enabled so it can be cleared on next render
  16219. state.buffers.depth.setTest(true);
  16220. state.buffers.depth.setMask(true);
  16221. state.buffers.color.setMask(true);
  16222. state.setPolygonOffset(false);
  16223. if (vr.enabled) {
  16224. if (multiview.isAvailable()) {
  16225. multiview.detachCamera(camera);
  16226. }
  16227. vr.submitFrame();
  16228. } // _gl.finish();
  16229. currentRenderList = null;
  16230. currentRenderState = null;
  16231. };
  16232. function projectObject(object, camera, groupOrder, sortObjects) {
  16233. if (object.visible === false) return;
  16234. var visible = object.layers.test(camera.layers);
  16235. if (visible) {
  16236. if (object.isGroup) {
  16237. groupOrder = object.renderOrder;
  16238. } else if (object.isLOD) {
  16239. if (object.autoUpdate === true) object.update(camera);
  16240. } else if (object.isLight) {
  16241. currentRenderState.pushLight(object);
  16242. if (object.castShadow) {
  16243. currentRenderState.pushShadow(object);
  16244. }
  16245. } else if (object.isSprite) {
  16246. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  16247. if (sortObjects) {
  16248. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  16249. }
  16250. var geometry = objects.update(object);
  16251. var material = object.material;
  16252. if (material.visible) {
  16253. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  16254. }
  16255. }
  16256. } else if (object.isImmediateRenderObject) {
  16257. if (sortObjects) {
  16258. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  16259. }
  16260. currentRenderList.push(object, null, object.material, groupOrder, _vector3.z, null);
  16261. } else if (object.isMesh || object.isLine || object.isPoints) {
  16262. if (object.isSkinnedMesh) {
  16263. // update skeleton only once in a frame
  16264. if (object.skeleton.frame !== info.render.frame) {
  16265. object.skeleton.update();
  16266. object.skeleton.frame = info.render.frame;
  16267. }
  16268. }
  16269. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  16270. if (sortObjects) {
  16271. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  16272. }
  16273. var geometry = objects.update(object);
  16274. var material = object.material;
  16275. if (Array.isArray(material)) {
  16276. var groups = geometry.groups;
  16277. for (var i = 0, l = groups.length; i < l; i++) {
  16278. var group = groups[i];
  16279. var groupMaterial = material[group.materialIndex];
  16280. if (groupMaterial && groupMaterial.visible) {
  16281. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  16282. }
  16283. }
  16284. } else if (material.visible) {
  16285. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  16286. }
  16287. }
  16288. }
  16289. }
  16290. var children = object.children;
  16291. for (var i = 0, l = children.length; i < l; i++) {
  16292. projectObject(children[i], camera, groupOrder, sortObjects);
  16293. }
  16294. }
  16295. function renderObjects(renderList, scene, camera, overrideMaterial) {
  16296. for (var i = 0, l = renderList.length; i < l; i++) {
  16297. var renderItem = renderList[i];
  16298. var object = renderItem.object;
  16299. var geometry = renderItem.geometry;
  16300. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  16301. var group = renderItem.group;
  16302. if (camera.isArrayCamera) {
  16303. _currentArrayCamera = camera;
  16304. if (vr.enabled && multiview.isAvailable()) {
  16305. renderObject(object, scene, camera, geometry, material, group);
  16306. } else {
  16307. var cameras = camera.cameras;
  16308. for (var j = 0, jl = cameras.length; j < jl; j++) {
  16309. var camera2 = cameras[j];
  16310. if (object.layers.test(camera2.layers)) {
  16311. state.viewport(_currentViewport.copy(camera2.viewport));
  16312. currentRenderState.setupLights(camera2);
  16313. renderObject(object, scene, camera2, geometry, material, group);
  16314. }
  16315. }
  16316. }
  16317. } else {
  16318. _currentArrayCamera = null;
  16319. renderObject(object, scene, camera, geometry, material, group);
  16320. }
  16321. }
  16322. }
  16323. function renderObject(object, scene, camera, geometry, material, group) {
  16324. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  16325. currentRenderState = renderStates.get(scene, _currentArrayCamera || camera);
  16326. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  16327. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  16328. if (object.isImmediateRenderObject) {
  16329. state.setMaterial(material);
  16330. var program = setProgram(camera, scene.fog, material, object);
  16331. _currentGeometryProgram.geometry = null;
  16332. _currentGeometryProgram.program = null;
  16333. _currentGeometryProgram.wireframe = false;
  16334. renderObjectImmediate(object, program);
  16335. } else {
  16336. _this.renderBufferDirect(camera, scene.fog, geometry, material, object, group);
  16337. }
  16338. object.onAfterRender(_this, scene, camera, geometry, material, group);
  16339. currentRenderState = renderStates.get(scene, _currentArrayCamera || camera);
  16340. }
  16341. function initMaterial(material, fog, object) {
  16342. var materialProperties = properties.get(material);
  16343. var lights = currentRenderState.state.lights;
  16344. var shadowsArray = currentRenderState.state.shadowsArray;
  16345. var lightsStateVersion = lights.state.version;
  16346. var parameters = programCache.getParameters(material, lights.state, shadowsArray, fog, _clipping.numPlanes, _clipping.numIntersection, object);
  16347. var code = programCache.getProgramCode(material, parameters);
  16348. var program = materialProperties.program;
  16349. var programChange = true;
  16350. if (program === undefined) {
  16351. // new material
  16352. material.addEventListener('dispose', onMaterialDispose);
  16353. } else if (program.code !== code) {
  16354. // changed glsl or parameters
  16355. releaseMaterialProgramReference(material);
  16356. } else if (materialProperties.lightsStateVersion !== lightsStateVersion) {
  16357. materialProperties.lightsStateVersion = lightsStateVersion;
  16358. programChange = false;
  16359. } else if (parameters.shaderID !== undefined) {
  16360. // same glsl and uniform list
  16361. return;
  16362. } else {
  16363. // only rebuild uniform list
  16364. programChange = false;
  16365. }
  16366. if (programChange) {
  16367. if (parameters.shaderID) {
  16368. var shader = ShaderLib[parameters.shaderID];
  16369. materialProperties.shader = {
  16370. name: material.type,
  16371. uniforms: cloneUniforms(shader.uniforms),
  16372. vertexShader: shader.vertexShader,
  16373. fragmentShader: shader.fragmentShader
  16374. };
  16375. } else {
  16376. materialProperties.shader = {
  16377. name: material.type,
  16378. uniforms: material.uniforms,
  16379. vertexShader: material.vertexShader,
  16380. fragmentShader: material.fragmentShader
  16381. };
  16382. }
  16383. material.onBeforeCompile(materialProperties.shader, _this); // Computing code again as onBeforeCompile may have changed the shaders
  16384. code = programCache.getProgramCode(material, parameters);
  16385. program = programCache.acquireProgram(material, materialProperties.shader, parameters, code);
  16386. materialProperties.program = program;
  16387. material.program = program;
  16388. }
  16389. var programAttributes = program.getAttributes();
  16390. if (material.morphTargets) {
  16391. material.numSupportedMorphTargets = 0;
  16392. for (var i = 0; i < _this.maxMorphTargets; i++) {
  16393. if (programAttributes['morphTarget' + i] >= 0) {
  16394. material.numSupportedMorphTargets++;
  16395. }
  16396. }
  16397. }
  16398. if (material.morphNormals) {
  16399. material.numSupportedMorphNormals = 0;
  16400. for (var i = 0; i < _this.maxMorphNormals; i++) {
  16401. if (programAttributes['morphNormal' + i] >= 0) {
  16402. material.numSupportedMorphNormals++;
  16403. }
  16404. }
  16405. }
  16406. var uniforms = materialProperties.shader.uniforms;
  16407. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  16408. materialProperties.numClippingPlanes = _clipping.numPlanes;
  16409. materialProperties.numIntersection = _clipping.numIntersection;
  16410. uniforms.clippingPlanes = _clipping.uniform;
  16411. }
  16412. materialProperties.fog = fog; // store the light setup it was created for
  16413. materialProperties.needsLights = materialNeedsLights(material);
  16414. materialProperties.lightsStateVersion = lightsStateVersion;
  16415. if (materialProperties.needsLights) {
  16416. // wire up the material to this renderer's lighting state
  16417. uniforms.ambientLightColor.value = lights.state.ambient;
  16418. uniforms.lightProbe.value = lights.state.probe;
  16419. uniforms.directionalLights.value = lights.state.directional;
  16420. uniforms.spotLights.value = lights.state.spot;
  16421. uniforms.rectAreaLights.value = lights.state.rectArea;
  16422. uniforms.pointLights.value = lights.state.point;
  16423. uniforms.hemisphereLights.value = lights.state.hemi;
  16424. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  16425. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  16426. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  16427. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  16428. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  16429. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  16430. }
  16431. var progUniforms = materialProperties.program.getUniforms(),
  16432. uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  16433. materialProperties.uniformsList = uniformsList;
  16434. }
  16435. function setProgram(camera, fog, material, object) {
  16436. textures.resetTextureUnits();
  16437. var materialProperties = properties.get(material);
  16438. var lights = currentRenderState.state.lights;
  16439. if (_clippingEnabled) {
  16440. if (_localClippingEnabled || camera !== _currentCamera) {
  16441. var useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  16442. // object instead of the material, once it becomes feasible
  16443. // (#8465, #8379)
  16444. _clipping.setState(material.clippingPlanes, material.clipIntersection, material.clipShadows, camera, materialProperties, useCache);
  16445. }
  16446. }
  16447. if (material.needsUpdate === false) {
  16448. if (materialProperties.program === undefined) {
  16449. material.needsUpdate = true;
  16450. } else if (material.fog && materialProperties.fog !== fog) {
  16451. material.needsUpdate = true;
  16452. } else if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  16453. material.needsUpdate = true;
  16454. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== _clipping.numPlanes || materialProperties.numIntersection !== _clipping.numIntersection)) {
  16455. material.needsUpdate = true;
  16456. }
  16457. }
  16458. if (material.needsUpdate) {
  16459. initMaterial(material, fog, object);
  16460. material.needsUpdate = false;
  16461. }
  16462. var refreshProgram = false;
  16463. var refreshMaterial = false;
  16464. var refreshLights = false;
  16465. var program = materialProperties.program,
  16466. p_uniforms = program.getUniforms(),
  16467. m_uniforms = materialProperties.shader.uniforms;
  16468. if (state.useProgram(program.program)) {
  16469. refreshProgram = true;
  16470. refreshMaterial = true;
  16471. refreshLights = true;
  16472. }
  16473. if (material.id !== _currentMaterialId) {
  16474. _currentMaterialId = material.id;
  16475. refreshMaterial = true;
  16476. }
  16477. if (refreshProgram || _currentCamera !== camera) {
  16478. if (program.numMultiviewViews > 0) {
  16479. multiview.updateCameraProjectionMatricesUniform(camera, p_uniforms);
  16480. } else {
  16481. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  16482. }
  16483. if (capabilities.logarithmicDepthBuffer) {
  16484. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  16485. }
  16486. if (_currentCamera !== camera) {
  16487. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  16488. // now, in case this material supports lights - or later, when
  16489. // the next material that does gets activated:
  16490. refreshMaterial = true; // set to true on material change
  16491. refreshLights = true; // remains set until update done
  16492. } // load material specific uniforms
  16493. // (shader material also gets them for the sake of genericity)
  16494. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.envMap) {
  16495. var uCamPos = p_uniforms.map.cameraPosition;
  16496. if (uCamPos !== undefined) {
  16497. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  16498. }
  16499. }
  16500. if (material.isMeshPhongMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.skinning) {
  16501. if (program.numMultiviewViews > 0) {
  16502. multiview.updateCameraViewMatricesUniform(camera, p_uniforms);
  16503. } else {
  16504. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  16505. }
  16506. }
  16507. } // skinning uniforms must be set even if material didn't change
  16508. // auto-setting of texture unit for bone texture must go before other textures
  16509. // not sure why, but otherwise weird things happen
  16510. if (material.skinning) {
  16511. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  16512. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  16513. var skeleton = object.skeleton;
  16514. if (skeleton) {
  16515. var bones = skeleton.bones;
  16516. if (capabilities.floatVertexTextures) {
  16517. if (skeleton.boneTexture === undefined) {
  16518. // layout (1 matrix = 4 pixels)
  16519. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  16520. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  16521. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  16522. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  16523. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  16524. var size = Math.sqrt(bones.length * 4); // 4 pixels needed for 1 matrix
  16525. size = _Math.ceilPowerOfTwo(size);
  16526. size = Math.max(size, 4);
  16527. var boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  16528. boneMatrices.set(skeleton.boneMatrices); // copy current values
  16529. var boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  16530. skeleton.boneMatrices = boneMatrices;
  16531. skeleton.boneTexture = boneTexture;
  16532. skeleton.boneTextureSize = size;
  16533. }
  16534. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  16535. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  16536. } else {
  16537. p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
  16538. }
  16539. }
  16540. }
  16541. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  16542. materialProperties.receiveShadow = object.receiveShadow;
  16543. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  16544. }
  16545. if (refreshMaterial) {
  16546. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  16547. p_uniforms.setValue(_gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint);
  16548. if (materialProperties.needsLights) {
  16549. // the current material requires lighting info
  16550. // note: all lighting uniforms are always set correctly
  16551. // they simply reference the renderer's state for their
  16552. // values
  16553. //
  16554. // use the current material's .needsUpdate flags to set
  16555. // the GL state when required
  16556. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  16557. } // refresh uniforms common to several materials
  16558. if (fog && material.fog) {
  16559. refreshUniformsFog(m_uniforms, fog);
  16560. }
  16561. if (material.isMeshBasicMaterial) {
  16562. refreshUniformsCommon(m_uniforms, material);
  16563. } else if (material.isMeshLambertMaterial) {
  16564. refreshUniformsCommon(m_uniforms, material);
  16565. refreshUniformsLambert(m_uniforms, material);
  16566. } else if (material.isMeshPhongMaterial) {
  16567. refreshUniformsCommon(m_uniforms, material);
  16568. if (material.isMeshToonMaterial) {
  16569. refreshUniformsToon(m_uniforms, material);
  16570. } else {
  16571. refreshUniformsPhong(m_uniforms, material);
  16572. }
  16573. } else if (material.isMeshStandardMaterial) {
  16574. refreshUniformsCommon(m_uniforms, material);
  16575. if (material.isMeshPhysicalMaterial) {
  16576. refreshUniformsPhysical(m_uniforms, material);
  16577. } else {
  16578. refreshUniformsStandard(m_uniforms, material);
  16579. }
  16580. } else if (material.isMeshMatcapMaterial) {
  16581. refreshUniformsCommon(m_uniforms, material);
  16582. refreshUniformsMatcap(m_uniforms, material);
  16583. } else if (material.isMeshDepthMaterial) {
  16584. refreshUniformsCommon(m_uniforms, material);
  16585. refreshUniformsDepth(m_uniforms, material);
  16586. } else if (material.isMeshDistanceMaterial) {
  16587. refreshUniformsCommon(m_uniforms, material);
  16588. refreshUniformsDistance(m_uniforms, material);
  16589. } else if (material.isMeshNormalMaterial) {
  16590. refreshUniformsCommon(m_uniforms, material);
  16591. refreshUniformsNormal(m_uniforms, material);
  16592. } else if (material.isLineBasicMaterial) {
  16593. refreshUniformsLine(m_uniforms, material);
  16594. if (material.isLineDashedMaterial) {
  16595. refreshUniformsDash(m_uniforms, material);
  16596. }
  16597. } else if (material.isPointsMaterial) {
  16598. refreshUniformsPoints(m_uniforms, material);
  16599. } else if (material.isSpriteMaterial) {
  16600. refreshUniformsSprites(m_uniforms, material);
  16601. } else if (material.isShadowMaterial) {
  16602. m_uniforms.color.value.copy(material.color);
  16603. m_uniforms.opacity.value = material.opacity;
  16604. } // RectAreaLight Texture
  16605. // TODO (mrdoob): Find a nicer implementation
  16606. if (m_uniforms.ltc_1 !== undefined) m_uniforms.ltc_1.value = UniformsLib.LTC_1;
  16607. if (m_uniforms.ltc_2 !== undefined) m_uniforms.ltc_2.value = UniformsLib.LTC_2;
  16608. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  16609. }
  16610. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  16611. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  16612. material.uniformsNeedUpdate = false;
  16613. }
  16614. if (material.isSpriteMaterial) {
  16615. p_uniforms.setValue(_gl, 'center', object.center);
  16616. } // common matrices
  16617. if (program.numMultiviewViews > 0) {
  16618. multiview.updateObjectMatricesUniforms(object, camera, p_uniforms);
  16619. } else {
  16620. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  16621. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  16622. }
  16623. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  16624. return program;
  16625. } // Uniforms (refresh uniforms objects)
  16626. function refreshUniformsCommon(uniforms, material) {
  16627. uniforms.opacity.value = material.opacity;
  16628. if (material.color) {
  16629. uniforms.diffuse.value.copy(material.color);
  16630. }
  16631. if (material.emissive) {
  16632. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  16633. }
  16634. if (material.map) {
  16635. uniforms.map.value = material.map;
  16636. }
  16637. if (material.alphaMap) {
  16638. uniforms.alphaMap.value = material.alphaMap;
  16639. }
  16640. if (material.specularMap) {
  16641. uniforms.specularMap.value = material.specularMap;
  16642. }
  16643. if (material.envMap) {
  16644. uniforms.envMap.value = material.envMap; // don't flip CubeTexture envMaps, flip everything else:
  16645. // WebGLRenderTargetCube will be flipped for backwards compatibility
  16646. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  16647. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  16648. uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? -1 : 1;
  16649. uniforms.reflectivity.value = material.reflectivity;
  16650. uniforms.refractionRatio.value = material.refractionRatio;
  16651. uniforms.maxMipLevel.value = properties.get(material.envMap).__maxMipLevel;
  16652. }
  16653. if (material.lightMap) {
  16654. uniforms.lightMap.value = material.lightMap;
  16655. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  16656. }
  16657. if (material.aoMap) {
  16658. uniforms.aoMap.value = material.aoMap;
  16659. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  16660. } // uv repeat and offset setting priorities
  16661. // 1. color map
  16662. // 2. specular map
  16663. // 3. normal map
  16664. // 4. bump map
  16665. // 5. alpha map
  16666. // 6. emissive map
  16667. var uvScaleMap;
  16668. if (material.map) {
  16669. uvScaleMap = material.map;
  16670. } else if (material.specularMap) {
  16671. uvScaleMap = material.specularMap;
  16672. } else if (material.displacementMap) {
  16673. uvScaleMap = material.displacementMap;
  16674. } else if (material.normalMap) {
  16675. uvScaleMap = material.normalMap;
  16676. } else if (material.bumpMap) {
  16677. uvScaleMap = material.bumpMap;
  16678. } else if (material.roughnessMap) {
  16679. uvScaleMap = material.roughnessMap;
  16680. } else if (material.metalnessMap) {
  16681. uvScaleMap = material.metalnessMap;
  16682. } else if (material.alphaMap) {
  16683. uvScaleMap = material.alphaMap;
  16684. } else if (material.emissiveMap) {
  16685. uvScaleMap = material.emissiveMap;
  16686. }
  16687. if (uvScaleMap !== undefined) {
  16688. // backwards compatibility
  16689. if (uvScaleMap.isWebGLRenderTarget) {
  16690. uvScaleMap = uvScaleMap.texture;
  16691. }
  16692. if (uvScaleMap.matrixAutoUpdate === true) {
  16693. uvScaleMap.updateMatrix();
  16694. }
  16695. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  16696. }
  16697. }
  16698. function refreshUniformsLine(uniforms, material) {
  16699. uniforms.diffuse.value.copy(material.color);
  16700. uniforms.opacity.value = material.opacity;
  16701. }
  16702. function refreshUniformsDash(uniforms, material) {
  16703. uniforms.dashSize.value = material.dashSize;
  16704. uniforms.totalSize.value = material.dashSize + material.gapSize;
  16705. uniforms.scale.value = material.scale;
  16706. }
  16707. function refreshUniformsPoints(uniforms, material) {
  16708. uniforms.diffuse.value.copy(material.color);
  16709. uniforms.opacity.value = material.opacity;
  16710. uniforms.size.value = material.size * _pixelRatio;
  16711. uniforms.scale.value = _height * 0.5;
  16712. uniforms.map.value = material.map;
  16713. if (material.map !== null) {
  16714. if (material.map.matrixAutoUpdate === true) {
  16715. material.map.updateMatrix();
  16716. }
  16717. uniforms.uvTransform.value.copy(material.map.matrix);
  16718. }
  16719. }
  16720. function refreshUniformsSprites(uniforms, material) {
  16721. uniforms.diffuse.value.copy(material.color);
  16722. uniforms.opacity.value = material.opacity;
  16723. uniforms.rotation.value = material.rotation;
  16724. uniforms.map.value = material.map;
  16725. if (material.map !== null) {
  16726. if (material.map.matrixAutoUpdate === true) {
  16727. material.map.updateMatrix();
  16728. }
  16729. uniforms.uvTransform.value.copy(material.map.matrix);
  16730. }
  16731. }
  16732. function refreshUniformsFog(uniforms, fog) {
  16733. uniforms.fogColor.value.copy(fog.color);
  16734. if (fog.isFog) {
  16735. uniforms.fogNear.value = fog.near;
  16736. uniforms.fogFar.value = fog.far;
  16737. } else if (fog.isFogExp2) {
  16738. uniforms.fogDensity.value = fog.density;
  16739. }
  16740. }
  16741. function refreshUniformsLambert(uniforms, material) {
  16742. if (material.emissiveMap) {
  16743. uniforms.emissiveMap.value = material.emissiveMap;
  16744. }
  16745. }
  16746. function refreshUniformsPhong(uniforms, material) {
  16747. uniforms.specular.value.copy(material.specular);
  16748. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  16749. if (material.emissiveMap) {
  16750. uniforms.emissiveMap.value = material.emissiveMap;
  16751. }
  16752. if (material.bumpMap) {
  16753. uniforms.bumpMap.value = material.bumpMap;
  16754. uniforms.bumpScale.value = material.bumpScale;
  16755. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  16756. }
  16757. if (material.normalMap) {
  16758. uniforms.normalMap.value = material.normalMap;
  16759. uniforms.normalScale.value.copy(material.normalScale);
  16760. if (material.side === BackSide) uniforms.normalScale.value.negate();
  16761. }
  16762. if (material.displacementMap) {
  16763. uniforms.displacementMap.value = material.displacementMap;
  16764. uniforms.displacementScale.value = material.displacementScale;
  16765. uniforms.displacementBias.value = material.displacementBias;
  16766. }
  16767. }
  16768. function refreshUniformsToon(uniforms, material) {
  16769. refreshUniformsPhong(uniforms, material);
  16770. if (material.gradientMap) {
  16771. uniforms.gradientMap.value = material.gradientMap;
  16772. }
  16773. }
  16774. function refreshUniformsStandard(uniforms, material) {
  16775. uniforms.roughness.value = material.roughness;
  16776. uniforms.metalness.value = material.metalness;
  16777. if (material.roughnessMap) {
  16778. uniforms.roughnessMap.value = material.roughnessMap;
  16779. }
  16780. if (material.metalnessMap) {
  16781. uniforms.metalnessMap.value = material.metalnessMap;
  16782. }
  16783. if (material.emissiveMap) {
  16784. uniforms.emissiveMap.value = material.emissiveMap;
  16785. }
  16786. if (material.bumpMap) {
  16787. uniforms.bumpMap.value = material.bumpMap;
  16788. uniforms.bumpScale.value = material.bumpScale;
  16789. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  16790. }
  16791. if (material.normalMap) {
  16792. uniforms.normalMap.value = material.normalMap;
  16793. uniforms.normalScale.value.copy(material.normalScale);
  16794. if (material.side === BackSide) uniforms.normalScale.value.negate();
  16795. }
  16796. if (material.displacementMap) {
  16797. uniforms.displacementMap.value = material.displacementMap;
  16798. uniforms.displacementScale.value = material.displacementScale;
  16799. uniforms.displacementBias.value = material.displacementBias;
  16800. }
  16801. if (material.envMap) {
  16802. //uniforms.envMap.value = material.envMap; // part of uniforms common
  16803. uniforms.envMapIntensity.value = material.envMapIntensity;
  16804. }
  16805. }
  16806. function refreshUniformsPhysical(uniforms, material) {
  16807. refreshUniformsStandard(uniforms, material);
  16808. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  16809. uniforms.clearcoat.value = material.clearcoat;
  16810. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  16811. if (material.sheen) uniforms.sheen.value.copy(material.sheen);
  16812. if (material.clearcoatNormalMap) {
  16813. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  16814. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  16815. if (material.side === BackSide) {
  16816. uniforms.clearcoatNormalScale.value.negate();
  16817. }
  16818. }
  16819. uniforms.transparency.value = material.transparency;
  16820. }
  16821. function refreshUniformsMatcap(uniforms, material) {
  16822. if (material.matcap) {
  16823. uniforms.matcap.value = material.matcap;
  16824. }
  16825. if (material.bumpMap) {
  16826. uniforms.bumpMap.value = material.bumpMap;
  16827. uniforms.bumpScale.value = material.bumpScale;
  16828. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  16829. }
  16830. if (material.normalMap) {
  16831. uniforms.normalMap.value = material.normalMap;
  16832. uniforms.normalScale.value.copy(material.normalScale);
  16833. if (material.side === BackSide) uniforms.normalScale.value.negate();
  16834. }
  16835. if (material.displacementMap) {
  16836. uniforms.displacementMap.value = material.displacementMap;
  16837. uniforms.displacementScale.value = material.displacementScale;
  16838. uniforms.displacementBias.value = material.displacementBias;
  16839. }
  16840. }
  16841. function refreshUniformsDepth(uniforms, material) {
  16842. if (material.displacementMap) {
  16843. uniforms.displacementMap.value = material.displacementMap;
  16844. uniforms.displacementScale.value = material.displacementScale;
  16845. uniforms.displacementBias.value = material.displacementBias;
  16846. }
  16847. }
  16848. function refreshUniformsDistance(uniforms, material) {
  16849. if (material.displacementMap) {
  16850. uniforms.displacementMap.value = material.displacementMap;
  16851. uniforms.displacementScale.value = material.displacementScale;
  16852. uniforms.displacementBias.value = material.displacementBias;
  16853. }
  16854. uniforms.referencePosition.value.copy(material.referencePosition);
  16855. uniforms.nearDistance.value = material.nearDistance;
  16856. uniforms.farDistance.value = material.farDistance;
  16857. }
  16858. function refreshUniformsNormal(uniforms, material) {
  16859. if (material.bumpMap) {
  16860. uniforms.bumpMap.value = material.bumpMap;
  16861. uniforms.bumpScale.value = material.bumpScale;
  16862. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  16863. }
  16864. if (material.normalMap) {
  16865. uniforms.normalMap.value = material.normalMap;
  16866. uniforms.normalScale.value.copy(material.normalScale);
  16867. if (material.side === BackSide) uniforms.normalScale.value.negate();
  16868. }
  16869. if (material.displacementMap) {
  16870. uniforms.displacementMap.value = material.displacementMap;
  16871. uniforms.displacementScale.value = material.displacementScale;
  16872. uniforms.displacementBias.value = material.displacementBias;
  16873. }
  16874. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  16875. function markUniformsLightsNeedsUpdate(uniforms, value) {
  16876. uniforms.ambientLightColor.needsUpdate = value;
  16877. uniforms.lightProbe.needsUpdate = value;
  16878. uniforms.directionalLights.needsUpdate = value;
  16879. uniforms.pointLights.needsUpdate = value;
  16880. uniforms.spotLights.needsUpdate = value;
  16881. uniforms.rectAreaLights.needsUpdate = value;
  16882. uniforms.hemisphereLights.needsUpdate = value;
  16883. }
  16884. function materialNeedsLights(material) {
  16885. return material.isMeshLambertMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  16886. } //
  16887. this.setFramebuffer = function (value) {
  16888. if (_framebuffer !== value) _gl.bindFramebuffer(36160, value);
  16889. _framebuffer = value;
  16890. };
  16891. this.getActiveCubeFace = function () {
  16892. return _currentActiveCubeFace;
  16893. };
  16894. this.getActiveMipmapLevel = function () {
  16895. return _currentActiveMipmapLevel;
  16896. };
  16897. this.getRenderTarget = function () {
  16898. return _currentRenderTarget;
  16899. };
  16900. this.setRenderTarget = function (renderTarget, activeCubeFace, activeMipmapLevel) {
  16901. _currentRenderTarget = renderTarget;
  16902. _currentActiveCubeFace = activeCubeFace;
  16903. _currentActiveMipmapLevel = activeMipmapLevel;
  16904. if (renderTarget && properties.get(renderTarget).__webglFramebuffer === undefined) {
  16905. textures.setupRenderTarget(renderTarget);
  16906. }
  16907. var framebuffer = _framebuffer;
  16908. var isCube = false;
  16909. if (renderTarget) {
  16910. var __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  16911. if (renderTarget.isWebGLRenderTargetCube) {
  16912. framebuffer = __webglFramebuffer[activeCubeFace || 0];
  16913. isCube = true;
  16914. } else if (renderTarget.isWebGLMultisampleRenderTarget) {
  16915. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  16916. } else {
  16917. framebuffer = __webglFramebuffer;
  16918. }
  16919. _currentViewport.copy(renderTarget.viewport);
  16920. _currentScissor.copy(renderTarget.scissor);
  16921. _currentScissorTest = renderTarget.scissorTest;
  16922. } else {
  16923. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  16924. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  16925. _currentScissorTest = _scissorTest;
  16926. }
  16927. if (_currentFramebuffer !== framebuffer) {
  16928. _gl.bindFramebuffer(36160, framebuffer);
  16929. _currentFramebuffer = framebuffer;
  16930. }
  16931. state.viewport(_currentViewport);
  16932. state.scissor(_currentScissor);
  16933. state.setScissorTest(_currentScissorTest);
  16934. if (isCube) {
  16935. var textureProperties = properties.get(renderTarget.texture);
  16936. _gl.framebufferTexture2D(36160, 36064, 34069 + (activeCubeFace || 0), textureProperties.__webglTexture, activeMipmapLevel || 0);
  16937. }
  16938. };
  16939. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  16940. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  16941. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  16942. return;
  16943. }
  16944. var framebuffer = properties.get(renderTarget).__webglFramebuffer;
  16945. if (renderTarget.isWebGLRenderTargetCube && activeCubeFaceIndex !== undefined) {
  16946. framebuffer = framebuffer[activeCubeFaceIndex];
  16947. }
  16948. if (framebuffer) {
  16949. var restore = false;
  16950. if (framebuffer !== _currentFramebuffer) {
  16951. _gl.bindFramebuffer(36160, framebuffer);
  16952. restore = true;
  16953. }
  16954. try {
  16955. var texture = renderTarget.texture;
  16956. var textureFormat = texture.format;
  16957. var textureType = texture.type;
  16958. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(35739)) {
  16959. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  16960. return;
  16961. }
  16962. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(35738) && // IE11, Edge and Chrome Mac < 52 (#9513)
  16963. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.get('OES_texture_float') || extensions.get('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  16964. !(textureType === HalfFloatType && (capabilities.isWebGL2 ? extensions.get('EXT_color_buffer_float') : extensions.get('EXT_color_buffer_half_float')))) {
  16965. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  16966. return;
  16967. }
  16968. if (_gl.checkFramebufferStatus(36160) === 36053) {
  16969. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  16970. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  16971. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  16972. }
  16973. } else {
  16974. console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
  16975. }
  16976. } finally {
  16977. if (restore) {
  16978. _gl.bindFramebuffer(36160, _currentFramebuffer);
  16979. }
  16980. }
  16981. }
  16982. };
  16983. this.copyFramebufferToTexture = function (position, texture, level) {
  16984. var width = texture.image.width;
  16985. var height = texture.image.height;
  16986. var glFormat = utils.convert(texture.format);
  16987. textures.setTexture2D(texture, 0);
  16988. _gl.copyTexImage2D(3553, level || 0, glFormat, position.x, position.y, width, height, 0);
  16989. };
  16990. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level) {
  16991. var width = srcTexture.image.width;
  16992. var height = srcTexture.image.height;
  16993. var glFormat = utils.convert(dstTexture.format);
  16994. var glType = utils.convert(dstTexture.type);
  16995. textures.setTexture2D(dstTexture, 0);
  16996. if (srcTexture.isDataTexture) {
  16997. _gl.texSubImage2D(3553, level || 0, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  16998. } else {
  16999. _gl.texSubImage2D(3553, level || 0, position.x, position.y, glFormat, glType, srcTexture.image);
  17000. }
  17001. };
  17002. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  17003. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  17004. detail: this
  17005. })); // eslint-disable-line no-undef
  17006. }
  17007. }
  17008. /**
  17009. * @author mrdoob / http://mrdoob.com/
  17010. * @author alteredq / http://alteredqualia.com/
  17011. */
  17012. function FogExp2(color, density) {
  17013. this.name = '';
  17014. this.color = new Color(color);
  17015. this.density = density !== undefined ? density : 0.00025;
  17016. }
  17017. Object.assign(FogExp2.prototype, {
  17018. isFogExp2: true,
  17019. clone: function () {
  17020. return new FogExp2(this.color, this.density);
  17021. },
  17022. toJSON: function ()
  17023. /* meta */
  17024. {
  17025. return {
  17026. type: 'FogExp2',
  17027. color: this.color.getHex(),
  17028. density: this.density
  17029. };
  17030. }
  17031. });
  17032. /**
  17033. * @author mrdoob / http://mrdoob.com/
  17034. * @author alteredq / http://alteredqualia.com/
  17035. */
  17036. function Fog(color, near, far) {
  17037. this.name = '';
  17038. this.color = new Color(color);
  17039. this.near = near !== undefined ? near : 1;
  17040. this.far = far !== undefined ? far : 1000;
  17041. }
  17042. Object.assign(Fog.prototype, {
  17043. isFog: true,
  17044. clone: function () {
  17045. return new Fog(this.color, this.near, this.far);
  17046. },
  17047. toJSON: function ()
  17048. /* meta */
  17049. {
  17050. return {
  17051. type: 'Fog',
  17052. color: this.color.getHex(),
  17053. near: this.near,
  17054. far: this.far
  17055. };
  17056. }
  17057. });
  17058. /**
  17059. * @author benaadams / https://twitter.com/ben_a_adams
  17060. */
  17061. function InterleavedBuffer(array, stride) {
  17062. this.array = array;
  17063. this.stride = stride;
  17064. this.count = array !== undefined ? array.length / stride : 0;
  17065. this.dynamic = false;
  17066. this.updateRange = {
  17067. offset: 0,
  17068. count: -1
  17069. };
  17070. this.version = 0;
  17071. }
  17072. Object.defineProperty(InterleavedBuffer.prototype, 'needsUpdate', {
  17073. set: function (value) {
  17074. if (value === true) this.version++;
  17075. }
  17076. });
  17077. Object.assign(InterleavedBuffer.prototype, {
  17078. isInterleavedBuffer: true,
  17079. onUploadCallback: function () {},
  17080. setDynamic: function (value) {
  17081. this.dynamic = value;
  17082. return this;
  17083. },
  17084. copy: function (source) {
  17085. this.array = new source.array.constructor(source.array);
  17086. this.count = source.count;
  17087. this.stride = source.stride;
  17088. this.dynamic = source.dynamic;
  17089. return this;
  17090. },
  17091. copyAt: function (index1, attribute, index2) {
  17092. index1 *= this.stride;
  17093. index2 *= attribute.stride;
  17094. for (var i = 0, l = this.stride; i < l; i++) {
  17095. this.array[index1 + i] = attribute.array[index2 + i];
  17096. }
  17097. return this;
  17098. },
  17099. set: function (value, offset) {
  17100. if (offset === undefined) offset = 0;
  17101. this.array.set(value, offset);
  17102. return this;
  17103. },
  17104. clone: function () {
  17105. return new this.constructor().copy(this);
  17106. },
  17107. onUpload: function (callback) {
  17108. this.onUploadCallback = callback;
  17109. return this;
  17110. }
  17111. });
  17112. /**
  17113. * @author benaadams / https://twitter.com/ben_a_adams
  17114. */
  17115. function InterleavedBufferAttribute(interleavedBuffer, itemSize, offset, normalized) {
  17116. this.data = interleavedBuffer;
  17117. this.itemSize = itemSize;
  17118. this.offset = offset;
  17119. this.normalized = normalized === true;
  17120. }
  17121. Object.defineProperties(InterleavedBufferAttribute.prototype, {
  17122. count: {
  17123. get: function () {
  17124. return this.data.count;
  17125. }
  17126. },
  17127. array: {
  17128. get: function () {
  17129. return this.data.array;
  17130. }
  17131. }
  17132. });
  17133. Object.assign(InterleavedBufferAttribute.prototype, {
  17134. isInterleavedBufferAttribute: true,
  17135. setX: function (index, x) {
  17136. this.data.array[index * this.data.stride + this.offset] = x;
  17137. return this;
  17138. },
  17139. setY: function (index, y) {
  17140. this.data.array[index * this.data.stride + this.offset + 1] = y;
  17141. return this;
  17142. },
  17143. setZ: function (index, z) {
  17144. this.data.array[index * this.data.stride + this.offset + 2] = z;
  17145. return this;
  17146. },
  17147. setW: function (index, w) {
  17148. this.data.array[index * this.data.stride + this.offset + 3] = w;
  17149. return this;
  17150. },
  17151. getX: function (index) {
  17152. return this.data.array[index * this.data.stride + this.offset];
  17153. },
  17154. getY: function (index) {
  17155. return this.data.array[index * this.data.stride + this.offset + 1];
  17156. },
  17157. getZ: function (index) {
  17158. return this.data.array[index * this.data.stride + this.offset + 2];
  17159. },
  17160. getW: function (index) {
  17161. return this.data.array[index * this.data.stride + this.offset + 3];
  17162. },
  17163. setXY: function (index, x, y) {
  17164. index = index * this.data.stride + this.offset;
  17165. this.data.array[index + 0] = x;
  17166. this.data.array[index + 1] = y;
  17167. return this;
  17168. },
  17169. setXYZ: function (index, x, y, z) {
  17170. index = index * this.data.stride + this.offset;
  17171. this.data.array[index + 0] = x;
  17172. this.data.array[index + 1] = y;
  17173. this.data.array[index + 2] = z;
  17174. return this;
  17175. },
  17176. setXYZW: function (index, x, y, z, w) {
  17177. index = index * this.data.stride + this.offset;
  17178. this.data.array[index + 0] = x;
  17179. this.data.array[index + 1] = y;
  17180. this.data.array[index + 2] = z;
  17181. this.data.array[index + 3] = w;
  17182. return this;
  17183. }
  17184. });
  17185. /**
  17186. * @author alteredq / http://alteredqualia.com/
  17187. *
  17188. * parameters = {
  17189. * color: <hex>,
  17190. * map: new THREE.Texture( <Image> ),
  17191. * rotation: <float>,
  17192. * sizeAttenuation: <bool>
  17193. * }
  17194. */
  17195. function SpriteMaterial(parameters) {
  17196. Material.call(this);
  17197. this.type = 'SpriteMaterial';
  17198. this.color = new Color(0xffffff);
  17199. this.map = null;
  17200. this.rotation = 0;
  17201. this.sizeAttenuation = true;
  17202. this.transparent = true;
  17203. this.setValues(parameters);
  17204. }
  17205. SpriteMaterial.prototype = Object.create(Material.prototype);
  17206. SpriteMaterial.prototype.constructor = SpriteMaterial;
  17207. SpriteMaterial.prototype.isSpriteMaterial = true;
  17208. SpriteMaterial.prototype.copy = function (source) {
  17209. Material.prototype.copy.call(this, source);
  17210. this.color.copy(source.color);
  17211. this.map = source.map;
  17212. this.rotation = source.rotation;
  17213. this.sizeAttenuation = source.sizeAttenuation;
  17214. return this;
  17215. };
  17216. /**
  17217. * @author mikael emtinger / http://gomo.se/
  17218. * @author alteredq / http://alteredqualia.com/
  17219. */
  17220. var _geometry;
  17221. var _intersectPoint = new Vector3();
  17222. var _worldScale = new Vector3();
  17223. var _mvPosition = new Vector3();
  17224. var _alignedPosition = new Vector2();
  17225. var _rotatedPosition = new Vector2();
  17226. var _viewWorldMatrix = new Matrix4();
  17227. var _vA$1 = new Vector3();
  17228. var _vB$1 = new Vector3();
  17229. var _vC$1 = new Vector3();
  17230. var _uvA$1 = new Vector2();
  17231. var _uvB$1 = new Vector2();
  17232. var _uvC$1 = new Vector2();
  17233. function Sprite(material) {
  17234. Object3D.call(this);
  17235. this.type = 'Sprite';
  17236. if (_geometry === undefined) {
  17237. _geometry = new BufferGeometry();
  17238. 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]);
  17239. var interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  17240. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  17241. _geometry.addAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  17242. _geometry.addAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  17243. }
  17244. this.geometry = _geometry;
  17245. this.material = material !== undefined ? material : new SpriteMaterial();
  17246. this.center = new Vector2(0.5, 0.5);
  17247. }
  17248. Sprite.prototype = Object.assign(Object.create(Object3D.prototype), {
  17249. constructor: Sprite,
  17250. isSprite: true,
  17251. raycast: function (raycaster, intersects) {
  17252. if (raycaster.camera === null) {
  17253. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  17254. }
  17255. _worldScale.setFromMatrixScale(this.matrixWorld);
  17256. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  17257. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  17258. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  17259. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  17260. _worldScale.multiplyScalar(-_mvPosition.z);
  17261. }
  17262. var rotation = this.material.rotation;
  17263. var sin, cos;
  17264. if (rotation !== 0) {
  17265. cos = Math.cos(rotation);
  17266. sin = Math.sin(rotation);
  17267. }
  17268. var center = this.center;
  17269. transformVertex(_vA$1.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17270. transformVertex(_vB$1.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17271. transformVertex(_vC$1.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17272. _uvA$1.set(0, 0);
  17273. _uvB$1.set(1, 0);
  17274. _uvC$1.set(1, 1); // check first triangle
  17275. var intersect = raycaster.ray.intersectTriangle(_vA$1, _vB$1, _vC$1, false, _intersectPoint);
  17276. if (intersect === null) {
  17277. // check second triangle
  17278. transformVertex(_vB$1.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17279. _uvB$1.set(0, 1);
  17280. intersect = raycaster.ray.intersectTriangle(_vA$1, _vC$1, _vB$1, false, _intersectPoint);
  17281. if (intersect === null) {
  17282. return;
  17283. }
  17284. }
  17285. var distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  17286. if (distance < raycaster.near || distance > raycaster.far) return;
  17287. intersects.push({
  17288. distance: distance,
  17289. point: _intersectPoint.clone(),
  17290. uv: Triangle.getUV(_intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2()),
  17291. face: null,
  17292. object: this
  17293. });
  17294. },
  17295. clone: function () {
  17296. return new this.constructor(this.material).copy(this);
  17297. },
  17298. copy: function (source) {
  17299. Object3D.prototype.copy.call(this, source);
  17300. if (source.center !== undefined) this.center.copy(source.center);
  17301. return this;
  17302. }
  17303. });
  17304. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  17305. // compute position in camera space
  17306. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  17307. if (sin !== undefined) {
  17308. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  17309. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  17310. } else {
  17311. _rotatedPosition.copy(_alignedPosition);
  17312. }
  17313. vertexPosition.copy(mvPosition);
  17314. vertexPosition.x += _rotatedPosition.x;
  17315. vertexPosition.y += _rotatedPosition.y; // transform to world space
  17316. vertexPosition.applyMatrix4(_viewWorldMatrix);
  17317. }
  17318. /**
  17319. * @author mikael emtinger / http://gomo.se/
  17320. * @author alteredq / http://alteredqualia.com/
  17321. * @author mrdoob / http://mrdoob.com/
  17322. */
  17323. var _v1$4 = new Vector3();
  17324. var _v2$2 = new Vector3();
  17325. function LOD() {
  17326. Object3D.call(this);
  17327. this.type = 'LOD';
  17328. Object.defineProperties(this, {
  17329. levels: {
  17330. enumerable: true,
  17331. value: []
  17332. }
  17333. });
  17334. this.autoUpdate = true;
  17335. }
  17336. LOD.prototype = Object.assign(Object.create(Object3D.prototype), {
  17337. constructor: LOD,
  17338. isLOD: true,
  17339. copy: function (source) {
  17340. Object3D.prototype.copy.call(this, source, false);
  17341. var levels = source.levels;
  17342. for (var i = 0, l = levels.length; i < l; i++) {
  17343. var level = levels[i];
  17344. this.addLevel(level.object.clone(), level.distance);
  17345. }
  17346. return this;
  17347. },
  17348. addLevel: function (object, distance) {
  17349. if (distance === undefined) distance = 0;
  17350. distance = Math.abs(distance);
  17351. var levels = this.levels;
  17352. for (var l = 0; l < levels.length; l++) {
  17353. if (distance < levels[l].distance) {
  17354. break;
  17355. }
  17356. }
  17357. levels.splice(l, 0, {
  17358. distance: distance,
  17359. object: object
  17360. });
  17361. this.add(object);
  17362. return this;
  17363. },
  17364. getObjectForDistance: function (distance) {
  17365. var levels = this.levels;
  17366. for (var i = 1, l = levels.length; i < l; i++) {
  17367. if (distance < levels[i].distance) {
  17368. break;
  17369. }
  17370. }
  17371. return levels[i - 1].object;
  17372. },
  17373. raycast: function (raycaster, intersects) {
  17374. _v1$4.setFromMatrixPosition(this.matrixWorld);
  17375. var distance = raycaster.ray.origin.distanceTo(_v1$4);
  17376. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  17377. },
  17378. update: function (camera) {
  17379. var levels = this.levels;
  17380. if (levels.length > 1) {
  17381. _v1$4.setFromMatrixPosition(camera.matrixWorld);
  17382. _v2$2.setFromMatrixPosition(this.matrixWorld);
  17383. var distance = _v1$4.distanceTo(_v2$2);
  17384. levels[0].object.visible = true;
  17385. for (var i = 1, l = levels.length; i < l; i++) {
  17386. if (distance >= levels[i].distance) {
  17387. levels[i - 1].object.visible = false;
  17388. levels[i].object.visible = true;
  17389. } else {
  17390. break;
  17391. }
  17392. }
  17393. for (; i < l; i++) {
  17394. levels[i].object.visible = false;
  17395. }
  17396. }
  17397. },
  17398. toJSON: function (meta) {
  17399. var data = Object3D.prototype.toJSON.call(this, meta);
  17400. data.object.levels = [];
  17401. var levels = this.levels;
  17402. for (var i = 0, l = levels.length; i < l; i++) {
  17403. var level = levels[i];
  17404. data.object.levels.push({
  17405. object: level.object.uuid,
  17406. distance: level.distance
  17407. });
  17408. }
  17409. return data;
  17410. }
  17411. });
  17412. /**
  17413. * @author mikael emtinger / http://gomo.se/
  17414. * @author alteredq / http://alteredqualia.com/
  17415. * @author ikerr / http://verold.com
  17416. */
  17417. function SkinnedMesh(geometry, material) {
  17418. if (geometry && geometry.isGeometry) {
  17419. console.error('THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17420. }
  17421. Mesh.call(this, geometry, material);
  17422. this.type = 'SkinnedMesh';
  17423. this.bindMode = 'attached';
  17424. this.bindMatrix = new Matrix4();
  17425. this.bindMatrixInverse = new Matrix4();
  17426. }
  17427. SkinnedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
  17428. constructor: SkinnedMesh,
  17429. isSkinnedMesh: true,
  17430. bind: function (skeleton, bindMatrix) {
  17431. this.skeleton = skeleton;
  17432. if (bindMatrix === undefined) {
  17433. this.updateMatrixWorld(true);
  17434. this.skeleton.calculateInverses();
  17435. bindMatrix = this.matrixWorld;
  17436. }
  17437. this.bindMatrix.copy(bindMatrix);
  17438. this.bindMatrixInverse.getInverse(bindMatrix);
  17439. },
  17440. pose: function () {
  17441. this.skeleton.pose();
  17442. },
  17443. normalizeSkinWeights: function () {
  17444. var vector = new Vector4();
  17445. var skinWeight = this.geometry.attributes.skinWeight;
  17446. for (var i = 0, l = skinWeight.count; i < l; i++) {
  17447. vector.x = skinWeight.getX(i);
  17448. vector.y = skinWeight.getY(i);
  17449. vector.z = skinWeight.getZ(i);
  17450. vector.w = skinWeight.getW(i);
  17451. var scale = 1.0 / vector.manhattanLength();
  17452. if (scale !== Infinity) {
  17453. vector.multiplyScalar(scale);
  17454. } else {
  17455. vector.set(1, 0, 0, 0); // do something reasonable
  17456. }
  17457. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  17458. }
  17459. },
  17460. updateMatrixWorld: function (force) {
  17461. Mesh.prototype.updateMatrixWorld.call(this, force);
  17462. if (this.bindMode === 'attached') {
  17463. this.bindMatrixInverse.getInverse(this.matrixWorld);
  17464. } else if (this.bindMode === 'detached') {
  17465. this.bindMatrixInverse.getInverse(this.bindMatrix);
  17466. } else {
  17467. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  17468. }
  17469. },
  17470. clone: function () {
  17471. return new this.constructor(this.geometry, this.material).copy(this);
  17472. }
  17473. });
  17474. /**
  17475. * @author mikael emtinger / http://gomo.se/
  17476. * @author alteredq / http://alteredqualia.com/
  17477. * @author michael guerrero / http://realitymeltdown.com
  17478. * @author ikerr / http://verold.com
  17479. */
  17480. var _offsetMatrix = new Matrix4();
  17481. var _identityMatrix = new Matrix4();
  17482. function Skeleton(bones, boneInverses) {
  17483. // copy the bone array
  17484. bones = bones || [];
  17485. this.bones = bones.slice(0);
  17486. this.boneMatrices = new Float32Array(this.bones.length * 16);
  17487. this.frame = -1; // use the supplied bone inverses or calculate the inverses
  17488. if (boneInverses === undefined) {
  17489. this.calculateInverses();
  17490. } else {
  17491. if (this.bones.length === boneInverses.length) {
  17492. this.boneInverses = boneInverses.slice(0);
  17493. } else {
  17494. console.warn('THREE.Skeleton boneInverses is the wrong length.');
  17495. this.boneInverses = [];
  17496. for (var i = 0, il = this.bones.length; i < il; i++) {
  17497. this.boneInverses.push(new Matrix4());
  17498. }
  17499. }
  17500. }
  17501. }
  17502. Object.assign(Skeleton.prototype, {
  17503. calculateInverses: function () {
  17504. this.boneInverses = [];
  17505. for (var i = 0, il = this.bones.length; i < il; i++) {
  17506. var inverse = new Matrix4();
  17507. if (this.bones[i]) {
  17508. inverse.getInverse(this.bones[i].matrixWorld);
  17509. }
  17510. this.boneInverses.push(inverse);
  17511. }
  17512. },
  17513. pose: function () {
  17514. var bone, i, il; // recover the bind-time world matrices
  17515. for (i = 0, il = this.bones.length; i < il; i++) {
  17516. bone = this.bones[i];
  17517. if (bone) {
  17518. bone.matrixWorld.getInverse(this.boneInverses[i]);
  17519. }
  17520. } // compute the local matrices, positions, rotations and scales
  17521. for (i = 0, il = this.bones.length; i < il; i++) {
  17522. bone = this.bones[i];
  17523. if (bone) {
  17524. if (bone.parent && bone.parent.isBone) {
  17525. bone.matrix.getInverse(bone.parent.matrixWorld);
  17526. bone.matrix.multiply(bone.matrixWorld);
  17527. } else {
  17528. bone.matrix.copy(bone.matrixWorld);
  17529. }
  17530. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  17531. }
  17532. }
  17533. },
  17534. update: function () {
  17535. var bones = this.bones;
  17536. var boneInverses = this.boneInverses;
  17537. var boneMatrices = this.boneMatrices;
  17538. var boneTexture = this.boneTexture; // flatten bone matrices to array
  17539. for (var i = 0, il = bones.length; i < il; i++) {
  17540. // compute the offset between the current and the original transform
  17541. var matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  17542. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  17543. _offsetMatrix.toArray(boneMatrices, i * 16);
  17544. }
  17545. if (boneTexture !== undefined) {
  17546. boneTexture.needsUpdate = true;
  17547. }
  17548. },
  17549. clone: function () {
  17550. return new Skeleton(this.bones, this.boneInverses);
  17551. },
  17552. getBoneByName: function (name) {
  17553. for (var i = 0, il = this.bones.length; i < il; i++) {
  17554. var bone = this.bones[i];
  17555. if (bone.name === name) {
  17556. return bone;
  17557. }
  17558. }
  17559. return undefined;
  17560. }
  17561. });
  17562. /**
  17563. * @author mikael emtinger / http://gomo.se/
  17564. * @author alteredq / http://alteredqualia.com/
  17565. * @author ikerr / http://verold.com
  17566. */
  17567. function Bone() {
  17568. Object3D.call(this);
  17569. this.type = 'Bone';
  17570. }
  17571. Bone.prototype = Object.assign(Object.create(Object3D.prototype), {
  17572. constructor: Bone,
  17573. isBone: true
  17574. });
  17575. /**
  17576. * @author mrdoob / http://mrdoob.com/
  17577. */
  17578. function InstancedMesh(geometry, material, count) {
  17579. Mesh.call(this, geometry, material);
  17580. this.instanceMatrix = new BufferAttribute(new Float32Array(count * 16), 16);
  17581. this.count = count;
  17582. }
  17583. InstancedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
  17584. constructor: InstancedMesh,
  17585. isInstancedMesh: true,
  17586. raycast: function () {},
  17587. setMatrixAt: function (index, matrix) {
  17588. matrix.toArray(this.instanceMatrix.array, index * 16);
  17589. },
  17590. updateMorphTargets: function () {}
  17591. });
  17592. /**
  17593. * @author mrdoob / http://mrdoob.com/
  17594. * @author alteredq / http://alteredqualia.com/
  17595. *
  17596. * parameters = {
  17597. * color: <hex>,
  17598. * opacity: <float>,
  17599. *
  17600. * linewidth: <float>,
  17601. * linecap: "round",
  17602. * linejoin: "round"
  17603. * }
  17604. */
  17605. function LineBasicMaterial(parameters) {
  17606. Material.call(this);
  17607. this.type = 'LineBasicMaterial';
  17608. this.color = new Color(0xffffff);
  17609. this.linewidth = 1;
  17610. this.linecap = 'round';
  17611. this.linejoin = 'round';
  17612. this.setValues(parameters);
  17613. }
  17614. LineBasicMaterial.prototype = Object.create(Material.prototype);
  17615. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  17616. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  17617. LineBasicMaterial.prototype.copy = function (source) {
  17618. Material.prototype.copy.call(this, source);
  17619. this.color.copy(source.color);
  17620. this.linewidth = source.linewidth;
  17621. this.linecap = source.linecap;
  17622. this.linejoin = source.linejoin;
  17623. return this;
  17624. };
  17625. /**
  17626. * @author mrdoob / http://mrdoob.com/
  17627. */
  17628. var _start = new Vector3();
  17629. var _end = new Vector3();
  17630. var _inverseMatrix$1 = new Matrix4();
  17631. var _ray$1 = new Ray();
  17632. var _sphere$2 = new Sphere();
  17633. function Line(geometry, material, mode) {
  17634. if (mode === 1) {
  17635. console.error('THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.');
  17636. }
  17637. Object3D.call(this);
  17638. this.type = 'Line';
  17639. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  17640. this.material = material !== undefined ? material : new LineBasicMaterial({
  17641. color: Math.random() * 0xffffff
  17642. });
  17643. }
  17644. Line.prototype = Object.assign(Object.create(Object3D.prototype), {
  17645. constructor: Line,
  17646. isLine: true,
  17647. computeLineDistances: function () {
  17648. var geometry = this.geometry;
  17649. if (geometry.isBufferGeometry) {
  17650. // we assume non-indexed geometry
  17651. if (geometry.index === null) {
  17652. var positionAttribute = geometry.attributes.position;
  17653. var lineDistances = [0];
  17654. for (var i = 1, l = positionAttribute.count; i < l; i++) {
  17655. _start.fromBufferAttribute(positionAttribute, i - 1);
  17656. _end.fromBufferAttribute(positionAttribute, i);
  17657. lineDistances[i] = lineDistances[i - 1];
  17658. lineDistances[i] += _start.distanceTo(_end);
  17659. }
  17660. geometry.addAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  17661. } else {
  17662. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  17663. }
  17664. } else if (geometry.isGeometry) {
  17665. var vertices = geometry.vertices;
  17666. var lineDistances = geometry.lineDistances;
  17667. lineDistances[0] = 0;
  17668. for (var i = 1, l = vertices.length; i < l; i++) {
  17669. lineDistances[i] = lineDistances[i - 1];
  17670. lineDistances[i] += vertices[i - 1].distanceTo(vertices[i]);
  17671. }
  17672. }
  17673. return this;
  17674. },
  17675. raycast: function (raycaster, intersects) {
  17676. var precision = raycaster.linePrecision;
  17677. var geometry = this.geometry;
  17678. var matrixWorld = this.matrixWorld; // Checking boundingSphere distance to ray
  17679. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  17680. _sphere$2.copy(geometry.boundingSphere);
  17681. _sphere$2.applyMatrix4(matrixWorld);
  17682. _sphere$2.radius += precision;
  17683. if (raycaster.ray.intersectsSphere(_sphere$2) === false) return; //
  17684. _inverseMatrix$1.getInverse(matrixWorld);
  17685. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  17686. var localPrecision = precision / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  17687. var localPrecisionSq = localPrecision * localPrecision;
  17688. var vStart = new Vector3();
  17689. var vEnd = new Vector3();
  17690. var interSegment = new Vector3();
  17691. var interRay = new Vector3();
  17692. var step = this && this.isLineSegments ? 2 : 1;
  17693. if (geometry.isBufferGeometry) {
  17694. var index = geometry.index;
  17695. var attributes = geometry.attributes;
  17696. var positions = attributes.position.array;
  17697. if (index !== null) {
  17698. var indices = index.array;
  17699. for (var i = 0, l = indices.length - 1; i < l; i += step) {
  17700. var a = indices[i];
  17701. var b = indices[i + 1];
  17702. vStart.fromArray(positions, a * 3);
  17703. vEnd.fromArray(positions, b * 3);
  17704. var distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  17705. if (distSq > localPrecisionSq) continue;
  17706. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  17707. var distance = raycaster.ray.origin.distanceTo(interRay);
  17708. if (distance < raycaster.near || distance > raycaster.far) continue;
  17709. intersects.push({
  17710. distance: distance,
  17711. // What do we want? intersection point on the ray or on the segment??
  17712. // point: raycaster.ray.at( distance ),
  17713. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  17714. index: i,
  17715. face: null,
  17716. faceIndex: null,
  17717. object: this
  17718. });
  17719. }
  17720. } else {
  17721. for (var i = 0, l = positions.length / 3 - 1; i < l; i += step) {
  17722. vStart.fromArray(positions, 3 * i);
  17723. vEnd.fromArray(positions, 3 * i + 3);
  17724. var distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  17725. if (distSq > localPrecisionSq) continue;
  17726. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  17727. var distance = raycaster.ray.origin.distanceTo(interRay);
  17728. if (distance < raycaster.near || distance > raycaster.far) continue;
  17729. intersects.push({
  17730. distance: distance,
  17731. // What do we want? intersection point on the ray or on the segment??
  17732. // point: raycaster.ray.at( distance ),
  17733. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  17734. index: i,
  17735. face: null,
  17736. faceIndex: null,
  17737. object: this
  17738. });
  17739. }
  17740. }
  17741. } else if (geometry.isGeometry) {
  17742. var vertices = geometry.vertices;
  17743. var nbVertices = vertices.length;
  17744. for (var i = 0; i < nbVertices - 1; i += step) {
  17745. var distSq = _ray$1.distanceSqToSegment(vertices[i], vertices[i + 1], interRay, interSegment);
  17746. if (distSq > localPrecisionSq) continue;
  17747. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  17748. var distance = raycaster.ray.origin.distanceTo(interRay);
  17749. if (distance < raycaster.near || distance > raycaster.far) continue;
  17750. intersects.push({
  17751. distance: distance,
  17752. // What do we want? intersection point on the ray or on the segment??
  17753. // point: raycaster.ray.at( distance ),
  17754. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  17755. index: i,
  17756. face: null,
  17757. faceIndex: null,
  17758. object: this
  17759. });
  17760. }
  17761. }
  17762. },
  17763. clone: function () {
  17764. return new this.constructor(this.geometry, this.material).copy(this);
  17765. }
  17766. });
  17767. /**
  17768. * @author mrdoob / http://mrdoob.com/
  17769. */
  17770. var _start$1 = new Vector3();
  17771. var _end$1 = new Vector3();
  17772. function LineSegments(geometry, material) {
  17773. Line.call(this, geometry, material);
  17774. this.type = 'LineSegments';
  17775. }
  17776. LineSegments.prototype = Object.assign(Object.create(Line.prototype), {
  17777. constructor: LineSegments,
  17778. isLineSegments: true,
  17779. computeLineDistances: function () {
  17780. var geometry = this.geometry;
  17781. if (geometry.isBufferGeometry) {
  17782. // we assume non-indexed geometry
  17783. if (geometry.index === null) {
  17784. var positionAttribute = geometry.attributes.position;
  17785. var lineDistances = [];
  17786. for (var i = 0, l = positionAttribute.count; i < l; i += 2) {
  17787. _start$1.fromBufferAttribute(positionAttribute, i);
  17788. _end$1.fromBufferAttribute(positionAttribute, i + 1);
  17789. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  17790. lineDistances[i + 1] = lineDistances[i] + _start$1.distanceTo(_end$1);
  17791. }
  17792. geometry.addAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  17793. } else {
  17794. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  17795. }
  17796. } else if (geometry.isGeometry) {
  17797. var vertices = geometry.vertices;
  17798. var lineDistances = geometry.lineDistances;
  17799. for (var i = 0, l = vertices.length; i < l; i += 2) {
  17800. _start$1.copy(vertices[i]);
  17801. _end$1.copy(vertices[i + 1]);
  17802. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  17803. lineDistances[i + 1] = lineDistances[i] + _start$1.distanceTo(_end$1);
  17804. }
  17805. }
  17806. return this;
  17807. }
  17808. });
  17809. /**
  17810. * @author mgreter / http://github.com/mgreter
  17811. */
  17812. function LineLoop(geometry, material) {
  17813. Line.call(this, geometry, material);
  17814. this.type = 'LineLoop';
  17815. }
  17816. LineLoop.prototype = Object.assign(Object.create(Line.prototype), {
  17817. constructor: LineLoop,
  17818. isLineLoop: true
  17819. });
  17820. /**
  17821. * @author mrdoob / http://mrdoob.com/
  17822. * @author alteredq / http://alteredqualia.com/
  17823. *
  17824. * parameters = {
  17825. * color: <hex>,
  17826. * opacity: <float>,
  17827. * map: new THREE.Texture( <Image> ),
  17828. *
  17829. * size: <float>,
  17830. * sizeAttenuation: <bool>
  17831. *
  17832. * morphTargets: <bool>
  17833. * }
  17834. */
  17835. function PointsMaterial(parameters) {
  17836. Material.call(this);
  17837. this.type = 'PointsMaterial';
  17838. this.color = new Color(0xffffff);
  17839. this.map = null;
  17840. this.size = 1;
  17841. this.sizeAttenuation = true;
  17842. this.morphTargets = false;
  17843. this.setValues(parameters);
  17844. }
  17845. PointsMaterial.prototype = Object.create(Material.prototype);
  17846. PointsMaterial.prototype.constructor = PointsMaterial;
  17847. PointsMaterial.prototype.isPointsMaterial = true;
  17848. PointsMaterial.prototype.copy = function (source) {
  17849. Material.prototype.copy.call(this, source);
  17850. this.color.copy(source.color);
  17851. this.map = source.map;
  17852. this.size = source.size;
  17853. this.sizeAttenuation = source.sizeAttenuation;
  17854. this.morphTargets = source.morphTargets;
  17855. return this;
  17856. };
  17857. /**
  17858. * @author alteredq / http://alteredqualia.com/
  17859. */
  17860. var _inverseMatrix$2 = new Matrix4();
  17861. var _ray$2 = new Ray();
  17862. var _sphere$3 = new Sphere();
  17863. var _position$1 = new Vector3();
  17864. function Points(geometry, material) {
  17865. Object3D.call(this);
  17866. this.type = 'Points';
  17867. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  17868. this.material = material !== undefined ? material : new PointsMaterial({
  17869. color: Math.random() * 0xffffff
  17870. });
  17871. this.updateMorphTargets();
  17872. }
  17873. Points.prototype = Object.assign(Object.create(Object3D.prototype), {
  17874. constructor: Points,
  17875. isPoints: true,
  17876. raycast: function (raycaster, intersects) {
  17877. var geometry = this.geometry;
  17878. var matrixWorld = this.matrixWorld;
  17879. var threshold = raycaster.params.Points.threshold; // Checking boundingSphere distance to ray
  17880. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  17881. _sphere$3.copy(geometry.boundingSphere);
  17882. _sphere$3.applyMatrix4(matrixWorld);
  17883. _sphere$3.radius += threshold;
  17884. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  17885. _inverseMatrix$2.getInverse(matrixWorld);
  17886. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2);
  17887. var localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  17888. var localThresholdSq = localThreshold * localThreshold;
  17889. if (geometry.isBufferGeometry) {
  17890. var index = geometry.index;
  17891. var attributes = geometry.attributes;
  17892. var positions = attributes.position.array;
  17893. if (index !== null) {
  17894. var indices = index.array;
  17895. for (var i = 0, il = indices.length; i < il; i++) {
  17896. var a = indices[i];
  17897. _position$1.fromArray(positions, a * 3);
  17898. testPoint(_position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17899. }
  17900. } else {
  17901. for (var i = 0, l = positions.length / 3; i < l; i++) {
  17902. _position$1.fromArray(positions, i * 3);
  17903. testPoint(_position$1, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17904. }
  17905. }
  17906. } else {
  17907. var vertices = geometry.vertices;
  17908. for (var i = 0, l = vertices.length; i < l; i++) {
  17909. testPoint(vertices[i], i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17910. }
  17911. }
  17912. },
  17913. updateMorphTargets: function () {
  17914. var geometry = this.geometry;
  17915. var m, ml, name;
  17916. if (geometry.isBufferGeometry) {
  17917. var morphAttributes = geometry.morphAttributes;
  17918. var keys = Object.keys(morphAttributes);
  17919. if (keys.length > 0) {
  17920. var morphAttribute = morphAttributes[keys[0]];
  17921. if (morphAttribute !== undefined) {
  17922. this.morphTargetInfluences = [];
  17923. this.morphTargetDictionary = {};
  17924. for (m = 0, ml = morphAttribute.length; m < ml; m++) {
  17925. name = morphAttribute[m].name || String(m);
  17926. this.morphTargetInfluences.push(0);
  17927. this.morphTargetDictionary[name] = m;
  17928. }
  17929. }
  17930. }
  17931. } else {
  17932. var morphTargets = geometry.morphTargets;
  17933. if (morphTargets !== undefined && morphTargets.length > 0) {
  17934. console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  17935. }
  17936. }
  17937. },
  17938. clone: function () {
  17939. return new this.constructor(this.geometry, this.material).copy(this);
  17940. }
  17941. });
  17942. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  17943. var rayPointDistanceSq = _ray$2.distanceSqToPoint(point);
  17944. if (rayPointDistanceSq < localThresholdSq) {
  17945. var intersectPoint = new Vector3();
  17946. _ray$2.closestPointToPoint(point, intersectPoint);
  17947. intersectPoint.applyMatrix4(matrixWorld);
  17948. var distance = raycaster.ray.origin.distanceTo(intersectPoint);
  17949. if (distance < raycaster.near || distance > raycaster.far) return;
  17950. intersects.push({
  17951. distance: distance,
  17952. distanceToRay: Math.sqrt(rayPointDistanceSq),
  17953. point: intersectPoint,
  17954. index: index,
  17955. face: null,
  17956. object: object
  17957. });
  17958. }
  17959. }
  17960. /**
  17961. * @author mrdoob / http://mrdoob.com/
  17962. */
  17963. function VideoTexture(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  17964. Texture.call(this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  17965. this.format = format !== undefined ? format : RGBFormat;
  17966. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  17967. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  17968. this.generateMipmaps = false;
  17969. }
  17970. VideoTexture.prototype = Object.assign(Object.create(Texture.prototype), {
  17971. constructor: VideoTexture,
  17972. isVideoTexture: true,
  17973. update: function () {
  17974. var video = this.image;
  17975. if (video.readyState >= video.HAVE_CURRENT_DATA) {
  17976. this.needsUpdate = true;
  17977. }
  17978. }
  17979. });
  17980. /**
  17981. * @author alteredq / http://alteredqualia.com/
  17982. */
  17983. function CompressedTexture(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  17984. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  17985. this.image = {
  17986. width: width,
  17987. height: height
  17988. };
  17989. this.mipmaps = mipmaps; // no flipping for cube textures
  17990. // (also flipping doesn't work for compressed textures )
  17991. this.flipY = false; // can't generate mipmaps for compressed textures
  17992. // mips must be embedded in DDS files
  17993. this.generateMipmaps = false;
  17994. }
  17995. CompressedTexture.prototype = Object.create(Texture.prototype);
  17996. CompressedTexture.prototype.constructor = CompressedTexture;
  17997. CompressedTexture.prototype.isCompressedTexture = true;
  17998. /**
  17999. * @author mrdoob / http://mrdoob.com/
  18000. */
  18001. function CanvasTexture(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  18002. Texture.call(this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  18003. this.needsUpdate = true;
  18004. }
  18005. CanvasTexture.prototype = Object.create(Texture.prototype);
  18006. CanvasTexture.prototype.constructor = CanvasTexture;
  18007. CanvasTexture.prototype.isCanvasTexture = true;
  18008. /**
  18009. * @author Matt DesLauriers / @mattdesl
  18010. * @author atix / arthursilber.de
  18011. */
  18012. function DepthTexture(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  18013. format = format !== undefined ? format : DepthFormat;
  18014. if (format !== DepthFormat && format !== DepthStencilFormat) {
  18015. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  18016. }
  18017. if (type === undefined && format === DepthFormat) type = UnsignedShortType;
  18018. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  18019. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  18020. this.image = {
  18021. width: width,
  18022. height: height
  18023. };
  18024. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  18025. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  18026. this.flipY = false;
  18027. this.generateMipmaps = false;
  18028. }
  18029. DepthTexture.prototype = Object.create(Texture.prototype);
  18030. DepthTexture.prototype.constructor = DepthTexture;
  18031. DepthTexture.prototype.isDepthTexture = true;
  18032. /**
  18033. * @author mrdoob / http://mrdoob.com/
  18034. * @author Mugen87 / https://github.com/Mugen87
  18035. */
  18036. function WireframeGeometry(geometry) {
  18037. BufferGeometry.call(this);
  18038. this.type = 'WireframeGeometry'; // buffer
  18039. var vertices = []; // helper variables
  18040. var i, j, l, o, ol;
  18041. var edge = [0, 0],
  18042. edges = {},
  18043. e,
  18044. edge1,
  18045. edge2;
  18046. var key,
  18047. keys = ['a', 'b', 'c'];
  18048. var vertex; // different logic for Geometry and BufferGeometry
  18049. if (geometry && geometry.isGeometry) {
  18050. // create a data structure that contains all edges without duplicates
  18051. var faces = geometry.faces;
  18052. for (i = 0, l = faces.length; i < l; i++) {
  18053. var face = faces[i];
  18054. for (j = 0; j < 3; j++) {
  18055. edge1 = face[keys[j]];
  18056. edge2 = face[keys[(j + 1) % 3]];
  18057. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  18058. edge[1] = Math.max(edge1, edge2);
  18059. key = edge[0] + ',' + edge[1];
  18060. if (edges[key] === undefined) {
  18061. edges[key] = {
  18062. index1: edge[0],
  18063. index2: edge[1]
  18064. };
  18065. }
  18066. }
  18067. } // generate vertices
  18068. for (key in edges) {
  18069. e = edges[key];
  18070. vertex = geometry.vertices[e.index1];
  18071. vertices.push(vertex.x, vertex.y, vertex.z);
  18072. vertex = geometry.vertices[e.index2];
  18073. vertices.push(vertex.x, vertex.y, vertex.z);
  18074. }
  18075. } else if (geometry && geometry.isBufferGeometry) {
  18076. var position, indices, groups;
  18077. var group, start, count;
  18078. var index1, index2;
  18079. vertex = new Vector3();
  18080. if (geometry.index !== null) {
  18081. // indexed BufferGeometry
  18082. position = geometry.attributes.position;
  18083. indices = geometry.index;
  18084. groups = geometry.groups;
  18085. if (groups.length === 0) {
  18086. groups = [{
  18087. start: 0,
  18088. count: indices.count,
  18089. materialIndex: 0
  18090. }];
  18091. } // create a data structure that contains all eges without duplicates
  18092. for (o = 0, ol = groups.length; o < ol; ++o) {
  18093. group = groups[o];
  18094. start = group.start;
  18095. count = group.count;
  18096. for (i = start, l = start + count; i < l; i += 3) {
  18097. for (j = 0; j < 3; j++) {
  18098. edge1 = indices.getX(i + j);
  18099. edge2 = indices.getX(i + (j + 1) % 3);
  18100. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  18101. edge[1] = Math.max(edge1, edge2);
  18102. key = edge[0] + ',' + edge[1];
  18103. if (edges[key] === undefined) {
  18104. edges[key] = {
  18105. index1: edge[0],
  18106. index2: edge[1]
  18107. };
  18108. }
  18109. }
  18110. }
  18111. } // generate vertices
  18112. for (key in edges) {
  18113. e = edges[key];
  18114. vertex.fromBufferAttribute(position, e.index1);
  18115. vertices.push(vertex.x, vertex.y, vertex.z);
  18116. vertex.fromBufferAttribute(position, e.index2);
  18117. vertices.push(vertex.x, vertex.y, vertex.z);
  18118. }
  18119. } else {
  18120. // non-indexed BufferGeometry
  18121. position = geometry.attributes.position;
  18122. for (i = 0, l = position.count / 3; i < l; i++) {
  18123. for (j = 0; j < 3; j++) {
  18124. // three edges per triangle, an edge is represented as (index1, index2)
  18125. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  18126. index1 = 3 * i + j;
  18127. vertex.fromBufferAttribute(position, index1);
  18128. vertices.push(vertex.x, vertex.y, vertex.z);
  18129. index2 = 3 * i + (j + 1) % 3;
  18130. vertex.fromBufferAttribute(position, index2);
  18131. vertices.push(vertex.x, vertex.y, vertex.z);
  18132. }
  18133. }
  18134. }
  18135. } // build geometry
  18136. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18137. }
  18138. WireframeGeometry.prototype = Object.create(BufferGeometry.prototype);
  18139. WireframeGeometry.prototype.constructor = WireframeGeometry;
  18140. /**
  18141. * @author zz85 / https://github.com/zz85
  18142. * @author Mugen87 / https://github.com/Mugen87
  18143. *
  18144. * Parametric Surfaces Geometry
  18145. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  18146. */
  18147. // ParametricGeometry
  18148. function ParametricGeometry(func, slices, stacks) {
  18149. Geometry.call(this);
  18150. this.type = 'ParametricGeometry';
  18151. this.parameters = {
  18152. func: func,
  18153. slices: slices,
  18154. stacks: stacks
  18155. };
  18156. this.fromBufferGeometry(new ParametricBufferGeometry(func, slices, stacks));
  18157. this.mergeVertices();
  18158. }
  18159. ParametricGeometry.prototype = Object.create(Geometry.prototype);
  18160. ParametricGeometry.prototype.constructor = ParametricGeometry; // ParametricBufferGeometry
  18161. function ParametricBufferGeometry(func, slices, stacks) {
  18162. BufferGeometry.call(this);
  18163. this.type = 'ParametricBufferGeometry';
  18164. this.parameters = {
  18165. func: func,
  18166. slices: slices,
  18167. stacks: stacks
  18168. }; // buffers
  18169. var indices = [];
  18170. var vertices = [];
  18171. var normals = [];
  18172. var uvs = [];
  18173. var EPS = 0.00001;
  18174. var normal = new Vector3();
  18175. var p0 = new Vector3(),
  18176. p1 = new Vector3();
  18177. var pu = new Vector3(),
  18178. pv = new Vector3();
  18179. var i, j;
  18180. if (func.length < 3) {
  18181. console.error('THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.');
  18182. } // generate vertices, normals and uvs
  18183. var sliceCount = slices + 1;
  18184. for (i = 0; i <= stacks; i++) {
  18185. var v = i / stacks;
  18186. for (j = 0; j <= slices; j++) {
  18187. var u = j / slices; // vertex
  18188. func(u, v, p0);
  18189. vertices.push(p0.x, p0.y, p0.z); // normal
  18190. // approximate tangent vectors via finite differences
  18191. if (u - EPS >= 0) {
  18192. func(u - EPS, v, p1);
  18193. pu.subVectors(p0, p1);
  18194. } else {
  18195. func(u + EPS, v, p1);
  18196. pu.subVectors(p1, p0);
  18197. }
  18198. if (v - EPS >= 0) {
  18199. func(u, v - EPS, p1);
  18200. pv.subVectors(p0, p1);
  18201. } else {
  18202. func(u, v + EPS, p1);
  18203. pv.subVectors(p1, p0);
  18204. } // cross product of tangent vectors returns surface normal
  18205. normal.crossVectors(pu, pv).normalize();
  18206. normals.push(normal.x, normal.y, normal.z); // uv
  18207. uvs.push(u, v);
  18208. }
  18209. } // generate indices
  18210. for (i = 0; i < stacks; i++) {
  18211. for (j = 0; j < slices; j++) {
  18212. var a = i * sliceCount + j;
  18213. var b = i * sliceCount + j + 1;
  18214. var c = (i + 1) * sliceCount + j + 1;
  18215. var d = (i + 1) * sliceCount + j; // faces one and two
  18216. indices.push(a, b, d);
  18217. indices.push(b, c, d);
  18218. }
  18219. } // build geometry
  18220. this.setIndex(indices);
  18221. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18222. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  18223. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18224. }
  18225. ParametricBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18226. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  18227. /**
  18228. * @author clockworkgeek / https://github.com/clockworkgeek
  18229. * @author timothypratley / https://github.com/timothypratley
  18230. * @author WestLangley / http://github.com/WestLangley
  18231. * @author Mugen87 / https://github.com/Mugen87
  18232. */
  18233. // PolyhedronGeometry
  18234. function PolyhedronGeometry(vertices, indices, radius, detail) {
  18235. Geometry.call(this);
  18236. this.type = 'PolyhedronGeometry';
  18237. this.parameters = {
  18238. vertices: vertices,
  18239. indices: indices,
  18240. radius: radius,
  18241. detail: detail
  18242. };
  18243. this.fromBufferGeometry(new PolyhedronBufferGeometry(vertices, indices, radius, detail));
  18244. this.mergeVertices();
  18245. }
  18246. PolyhedronGeometry.prototype = Object.create(Geometry.prototype);
  18247. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry; // PolyhedronBufferGeometry
  18248. function PolyhedronBufferGeometry(vertices, indices, radius, detail) {
  18249. BufferGeometry.call(this);
  18250. this.type = 'PolyhedronBufferGeometry';
  18251. this.parameters = {
  18252. vertices: vertices,
  18253. indices: indices,
  18254. radius: radius,
  18255. detail: detail
  18256. };
  18257. radius = radius || 1;
  18258. detail = detail || 0; // default buffer data
  18259. var vertexBuffer = [];
  18260. var uvBuffer = []; // the subdivision creates the vertex buffer data
  18261. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  18262. applyRadius(radius); // finally, create the uv data
  18263. generateUVs(); // build non-indexed geometry
  18264. this.addAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  18265. this.addAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  18266. this.addAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  18267. if (detail === 0) {
  18268. this.computeVertexNormals(); // flat normals
  18269. } else {
  18270. this.normalizeNormals(); // smooth normals
  18271. } // helper functions
  18272. function subdivide(detail) {
  18273. var a = new Vector3();
  18274. var b = new Vector3();
  18275. var c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  18276. for (var i = 0; i < indices.length; i += 3) {
  18277. // get the vertices of the face
  18278. getVertexByIndex(indices[i + 0], a);
  18279. getVertexByIndex(indices[i + 1], b);
  18280. getVertexByIndex(indices[i + 2], c); // perform subdivision
  18281. subdivideFace(a, b, c, detail);
  18282. }
  18283. }
  18284. function subdivideFace(a, b, c, detail) {
  18285. var cols = Math.pow(2, detail); // we use this multidimensional array as a data structure for creating the subdivision
  18286. var v = [];
  18287. var i, j; // construct all of the vertices for this subdivision
  18288. for (i = 0; i <= cols; i++) {
  18289. v[i] = [];
  18290. var aj = a.clone().lerp(c, i / cols);
  18291. var bj = b.clone().lerp(c, i / cols);
  18292. var rows = cols - i;
  18293. for (j = 0; j <= rows; j++) {
  18294. if (j === 0 && i === cols) {
  18295. v[i][j] = aj;
  18296. } else {
  18297. v[i][j] = aj.clone().lerp(bj, j / rows);
  18298. }
  18299. }
  18300. } // construct all of the faces
  18301. for (i = 0; i < cols; i++) {
  18302. for (j = 0; j < 2 * (cols - i) - 1; j++) {
  18303. var k = Math.floor(j / 2);
  18304. if (j % 2 === 0) {
  18305. pushVertex(v[i][k + 1]);
  18306. pushVertex(v[i + 1][k]);
  18307. pushVertex(v[i][k]);
  18308. } else {
  18309. pushVertex(v[i][k + 1]);
  18310. pushVertex(v[i + 1][k + 1]);
  18311. pushVertex(v[i + 1][k]);
  18312. }
  18313. }
  18314. }
  18315. }
  18316. function applyRadius(radius) {
  18317. var vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  18318. for (var i = 0; i < vertexBuffer.length; i += 3) {
  18319. vertex.x = vertexBuffer[i + 0];
  18320. vertex.y = vertexBuffer[i + 1];
  18321. vertex.z = vertexBuffer[i + 2];
  18322. vertex.normalize().multiplyScalar(radius);
  18323. vertexBuffer[i + 0] = vertex.x;
  18324. vertexBuffer[i + 1] = vertex.y;
  18325. vertexBuffer[i + 2] = vertex.z;
  18326. }
  18327. }
  18328. function generateUVs() {
  18329. var vertex = new Vector3();
  18330. for (var i = 0; i < vertexBuffer.length; i += 3) {
  18331. vertex.x = vertexBuffer[i + 0];
  18332. vertex.y = vertexBuffer[i + 1];
  18333. vertex.z = vertexBuffer[i + 2];
  18334. var u = azimuth(vertex) / 2 / Math.PI + 0.5;
  18335. var v = inclination(vertex) / Math.PI + 0.5;
  18336. uvBuffer.push(u, 1 - v);
  18337. }
  18338. correctUVs();
  18339. correctSeam();
  18340. }
  18341. function correctSeam() {
  18342. // handle case when face straddles the seam, see #3269
  18343. for (var i = 0; i < uvBuffer.length; i += 6) {
  18344. // uv data of a single face
  18345. var x0 = uvBuffer[i + 0];
  18346. var x1 = uvBuffer[i + 2];
  18347. var x2 = uvBuffer[i + 4];
  18348. var max = Math.max(x0, x1, x2);
  18349. var min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  18350. if (max > 0.9 && min < 0.1) {
  18351. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  18352. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  18353. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  18354. }
  18355. }
  18356. }
  18357. function pushVertex(vertex) {
  18358. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  18359. }
  18360. function getVertexByIndex(index, vertex) {
  18361. var stride = index * 3;
  18362. vertex.x = vertices[stride + 0];
  18363. vertex.y = vertices[stride + 1];
  18364. vertex.z = vertices[stride + 2];
  18365. }
  18366. function correctUVs() {
  18367. var a = new Vector3();
  18368. var b = new Vector3();
  18369. var c = new Vector3();
  18370. var centroid = new Vector3();
  18371. var uvA = new Vector2();
  18372. var uvB = new Vector2();
  18373. var uvC = new Vector2();
  18374. for (var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  18375. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  18376. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  18377. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  18378. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  18379. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  18380. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  18381. centroid.copy(a).add(b).add(c).divideScalar(3);
  18382. var azi = azimuth(centroid);
  18383. correctUV(uvA, j + 0, a, azi);
  18384. correctUV(uvB, j + 2, b, azi);
  18385. correctUV(uvC, j + 4, c, azi);
  18386. }
  18387. }
  18388. function correctUV(uv, stride, vector, azimuth) {
  18389. if (azimuth < 0 && uv.x === 1) {
  18390. uvBuffer[stride] = uv.x - 1;
  18391. }
  18392. if (vector.x === 0 && vector.z === 0) {
  18393. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  18394. }
  18395. } // Angle around the Y axis, counter-clockwise when looking from above.
  18396. function azimuth(vector) {
  18397. return Math.atan2(vector.z, -vector.x);
  18398. } // Angle above the XZ plane.
  18399. function inclination(vector) {
  18400. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  18401. }
  18402. }
  18403. PolyhedronBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18404. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  18405. /**
  18406. * @author timothypratley / https://github.com/timothypratley
  18407. * @author Mugen87 / https://github.com/Mugen87
  18408. */
  18409. // TetrahedronGeometry
  18410. function TetrahedronGeometry(radius, detail) {
  18411. Geometry.call(this);
  18412. this.type = 'TetrahedronGeometry';
  18413. this.parameters = {
  18414. radius: radius,
  18415. detail: detail
  18416. };
  18417. this.fromBufferGeometry(new TetrahedronBufferGeometry(radius, detail));
  18418. this.mergeVertices();
  18419. }
  18420. TetrahedronGeometry.prototype = Object.create(Geometry.prototype);
  18421. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry; // TetrahedronBufferGeometry
  18422. function TetrahedronBufferGeometry(radius, detail) {
  18423. var vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  18424. var indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  18425. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  18426. this.type = 'TetrahedronBufferGeometry';
  18427. this.parameters = {
  18428. radius: radius,
  18429. detail: detail
  18430. };
  18431. }
  18432. TetrahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  18433. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  18434. /**
  18435. * @author timothypratley / https://github.com/timothypratley
  18436. * @author Mugen87 / https://github.com/Mugen87
  18437. */
  18438. // OctahedronGeometry
  18439. function OctahedronGeometry(radius, detail) {
  18440. Geometry.call(this);
  18441. this.type = 'OctahedronGeometry';
  18442. this.parameters = {
  18443. radius: radius,
  18444. detail: detail
  18445. };
  18446. this.fromBufferGeometry(new OctahedronBufferGeometry(radius, detail));
  18447. this.mergeVertices();
  18448. }
  18449. OctahedronGeometry.prototype = Object.create(Geometry.prototype);
  18450. OctahedronGeometry.prototype.constructor = OctahedronGeometry; // OctahedronBufferGeometry
  18451. function OctahedronBufferGeometry(radius, detail) {
  18452. var vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  18453. 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];
  18454. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  18455. this.type = 'OctahedronBufferGeometry';
  18456. this.parameters = {
  18457. radius: radius,
  18458. detail: detail
  18459. };
  18460. }
  18461. OctahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  18462. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  18463. /**
  18464. * @author timothypratley / https://github.com/timothypratley
  18465. * @author Mugen87 / https://github.com/Mugen87
  18466. */
  18467. // IcosahedronGeometry
  18468. function IcosahedronGeometry(radius, detail) {
  18469. Geometry.call(this);
  18470. this.type = 'IcosahedronGeometry';
  18471. this.parameters = {
  18472. radius: radius,
  18473. detail: detail
  18474. };
  18475. this.fromBufferGeometry(new IcosahedronBufferGeometry(radius, detail));
  18476. this.mergeVertices();
  18477. }
  18478. IcosahedronGeometry.prototype = Object.create(Geometry.prototype);
  18479. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry; // IcosahedronBufferGeometry
  18480. function IcosahedronBufferGeometry(radius, detail) {
  18481. var t = (1 + Math.sqrt(5)) / 2;
  18482. 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];
  18483. 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];
  18484. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  18485. this.type = 'IcosahedronBufferGeometry';
  18486. this.parameters = {
  18487. radius: radius,
  18488. detail: detail
  18489. };
  18490. }
  18491. IcosahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  18492. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  18493. /**
  18494. * @author Abe Pazos / https://hamoid.com
  18495. * @author Mugen87 / https://github.com/Mugen87
  18496. */
  18497. // DodecahedronGeometry
  18498. function DodecahedronGeometry(radius, detail) {
  18499. Geometry.call(this);
  18500. this.type = 'DodecahedronGeometry';
  18501. this.parameters = {
  18502. radius: radius,
  18503. detail: detail
  18504. };
  18505. this.fromBufferGeometry(new DodecahedronBufferGeometry(radius, detail));
  18506. this.mergeVertices();
  18507. }
  18508. DodecahedronGeometry.prototype = Object.create(Geometry.prototype);
  18509. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry; // DodecahedronBufferGeometry
  18510. function DodecahedronBufferGeometry(radius, detail) {
  18511. var t = (1 + Math.sqrt(5)) / 2;
  18512. var r = 1 / t;
  18513. var vertices = [// (±1, ±1, ±1)
  18514. -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/φ, ±φ)
  18515. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  18516. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  18517. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  18518. 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];
  18519. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  18520. this.type = 'DodecahedronBufferGeometry';
  18521. this.parameters = {
  18522. radius: radius,
  18523. detail: detail
  18524. };
  18525. }
  18526. DodecahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  18527. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  18528. /**
  18529. * @author oosmoxiecode / https://github.com/oosmoxiecode
  18530. * @author WestLangley / https://github.com/WestLangley
  18531. * @author zz85 / https://github.com/zz85
  18532. * @author miningold / https://github.com/miningold
  18533. * @author jonobr1 / https://github.com/jonobr1
  18534. * @author Mugen87 / https://github.com/Mugen87
  18535. *
  18536. */
  18537. // TubeGeometry
  18538. function TubeGeometry(path, tubularSegments, radius, radialSegments, closed, taper) {
  18539. Geometry.call(this);
  18540. this.type = 'TubeGeometry';
  18541. this.parameters = {
  18542. path: path,
  18543. tubularSegments: tubularSegments,
  18544. radius: radius,
  18545. radialSegments: radialSegments,
  18546. closed: closed
  18547. };
  18548. if (taper !== undefined) console.warn('THREE.TubeGeometry: taper has been removed.');
  18549. var bufferGeometry = new TubeBufferGeometry(path, tubularSegments, radius, radialSegments, closed); // expose internals
  18550. this.tangents = bufferGeometry.tangents;
  18551. this.normals = bufferGeometry.normals;
  18552. this.binormals = bufferGeometry.binormals; // create geometry
  18553. this.fromBufferGeometry(bufferGeometry);
  18554. this.mergeVertices();
  18555. }
  18556. TubeGeometry.prototype = Object.create(Geometry.prototype);
  18557. TubeGeometry.prototype.constructor = TubeGeometry; // TubeBufferGeometry
  18558. function TubeBufferGeometry(path, tubularSegments, radius, radialSegments, closed) {
  18559. BufferGeometry.call(this);
  18560. this.type = 'TubeBufferGeometry';
  18561. this.parameters = {
  18562. path: path,
  18563. tubularSegments: tubularSegments,
  18564. radius: radius,
  18565. radialSegments: radialSegments,
  18566. closed: closed
  18567. };
  18568. tubularSegments = tubularSegments || 64;
  18569. radius = radius || 1;
  18570. radialSegments = radialSegments || 8;
  18571. closed = closed || false;
  18572. var frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  18573. this.tangents = frames.tangents;
  18574. this.normals = frames.normals;
  18575. this.binormals = frames.binormals; // helper variables
  18576. var vertex = new Vector3();
  18577. var normal = new Vector3();
  18578. var uv = new Vector2();
  18579. var P = new Vector3();
  18580. var i, j; // buffer
  18581. var vertices = [];
  18582. var normals = [];
  18583. var uvs = [];
  18584. var indices = []; // create buffer data
  18585. generateBufferData(); // build geometry
  18586. this.setIndex(indices);
  18587. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18588. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  18589. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  18590. function generateBufferData() {
  18591. for (i = 0; i < tubularSegments; i++) {
  18592. generateSegment(i);
  18593. } // if the geometry is not closed, generate the last row of vertices and normals
  18594. // at the regular position on the given path
  18595. //
  18596. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  18597. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  18598. // this makes it easy compute correct values for closed geometries
  18599. generateUVs(); // finally create faces
  18600. generateIndices();
  18601. }
  18602. function generateSegment(i) {
  18603. // we use getPointAt to sample evenly distributed points from the given path
  18604. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  18605. var N = frames.normals[i];
  18606. var B = frames.binormals[i]; // generate normals and vertices for the current segment
  18607. for (j = 0; j <= radialSegments; j++) {
  18608. var v = j / radialSegments * Math.PI * 2;
  18609. var sin = Math.sin(v);
  18610. var cos = -Math.cos(v); // normal
  18611. normal.x = cos * N.x + sin * B.x;
  18612. normal.y = cos * N.y + sin * B.y;
  18613. normal.z = cos * N.z + sin * B.z;
  18614. normal.normalize();
  18615. normals.push(normal.x, normal.y, normal.z); // vertex
  18616. vertex.x = P.x + radius * normal.x;
  18617. vertex.y = P.y + radius * normal.y;
  18618. vertex.z = P.z + radius * normal.z;
  18619. vertices.push(vertex.x, vertex.y, vertex.z);
  18620. }
  18621. }
  18622. function generateIndices() {
  18623. for (j = 1; j <= tubularSegments; j++) {
  18624. for (i = 1; i <= radialSegments; i++) {
  18625. var a = (radialSegments + 1) * (j - 1) + (i - 1);
  18626. var b = (radialSegments + 1) * j + (i - 1);
  18627. var c = (radialSegments + 1) * j + i;
  18628. var d = (radialSegments + 1) * (j - 1) + i; // faces
  18629. indices.push(a, b, d);
  18630. indices.push(b, c, d);
  18631. }
  18632. }
  18633. }
  18634. function generateUVs() {
  18635. for (i = 0; i <= tubularSegments; i++) {
  18636. for (j = 0; j <= radialSegments; j++) {
  18637. uv.x = i / tubularSegments;
  18638. uv.y = j / radialSegments;
  18639. uvs.push(uv.x, uv.y);
  18640. }
  18641. }
  18642. }
  18643. }
  18644. TubeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18645. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  18646. TubeBufferGeometry.prototype.toJSON = function () {
  18647. var data = BufferGeometry.prototype.toJSON.call(this);
  18648. data.path = this.parameters.path.toJSON();
  18649. return data;
  18650. };
  18651. /**
  18652. * @author oosmoxiecode
  18653. * @author Mugen87 / https://github.com/Mugen87
  18654. *
  18655. * based on http://www.blackpawn.com/texts/pqtorus/
  18656. */
  18657. // TorusKnotGeometry
  18658. function TorusKnotGeometry(radius, tube, tubularSegments, radialSegments, p, q, heightScale) {
  18659. Geometry.call(this);
  18660. this.type = 'TorusKnotGeometry';
  18661. this.parameters = {
  18662. radius: radius,
  18663. tube: tube,
  18664. tubularSegments: tubularSegments,
  18665. radialSegments: radialSegments,
  18666. p: p,
  18667. q: q
  18668. };
  18669. if (heightScale !== undefined) console.warn('THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.');
  18670. this.fromBufferGeometry(new TorusKnotBufferGeometry(radius, tube, tubularSegments, radialSegments, p, q));
  18671. this.mergeVertices();
  18672. }
  18673. TorusKnotGeometry.prototype = Object.create(Geometry.prototype);
  18674. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry; // TorusKnotBufferGeometry
  18675. function TorusKnotBufferGeometry(radius, tube, tubularSegments, radialSegments, p, q) {
  18676. BufferGeometry.call(this);
  18677. this.type = 'TorusKnotBufferGeometry';
  18678. this.parameters = {
  18679. radius: radius,
  18680. tube: tube,
  18681. tubularSegments: tubularSegments,
  18682. radialSegments: radialSegments,
  18683. p: p,
  18684. q: q
  18685. };
  18686. radius = radius || 1;
  18687. tube = tube || 0.4;
  18688. tubularSegments = Math.floor(tubularSegments) || 64;
  18689. radialSegments = Math.floor(radialSegments) || 8;
  18690. p = p || 2;
  18691. q = q || 3; // buffers
  18692. var indices = [];
  18693. var vertices = [];
  18694. var normals = [];
  18695. var uvs = []; // helper variables
  18696. var i, j;
  18697. var vertex = new Vector3();
  18698. var normal = new Vector3();
  18699. var P1 = new Vector3();
  18700. var P2 = new Vector3();
  18701. var B = new Vector3();
  18702. var T = new Vector3();
  18703. var N = new Vector3(); // generate vertices, normals and uvs
  18704. for (i = 0; i <= tubularSegments; ++i) {
  18705. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  18706. 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.
  18707. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  18708. calculatePositionOnCurve(u, p, q, radius, P1);
  18709. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  18710. T.subVectors(P2, P1);
  18711. N.addVectors(P2, P1);
  18712. B.crossVectors(T, N);
  18713. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  18714. B.normalize();
  18715. N.normalize();
  18716. for (j = 0; j <= radialSegments; ++j) {
  18717. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  18718. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  18719. var v = j / radialSegments * Math.PI * 2;
  18720. var cx = -tube * Math.cos(v);
  18721. var cy = tube * Math.sin(v); // now calculate the final vertex position.
  18722. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  18723. vertex.x = P1.x + (cx * N.x + cy * B.x);
  18724. vertex.y = P1.y + (cx * N.y + cy * B.y);
  18725. vertex.z = P1.z + (cx * N.z + cy * B.z);
  18726. 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)
  18727. normal.subVectors(vertex, P1).normalize();
  18728. normals.push(normal.x, normal.y, normal.z); // uv
  18729. uvs.push(i / tubularSegments);
  18730. uvs.push(j / radialSegments);
  18731. }
  18732. } // generate indices
  18733. for (j = 1; j <= tubularSegments; j++) {
  18734. for (i = 1; i <= radialSegments; i++) {
  18735. // indices
  18736. var a = (radialSegments + 1) * (j - 1) + (i - 1);
  18737. var b = (radialSegments + 1) * j + (i - 1);
  18738. var c = (radialSegments + 1) * j + i;
  18739. var d = (radialSegments + 1) * (j - 1) + i; // faces
  18740. indices.push(a, b, d);
  18741. indices.push(b, c, d);
  18742. }
  18743. } // build geometry
  18744. this.setIndex(indices);
  18745. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18746. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  18747. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  18748. function calculatePositionOnCurve(u, p, q, radius, position) {
  18749. var cu = Math.cos(u);
  18750. var su = Math.sin(u);
  18751. var quOverP = q / p * u;
  18752. var cs = Math.cos(quOverP);
  18753. position.x = radius * (2 + cs) * 0.5 * cu;
  18754. position.y = radius * (2 + cs) * su * 0.5;
  18755. position.z = radius * Math.sin(quOverP) * 0.5;
  18756. }
  18757. }
  18758. TorusKnotBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18759. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  18760. /**
  18761. * @author oosmoxiecode
  18762. * @author mrdoob / http://mrdoob.com/
  18763. * @author Mugen87 / https://github.com/Mugen87
  18764. */
  18765. // TorusGeometry
  18766. function TorusGeometry(radius, tube, radialSegments, tubularSegments, arc) {
  18767. Geometry.call(this);
  18768. this.type = 'TorusGeometry';
  18769. this.parameters = {
  18770. radius: radius,
  18771. tube: tube,
  18772. radialSegments: radialSegments,
  18773. tubularSegments: tubularSegments,
  18774. arc: arc
  18775. };
  18776. this.fromBufferGeometry(new TorusBufferGeometry(radius, tube, radialSegments, tubularSegments, arc));
  18777. this.mergeVertices();
  18778. }
  18779. TorusGeometry.prototype = Object.create(Geometry.prototype);
  18780. TorusGeometry.prototype.constructor = TorusGeometry; // TorusBufferGeometry
  18781. function TorusBufferGeometry(radius, tube, radialSegments, tubularSegments, arc) {
  18782. BufferGeometry.call(this);
  18783. this.type = 'TorusBufferGeometry';
  18784. this.parameters = {
  18785. radius: radius,
  18786. tube: tube,
  18787. radialSegments: radialSegments,
  18788. tubularSegments: tubularSegments,
  18789. arc: arc
  18790. };
  18791. radius = radius || 1;
  18792. tube = tube || 0.4;
  18793. radialSegments = Math.floor(radialSegments) || 8;
  18794. tubularSegments = Math.floor(tubularSegments) || 6;
  18795. arc = arc || Math.PI * 2; // buffers
  18796. var indices = [];
  18797. var vertices = [];
  18798. var normals = [];
  18799. var uvs = []; // helper variables
  18800. var center = new Vector3();
  18801. var vertex = new Vector3();
  18802. var normal = new Vector3();
  18803. var j, i; // generate vertices, normals and uvs
  18804. for (j = 0; j <= radialSegments; j++) {
  18805. for (i = 0; i <= tubularSegments; i++) {
  18806. var u = i / tubularSegments * arc;
  18807. var v = j / radialSegments * Math.PI * 2; // vertex
  18808. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  18809. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  18810. vertex.z = tube * Math.sin(v);
  18811. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  18812. center.x = radius * Math.cos(u);
  18813. center.y = radius * Math.sin(u);
  18814. normal.subVectors(vertex, center).normalize();
  18815. normals.push(normal.x, normal.y, normal.z); // uv
  18816. uvs.push(i / tubularSegments);
  18817. uvs.push(j / radialSegments);
  18818. }
  18819. } // generate indices
  18820. for (j = 1; j <= radialSegments; j++) {
  18821. for (i = 1; i <= tubularSegments; i++) {
  18822. // indices
  18823. var a = (tubularSegments + 1) * j + i - 1;
  18824. var b = (tubularSegments + 1) * (j - 1) + i - 1;
  18825. var c = (tubularSegments + 1) * (j - 1) + i;
  18826. var d = (tubularSegments + 1) * j + i; // faces
  18827. indices.push(a, b, d);
  18828. indices.push(b, c, d);
  18829. }
  18830. } // build geometry
  18831. this.setIndex(indices);
  18832. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18833. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  18834. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18835. }
  18836. TorusBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18837. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  18838. /**
  18839. * @author Mugen87 / https://github.com/Mugen87
  18840. * Port from https://github.com/mapbox/earcut (v2.1.5)
  18841. */
  18842. var Earcut = {
  18843. triangulate: function (data, holeIndices, dim) {
  18844. dim = dim || 2;
  18845. var hasHoles = holeIndices && holeIndices.length,
  18846. outerLen = hasHoles ? holeIndices[0] * dim : data.length,
  18847. outerNode = linkedList(data, 0, outerLen, dim, true),
  18848. triangles = [];
  18849. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  18850. var minX, minY, maxX, maxY, x, y, invSize;
  18851. 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
  18852. if (data.length > 80 * dim) {
  18853. minX = maxX = data[0];
  18854. minY = maxY = data[1];
  18855. for (var i = dim; i < outerLen; i += dim) {
  18856. x = data[i];
  18857. y = data[i + 1];
  18858. if (x < minX) minX = x;
  18859. if (y < minY) minY = y;
  18860. if (x > maxX) maxX = x;
  18861. if (y > maxY) maxY = y;
  18862. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  18863. invSize = Math.max(maxX - minX, maxY - minY);
  18864. invSize = invSize !== 0 ? 1 / invSize : 0;
  18865. }
  18866. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  18867. return triangles;
  18868. }
  18869. }; // create a circular doubly linked list from polygon points in the specified winding order
  18870. function linkedList(data, start, end, dim, clockwise) {
  18871. var i, last;
  18872. if (clockwise === signedArea(data, start, end, dim) > 0) {
  18873. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  18874. } else {
  18875. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  18876. }
  18877. if (last && equals(last, last.next)) {
  18878. removeNode(last);
  18879. last = last.next;
  18880. }
  18881. return last;
  18882. } // eliminate colinear or duplicate points
  18883. function filterPoints(start, end) {
  18884. if (!start) return start;
  18885. if (!end) end = start;
  18886. var p = start,
  18887. again;
  18888. do {
  18889. again = false;
  18890. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  18891. removeNode(p);
  18892. p = end = p.prev;
  18893. if (p === p.next) break;
  18894. again = true;
  18895. } else {
  18896. p = p.next;
  18897. }
  18898. } while (again || p !== end);
  18899. return end;
  18900. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  18901. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  18902. if (!ear) return; // interlink polygon nodes in z-order
  18903. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  18904. var stop = ear,
  18905. prev,
  18906. next; // iterate through ears, slicing them one by one
  18907. while (ear.prev !== ear.next) {
  18908. prev = ear.prev;
  18909. next = ear.next;
  18910. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  18911. // cut off the triangle
  18912. triangles.push(prev.i / dim);
  18913. triangles.push(ear.i / dim);
  18914. triangles.push(next.i / dim);
  18915. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  18916. ear = next.next;
  18917. stop = next.next;
  18918. continue;
  18919. }
  18920. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  18921. if (ear === stop) {
  18922. // try filtering points and slicing again
  18923. if (!pass) {
  18924. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  18925. } else if (pass === 1) {
  18926. ear = cureLocalIntersections(ear, triangles, dim);
  18927. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  18928. } else if (pass === 2) {
  18929. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  18930. }
  18931. break;
  18932. }
  18933. }
  18934. } // check whether a polygon node forms a valid ear with adjacent nodes
  18935. function isEar(ear) {
  18936. var a = ear.prev,
  18937. b = ear,
  18938. c = ear.next;
  18939. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  18940. // now make sure we don't have other points inside the potential ear
  18941. var p = ear.next.next;
  18942. while (p !== ear.prev) {
  18943. 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;
  18944. p = p.next;
  18945. }
  18946. return true;
  18947. }
  18948. function isEarHashed(ear, minX, minY, invSize) {
  18949. var a = ear.prev,
  18950. b = ear,
  18951. c = ear.next;
  18952. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  18953. // triangle bbox; min & max are calculated like this for speed
  18954. var minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  18955. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  18956. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  18957. 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;
  18958. var minZ = zOrder(minTX, minTY, minX, minY, invSize),
  18959. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  18960. var p = ear.prevZ,
  18961. n = ear.nextZ; // look for points inside the triangle in both directions
  18962. while (p && p.z >= minZ && n && n.z <= maxZ) {
  18963. 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;
  18964. p = p.prevZ;
  18965. 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;
  18966. n = n.nextZ;
  18967. } // look for remaining points in decreasing z-order
  18968. while (p && p.z >= minZ) {
  18969. 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;
  18970. p = p.prevZ;
  18971. } // look for remaining points in increasing z-order
  18972. while (n && n.z <= maxZ) {
  18973. 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;
  18974. n = n.nextZ;
  18975. }
  18976. return true;
  18977. } // go through all polygon nodes and cure small local self-intersections
  18978. function cureLocalIntersections(start, triangles, dim) {
  18979. var p = start;
  18980. do {
  18981. var a = p.prev,
  18982. b = p.next.next;
  18983. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  18984. triangles.push(a.i / dim);
  18985. triangles.push(p.i / dim);
  18986. triangles.push(b.i / dim); // remove two nodes involved
  18987. removeNode(p);
  18988. removeNode(p.next);
  18989. p = start = b;
  18990. }
  18991. p = p.next;
  18992. } while (p !== start);
  18993. return p;
  18994. } // try splitting polygon into two and triangulate them independently
  18995. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  18996. // look for a valid diagonal that divides the polygon into two
  18997. var a = start;
  18998. do {
  18999. var b = a.next.next;
  19000. while (b !== a.prev) {
  19001. if (a.i !== b.i && isValidDiagonal(a, b)) {
  19002. // split the polygon in two by the diagonal
  19003. var c = splitPolygon(a, b); // filter colinear points around the cuts
  19004. a = filterPoints(a, a.next);
  19005. c = filterPoints(c, c.next); // run earcut on each half
  19006. earcutLinked(a, triangles, dim, minX, minY, invSize);
  19007. earcutLinked(c, triangles, dim, minX, minY, invSize);
  19008. return;
  19009. }
  19010. b = b.next;
  19011. }
  19012. a = a.next;
  19013. } while (a !== start);
  19014. } // link every hole into the outer loop, producing a single-ring polygon without holes
  19015. function eliminateHoles(data, holeIndices, outerNode, dim) {
  19016. var queue = [],
  19017. i,
  19018. len,
  19019. start,
  19020. end,
  19021. list;
  19022. for (i = 0, len = holeIndices.length; i < len; i++) {
  19023. start = holeIndices[i] * dim;
  19024. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  19025. list = linkedList(data, start, end, dim, false);
  19026. if (list === list.next) list.steiner = true;
  19027. queue.push(getLeftmost(list));
  19028. }
  19029. queue.sort(compareX); // process holes from left to right
  19030. for (i = 0; i < queue.length; i++) {
  19031. eliminateHole(queue[i], outerNode);
  19032. outerNode = filterPoints(outerNode, outerNode.next);
  19033. }
  19034. return outerNode;
  19035. }
  19036. function compareX(a, b) {
  19037. return a.x - b.x;
  19038. } // find a bridge between vertices that connects hole with an outer ring and and link it
  19039. function eliminateHole(hole, outerNode) {
  19040. outerNode = findHoleBridge(hole, outerNode);
  19041. if (outerNode) {
  19042. var b = splitPolygon(outerNode, hole);
  19043. filterPoints(b, b.next);
  19044. }
  19045. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  19046. function findHoleBridge(hole, outerNode) {
  19047. var p = outerNode,
  19048. hx = hole.x,
  19049. hy = hole.y,
  19050. qx = -Infinity,
  19051. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  19052. // segment's endpoint with lesser x will be potential connection point
  19053. do {
  19054. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  19055. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  19056. if (x <= hx && x > qx) {
  19057. qx = x;
  19058. if (x === hx) {
  19059. if (hy === p.y) return p;
  19060. if (hy === p.next.y) return p.next;
  19061. }
  19062. m = p.x < p.next.x ? p : p.next;
  19063. }
  19064. }
  19065. p = p.next;
  19066. } while (p !== outerNode);
  19067. if (!m) return null;
  19068. if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint
  19069. // look for points inside the triangle of hole point, segment intersection and endpoint;
  19070. // if there are no points found, we have a valid connection;
  19071. // otherwise choose the point of the minimum angle with the ray as connection point
  19072. var stop = m,
  19073. mx = m.x,
  19074. my = m.y,
  19075. tanMin = Infinity,
  19076. tan;
  19077. p = m.next;
  19078. while (p !== stop) {
  19079. 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)) {
  19080. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  19081. if ((tan < tanMin || tan === tanMin && p.x > m.x) && locallyInside(p, hole)) {
  19082. m = p;
  19083. tanMin = tan;
  19084. }
  19085. }
  19086. p = p.next;
  19087. }
  19088. return m;
  19089. } // interlink polygon nodes in z-order
  19090. function indexCurve(start, minX, minY, invSize) {
  19091. var p = start;
  19092. do {
  19093. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  19094. p.prevZ = p.prev;
  19095. p.nextZ = p.next;
  19096. p = p.next;
  19097. } while (p !== start);
  19098. p.prevZ.nextZ = null;
  19099. p.prevZ = null;
  19100. sortLinked(p);
  19101. } // Simon Tatham's linked list merge sort algorithm
  19102. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  19103. function sortLinked(list) {
  19104. var i,
  19105. p,
  19106. q,
  19107. e,
  19108. tail,
  19109. numMerges,
  19110. pSize,
  19111. qSize,
  19112. inSize = 1;
  19113. do {
  19114. p = list;
  19115. list = null;
  19116. tail = null;
  19117. numMerges = 0;
  19118. while (p) {
  19119. numMerges++;
  19120. q = p;
  19121. pSize = 0;
  19122. for (i = 0; i < inSize; i++) {
  19123. pSize++;
  19124. q = q.nextZ;
  19125. if (!q) break;
  19126. }
  19127. qSize = inSize;
  19128. while (pSize > 0 || qSize > 0 && q) {
  19129. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  19130. e = p;
  19131. p = p.nextZ;
  19132. pSize--;
  19133. } else {
  19134. e = q;
  19135. q = q.nextZ;
  19136. qSize--;
  19137. }
  19138. if (tail) tail.nextZ = e;else list = e;
  19139. e.prevZ = tail;
  19140. tail = e;
  19141. }
  19142. p = q;
  19143. }
  19144. tail.nextZ = null;
  19145. inSize *= 2;
  19146. } while (numMerges > 1);
  19147. return list;
  19148. } // z-order of a point given coords and inverse of the longer side of data bbox
  19149. function zOrder(x, y, minX, minY, invSize) {
  19150. // coords are transformed into non-negative 15-bit integer range
  19151. x = 32767 * (x - minX) * invSize;
  19152. y = 32767 * (y - minY) * invSize;
  19153. x = (x | x << 8) & 0x00FF00FF;
  19154. x = (x | x << 4) & 0x0F0F0F0F;
  19155. x = (x | x << 2) & 0x33333333;
  19156. x = (x | x << 1) & 0x55555555;
  19157. y = (y | y << 8) & 0x00FF00FF;
  19158. y = (y | y << 4) & 0x0F0F0F0F;
  19159. y = (y | y << 2) & 0x33333333;
  19160. y = (y | y << 1) & 0x55555555;
  19161. return x | y << 1;
  19162. } // find the leftmost node of a polygon ring
  19163. function getLeftmost(start) {
  19164. var p = start,
  19165. leftmost = start;
  19166. do {
  19167. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  19168. p = p.next;
  19169. } while (p !== start);
  19170. return leftmost;
  19171. } // check if a point lies within a convex triangle
  19172. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  19173. 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;
  19174. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  19175. function isValidDiagonal(a, b) {
  19176. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
  19177. } // signed area of a triangle
  19178. function area(p, q, r) {
  19179. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  19180. } // check if two points are equal
  19181. function equals(p1, p2) {
  19182. return p1.x === p2.x && p1.y === p2.y;
  19183. } // check if two segments intersect
  19184. function intersects(p1, q1, p2, q2) {
  19185. if (equals(p1, p2) && equals(q1, q2) || equals(p1, q2) && equals(p2, q1)) return true;
  19186. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  19187. } // check if a polygon diagonal intersects any polygon segments
  19188. function intersectsPolygon(a, b) {
  19189. var p = a;
  19190. do {
  19191. 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;
  19192. p = p.next;
  19193. } while (p !== a);
  19194. return false;
  19195. } // check if a polygon diagonal is locally inside the polygon
  19196. function locallyInside(a, b) {
  19197. 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;
  19198. } // check if the middle point of a polygon diagonal is inside the polygon
  19199. function middleInside(a, b) {
  19200. var p = a,
  19201. inside = false,
  19202. px = (a.x + b.x) / 2,
  19203. py = (a.y + b.y) / 2;
  19204. do {
  19205. 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;
  19206. p = p.next;
  19207. } while (p !== a);
  19208. return inside;
  19209. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  19210. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  19211. function splitPolygon(a, b) {
  19212. var a2 = new Node(a.i, a.x, a.y),
  19213. b2 = new Node(b.i, b.x, b.y),
  19214. an = a.next,
  19215. bp = b.prev;
  19216. a.next = b;
  19217. b.prev = a;
  19218. a2.next = an;
  19219. an.prev = a2;
  19220. b2.next = a2;
  19221. a2.prev = b2;
  19222. bp.next = b2;
  19223. b2.prev = bp;
  19224. return b2;
  19225. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  19226. function insertNode(i, x, y, last) {
  19227. var p = new Node(i, x, y);
  19228. if (!last) {
  19229. p.prev = p;
  19230. p.next = p;
  19231. } else {
  19232. p.next = last.next;
  19233. p.prev = last;
  19234. last.next.prev = p;
  19235. last.next = p;
  19236. }
  19237. return p;
  19238. }
  19239. function removeNode(p) {
  19240. p.next.prev = p.prev;
  19241. p.prev.next = p.next;
  19242. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  19243. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  19244. }
  19245. function Node(i, x, y) {
  19246. // vertex index in coordinates array
  19247. this.i = i; // vertex coordinates
  19248. this.x = x;
  19249. this.y = y; // previous and next vertex nodes in a polygon ring
  19250. this.prev = null;
  19251. this.next = null; // z-order curve value
  19252. this.z = null; // previous and next nodes in z-order
  19253. this.prevZ = null;
  19254. this.nextZ = null; // indicates whether this is a steiner point
  19255. this.steiner = false;
  19256. }
  19257. function signedArea(data, start, end, dim) {
  19258. var sum = 0;
  19259. for (var i = start, j = end - dim; i < end; i += dim) {
  19260. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  19261. j = i;
  19262. }
  19263. return sum;
  19264. }
  19265. /**
  19266. * @author zz85 / http://www.lab4games.net/zz85/blog
  19267. */
  19268. var ShapeUtils = {
  19269. // calculate area of the contour polygon
  19270. area: function (contour) {
  19271. var n = contour.length;
  19272. var a = 0.0;
  19273. for (var p = n - 1, q = 0; q < n; p = q++) {
  19274. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  19275. }
  19276. return a * 0.5;
  19277. },
  19278. isClockWise: function (pts) {
  19279. return ShapeUtils.area(pts) < 0;
  19280. },
  19281. triangulateShape: function (contour, holes) {
  19282. var vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  19283. var holeIndices = []; // array of hole indices
  19284. var faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  19285. removeDupEndPts(contour);
  19286. addContour(vertices, contour); //
  19287. var holeIndex = contour.length;
  19288. holes.forEach(removeDupEndPts);
  19289. for (var i = 0; i < holes.length; i++) {
  19290. holeIndices.push(holeIndex);
  19291. holeIndex += holes[i].length;
  19292. addContour(vertices, holes[i]);
  19293. } //
  19294. var triangles = Earcut.triangulate(vertices, holeIndices); //
  19295. for (var i = 0; i < triangles.length; i += 3) {
  19296. faces.push(triangles.slice(i, i + 3));
  19297. }
  19298. return faces;
  19299. }
  19300. };
  19301. exports.ShapeUtils = ShapeUtils;
  19302. function removeDupEndPts(points) {
  19303. var l = points.length;
  19304. if (l > 2 && points[l - 1].equals(points[0])) {
  19305. points.pop();
  19306. }
  19307. }
  19308. function addContour(vertices, contour) {
  19309. for (var i = 0; i < contour.length; i++) {
  19310. vertices.push(contour[i].x);
  19311. vertices.push(contour[i].y);
  19312. }
  19313. }
  19314. /**
  19315. * @author zz85 / http://www.lab4games.net/zz85/blog
  19316. *
  19317. * Creates extruded geometry from a path shape.
  19318. *
  19319. * parameters = {
  19320. *
  19321. * curveSegments: <int>, // number of points on the curves
  19322. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  19323. * depth: <float>, // Depth to extrude the shape
  19324. *
  19325. * bevelEnabled: <bool>, // turn on bevel
  19326. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19327. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  19328. * bevelOffset: <float>, // how far from shape outline does bevel start
  19329. * bevelSegments: <int>, // number of bevel layers
  19330. *
  19331. * extrudePath: <THREE.Curve> // curve to extrude shape along
  19332. *
  19333. * UVGenerator: <Object> // object that provides UV generator functions
  19334. *
  19335. * }
  19336. */
  19337. // ExtrudeGeometry
  19338. function ExtrudeGeometry(shapes, options) {
  19339. Geometry.call(this);
  19340. this.type = 'ExtrudeGeometry';
  19341. this.parameters = {
  19342. shapes: shapes,
  19343. options: options
  19344. };
  19345. this.fromBufferGeometry(new ExtrudeBufferGeometry(shapes, options));
  19346. this.mergeVertices();
  19347. }
  19348. ExtrudeGeometry.prototype = Object.create(Geometry.prototype);
  19349. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  19350. ExtrudeGeometry.prototype.toJSON = function () {
  19351. var data = Geometry.prototype.toJSON.call(this);
  19352. var shapes = this.parameters.shapes;
  19353. var options = this.parameters.options;
  19354. return toJSON(shapes, options, data);
  19355. }; // ExtrudeBufferGeometry
  19356. function ExtrudeBufferGeometry(shapes, options) {
  19357. BufferGeometry.call(this);
  19358. this.type = 'ExtrudeBufferGeometry';
  19359. this.parameters = {
  19360. shapes: shapes,
  19361. options: options
  19362. };
  19363. shapes = Array.isArray(shapes) ? shapes : [shapes];
  19364. var scope = this;
  19365. var verticesArray = [];
  19366. var uvArray = [];
  19367. for (var i = 0, l = shapes.length; i < l; i++) {
  19368. var shape = shapes[i];
  19369. addShape(shape);
  19370. } // build geometry
  19371. this.addAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  19372. this.addAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  19373. this.computeVertexNormals(); // functions
  19374. function addShape(shape) {
  19375. var placeholder = []; // options
  19376. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19377. var steps = options.steps !== undefined ? options.steps : 1;
  19378. var depth = options.depth !== undefined ? options.depth : 100;
  19379. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  19380. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  19381. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  19382. var bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  19383. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19384. var extrudePath = options.extrudePath;
  19385. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
  19386. if (options.amount !== undefined) {
  19387. console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
  19388. depth = options.amount;
  19389. } //
  19390. var extrudePts,
  19391. extrudeByPath = false;
  19392. var splineTube, binormal, normal, position2;
  19393. if (extrudePath) {
  19394. extrudePts = extrudePath.getSpacedPoints(steps);
  19395. extrudeByPath = true;
  19396. bevelEnabled = false; // bevels not supported for path extrusion
  19397. // SETUP TNB variables
  19398. // TODO1 - have a .isClosed in spline?
  19399. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19400. binormal = new Vector3();
  19401. normal = new Vector3();
  19402. position2 = new Vector3();
  19403. } // Safeguards if bevels are not enabled
  19404. if (!bevelEnabled) {
  19405. bevelSegments = 0;
  19406. bevelThickness = 0;
  19407. bevelSize = 0;
  19408. bevelOffset = 0;
  19409. } // Variables initialization
  19410. var ahole, h, hl; // looping of holes
  19411. var shapePoints = shape.extractPoints(curveSegments);
  19412. var vertices = shapePoints.shape;
  19413. var holes = shapePoints.holes;
  19414. var reverse = !ShapeUtils.isClockWise(vertices);
  19415. if (reverse) {
  19416. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19417. for (h = 0, hl = holes.length; h < hl; h++) {
  19418. ahole = holes[h];
  19419. if (ShapeUtils.isClockWise(ahole)) {
  19420. holes[h] = ahole.reverse();
  19421. }
  19422. }
  19423. }
  19424. var faces = ShapeUtils.triangulateShape(vertices, holes);
  19425. /* Vertices */
  19426. var contour = vertices; // vertices has all points but contour has only points of circumference
  19427. for (h = 0, hl = holes.length; h < hl; h++) {
  19428. ahole = holes[h];
  19429. vertices = vertices.concat(ahole);
  19430. }
  19431. function scalePt2(pt, vec, size) {
  19432. if (!vec) console.error("THREE.ExtrudeGeometry: vec does not exist");
  19433. return vec.clone().multiplyScalar(size).add(pt);
  19434. }
  19435. var b,
  19436. bs,
  19437. t,
  19438. z,
  19439. vert,
  19440. vlen = vertices.length,
  19441. face,
  19442. flen = faces.length; // Find directions for point movement
  19443. function getBevelVec(inPt, inPrev, inNext) {
  19444. // computes for inPt the corresponding point inPt' on a new contour
  19445. // shifted by 1 unit (length of normalized vector) to the left
  19446. // if we walk along contour clockwise, this new contour is outside the old one
  19447. //
  19448. // inPt' is the intersection of the two lines parallel to the two
  19449. // adjacent edges of inPt at a distance of 1 unit on the left side.
  19450. var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  19451. // good reading for geometry algorithms (here: line-line intersection)
  19452. // http://geomalgorithms.com/a05-_intersect-1.html
  19453. var v_prev_x = inPt.x - inPrev.x,
  19454. v_prev_y = inPt.y - inPrev.y;
  19455. var v_next_x = inNext.x - inPt.x,
  19456. v_next_y = inNext.y - inPt.y;
  19457. var v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  19458. var collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  19459. if (Math.abs(collinear0) > Number.EPSILON) {
  19460. // not collinear
  19461. // length of vectors for normalizing
  19462. var v_prev_len = Math.sqrt(v_prev_lensq);
  19463. 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
  19464. var ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  19465. var ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  19466. var ptNextShift_x = inNext.x - v_next_y / v_next_len;
  19467. var ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  19468. 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
  19469. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  19470. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  19471. // but prevent crazy spikes
  19472. var v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  19473. if (v_trans_lensq <= 2) {
  19474. return new Vector2(v_trans_x, v_trans_y);
  19475. } else {
  19476. shrink_by = Math.sqrt(v_trans_lensq / 2);
  19477. }
  19478. } else {
  19479. // handle special case of collinear edges
  19480. var direction_eq = false; // assumes: opposite
  19481. if (v_prev_x > Number.EPSILON) {
  19482. if (v_next_x > Number.EPSILON) {
  19483. direction_eq = true;
  19484. }
  19485. } else {
  19486. if (v_prev_x < -Number.EPSILON) {
  19487. if (v_next_x < -Number.EPSILON) {
  19488. direction_eq = true;
  19489. }
  19490. } else {
  19491. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  19492. direction_eq = true;
  19493. }
  19494. }
  19495. }
  19496. if (direction_eq) {
  19497. // console.log("Warning: lines are a straight sequence");
  19498. v_trans_x = -v_prev_y;
  19499. v_trans_y = v_prev_x;
  19500. shrink_by = Math.sqrt(v_prev_lensq);
  19501. } else {
  19502. // console.log("Warning: lines are a straight spike");
  19503. v_trans_x = v_prev_x;
  19504. v_trans_y = v_prev_y;
  19505. shrink_by = Math.sqrt(v_prev_lensq / 2);
  19506. }
  19507. }
  19508. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  19509. }
  19510. var contourMovements = [];
  19511. for (var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  19512. if (j === il) j = 0;
  19513. if (k === il) k = 0; // (j)---(i)---(k)
  19514. // console.log('i,j,k', i, j , k)
  19515. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  19516. }
  19517. var holesMovements = [],
  19518. oneHoleMovements,
  19519. verticesMovements = contourMovements.concat();
  19520. for (h = 0, hl = holes.length; h < hl; h++) {
  19521. ahole = holes[h];
  19522. oneHoleMovements = [];
  19523. for (i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  19524. if (j === il) j = 0;
  19525. if (k === il) k = 0; // (j)---(i)---(k)
  19526. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  19527. }
  19528. holesMovements.push(oneHoleMovements);
  19529. verticesMovements = verticesMovements.concat(oneHoleMovements);
  19530. } // Loop bevelSegments, 1 for the front, 1 for the back
  19531. for (b = 0; b < bevelSegments; b++) {
  19532. //for ( b = bevelSegments; b > 0; b -- ) {
  19533. t = b / bevelSegments;
  19534. z = bevelThickness * Math.cos(t * Math.PI / 2);
  19535. bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  19536. for (i = 0, il = contour.length; i < il; i++) {
  19537. vert = scalePt2(contour[i], contourMovements[i], bs);
  19538. v(vert.x, vert.y, -z);
  19539. } // expand holes
  19540. for (h = 0, hl = holes.length; h < hl; h++) {
  19541. ahole = holes[h];
  19542. oneHoleMovements = holesMovements[h];
  19543. for (i = 0, il = ahole.length; i < il; i++) {
  19544. vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  19545. v(vert.x, vert.y, -z);
  19546. }
  19547. }
  19548. }
  19549. bs = bevelSize + bevelOffset; // Back facing vertices
  19550. for (i = 0; i < vlen; i++) {
  19551. vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  19552. if (!extrudeByPath) {
  19553. v(vert.x, vert.y, 0);
  19554. } else {
  19555. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19556. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  19557. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  19558. position2.copy(extrudePts[0]).add(normal).add(binormal);
  19559. v(position2.x, position2.y, position2.z);
  19560. }
  19561. } // Add stepped vertices...
  19562. // Including front facing vertices
  19563. var s;
  19564. for (s = 1; s <= steps; s++) {
  19565. for (i = 0; i < vlen; i++) {
  19566. vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  19567. if (!extrudeByPath) {
  19568. v(vert.x, vert.y, depth / steps * s);
  19569. } else {
  19570. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19571. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  19572. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  19573. position2.copy(extrudePts[s]).add(normal).add(binormal);
  19574. v(position2.x, position2.y, position2.z);
  19575. }
  19576. }
  19577. } // Add bevel segments planes
  19578. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19579. for (b = bevelSegments - 1; b >= 0; b--) {
  19580. t = b / bevelSegments;
  19581. z = bevelThickness * Math.cos(t * Math.PI / 2);
  19582. bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  19583. for (i = 0, il = contour.length; i < il; i++) {
  19584. vert = scalePt2(contour[i], contourMovements[i], bs);
  19585. v(vert.x, vert.y, depth + z);
  19586. } // expand holes
  19587. for (h = 0, hl = holes.length; h < hl; h++) {
  19588. ahole = holes[h];
  19589. oneHoleMovements = holesMovements[h];
  19590. for (i = 0, il = ahole.length; i < il; i++) {
  19591. vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  19592. if (!extrudeByPath) {
  19593. v(vert.x, vert.y, depth + z);
  19594. } else {
  19595. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  19596. }
  19597. }
  19598. }
  19599. }
  19600. /* Faces */
  19601. // Top and bottom faces
  19602. buildLidFaces(); // Sides faces
  19603. buildSideFaces(); ///// Internal functions
  19604. function buildLidFaces() {
  19605. var start = verticesArray.length / 3;
  19606. if (bevelEnabled) {
  19607. var layer = 0; // steps + 1
  19608. var offset = vlen * layer; // Bottom faces
  19609. for (i = 0; i < flen; i++) {
  19610. face = faces[i];
  19611. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  19612. }
  19613. layer = steps + bevelSegments * 2;
  19614. offset = vlen * layer; // Top faces
  19615. for (i = 0; i < flen; i++) {
  19616. face = faces[i];
  19617. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  19618. }
  19619. } else {
  19620. // Bottom faces
  19621. for (i = 0; i < flen; i++) {
  19622. face = faces[i];
  19623. f3(face[2], face[1], face[0]);
  19624. } // Top faces
  19625. for (i = 0; i < flen; i++) {
  19626. face = faces[i];
  19627. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  19628. }
  19629. }
  19630. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  19631. } // Create faces for the z-sides of the shape
  19632. function buildSideFaces() {
  19633. var start = verticesArray.length / 3;
  19634. var layeroffset = 0;
  19635. sidewalls(contour, layeroffset);
  19636. layeroffset += contour.length;
  19637. for (h = 0, hl = holes.length; h < hl; h++) {
  19638. ahole = holes[h];
  19639. sidewalls(ahole, layeroffset); //, true
  19640. layeroffset += ahole.length;
  19641. }
  19642. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  19643. }
  19644. function sidewalls(contour, layeroffset) {
  19645. var j, k;
  19646. i = contour.length;
  19647. while (--i >= 0) {
  19648. j = i;
  19649. k = i - 1;
  19650. if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  19651. var s = 0,
  19652. sl = steps + bevelSegments * 2;
  19653. for (s = 0; s < sl; s++) {
  19654. var slen1 = vlen * s;
  19655. var slen2 = vlen * (s + 1);
  19656. var a = layeroffset + j + slen1,
  19657. b = layeroffset + k + slen1,
  19658. c = layeroffset + k + slen2,
  19659. d = layeroffset + j + slen2;
  19660. f4(a, b, c, d);
  19661. }
  19662. }
  19663. }
  19664. function v(x, y, z) {
  19665. placeholder.push(x);
  19666. placeholder.push(y);
  19667. placeholder.push(z);
  19668. }
  19669. function f3(a, b, c) {
  19670. addVertex(a);
  19671. addVertex(b);
  19672. addVertex(c);
  19673. var nextIndex = verticesArray.length / 3;
  19674. var uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  19675. addUV(uvs[0]);
  19676. addUV(uvs[1]);
  19677. addUV(uvs[2]);
  19678. }
  19679. function f4(a, b, c, d) {
  19680. addVertex(a);
  19681. addVertex(b);
  19682. addVertex(d);
  19683. addVertex(b);
  19684. addVertex(c);
  19685. addVertex(d);
  19686. var nextIndex = verticesArray.length / 3;
  19687. var uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  19688. addUV(uvs[0]);
  19689. addUV(uvs[1]);
  19690. addUV(uvs[3]);
  19691. addUV(uvs[1]);
  19692. addUV(uvs[2]);
  19693. addUV(uvs[3]);
  19694. }
  19695. function addVertex(index) {
  19696. verticesArray.push(placeholder[index * 3 + 0]);
  19697. verticesArray.push(placeholder[index * 3 + 1]);
  19698. verticesArray.push(placeholder[index * 3 + 2]);
  19699. }
  19700. function addUV(vector2) {
  19701. uvArray.push(vector2.x);
  19702. uvArray.push(vector2.y);
  19703. }
  19704. }
  19705. }
  19706. ExtrudeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19707. ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry;
  19708. ExtrudeBufferGeometry.prototype.toJSON = function () {
  19709. var data = BufferGeometry.prototype.toJSON.call(this);
  19710. var shapes = this.parameters.shapes;
  19711. var options = this.parameters.options;
  19712. return toJSON(shapes, options, data);
  19713. }; //
  19714. var WorldUVGenerator = {
  19715. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  19716. var a_x = vertices[indexA * 3];
  19717. var a_y = vertices[indexA * 3 + 1];
  19718. var b_x = vertices[indexB * 3];
  19719. var b_y = vertices[indexB * 3 + 1];
  19720. var c_x = vertices[indexC * 3];
  19721. var c_y = vertices[indexC * 3 + 1];
  19722. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  19723. },
  19724. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  19725. var a_x = vertices[indexA * 3];
  19726. var a_y = vertices[indexA * 3 + 1];
  19727. var a_z = vertices[indexA * 3 + 2];
  19728. var b_x = vertices[indexB * 3];
  19729. var b_y = vertices[indexB * 3 + 1];
  19730. var b_z = vertices[indexB * 3 + 2];
  19731. var c_x = vertices[indexC * 3];
  19732. var c_y = vertices[indexC * 3 + 1];
  19733. var c_z = vertices[indexC * 3 + 2];
  19734. var d_x = vertices[indexD * 3];
  19735. var d_y = vertices[indexD * 3 + 1];
  19736. var d_z = vertices[indexD * 3 + 2];
  19737. if (Math.abs(a_y - b_y) < 0.01) {
  19738. 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)];
  19739. } else {
  19740. 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)];
  19741. }
  19742. }
  19743. };
  19744. function toJSON(shapes, options, data) {
  19745. //
  19746. data.shapes = [];
  19747. if (Array.isArray(shapes)) {
  19748. for (var i = 0, l = shapes.length; i < l; i++) {
  19749. var shape = shapes[i];
  19750. data.shapes.push(shape.uuid);
  19751. }
  19752. } else {
  19753. data.shapes.push(shapes.uuid);
  19754. } //
  19755. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  19756. return data;
  19757. }
  19758. /**
  19759. * @author zz85 / http://www.lab4games.net/zz85/blog
  19760. * @author alteredq / http://alteredqualia.com/
  19761. *
  19762. * Text = 3D Text
  19763. *
  19764. * parameters = {
  19765. * font: <THREE.Font>, // font
  19766. *
  19767. * size: <float>, // size of the text
  19768. * height: <float>, // thickness to extrude text
  19769. * curveSegments: <int>, // number of points on the curves
  19770. *
  19771. * bevelEnabled: <bool>, // turn on bevel
  19772. * bevelThickness: <float>, // how deep into text bevel goes
  19773. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  19774. * bevelOffset: <float> // how far from text outline does bevel start
  19775. * }
  19776. */
  19777. // TextGeometry
  19778. function TextGeometry(text, parameters) {
  19779. Geometry.call(this);
  19780. this.type = 'TextGeometry';
  19781. this.parameters = {
  19782. text: text,
  19783. parameters: parameters
  19784. };
  19785. this.fromBufferGeometry(new TextBufferGeometry(text, parameters));
  19786. this.mergeVertices();
  19787. }
  19788. TextGeometry.prototype = Object.create(Geometry.prototype);
  19789. TextGeometry.prototype.constructor = TextGeometry; // TextBufferGeometry
  19790. function TextBufferGeometry(text, parameters) {
  19791. parameters = parameters || {};
  19792. var font = parameters.font;
  19793. if (!(font && font.isFont)) {
  19794. console.error('THREE.TextGeometry: font parameter is not an instance of THREE.Font.');
  19795. return new Geometry();
  19796. }
  19797. var shapes = font.generateShapes(text, parameters.size); // translate parameters to ExtrudeGeometry API
  19798. parameters.depth = parameters.height !== undefined ? parameters.height : 50; // defaults
  19799. if (parameters.bevelThickness === undefined) parameters.bevelThickness = 10;
  19800. if (parameters.bevelSize === undefined) parameters.bevelSize = 8;
  19801. if (parameters.bevelEnabled === undefined) parameters.bevelEnabled = false;
  19802. ExtrudeBufferGeometry.call(this, shapes, parameters);
  19803. this.type = 'TextBufferGeometry';
  19804. }
  19805. TextBufferGeometry.prototype = Object.create(ExtrudeBufferGeometry.prototype);
  19806. TextBufferGeometry.prototype.constructor = TextBufferGeometry;
  19807. /**
  19808. * @author mrdoob / http://mrdoob.com/
  19809. * @author benaadams / https://twitter.com/ben_a_adams
  19810. * @author Mugen87 / https://github.com/Mugen87
  19811. */
  19812. // SphereGeometry
  19813. function SphereGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
  19814. Geometry.call(this);
  19815. this.type = 'SphereGeometry';
  19816. this.parameters = {
  19817. radius: radius,
  19818. widthSegments: widthSegments,
  19819. heightSegments: heightSegments,
  19820. phiStart: phiStart,
  19821. phiLength: phiLength,
  19822. thetaStart: thetaStart,
  19823. thetaLength: thetaLength
  19824. };
  19825. this.fromBufferGeometry(new SphereBufferGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength));
  19826. this.mergeVertices();
  19827. }
  19828. SphereGeometry.prototype = Object.create(Geometry.prototype);
  19829. SphereGeometry.prototype.constructor = SphereGeometry; // SphereBufferGeometry
  19830. function SphereBufferGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
  19831. BufferGeometry.call(this);
  19832. this.type = 'SphereBufferGeometry';
  19833. this.parameters = {
  19834. radius: radius,
  19835. widthSegments: widthSegments,
  19836. heightSegments: heightSegments,
  19837. phiStart: phiStart,
  19838. phiLength: phiLength,
  19839. thetaStart: thetaStart,
  19840. thetaLength: thetaLength
  19841. };
  19842. radius = radius || 1;
  19843. widthSegments = Math.max(3, Math.floor(widthSegments) || 8);
  19844. heightSegments = Math.max(2, Math.floor(heightSegments) || 6);
  19845. phiStart = phiStart !== undefined ? phiStart : 0;
  19846. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19847. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19848. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19849. var thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  19850. var ix, iy;
  19851. var index = 0;
  19852. var grid = [];
  19853. var vertex = new Vector3();
  19854. var normal = new Vector3(); // buffers
  19855. var indices = [];
  19856. var vertices = [];
  19857. var normals = [];
  19858. var uvs = []; // generate vertices, normals and uvs
  19859. for (iy = 0; iy <= heightSegments; iy++) {
  19860. var verticesRow = [];
  19861. var v = iy / heightSegments; // special case for the poles
  19862. var uOffset = 0;
  19863. if (iy == 0 && thetaStart == 0) {
  19864. uOffset = 0.5 / widthSegments;
  19865. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  19866. uOffset = -0.5 / widthSegments;
  19867. }
  19868. for (ix = 0; ix <= widthSegments; ix++) {
  19869. var u = ix / widthSegments; // vertex
  19870. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  19871. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  19872. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  19873. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19874. normal.copy(vertex).normalize();
  19875. normals.push(normal.x, normal.y, normal.z); // uv
  19876. uvs.push(u + uOffset, 1 - v);
  19877. verticesRow.push(index++);
  19878. }
  19879. grid.push(verticesRow);
  19880. } // indices
  19881. for (iy = 0; iy < heightSegments; iy++) {
  19882. for (ix = 0; ix < widthSegments; ix++) {
  19883. var a = grid[iy][ix + 1];
  19884. var b = grid[iy][ix];
  19885. var c = grid[iy + 1][ix];
  19886. var d = grid[iy + 1][ix + 1];
  19887. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  19888. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  19889. }
  19890. } // build geometry
  19891. this.setIndex(indices);
  19892. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  19893. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  19894. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19895. }
  19896. SphereBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19897. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  19898. /**
  19899. * @author Kaleb Murphy
  19900. * @author Mugen87 / https://github.com/Mugen87
  19901. */
  19902. // RingGeometry
  19903. function RingGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
  19904. Geometry.call(this);
  19905. this.type = 'RingGeometry';
  19906. this.parameters = {
  19907. innerRadius: innerRadius,
  19908. outerRadius: outerRadius,
  19909. thetaSegments: thetaSegments,
  19910. phiSegments: phiSegments,
  19911. thetaStart: thetaStart,
  19912. thetaLength: thetaLength
  19913. };
  19914. this.fromBufferGeometry(new RingBufferGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength));
  19915. this.mergeVertices();
  19916. }
  19917. RingGeometry.prototype = Object.create(Geometry.prototype);
  19918. RingGeometry.prototype.constructor = RingGeometry; // RingBufferGeometry
  19919. function RingBufferGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
  19920. BufferGeometry.call(this);
  19921. this.type = 'RingBufferGeometry';
  19922. this.parameters = {
  19923. innerRadius: innerRadius,
  19924. outerRadius: outerRadius,
  19925. thetaSegments: thetaSegments,
  19926. phiSegments: phiSegments,
  19927. thetaStart: thetaStart,
  19928. thetaLength: thetaLength
  19929. };
  19930. innerRadius = innerRadius || 0.5;
  19931. outerRadius = outerRadius || 1;
  19932. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19933. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19934. thetaSegments = thetaSegments !== undefined ? Math.max(3, thetaSegments) : 8;
  19935. phiSegments = phiSegments !== undefined ? Math.max(1, phiSegments) : 1; // buffers
  19936. var indices = [];
  19937. var vertices = [];
  19938. var normals = [];
  19939. var uvs = []; // some helper variables
  19940. var segment;
  19941. var radius = innerRadius;
  19942. var radiusStep = (outerRadius - innerRadius) / phiSegments;
  19943. var vertex = new Vector3();
  19944. var uv = new Vector2();
  19945. var j, i; // generate vertices, normals and uvs
  19946. for (j = 0; j <= phiSegments; j++) {
  19947. for (i = 0; i <= thetaSegments; i++) {
  19948. // values are generate from the inside of the ring to the outside
  19949. segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  19950. vertex.x = radius * Math.cos(segment);
  19951. vertex.y = radius * Math.sin(segment);
  19952. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19953. normals.push(0, 0, 1); // uv
  19954. uv.x = (vertex.x / outerRadius + 1) / 2;
  19955. uv.y = (vertex.y / outerRadius + 1) / 2;
  19956. uvs.push(uv.x, uv.y);
  19957. } // increase the radius for next row of vertices
  19958. radius += radiusStep;
  19959. } // indices
  19960. for (j = 0; j < phiSegments; j++) {
  19961. var thetaSegmentLevel = j * (thetaSegments + 1);
  19962. for (i = 0; i < thetaSegments; i++) {
  19963. segment = i + thetaSegmentLevel;
  19964. var a = segment;
  19965. var b = segment + thetaSegments + 1;
  19966. var c = segment + thetaSegments + 2;
  19967. var d = segment + 1; // faces
  19968. indices.push(a, b, d);
  19969. indices.push(b, c, d);
  19970. }
  19971. } // build geometry
  19972. this.setIndex(indices);
  19973. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  19974. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  19975. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19976. }
  19977. RingBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19978. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  19979. /**
  19980. * @author zz85 / https://github.com/zz85
  19981. * @author bhouston / http://clara.io
  19982. * @author Mugen87 / https://github.com/Mugen87
  19983. */
  19984. // LatheGeometry
  19985. function LatheGeometry(points, segments, phiStart, phiLength) {
  19986. Geometry.call(this);
  19987. this.type = 'LatheGeometry';
  19988. this.parameters = {
  19989. points: points,
  19990. segments: segments,
  19991. phiStart: phiStart,
  19992. phiLength: phiLength
  19993. };
  19994. this.fromBufferGeometry(new LatheBufferGeometry(points, segments, phiStart, phiLength));
  19995. this.mergeVertices();
  19996. }
  19997. LatheGeometry.prototype = Object.create(Geometry.prototype);
  19998. LatheGeometry.prototype.constructor = LatheGeometry; // LatheBufferGeometry
  19999. function LatheBufferGeometry(points, segments, phiStart, phiLength) {
  20000. BufferGeometry.call(this);
  20001. this.type = 'LatheBufferGeometry';
  20002. this.parameters = {
  20003. points: points,
  20004. segments: segments,
  20005. phiStart: phiStart,
  20006. phiLength: phiLength
  20007. };
  20008. segments = Math.floor(segments) || 12;
  20009. phiStart = phiStart || 0;
  20010. phiLength = phiLength || Math.PI * 2; // clamp phiLength so it's in range of [ 0, 2PI ]
  20011. phiLength = _Math.clamp(phiLength, 0, Math.PI * 2); // buffers
  20012. var indices = [];
  20013. var vertices = [];
  20014. var uvs = []; // helper variables
  20015. var base;
  20016. var inverseSegments = 1.0 / segments;
  20017. var vertex = new Vector3();
  20018. var uv = new Vector2();
  20019. var i, j; // generate vertices and uvs
  20020. for (i = 0; i <= segments; i++) {
  20021. var phi = phiStart + i * inverseSegments * phiLength;
  20022. var sin = Math.sin(phi);
  20023. var cos = Math.cos(phi);
  20024. for (j = 0; j <= points.length - 1; j++) {
  20025. // vertex
  20026. vertex.x = points[j].x * sin;
  20027. vertex.y = points[j].y;
  20028. vertex.z = points[j].x * cos;
  20029. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  20030. uv.x = i / segments;
  20031. uv.y = j / (points.length - 1);
  20032. uvs.push(uv.x, uv.y);
  20033. }
  20034. } // indices
  20035. for (i = 0; i < segments; i++) {
  20036. for (j = 0; j < points.length - 1; j++) {
  20037. base = j + i * points.length;
  20038. var a = base;
  20039. var b = base + points.length;
  20040. var c = base + points.length + 1;
  20041. var d = base + 1; // faces
  20042. indices.push(a, b, d);
  20043. indices.push(b, c, d);
  20044. }
  20045. } // build geometry
  20046. this.setIndex(indices);
  20047. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  20048. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // generate normals
  20049. this.computeVertexNormals(); // if the geometry is closed, we need to average the normals along the seam.
  20050. // because the corresponding vertices are identical (but still have different UVs).
  20051. if (phiLength === Math.PI * 2) {
  20052. var normals = this.attributes.normal.array;
  20053. var n1 = new Vector3();
  20054. var n2 = new Vector3();
  20055. var n = new Vector3(); // this is the buffer offset for the last line of vertices
  20056. base = segments * points.length * 3;
  20057. for (i = 0, j = 0; i < points.length; i++, j += 3) {
  20058. // select the normal of the vertex in the first line
  20059. n1.x = normals[j + 0];
  20060. n1.y = normals[j + 1];
  20061. n1.z = normals[j + 2]; // select the normal of the vertex in the last line
  20062. n2.x = normals[base + j + 0];
  20063. n2.y = normals[base + j + 1];
  20064. n2.z = normals[base + j + 2]; // average normals
  20065. n.addVectors(n1, n2).normalize(); // assign the new values to both normals
  20066. normals[j + 0] = normals[base + j + 0] = n.x;
  20067. normals[j + 1] = normals[base + j + 1] = n.y;
  20068. normals[j + 2] = normals[base + j + 2] = n.z;
  20069. }
  20070. }
  20071. }
  20072. LatheBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  20073. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  20074. /**
  20075. * @author jonobr1 / http://jonobr1.com
  20076. * @author Mugen87 / https://github.com/Mugen87
  20077. */
  20078. // ShapeGeometry
  20079. function ShapeGeometry(shapes, curveSegments) {
  20080. Geometry.call(this);
  20081. this.type = 'ShapeGeometry';
  20082. if (typeof curveSegments === 'object') {
  20083. console.warn('THREE.ShapeGeometry: Options parameter has been removed.');
  20084. curveSegments = curveSegments.curveSegments;
  20085. }
  20086. this.parameters = {
  20087. shapes: shapes,
  20088. curveSegments: curveSegments
  20089. };
  20090. this.fromBufferGeometry(new ShapeBufferGeometry(shapes, curveSegments));
  20091. this.mergeVertices();
  20092. }
  20093. ShapeGeometry.prototype = Object.create(Geometry.prototype);
  20094. ShapeGeometry.prototype.constructor = ShapeGeometry;
  20095. ShapeGeometry.prototype.toJSON = function () {
  20096. var data = Geometry.prototype.toJSON.call(this);
  20097. var shapes = this.parameters.shapes;
  20098. return toJSON$1(shapes, data);
  20099. }; // ShapeBufferGeometry
  20100. function ShapeBufferGeometry(shapes, curveSegments) {
  20101. BufferGeometry.call(this);
  20102. this.type = 'ShapeBufferGeometry';
  20103. this.parameters = {
  20104. shapes: shapes,
  20105. curveSegments: curveSegments
  20106. };
  20107. curveSegments = curveSegments || 12; // buffers
  20108. var indices = [];
  20109. var vertices = [];
  20110. var normals = [];
  20111. var uvs = []; // helper variables
  20112. var groupStart = 0;
  20113. var groupCount = 0; // allow single and array values for "shapes" parameter
  20114. if (Array.isArray(shapes) === false) {
  20115. addShape(shapes);
  20116. } else {
  20117. for (var i = 0; i < shapes.length; i++) {
  20118. addShape(shapes[i]);
  20119. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  20120. groupStart += groupCount;
  20121. groupCount = 0;
  20122. }
  20123. } // build geometry
  20124. this.setIndex(indices);
  20125. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  20126. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  20127. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  20128. function addShape(shape) {
  20129. var i, l, shapeHole;
  20130. var indexOffset = vertices.length / 3;
  20131. var points = shape.extractPoints(curveSegments);
  20132. var shapeVertices = points.shape;
  20133. var shapeHoles = points.holes; // check direction of vertices
  20134. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  20135. shapeVertices = shapeVertices.reverse();
  20136. }
  20137. for (i = 0, l = shapeHoles.length; i < l; i++) {
  20138. shapeHole = shapeHoles[i];
  20139. if (ShapeUtils.isClockWise(shapeHole) === true) {
  20140. shapeHoles[i] = shapeHole.reverse();
  20141. }
  20142. }
  20143. var faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  20144. for (i = 0, l = shapeHoles.length; i < l; i++) {
  20145. shapeHole = shapeHoles[i];
  20146. shapeVertices = shapeVertices.concat(shapeHole);
  20147. } // vertices, normals, uvs
  20148. for (i = 0, l = shapeVertices.length; i < l; i++) {
  20149. var vertex = shapeVertices[i];
  20150. vertices.push(vertex.x, vertex.y, 0);
  20151. normals.push(0, 0, 1);
  20152. uvs.push(vertex.x, vertex.y); // world uvs
  20153. } // incides
  20154. for (i = 0, l = faces.length; i < l; i++) {
  20155. var face = faces[i];
  20156. var a = face[0] + indexOffset;
  20157. var b = face[1] + indexOffset;
  20158. var c = face[2] + indexOffset;
  20159. indices.push(a, b, c);
  20160. groupCount += 3;
  20161. }
  20162. }
  20163. }
  20164. ShapeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  20165. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  20166. ShapeBufferGeometry.prototype.toJSON = function () {
  20167. var data = BufferGeometry.prototype.toJSON.call(this);
  20168. var shapes = this.parameters.shapes;
  20169. return toJSON$1(shapes, data);
  20170. }; //
  20171. function toJSON$1(shapes, data) {
  20172. data.shapes = [];
  20173. if (Array.isArray(shapes)) {
  20174. for (var i = 0, l = shapes.length; i < l; i++) {
  20175. var shape = shapes[i];
  20176. data.shapes.push(shape.uuid);
  20177. }
  20178. } else {
  20179. data.shapes.push(shapes.uuid);
  20180. }
  20181. return data;
  20182. }
  20183. /**
  20184. * @author WestLangley / http://github.com/WestLangley
  20185. * @author Mugen87 / https://github.com/Mugen87
  20186. */
  20187. function EdgesGeometry(geometry, thresholdAngle) {
  20188. BufferGeometry.call(this);
  20189. this.type = 'EdgesGeometry';
  20190. this.parameters = {
  20191. thresholdAngle: thresholdAngle
  20192. };
  20193. thresholdAngle = thresholdAngle !== undefined ? thresholdAngle : 1; // buffer
  20194. var vertices = []; // helper variables
  20195. var thresholdDot = Math.cos(_Math.DEG2RAD * thresholdAngle);
  20196. var edge = [0, 0],
  20197. edges = {},
  20198. edge1,
  20199. edge2;
  20200. var key,
  20201. keys = ['a', 'b', 'c']; // prepare source geometry
  20202. var geometry2;
  20203. if (geometry.isBufferGeometry) {
  20204. geometry2 = new Geometry();
  20205. geometry2.fromBufferGeometry(geometry);
  20206. } else {
  20207. geometry2 = geometry.clone();
  20208. }
  20209. geometry2.mergeVertices();
  20210. geometry2.computeFaceNormals();
  20211. var sourceVertices = geometry2.vertices;
  20212. var faces = geometry2.faces; // now create a data structure where each entry represents an edge with its adjoining faces
  20213. for (var i = 0, l = faces.length; i < l; i++) {
  20214. var face = faces[i];
  20215. for (var j = 0; j < 3; j++) {
  20216. edge1 = face[keys[j]];
  20217. edge2 = face[keys[(j + 1) % 3]];
  20218. edge[0] = Math.min(edge1, edge2);
  20219. edge[1] = Math.max(edge1, edge2);
  20220. key = edge[0] + ',' + edge[1];
  20221. if (edges[key] === undefined) {
  20222. edges[key] = {
  20223. index1: edge[0],
  20224. index2: edge[1],
  20225. face1: i,
  20226. face2: undefined
  20227. };
  20228. } else {
  20229. edges[key].face2 = i;
  20230. }
  20231. }
  20232. } // generate vertices
  20233. for (key in edges) {
  20234. 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.
  20235. if (e.face2 === undefined || faces[e.face1].normal.dot(faces[e.face2].normal) <= thresholdDot) {
  20236. var vertex = sourceVertices[e.index1];
  20237. vertices.push(vertex.x, vertex.y, vertex.z);
  20238. vertex = sourceVertices[e.index2];
  20239. vertices.push(vertex.x, vertex.y, vertex.z);
  20240. }
  20241. } // build geometry
  20242. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  20243. }
  20244. EdgesGeometry.prototype = Object.create(BufferGeometry.prototype);
  20245. EdgesGeometry.prototype.constructor = EdgesGeometry;
  20246. /**
  20247. * @author mrdoob / http://mrdoob.com/
  20248. * @author Mugen87 / https://github.com/Mugen87
  20249. */
  20250. // CylinderGeometry
  20251. function CylinderGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  20252. Geometry.call(this);
  20253. this.type = 'CylinderGeometry';
  20254. this.parameters = {
  20255. radiusTop: radiusTop,
  20256. radiusBottom: radiusBottom,
  20257. height: height,
  20258. radialSegments: radialSegments,
  20259. heightSegments: heightSegments,
  20260. openEnded: openEnded,
  20261. thetaStart: thetaStart,
  20262. thetaLength: thetaLength
  20263. };
  20264. this.fromBufferGeometry(new CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength));
  20265. this.mergeVertices();
  20266. }
  20267. CylinderGeometry.prototype = Object.create(Geometry.prototype);
  20268. CylinderGeometry.prototype.constructor = CylinderGeometry; // CylinderBufferGeometry
  20269. function CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  20270. BufferGeometry.call(this);
  20271. this.type = 'CylinderBufferGeometry';
  20272. this.parameters = {
  20273. radiusTop: radiusTop,
  20274. radiusBottom: radiusBottom,
  20275. height: height,
  20276. radialSegments: radialSegments,
  20277. heightSegments: heightSegments,
  20278. openEnded: openEnded,
  20279. thetaStart: thetaStart,
  20280. thetaLength: thetaLength
  20281. };
  20282. var scope = this;
  20283. radiusTop = radiusTop !== undefined ? radiusTop : 1;
  20284. radiusBottom = radiusBottom !== undefined ? radiusBottom : 1;
  20285. height = height || 1;
  20286. radialSegments = Math.floor(radialSegments) || 8;
  20287. heightSegments = Math.floor(heightSegments) || 1;
  20288. openEnded = openEnded !== undefined ? openEnded : false;
  20289. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  20290. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; // buffers
  20291. var indices = [];
  20292. var vertices = [];
  20293. var normals = [];
  20294. var uvs = []; // helper variables
  20295. var index = 0;
  20296. var indexArray = [];
  20297. var halfHeight = height / 2;
  20298. var groupStart = 0; // generate geometry
  20299. generateTorso();
  20300. if (openEnded === false) {
  20301. if (radiusTop > 0) generateCap(true);
  20302. if (radiusBottom > 0) generateCap(false);
  20303. } // build geometry
  20304. this.setIndex(indices);
  20305. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  20306. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  20307. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20308. function generateTorso() {
  20309. var x, y;
  20310. var normal = new Vector3();
  20311. var vertex = new Vector3();
  20312. var groupCount = 0; // this will be used to calculate the normal
  20313. var slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  20314. for (y = 0; y <= heightSegments; y++) {
  20315. var indexRow = [];
  20316. var v = y / heightSegments; // calculate the radius of the current row
  20317. var radius = v * (radiusBottom - radiusTop) + radiusTop;
  20318. for (x = 0; x <= radialSegments; x++) {
  20319. var u = x / radialSegments;
  20320. var theta = u * thetaLength + thetaStart;
  20321. var sinTheta = Math.sin(theta);
  20322. var cosTheta = Math.cos(theta); // vertex
  20323. vertex.x = radius * sinTheta;
  20324. vertex.y = -v * height + halfHeight;
  20325. vertex.z = radius * cosTheta;
  20326. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20327. normal.set(sinTheta, slope, cosTheta).normalize();
  20328. normals.push(normal.x, normal.y, normal.z); // uv
  20329. uvs.push(u, 1 - v); // save index of vertex in respective row
  20330. indexRow.push(index++);
  20331. } // now save vertices of the row in our index array
  20332. indexArray.push(indexRow);
  20333. } // generate indices
  20334. for (x = 0; x < radialSegments; x++) {
  20335. for (y = 0; y < heightSegments; y++) {
  20336. // we use the index array to access the correct indices
  20337. var a = indexArray[y][x];
  20338. var b = indexArray[y + 1][x];
  20339. var c = indexArray[y + 1][x + 1];
  20340. var d = indexArray[y][x + 1]; // faces
  20341. indices.push(a, b, d);
  20342. indices.push(b, c, d); // update group counter
  20343. groupCount += 6;
  20344. }
  20345. } // add a group to the geometry. this will ensure multi material support
  20346. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  20347. groupStart += groupCount;
  20348. }
  20349. function generateCap(top) {
  20350. var x, centerIndexStart, centerIndexEnd;
  20351. var uv = new Vector2();
  20352. var vertex = new Vector3();
  20353. var groupCount = 0;
  20354. var radius = top === true ? radiusTop : radiusBottom;
  20355. var sign = top === true ? 1 : -1; // save the index of the first center vertex
  20356. centerIndexStart = index; // first we generate the center vertex data of the cap.
  20357. // because the geometry needs one set of uvs per face,
  20358. // we must generate a center vertex per face/segment
  20359. for (x = 1; x <= radialSegments; x++) {
  20360. // vertex
  20361. vertices.push(0, halfHeight * sign, 0); // normal
  20362. normals.push(0, sign, 0); // uv
  20363. uvs.push(0.5, 0.5); // increase index
  20364. index++;
  20365. } // save the index of the last center vertex
  20366. centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  20367. for (x = 0; x <= radialSegments; x++) {
  20368. var u = x / radialSegments;
  20369. var theta = u * thetaLength + thetaStart;
  20370. var cosTheta = Math.cos(theta);
  20371. var sinTheta = Math.sin(theta); // vertex
  20372. vertex.x = radius * sinTheta;
  20373. vertex.y = halfHeight * sign;
  20374. vertex.z = radius * cosTheta;
  20375. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20376. normals.push(0, sign, 0); // uv
  20377. uv.x = cosTheta * 0.5 + 0.5;
  20378. uv.y = sinTheta * 0.5 * sign + 0.5;
  20379. uvs.push(uv.x, uv.y); // increase index
  20380. index++;
  20381. } // generate indices
  20382. for (x = 0; x < radialSegments; x++) {
  20383. var c = centerIndexStart + x;
  20384. var i = centerIndexEnd + x;
  20385. if (top === true) {
  20386. // face top
  20387. indices.push(i, i + 1, c);
  20388. } else {
  20389. // face bottom
  20390. indices.push(i + 1, i, c);
  20391. }
  20392. groupCount += 3;
  20393. } // add a group to the geometry. this will ensure multi material support
  20394. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  20395. groupStart += groupCount;
  20396. }
  20397. }
  20398. CylinderBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  20399. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  20400. /**
  20401. * @author abelnation / http://github.com/abelnation
  20402. */
  20403. // ConeGeometry
  20404. function ConeGeometry(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  20405. CylinderGeometry.call(this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  20406. this.type = 'ConeGeometry';
  20407. this.parameters = {
  20408. radius: radius,
  20409. height: height,
  20410. radialSegments: radialSegments,
  20411. heightSegments: heightSegments,
  20412. openEnded: openEnded,
  20413. thetaStart: thetaStart,
  20414. thetaLength: thetaLength
  20415. };
  20416. }
  20417. ConeGeometry.prototype = Object.create(CylinderGeometry.prototype);
  20418. ConeGeometry.prototype.constructor = ConeGeometry; // ConeBufferGeometry
  20419. function ConeBufferGeometry(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  20420. CylinderBufferGeometry.call(this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  20421. this.type = 'ConeBufferGeometry';
  20422. this.parameters = {
  20423. radius: radius,
  20424. height: height,
  20425. radialSegments: radialSegments,
  20426. heightSegments: heightSegments,
  20427. openEnded: openEnded,
  20428. thetaStart: thetaStart,
  20429. thetaLength: thetaLength
  20430. };
  20431. }
  20432. ConeBufferGeometry.prototype = Object.create(CylinderBufferGeometry.prototype);
  20433. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  20434. /**
  20435. * @author benaadams / https://twitter.com/ben_a_adams
  20436. * @author Mugen87 / https://github.com/Mugen87
  20437. * @author hughes
  20438. */
  20439. // CircleGeometry
  20440. function CircleGeometry(radius, segments, thetaStart, thetaLength) {
  20441. Geometry.call(this);
  20442. this.type = 'CircleGeometry';
  20443. this.parameters = {
  20444. radius: radius,
  20445. segments: segments,
  20446. thetaStart: thetaStart,
  20447. thetaLength: thetaLength
  20448. };
  20449. this.fromBufferGeometry(new CircleBufferGeometry(radius, segments, thetaStart, thetaLength));
  20450. this.mergeVertices();
  20451. }
  20452. CircleGeometry.prototype = Object.create(Geometry.prototype);
  20453. CircleGeometry.prototype.constructor = CircleGeometry; // CircleBufferGeometry
  20454. function CircleBufferGeometry(radius, segments, thetaStart, thetaLength) {
  20455. BufferGeometry.call(this);
  20456. this.type = 'CircleBufferGeometry';
  20457. this.parameters = {
  20458. radius: radius,
  20459. segments: segments,
  20460. thetaStart: thetaStart,
  20461. thetaLength: thetaLength
  20462. };
  20463. radius = radius || 1;
  20464. segments = segments !== undefined ? Math.max(3, segments) : 8;
  20465. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  20466. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; // buffers
  20467. var indices = [];
  20468. var vertices = [];
  20469. var normals = [];
  20470. var uvs = []; // helper variables
  20471. var i, s;
  20472. var vertex = new Vector3();
  20473. var uv = new Vector2(); // center point
  20474. vertices.push(0, 0, 0);
  20475. normals.push(0, 0, 1);
  20476. uvs.push(0.5, 0.5);
  20477. for (s = 0, i = 3; s <= segments; s++, i += 3) {
  20478. var segment = thetaStart + s / segments * thetaLength; // vertex
  20479. vertex.x = radius * Math.cos(segment);
  20480. vertex.y = radius * Math.sin(segment);
  20481. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20482. normals.push(0, 0, 1); // uvs
  20483. uv.x = (vertices[i] / radius + 1) / 2;
  20484. uv.y = (vertices[i + 1] / radius + 1) / 2;
  20485. uvs.push(uv.x, uv.y);
  20486. } // indices
  20487. for (i = 1; i <= segments; i++) {
  20488. indices.push(i, i + 1, 0);
  20489. } // build geometry
  20490. this.setIndex(indices);
  20491. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  20492. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  20493. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20494. }
  20495. CircleBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  20496. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  20497. var Geometries =
  20498. /*#__PURE__*/
  20499. Object.freeze({
  20500. WireframeGeometry: WireframeGeometry,
  20501. ParametricGeometry: ParametricGeometry,
  20502. ParametricBufferGeometry: ParametricBufferGeometry,
  20503. TetrahedronGeometry: TetrahedronGeometry,
  20504. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  20505. OctahedronGeometry: OctahedronGeometry,
  20506. OctahedronBufferGeometry: OctahedronBufferGeometry,
  20507. IcosahedronGeometry: IcosahedronGeometry,
  20508. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  20509. DodecahedronGeometry: DodecahedronGeometry,
  20510. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  20511. PolyhedronGeometry: PolyhedronGeometry,
  20512. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  20513. TubeGeometry: TubeGeometry,
  20514. TubeBufferGeometry: TubeBufferGeometry,
  20515. TorusKnotGeometry: TorusKnotGeometry,
  20516. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  20517. TorusGeometry: TorusGeometry,
  20518. TorusBufferGeometry: TorusBufferGeometry,
  20519. TextGeometry: TextGeometry,
  20520. TextBufferGeometry: TextBufferGeometry,
  20521. SphereGeometry: SphereGeometry,
  20522. SphereBufferGeometry: SphereBufferGeometry,
  20523. RingGeometry: RingGeometry,
  20524. RingBufferGeometry: RingBufferGeometry,
  20525. PlaneGeometry: PlaneGeometry,
  20526. PlaneBufferGeometry: PlaneBufferGeometry,
  20527. LatheGeometry: LatheGeometry,
  20528. LatheBufferGeometry: LatheBufferGeometry,
  20529. ShapeGeometry: ShapeGeometry,
  20530. ShapeBufferGeometry: ShapeBufferGeometry,
  20531. ExtrudeGeometry: ExtrudeGeometry,
  20532. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  20533. EdgesGeometry: EdgesGeometry,
  20534. ConeGeometry: ConeGeometry,
  20535. ConeBufferGeometry: ConeBufferGeometry,
  20536. CylinderGeometry: CylinderGeometry,
  20537. CylinderBufferGeometry: CylinderBufferGeometry,
  20538. CircleGeometry: CircleGeometry,
  20539. CircleBufferGeometry: CircleBufferGeometry,
  20540. BoxGeometry: BoxGeometry,
  20541. BoxBufferGeometry: BoxBufferGeometry
  20542. });
  20543. /**
  20544. * @author mrdoob / http://mrdoob.com/
  20545. *
  20546. * parameters = {
  20547. * color: <THREE.Color>
  20548. * }
  20549. */
  20550. function ShadowMaterial(parameters) {
  20551. Material.call(this);
  20552. this.type = 'ShadowMaterial';
  20553. this.color = new Color(0x000000);
  20554. this.transparent = true;
  20555. this.setValues(parameters);
  20556. }
  20557. ShadowMaterial.prototype = Object.create(Material.prototype);
  20558. ShadowMaterial.prototype.constructor = ShadowMaterial;
  20559. ShadowMaterial.prototype.isShadowMaterial = true;
  20560. ShadowMaterial.prototype.copy = function (source) {
  20561. Material.prototype.copy.call(this, source);
  20562. this.color.copy(source.color);
  20563. return this;
  20564. };
  20565. /**
  20566. * @author mrdoob / http://mrdoob.com/
  20567. */
  20568. function RawShaderMaterial(parameters) {
  20569. ShaderMaterial.call(this, parameters);
  20570. this.type = 'RawShaderMaterial';
  20571. }
  20572. RawShaderMaterial.prototype = Object.create(ShaderMaterial.prototype);
  20573. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  20574. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  20575. /**
  20576. * @author WestLangley / http://github.com/WestLangley
  20577. *
  20578. * parameters = {
  20579. * color: <hex>,
  20580. * roughness: <float>,
  20581. * metalness: <float>,
  20582. * opacity: <float>,
  20583. *
  20584. * map: new THREE.Texture( <Image> ),
  20585. *
  20586. * lightMap: new THREE.Texture( <Image> ),
  20587. * lightMapIntensity: <float>
  20588. *
  20589. * aoMap: new THREE.Texture( <Image> ),
  20590. * aoMapIntensity: <float>
  20591. *
  20592. * emissive: <hex>,
  20593. * emissiveIntensity: <float>
  20594. * emissiveMap: new THREE.Texture( <Image> ),
  20595. *
  20596. * bumpMap: new THREE.Texture( <Image> ),
  20597. * bumpScale: <float>,
  20598. *
  20599. * normalMap: new THREE.Texture( <Image> ),
  20600. * normalMapType: THREE.TangentSpaceNormalMap,
  20601. * normalScale: <Vector2>,
  20602. *
  20603. * displacementMap: new THREE.Texture( <Image> ),
  20604. * displacementScale: <float>,
  20605. * displacementBias: <float>,
  20606. *
  20607. * roughnessMap: new THREE.Texture( <Image> ),
  20608. *
  20609. * metalnessMap: new THREE.Texture( <Image> ),
  20610. *
  20611. * alphaMap: new THREE.Texture( <Image> ),
  20612. *
  20613. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20614. * envMapIntensity: <float>
  20615. *
  20616. * refractionRatio: <float>,
  20617. *
  20618. * wireframe: <boolean>,
  20619. * wireframeLinewidth: <float>,
  20620. *
  20621. * skinning: <bool>,
  20622. * morphTargets: <bool>,
  20623. * morphNormals: <bool>
  20624. * }
  20625. */
  20626. function MeshStandardMaterial(parameters) {
  20627. Material.call(this);
  20628. this.defines = {
  20629. 'STANDARD': ''
  20630. };
  20631. this.type = 'MeshStandardMaterial';
  20632. this.color = new Color(0xffffff); // diffuse
  20633. this.roughness = 0.5;
  20634. this.metalness = 0.5;
  20635. this.map = null;
  20636. this.lightMap = null;
  20637. this.lightMapIntensity = 1.0;
  20638. this.aoMap = null;
  20639. this.aoMapIntensity = 1.0;
  20640. this.emissive = new Color(0x000000);
  20641. this.emissiveIntensity = 1.0;
  20642. this.emissiveMap = null;
  20643. this.bumpMap = null;
  20644. this.bumpScale = 1;
  20645. this.normalMap = null;
  20646. this.normalMapType = TangentSpaceNormalMap;
  20647. this.normalScale = new Vector2(1, 1);
  20648. this.displacementMap = null;
  20649. this.displacementScale = 1;
  20650. this.displacementBias = 0;
  20651. this.roughnessMap = null;
  20652. this.metalnessMap = null;
  20653. this.alphaMap = null;
  20654. this.envMap = null;
  20655. this.envMapIntensity = 1.0;
  20656. this.refractionRatio = 0.98;
  20657. this.wireframe = false;
  20658. this.wireframeLinewidth = 1;
  20659. this.wireframeLinecap = 'round';
  20660. this.wireframeLinejoin = 'round';
  20661. this.skinning = false;
  20662. this.morphTargets = false;
  20663. this.morphNormals = false;
  20664. this.setValues(parameters);
  20665. }
  20666. MeshStandardMaterial.prototype = Object.create(Material.prototype);
  20667. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  20668. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  20669. MeshStandardMaterial.prototype.copy = function (source) {
  20670. Material.prototype.copy.call(this, source);
  20671. this.defines = {
  20672. 'STANDARD': ''
  20673. };
  20674. this.color.copy(source.color);
  20675. this.roughness = source.roughness;
  20676. this.metalness = source.metalness;
  20677. this.map = source.map;
  20678. this.lightMap = source.lightMap;
  20679. this.lightMapIntensity = source.lightMapIntensity;
  20680. this.aoMap = source.aoMap;
  20681. this.aoMapIntensity = source.aoMapIntensity;
  20682. this.emissive.copy(source.emissive);
  20683. this.emissiveMap = source.emissiveMap;
  20684. this.emissiveIntensity = source.emissiveIntensity;
  20685. this.bumpMap = source.bumpMap;
  20686. this.bumpScale = source.bumpScale;
  20687. this.normalMap = source.normalMap;
  20688. this.normalMapType = source.normalMapType;
  20689. this.normalScale.copy(source.normalScale);
  20690. this.displacementMap = source.displacementMap;
  20691. this.displacementScale = source.displacementScale;
  20692. this.displacementBias = source.displacementBias;
  20693. this.roughnessMap = source.roughnessMap;
  20694. this.metalnessMap = source.metalnessMap;
  20695. this.alphaMap = source.alphaMap;
  20696. this.envMap = source.envMap;
  20697. this.envMapIntensity = source.envMapIntensity;
  20698. this.refractionRatio = source.refractionRatio;
  20699. this.wireframe = source.wireframe;
  20700. this.wireframeLinewidth = source.wireframeLinewidth;
  20701. this.wireframeLinecap = source.wireframeLinecap;
  20702. this.wireframeLinejoin = source.wireframeLinejoin;
  20703. this.skinning = source.skinning;
  20704. this.morphTargets = source.morphTargets;
  20705. this.morphNormals = source.morphNormals;
  20706. return this;
  20707. };
  20708. /**
  20709. * @author WestLangley / http://github.com/WestLangley
  20710. *
  20711. * parameters = {
  20712. * reflectivity: <float>
  20713. * clearcoat: <float>
  20714. * clearcoatRoughness: <float>
  20715. *
  20716. * sheen: <Color>
  20717. *
  20718. * clearcoatNormalScale: <Vector2>,
  20719. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  20720. * }
  20721. */
  20722. function MeshPhysicalMaterial(parameters) {
  20723. MeshStandardMaterial.call(this);
  20724. this.defines = {
  20725. 'STANDARD': '',
  20726. 'PHYSICAL': ''
  20727. };
  20728. this.type = 'MeshPhysicalMaterial';
  20729. this.reflectivity = 0.5; // maps to F0 = 0.04
  20730. this.clearcoat = 0.0;
  20731. this.clearcoatRoughness = 0.0;
  20732. this.sheen = null; // null will disable sheen bsdf
  20733. this.clearcoatNormalScale = new Vector2(1, 1);
  20734. this.clearcoatNormalMap = null;
  20735. this.transparency = 0.0;
  20736. this.setValues(parameters);
  20737. }
  20738. MeshPhysicalMaterial.prototype = Object.create(MeshStandardMaterial.prototype);
  20739. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  20740. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  20741. MeshPhysicalMaterial.prototype.copy = function (source) {
  20742. MeshStandardMaterial.prototype.copy.call(this, source);
  20743. this.defines = {
  20744. 'STANDARD': '',
  20745. 'PHYSICAL': ''
  20746. };
  20747. this.reflectivity = source.reflectivity;
  20748. this.clearcoat = source.clearcoat;
  20749. this.clearcoatRoughness = source.clearcoatRoughness;
  20750. if (source.sheen) this.sheen = (this.sheen || new Color()).copy(source.sheen);else this.sheen = null;
  20751. this.clearcoatNormalMap = source.clearcoatNormalMap;
  20752. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  20753. this.transparency = source.transparency;
  20754. return this;
  20755. };
  20756. /**
  20757. * @author mrdoob / http://mrdoob.com/
  20758. * @author alteredq / http://alteredqualia.com/
  20759. *
  20760. * parameters = {
  20761. * color: <hex>,
  20762. * specular: <hex>,
  20763. * shininess: <float>,
  20764. * opacity: <float>,
  20765. *
  20766. * map: new THREE.Texture( <Image> ),
  20767. *
  20768. * lightMap: new THREE.Texture( <Image> ),
  20769. * lightMapIntensity: <float>
  20770. *
  20771. * aoMap: new THREE.Texture( <Image> ),
  20772. * aoMapIntensity: <float>
  20773. *
  20774. * emissive: <hex>,
  20775. * emissiveIntensity: <float>
  20776. * emissiveMap: new THREE.Texture( <Image> ),
  20777. *
  20778. * bumpMap: new THREE.Texture( <Image> ),
  20779. * bumpScale: <float>,
  20780. *
  20781. * normalMap: new THREE.Texture( <Image> ),
  20782. * normalMapType: THREE.TangentSpaceNormalMap,
  20783. * normalScale: <Vector2>,
  20784. *
  20785. * displacementMap: new THREE.Texture( <Image> ),
  20786. * displacementScale: <float>,
  20787. * displacementBias: <float>,
  20788. *
  20789. * specularMap: new THREE.Texture( <Image> ),
  20790. *
  20791. * alphaMap: new THREE.Texture( <Image> ),
  20792. *
  20793. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20794. * combine: THREE.Multiply,
  20795. * reflectivity: <float>,
  20796. * refractionRatio: <float>,
  20797. *
  20798. * wireframe: <boolean>,
  20799. * wireframeLinewidth: <float>,
  20800. *
  20801. * skinning: <bool>,
  20802. * morphTargets: <bool>,
  20803. * morphNormals: <bool>
  20804. * }
  20805. */
  20806. function MeshPhongMaterial(parameters) {
  20807. Material.call(this);
  20808. this.type = 'MeshPhongMaterial';
  20809. this.color = new Color(0xffffff); // diffuse
  20810. this.specular = new Color(0x111111);
  20811. this.shininess = 30;
  20812. this.map = null;
  20813. this.lightMap = null;
  20814. this.lightMapIntensity = 1.0;
  20815. this.aoMap = null;
  20816. this.aoMapIntensity = 1.0;
  20817. this.emissive = new Color(0x000000);
  20818. this.emissiveIntensity = 1.0;
  20819. this.emissiveMap = null;
  20820. this.bumpMap = null;
  20821. this.bumpScale = 1;
  20822. this.normalMap = null;
  20823. this.normalMapType = TangentSpaceNormalMap;
  20824. this.normalScale = new Vector2(1, 1);
  20825. this.displacementMap = null;
  20826. this.displacementScale = 1;
  20827. this.displacementBias = 0;
  20828. this.specularMap = null;
  20829. this.alphaMap = null;
  20830. this.envMap = null;
  20831. this.combine = MultiplyOperation;
  20832. this.reflectivity = 1;
  20833. this.refractionRatio = 0.98;
  20834. this.wireframe = false;
  20835. this.wireframeLinewidth = 1;
  20836. this.wireframeLinecap = 'round';
  20837. this.wireframeLinejoin = 'round';
  20838. this.skinning = false;
  20839. this.morphTargets = false;
  20840. this.morphNormals = false;
  20841. this.setValues(parameters);
  20842. }
  20843. MeshPhongMaterial.prototype = Object.create(Material.prototype);
  20844. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  20845. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  20846. MeshPhongMaterial.prototype.copy = function (source) {
  20847. Material.prototype.copy.call(this, source);
  20848. this.color.copy(source.color);
  20849. this.specular.copy(source.specular);
  20850. this.shininess = source.shininess;
  20851. this.map = source.map;
  20852. this.lightMap = source.lightMap;
  20853. this.lightMapIntensity = source.lightMapIntensity;
  20854. this.aoMap = source.aoMap;
  20855. this.aoMapIntensity = source.aoMapIntensity;
  20856. this.emissive.copy(source.emissive);
  20857. this.emissiveMap = source.emissiveMap;
  20858. this.emissiveIntensity = source.emissiveIntensity;
  20859. this.bumpMap = source.bumpMap;
  20860. this.bumpScale = source.bumpScale;
  20861. this.normalMap = source.normalMap;
  20862. this.normalMapType = source.normalMapType;
  20863. this.normalScale.copy(source.normalScale);
  20864. this.displacementMap = source.displacementMap;
  20865. this.displacementScale = source.displacementScale;
  20866. this.displacementBias = source.displacementBias;
  20867. this.specularMap = source.specularMap;
  20868. this.alphaMap = source.alphaMap;
  20869. this.envMap = source.envMap;
  20870. this.combine = source.combine;
  20871. this.reflectivity = source.reflectivity;
  20872. this.refractionRatio = source.refractionRatio;
  20873. this.wireframe = source.wireframe;
  20874. this.wireframeLinewidth = source.wireframeLinewidth;
  20875. this.wireframeLinecap = source.wireframeLinecap;
  20876. this.wireframeLinejoin = source.wireframeLinejoin;
  20877. this.skinning = source.skinning;
  20878. this.morphTargets = source.morphTargets;
  20879. this.morphNormals = source.morphNormals;
  20880. return this;
  20881. };
  20882. /**
  20883. * @author takahirox / http://github.com/takahirox
  20884. *
  20885. * parameters = {
  20886. * gradientMap: new THREE.Texture( <Image> )
  20887. * }
  20888. */
  20889. function MeshToonMaterial(parameters) {
  20890. MeshPhongMaterial.call(this);
  20891. this.defines = {
  20892. 'TOON': ''
  20893. };
  20894. this.type = 'MeshToonMaterial';
  20895. this.gradientMap = null;
  20896. this.setValues(parameters);
  20897. }
  20898. MeshToonMaterial.prototype = Object.create(MeshPhongMaterial.prototype);
  20899. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  20900. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  20901. MeshToonMaterial.prototype.copy = function (source) {
  20902. MeshPhongMaterial.prototype.copy.call(this, source);
  20903. this.gradientMap = source.gradientMap;
  20904. return this;
  20905. };
  20906. /**
  20907. * @author mrdoob / http://mrdoob.com/
  20908. * @author WestLangley / http://github.com/WestLangley
  20909. *
  20910. * parameters = {
  20911. * opacity: <float>,
  20912. *
  20913. * bumpMap: new THREE.Texture( <Image> ),
  20914. * bumpScale: <float>,
  20915. *
  20916. * normalMap: new THREE.Texture( <Image> ),
  20917. * normalMapType: THREE.TangentSpaceNormalMap,
  20918. * normalScale: <Vector2>,
  20919. *
  20920. * displacementMap: new THREE.Texture( <Image> ),
  20921. * displacementScale: <float>,
  20922. * displacementBias: <float>,
  20923. *
  20924. * wireframe: <boolean>,
  20925. * wireframeLinewidth: <float>
  20926. *
  20927. * skinning: <bool>,
  20928. * morphTargets: <bool>,
  20929. * morphNormals: <bool>
  20930. * }
  20931. */
  20932. function MeshNormalMaterial(parameters) {
  20933. Material.call(this);
  20934. this.type = 'MeshNormalMaterial';
  20935. this.bumpMap = null;
  20936. this.bumpScale = 1;
  20937. this.normalMap = null;
  20938. this.normalMapType = TangentSpaceNormalMap;
  20939. this.normalScale = new Vector2(1, 1);
  20940. this.displacementMap = null;
  20941. this.displacementScale = 1;
  20942. this.displacementBias = 0;
  20943. this.wireframe = false;
  20944. this.wireframeLinewidth = 1;
  20945. this.fog = false;
  20946. this.skinning = false;
  20947. this.morphTargets = false;
  20948. this.morphNormals = false;
  20949. this.setValues(parameters);
  20950. }
  20951. MeshNormalMaterial.prototype = Object.create(Material.prototype);
  20952. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  20953. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  20954. MeshNormalMaterial.prototype.copy = function (source) {
  20955. Material.prototype.copy.call(this, source);
  20956. this.bumpMap = source.bumpMap;
  20957. this.bumpScale = source.bumpScale;
  20958. this.normalMap = source.normalMap;
  20959. this.normalMapType = source.normalMapType;
  20960. this.normalScale.copy(source.normalScale);
  20961. this.displacementMap = source.displacementMap;
  20962. this.displacementScale = source.displacementScale;
  20963. this.displacementBias = source.displacementBias;
  20964. this.wireframe = source.wireframe;
  20965. this.wireframeLinewidth = source.wireframeLinewidth;
  20966. this.skinning = source.skinning;
  20967. this.morphTargets = source.morphTargets;
  20968. this.morphNormals = source.morphNormals;
  20969. return this;
  20970. };
  20971. /**
  20972. * @author mrdoob / http://mrdoob.com/
  20973. * @author alteredq / http://alteredqualia.com/
  20974. *
  20975. * parameters = {
  20976. * color: <hex>,
  20977. * opacity: <float>,
  20978. *
  20979. * map: new THREE.Texture( <Image> ),
  20980. *
  20981. * lightMap: new THREE.Texture( <Image> ),
  20982. * lightMapIntensity: <float>
  20983. *
  20984. * aoMap: new THREE.Texture( <Image> ),
  20985. * aoMapIntensity: <float>
  20986. *
  20987. * emissive: <hex>,
  20988. * emissiveIntensity: <float>
  20989. * emissiveMap: new THREE.Texture( <Image> ),
  20990. *
  20991. * specularMap: new THREE.Texture( <Image> ),
  20992. *
  20993. * alphaMap: new THREE.Texture( <Image> ),
  20994. *
  20995. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20996. * combine: THREE.Multiply,
  20997. * reflectivity: <float>,
  20998. * refractionRatio: <float>,
  20999. *
  21000. * wireframe: <boolean>,
  21001. * wireframeLinewidth: <float>,
  21002. *
  21003. * skinning: <bool>,
  21004. * morphTargets: <bool>,
  21005. * morphNormals: <bool>
  21006. * }
  21007. */
  21008. function MeshLambertMaterial(parameters) {
  21009. Material.call(this);
  21010. this.type = 'MeshLambertMaterial';
  21011. this.color = new Color(0xffffff); // diffuse
  21012. this.map = null;
  21013. this.lightMap = null;
  21014. this.lightMapIntensity = 1.0;
  21015. this.aoMap = null;
  21016. this.aoMapIntensity = 1.0;
  21017. this.emissive = new Color(0x000000);
  21018. this.emissiveIntensity = 1.0;
  21019. this.emissiveMap = null;
  21020. this.specularMap = null;
  21021. this.alphaMap = null;
  21022. this.envMap = null;
  21023. this.combine = MultiplyOperation;
  21024. this.reflectivity = 1;
  21025. this.refractionRatio = 0.98;
  21026. this.wireframe = false;
  21027. this.wireframeLinewidth = 1;
  21028. this.wireframeLinecap = 'round';
  21029. this.wireframeLinejoin = 'round';
  21030. this.skinning = false;
  21031. this.morphTargets = false;
  21032. this.morphNormals = false;
  21033. this.setValues(parameters);
  21034. }
  21035. MeshLambertMaterial.prototype = Object.create(Material.prototype);
  21036. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  21037. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  21038. MeshLambertMaterial.prototype.copy = function (source) {
  21039. Material.prototype.copy.call(this, source);
  21040. this.color.copy(source.color);
  21041. this.map = source.map;
  21042. this.lightMap = source.lightMap;
  21043. this.lightMapIntensity = source.lightMapIntensity;
  21044. this.aoMap = source.aoMap;
  21045. this.aoMapIntensity = source.aoMapIntensity;
  21046. this.emissive.copy(source.emissive);
  21047. this.emissiveMap = source.emissiveMap;
  21048. this.emissiveIntensity = source.emissiveIntensity;
  21049. this.specularMap = source.specularMap;
  21050. this.alphaMap = source.alphaMap;
  21051. this.envMap = source.envMap;
  21052. this.combine = source.combine;
  21053. this.reflectivity = source.reflectivity;
  21054. this.refractionRatio = source.refractionRatio;
  21055. this.wireframe = source.wireframe;
  21056. this.wireframeLinewidth = source.wireframeLinewidth;
  21057. this.wireframeLinecap = source.wireframeLinecap;
  21058. this.wireframeLinejoin = source.wireframeLinejoin;
  21059. this.skinning = source.skinning;
  21060. this.morphTargets = source.morphTargets;
  21061. this.morphNormals = source.morphNormals;
  21062. return this;
  21063. };
  21064. /**
  21065. * @author WestLangley / http://github.com/WestLangley
  21066. *
  21067. * parameters = {
  21068. * color: <hex>,
  21069. * opacity: <float>,
  21070. *
  21071. * matcap: new THREE.Texture( <Image> ),
  21072. *
  21073. * map: new THREE.Texture( <Image> ),
  21074. *
  21075. * bumpMap: new THREE.Texture( <Image> ),
  21076. * bumpScale: <float>,
  21077. *
  21078. * normalMap: new THREE.Texture( <Image> ),
  21079. * normalMapType: THREE.TangentSpaceNormalMap,
  21080. * normalScale: <Vector2>,
  21081. *
  21082. * displacementMap: new THREE.Texture( <Image> ),
  21083. * displacementScale: <float>,
  21084. * displacementBias: <float>,
  21085. *
  21086. * alphaMap: new THREE.Texture( <Image> ),
  21087. *
  21088. * skinning: <bool>,
  21089. * morphTargets: <bool>,
  21090. * morphNormals: <bool>
  21091. * }
  21092. */
  21093. function MeshMatcapMaterial(parameters) {
  21094. Material.call(this);
  21095. this.defines = {
  21096. 'MATCAP': ''
  21097. };
  21098. this.type = 'MeshMatcapMaterial';
  21099. this.color = new Color(0xffffff); // diffuse
  21100. this.matcap = null;
  21101. this.map = null;
  21102. this.bumpMap = null;
  21103. this.bumpScale = 1;
  21104. this.normalMap = null;
  21105. this.normalMapType = TangentSpaceNormalMap;
  21106. this.normalScale = new Vector2(1, 1);
  21107. this.displacementMap = null;
  21108. this.displacementScale = 1;
  21109. this.displacementBias = 0;
  21110. this.alphaMap = null;
  21111. this.skinning = false;
  21112. this.morphTargets = false;
  21113. this.morphNormals = false;
  21114. this.setValues(parameters);
  21115. }
  21116. MeshMatcapMaterial.prototype = Object.create(Material.prototype);
  21117. MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial;
  21118. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  21119. MeshMatcapMaterial.prototype.copy = function (source) {
  21120. Material.prototype.copy.call(this, source);
  21121. this.defines = {
  21122. 'MATCAP': ''
  21123. };
  21124. this.color.copy(source.color);
  21125. this.matcap = source.matcap;
  21126. this.map = source.map;
  21127. this.bumpMap = source.bumpMap;
  21128. this.bumpScale = source.bumpScale;
  21129. this.normalMap = source.normalMap;
  21130. this.normalMapType = source.normalMapType;
  21131. this.normalScale.copy(source.normalScale);
  21132. this.displacementMap = source.displacementMap;
  21133. this.displacementScale = source.displacementScale;
  21134. this.displacementBias = source.displacementBias;
  21135. this.alphaMap = source.alphaMap;
  21136. this.skinning = source.skinning;
  21137. this.morphTargets = source.morphTargets;
  21138. this.morphNormals = source.morphNormals;
  21139. return this;
  21140. };
  21141. /**
  21142. * @author alteredq / http://alteredqualia.com/
  21143. *
  21144. * parameters = {
  21145. * color: <hex>,
  21146. * opacity: <float>,
  21147. *
  21148. * linewidth: <float>,
  21149. *
  21150. * scale: <float>,
  21151. * dashSize: <float>,
  21152. * gapSize: <float>
  21153. * }
  21154. */
  21155. function LineDashedMaterial(parameters) {
  21156. LineBasicMaterial.call(this);
  21157. this.type = 'LineDashedMaterial';
  21158. this.scale = 1;
  21159. this.dashSize = 3;
  21160. this.gapSize = 1;
  21161. this.setValues(parameters);
  21162. }
  21163. LineDashedMaterial.prototype = Object.create(LineBasicMaterial.prototype);
  21164. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  21165. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  21166. LineDashedMaterial.prototype.copy = function (source) {
  21167. LineBasicMaterial.prototype.copy.call(this, source);
  21168. this.scale = source.scale;
  21169. this.dashSize = source.dashSize;
  21170. this.gapSize = source.gapSize;
  21171. return this;
  21172. };
  21173. var Materials =
  21174. /*#__PURE__*/
  21175. Object.freeze({
  21176. ShadowMaterial: ShadowMaterial,
  21177. SpriteMaterial: SpriteMaterial,
  21178. RawShaderMaterial: RawShaderMaterial,
  21179. ShaderMaterial: ShaderMaterial,
  21180. PointsMaterial: PointsMaterial,
  21181. MeshPhysicalMaterial: MeshPhysicalMaterial,
  21182. MeshStandardMaterial: MeshStandardMaterial,
  21183. MeshPhongMaterial: MeshPhongMaterial,
  21184. MeshToonMaterial: MeshToonMaterial,
  21185. MeshNormalMaterial: MeshNormalMaterial,
  21186. MeshLambertMaterial: MeshLambertMaterial,
  21187. MeshDepthMaterial: MeshDepthMaterial,
  21188. MeshDistanceMaterial: MeshDistanceMaterial,
  21189. MeshBasicMaterial: MeshBasicMaterial,
  21190. MeshMatcapMaterial: MeshMatcapMaterial,
  21191. LineDashedMaterial: LineDashedMaterial,
  21192. LineBasicMaterial: LineBasicMaterial,
  21193. Material: Material
  21194. });
  21195. /**
  21196. * @author tschw
  21197. * @author Ben Houston / http://clara.io/
  21198. * @author David Sarno / http://lighthaus.us/
  21199. */
  21200. var AnimationUtils = {
  21201. // same as Array.prototype.slice, but also works on typed arrays
  21202. arraySlice: function (array, from, to) {
  21203. if (AnimationUtils.isTypedArray(array)) {
  21204. // in ios9 array.subarray(from, undefined) will return empty array
  21205. // but array.subarray(from) or array.subarray(from, len) is correct
  21206. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  21207. }
  21208. return array.slice(from, to);
  21209. },
  21210. // converts an array to a specific type
  21211. convertArray: function (array, type, forceClone) {
  21212. if (!array || // let 'undefined' and 'null' pass
  21213. !forceClone && array.constructor === type) return array;
  21214. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  21215. return new type(array); // create typed array
  21216. }
  21217. return Array.prototype.slice.call(array); // create Array
  21218. },
  21219. isTypedArray: function (object) {
  21220. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  21221. },
  21222. // returns an array by which times and values can be sorted
  21223. getKeyframeOrder: function (times) {
  21224. function compareTime(i, j) {
  21225. return times[i] - times[j];
  21226. }
  21227. var n = times.length;
  21228. var result = new Array(n);
  21229. for (var i = 0; i !== n; ++i) result[i] = i;
  21230. result.sort(compareTime);
  21231. return result;
  21232. },
  21233. // uses the array previously returned by 'getKeyframeOrder' to sort data
  21234. sortedArray: function (values, stride, order) {
  21235. var nValues = values.length;
  21236. var result = new values.constructor(nValues);
  21237. for (var i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  21238. var srcOffset = order[i] * stride;
  21239. for (var j = 0; j !== stride; ++j) {
  21240. result[dstOffset++] = values[srcOffset + j];
  21241. }
  21242. }
  21243. return result;
  21244. },
  21245. // function for parsing AOS keyframe formats
  21246. flattenJSON: function (jsonKeys, times, values, valuePropertyName) {
  21247. var i = 1,
  21248. key = jsonKeys[0];
  21249. while (key !== undefined && key[valuePropertyName] === undefined) {
  21250. key = jsonKeys[i++];
  21251. }
  21252. if (key === undefined) return; // no data
  21253. var value = key[valuePropertyName];
  21254. if (value === undefined) return; // no data
  21255. if (Array.isArray(value)) {
  21256. do {
  21257. value = key[valuePropertyName];
  21258. if (value !== undefined) {
  21259. times.push(key.time);
  21260. values.push.apply(values, value); // push all elements
  21261. }
  21262. key = jsonKeys[i++];
  21263. } while (key !== undefined);
  21264. } else if (value.toArray !== undefined) {
  21265. // ...assume THREE.Math-ish
  21266. do {
  21267. value = key[valuePropertyName];
  21268. if (value !== undefined) {
  21269. times.push(key.time);
  21270. value.toArray(values, values.length);
  21271. }
  21272. key = jsonKeys[i++];
  21273. } while (key !== undefined);
  21274. } else {
  21275. // otherwise push as-is
  21276. do {
  21277. value = key[valuePropertyName];
  21278. if (value !== undefined) {
  21279. times.push(key.time);
  21280. values.push(value);
  21281. }
  21282. key = jsonKeys[i++];
  21283. } while (key !== undefined);
  21284. }
  21285. }
  21286. };
  21287. /**
  21288. * Abstract base class of interpolants over parametric samples.
  21289. *
  21290. * The parameter domain is one dimensional, typically the time or a path
  21291. * along a curve defined by the data.
  21292. *
  21293. * The sample values can have any dimensionality and derived classes may
  21294. * apply special interpretations to the data.
  21295. *
  21296. * This class provides the interval seek in a Template Method, deferring
  21297. * the actual interpolation to derived classes.
  21298. *
  21299. * Time complexity is O(1) for linear access crossing at most two points
  21300. * and O(log N) for random access, where N is the number of positions.
  21301. *
  21302. * References:
  21303. *
  21304. * http://www.oodesign.com/template-method-pattern.html
  21305. *
  21306. * @author tschw
  21307. */
  21308. exports.AnimationUtils = AnimationUtils;
  21309. function Interpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21310. this.parameterPositions = parameterPositions;
  21311. this._cachedIndex = 0;
  21312. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  21313. this.sampleValues = sampleValues;
  21314. this.valueSize = sampleSize;
  21315. }
  21316. Object.assign(Interpolant.prototype, {
  21317. evaluate: function (t) {
  21318. var pp = this.parameterPositions,
  21319. i1 = this._cachedIndex,
  21320. t1 = pp[i1],
  21321. t0 = pp[i1 - 1];
  21322. validate_interval: {
  21323. seek: {
  21324. var right;
  21325. linear_scan: {
  21326. //- See http://jsperf.com/comparison-to-undefined/3
  21327. //- slower code:
  21328. //-
  21329. //- if ( t >= t1 || t1 === undefined ) {
  21330. forward_scan: if (!(t < t1)) {
  21331. for (var giveUpAt = i1 + 2;;) {
  21332. if (t1 === undefined) {
  21333. if (t < t0) break forward_scan; // after end
  21334. i1 = pp.length;
  21335. this._cachedIndex = i1;
  21336. return this.afterEnd_(i1 - 1, t, t0);
  21337. }
  21338. if (i1 === giveUpAt) break; // this loop
  21339. t0 = t1;
  21340. t1 = pp[++i1];
  21341. if (t < t1) {
  21342. // we have arrived at the sought interval
  21343. break seek;
  21344. }
  21345. } // prepare binary search on the right side of the index
  21346. right = pp.length;
  21347. break linear_scan;
  21348. } //- slower code:
  21349. //- if ( t < t0 || t0 === undefined ) {
  21350. if (!(t >= t0)) {
  21351. // looping?
  21352. var t1global = pp[1];
  21353. if (t < t1global) {
  21354. i1 = 2; // + 1, using the scan for the details
  21355. t0 = t1global;
  21356. } // linear reverse scan
  21357. for (var giveUpAt = i1 - 2;;) {
  21358. if (t0 === undefined) {
  21359. // before start
  21360. this._cachedIndex = 0;
  21361. return this.beforeStart_(0, t, t1);
  21362. }
  21363. if (i1 === giveUpAt) break; // this loop
  21364. t1 = t0;
  21365. t0 = pp[--i1 - 1];
  21366. if (t >= t0) {
  21367. // we have arrived at the sought interval
  21368. break seek;
  21369. }
  21370. } // prepare binary search on the left side of the index
  21371. right = i1;
  21372. i1 = 0;
  21373. break linear_scan;
  21374. } // the interval is valid
  21375. break validate_interval;
  21376. } // linear scan
  21377. // binary search
  21378. while (i1 < right) {
  21379. var mid = i1 + right >>> 1;
  21380. if (t < pp[mid]) {
  21381. right = mid;
  21382. } else {
  21383. i1 = mid + 1;
  21384. }
  21385. }
  21386. t1 = pp[i1];
  21387. t0 = pp[i1 - 1]; // check boundary cases, again
  21388. if (t0 === undefined) {
  21389. this._cachedIndex = 0;
  21390. return this.beforeStart_(0, t, t1);
  21391. }
  21392. if (t1 === undefined) {
  21393. i1 = pp.length;
  21394. this._cachedIndex = i1;
  21395. return this.afterEnd_(i1 - 1, t0, t);
  21396. }
  21397. } // seek
  21398. this._cachedIndex = i1;
  21399. this.intervalChanged_(i1, t0, t1);
  21400. } // validate_interval
  21401. return this.interpolate_(i1, t0, t, t1);
  21402. },
  21403. settings: null,
  21404. // optional, subclass-specific settings structure
  21405. // Note: The indirection allows central control of many interpolants.
  21406. // --- Protected interface
  21407. DefaultSettings_: {},
  21408. getSettings_: function () {
  21409. return this.settings || this.DefaultSettings_;
  21410. },
  21411. copySampleValue_: function (index) {
  21412. // copies a sample value to the result buffer
  21413. var result = this.resultBuffer,
  21414. values = this.sampleValues,
  21415. stride = this.valueSize,
  21416. offset = index * stride;
  21417. for (var i = 0; i !== stride; ++i) {
  21418. result[i] = values[offset + i];
  21419. }
  21420. return result;
  21421. },
  21422. // Template methods for derived classes:
  21423. interpolate_: function ()
  21424. /* i1, t0, t, t1 */
  21425. {
  21426. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  21427. },
  21428. intervalChanged_: function ()
  21429. /* i1, t0, t1 */
  21430. {// empty
  21431. }
  21432. }); //!\ DECLARE ALIAS AFTER assign prototype !
  21433. Object.assign(Interpolant.prototype, {
  21434. //( 0, t, t0 ), returns this.resultBuffer
  21435. beforeStart_: Interpolant.prototype.copySampleValue_,
  21436. //( N-1, tN-1, t ), returns this.resultBuffer
  21437. afterEnd_: Interpolant.prototype.copySampleValue_
  21438. });
  21439. /**
  21440. * Fast and simple cubic spline interpolant.
  21441. *
  21442. * It was derived from a Hermitian construction setting the first derivative
  21443. * at each sample position to the linear slope between neighboring positions
  21444. * over their parameter interval.
  21445. *
  21446. * @author tschw
  21447. */
  21448. function CubicInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21449. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21450. this._weightPrev = -0;
  21451. this._offsetPrev = -0;
  21452. this._weightNext = -0;
  21453. this._offsetNext = -0;
  21454. }
  21455. CubicInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21456. constructor: CubicInterpolant,
  21457. DefaultSettings_: {
  21458. endingStart: ZeroCurvatureEnding,
  21459. endingEnd: ZeroCurvatureEnding
  21460. },
  21461. intervalChanged_: function (i1, t0, t1) {
  21462. var pp = this.parameterPositions,
  21463. iPrev = i1 - 2,
  21464. iNext = i1 + 1,
  21465. tPrev = pp[iPrev],
  21466. tNext = pp[iNext];
  21467. if (tPrev === undefined) {
  21468. switch (this.getSettings_().endingStart) {
  21469. case ZeroSlopeEnding:
  21470. // f'(t0) = 0
  21471. iPrev = i1;
  21472. tPrev = 2 * t0 - t1;
  21473. break;
  21474. case WrapAroundEnding:
  21475. // use the other end of the curve
  21476. iPrev = pp.length - 2;
  21477. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  21478. break;
  21479. default:
  21480. // ZeroCurvatureEnding
  21481. // f''(t0) = 0 a.k.a. Natural Spline
  21482. iPrev = i1;
  21483. tPrev = t1;
  21484. }
  21485. }
  21486. if (tNext === undefined) {
  21487. switch (this.getSettings_().endingEnd) {
  21488. case ZeroSlopeEnding:
  21489. // f'(tN) = 0
  21490. iNext = i1;
  21491. tNext = 2 * t1 - t0;
  21492. break;
  21493. case WrapAroundEnding:
  21494. // use the other end of the curve
  21495. iNext = 1;
  21496. tNext = t1 + pp[1] - pp[0];
  21497. break;
  21498. default:
  21499. // ZeroCurvatureEnding
  21500. // f''(tN) = 0, a.k.a. Natural Spline
  21501. iNext = i1 - 1;
  21502. tNext = t0;
  21503. }
  21504. }
  21505. var halfDt = (t1 - t0) * 0.5,
  21506. stride = this.valueSize;
  21507. this._weightPrev = halfDt / (t0 - tPrev);
  21508. this._weightNext = halfDt / (tNext - t1);
  21509. this._offsetPrev = iPrev * stride;
  21510. this._offsetNext = iNext * stride;
  21511. },
  21512. interpolate_: function (i1, t0, t, t1) {
  21513. var result = this.resultBuffer,
  21514. values = this.sampleValues,
  21515. stride = this.valueSize,
  21516. o1 = i1 * stride,
  21517. o0 = o1 - stride,
  21518. oP = this._offsetPrev,
  21519. oN = this._offsetNext,
  21520. wP = this._weightPrev,
  21521. wN = this._weightNext,
  21522. p = (t - t0) / (t1 - t0),
  21523. pp = p * p,
  21524. ppp = pp * p; // evaluate polynomials
  21525. var sP = -wP * ppp + 2 * wP * pp - wP * p;
  21526. var s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  21527. var s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  21528. var sN = wN * ppp - wN * pp; // combine data linearly
  21529. for (var i = 0; i !== stride; ++i) {
  21530. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  21531. }
  21532. return result;
  21533. }
  21534. });
  21535. /**
  21536. * @author tschw
  21537. */
  21538. function LinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21539. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21540. }
  21541. LinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21542. constructor: LinearInterpolant,
  21543. interpolate_: function (i1, t0, t, t1) {
  21544. var result = this.resultBuffer,
  21545. values = this.sampleValues,
  21546. stride = this.valueSize,
  21547. offset1 = i1 * stride,
  21548. offset0 = offset1 - stride,
  21549. weight1 = (t - t0) / (t1 - t0),
  21550. weight0 = 1 - weight1;
  21551. for (var i = 0; i !== stride; ++i) {
  21552. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  21553. }
  21554. return result;
  21555. }
  21556. });
  21557. /**
  21558. *
  21559. * Interpolant that evaluates to the sample value at the position preceeding
  21560. * the parameter.
  21561. *
  21562. * @author tschw
  21563. */
  21564. function DiscreteInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21565. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21566. }
  21567. DiscreteInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21568. constructor: DiscreteInterpolant,
  21569. interpolate_: function (i1
  21570. /*, t0, t, t1 */
  21571. ) {
  21572. return this.copySampleValue_(i1 - 1);
  21573. }
  21574. });
  21575. /**
  21576. *
  21577. * A timed sequence of keyframes for a specific property.
  21578. *
  21579. *
  21580. * @author Ben Houston / http://clara.io/
  21581. * @author David Sarno / http://lighthaus.us/
  21582. * @author tschw
  21583. */
  21584. function KeyframeTrack(name, times, values, interpolation) {
  21585. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  21586. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  21587. this.name = name;
  21588. this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
  21589. this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
  21590. this.setInterpolation(interpolation || this.DefaultInterpolation);
  21591. } // Static methods
  21592. Object.assign(KeyframeTrack, {
  21593. // Serialization (in static context, because of constructor invocation
  21594. // and automatic invocation of .toJSON):
  21595. toJSON: function (track) {
  21596. var trackType = track.constructor;
  21597. var json; // derived classes can define a static toJSON method
  21598. if (trackType.toJSON !== undefined) {
  21599. json = trackType.toJSON(track);
  21600. } else {
  21601. // by default, we assume the data can be serialized as-is
  21602. json = {
  21603. 'name': track.name,
  21604. 'times': AnimationUtils.convertArray(track.times, Array),
  21605. 'values': AnimationUtils.convertArray(track.values, Array)
  21606. };
  21607. var interpolation = track.getInterpolation();
  21608. if (interpolation !== track.DefaultInterpolation) {
  21609. json.interpolation = interpolation;
  21610. }
  21611. }
  21612. json.type = track.ValueTypeName; // mandatory
  21613. return json;
  21614. }
  21615. });
  21616. Object.assign(KeyframeTrack.prototype, {
  21617. constructor: KeyframeTrack,
  21618. TimeBufferType: Float32Array,
  21619. ValueBufferType: Float32Array,
  21620. DefaultInterpolation: InterpolateLinear,
  21621. InterpolantFactoryMethodDiscrete: function (result) {
  21622. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  21623. },
  21624. InterpolantFactoryMethodLinear: function (result) {
  21625. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  21626. },
  21627. InterpolantFactoryMethodSmooth: function (result) {
  21628. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  21629. },
  21630. setInterpolation: function (interpolation) {
  21631. var factoryMethod;
  21632. switch (interpolation) {
  21633. case InterpolateDiscrete:
  21634. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  21635. break;
  21636. case InterpolateLinear:
  21637. factoryMethod = this.InterpolantFactoryMethodLinear;
  21638. break;
  21639. case InterpolateSmooth:
  21640. factoryMethod = this.InterpolantFactoryMethodSmooth;
  21641. break;
  21642. }
  21643. if (factoryMethod === undefined) {
  21644. var message = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name;
  21645. if (this.createInterpolant === undefined) {
  21646. // fall back to default, unless the default itself is messed up
  21647. if (interpolation !== this.DefaultInterpolation) {
  21648. this.setInterpolation(this.DefaultInterpolation);
  21649. } else {
  21650. throw new Error(message); // fatal, in this case
  21651. }
  21652. }
  21653. console.warn('THREE.KeyframeTrack:', message);
  21654. return this;
  21655. }
  21656. this.createInterpolant = factoryMethod;
  21657. return this;
  21658. },
  21659. getInterpolation: function () {
  21660. switch (this.createInterpolant) {
  21661. case this.InterpolantFactoryMethodDiscrete:
  21662. return InterpolateDiscrete;
  21663. case this.InterpolantFactoryMethodLinear:
  21664. return InterpolateLinear;
  21665. case this.InterpolantFactoryMethodSmooth:
  21666. return InterpolateSmooth;
  21667. }
  21668. },
  21669. getValueSize: function () {
  21670. return this.values.length / this.times.length;
  21671. },
  21672. // move all keyframes either forwards or backwards in time
  21673. shift: function (timeOffset) {
  21674. if (timeOffset !== 0.0) {
  21675. var times = this.times;
  21676. for (var i = 0, n = times.length; i !== n; ++i) {
  21677. times[i] += timeOffset;
  21678. }
  21679. }
  21680. return this;
  21681. },
  21682. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  21683. scale: function (timeScale) {
  21684. if (timeScale !== 1.0) {
  21685. var times = this.times;
  21686. for (var i = 0, n = times.length; i !== n; ++i) {
  21687. times[i] *= timeScale;
  21688. }
  21689. }
  21690. return this;
  21691. },
  21692. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  21693. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  21694. trim: function (startTime, endTime) {
  21695. var times = this.times,
  21696. nKeys = times.length,
  21697. from = 0,
  21698. to = nKeys - 1;
  21699. while (from !== nKeys && times[from] < startTime) {
  21700. ++from;
  21701. }
  21702. while (to !== -1 && times[to] > endTime) {
  21703. --to;
  21704. }
  21705. ++to; // inclusive -> exclusive bound
  21706. if (from !== 0 || to !== nKeys) {
  21707. // empty tracks are forbidden, so keep at least one keyframe
  21708. if (from >= to) to = Math.max(to, 1), from = to - 1;
  21709. var stride = this.getValueSize();
  21710. this.times = AnimationUtils.arraySlice(times, from, to);
  21711. this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
  21712. }
  21713. return this;
  21714. },
  21715. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  21716. validate: function () {
  21717. var valid = true;
  21718. var valueSize = this.getValueSize();
  21719. if (valueSize - Math.floor(valueSize) !== 0) {
  21720. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  21721. valid = false;
  21722. }
  21723. var times = this.times,
  21724. values = this.values,
  21725. nKeys = times.length;
  21726. if (nKeys === 0) {
  21727. console.error('THREE.KeyframeTrack: Track is empty.', this);
  21728. valid = false;
  21729. }
  21730. var prevTime = null;
  21731. for (var i = 0; i !== nKeys; i++) {
  21732. var currTime = times[i];
  21733. if (typeof currTime === 'number' && isNaN(currTime)) {
  21734. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  21735. valid = false;
  21736. break;
  21737. }
  21738. if (prevTime !== null && prevTime > currTime) {
  21739. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  21740. valid = false;
  21741. break;
  21742. }
  21743. prevTime = currTime;
  21744. }
  21745. if (values !== undefined) {
  21746. if (AnimationUtils.isTypedArray(values)) {
  21747. for (var i = 0, n = values.length; i !== n; ++i) {
  21748. var value = values[i];
  21749. if (isNaN(value)) {
  21750. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  21751. valid = false;
  21752. break;
  21753. }
  21754. }
  21755. }
  21756. }
  21757. return valid;
  21758. },
  21759. // removes equivalent sequential keys as common in morph target sequences
  21760. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  21761. optimize: function () {
  21762. var times = this.times,
  21763. values = this.values,
  21764. stride = this.getValueSize(),
  21765. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  21766. writeIndex = 1,
  21767. lastIndex = times.length - 1;
  21768. for (var i = 1; i < lastIndex; ++i) {
  21769. var keep = false;
  21770. var time = times[i];
  21771. var timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  21772. if (time !== timeNext && (i !== 1 || time !== time[0])) {
  21773. if (!smoothInterpolation) {
  21774. // remove unnecessary keyframes same as their neighbors
  21775. var offset = i * stride,
  21776. offsetP = offset - stride,
  21777. offsetN = offset + stride;
  21778. for (var j = 0; j !== stride; ++j) {
  21779. var value = values[offset + j];
  21780. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  21781. keep = true;
  21782. break;
  21783. }
  21784. }
  21785. } else {
  21786. keep = true;
  21787. }
  21788. } // in-place compaction
  21789. if (keep) {
  21790. if (i !== writeIndex) {
  21791. times[writeIndex] = times[i];
  21792. var readOffset = i * stride,
  21793. writeOffset = writeIndex * stride;
  21794. for (var j = 0; j !== stride; ++j) {
  21795. values[writeOffset + j] = values[readOffset + j];
  21796. }
  21797. }
  21798. ++writeIndex;
  21799. }
  21800. } // flush last keyframe (compaction looks ahead)
  21801. if (lastIndex > 0) {
  21802. times[writeIndex] = times[lastIndex];
  21803. for (var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  21804. values[writeOffset + j] = values[readOffset + j];
  21805. }
  21806. ++writeIndex;
  21807. }
  21808. if (writeIndex !== times.length) {
  21809. this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
  21810. this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
  21811. }
  21812. return this;
  21813. },
  21814. clone: function () {
  21815. var times = AnimationUtils.arraySlice(this.times, 0);
  21816. var values = AnimationUtils.arraySlice(this.values, 0);
  21817. var TypedKeyframeTrack = this.constructor;
  21818. var track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  21819. track.createInterpolant = this.createInterpolant;
  21820. return track;
  21821. }
  21822. });
  21823. /**
  21824. *
  21825. * A Track of Boolean keyframe values.
  21826. *
  21827. *
  21828. * @author Ben Houston / http://clara.io/
  21829. * @author David Sarno / http://lighthaus.us/
  21830. * @author tschw
  21831. */
  21832. function BooleanKeyframeTrack(name, times, values) {
  21833. KeyframeTrack.call(this, name, times, values);
  21834. }
  21835. BooleanKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21836. constructor: BooleanKeyframeTrack,
  21837. ValueTypeName: 'bool',
  21838. ValueBufferType: Array,
  21839. DefaultInterpolation: InterpolateDiscrete,
  21840. InterpolantFactoryMethodLinear: undefined,
  21841. InterpolantFactoryMethodSmooth: undefined // Note: Actually this track could have a optimized / compressed
  21842. // representation of a single value and a custom interpolant that
  21843. // computes "firstValue ^ isOdd( index )".
  21844. });
  21845. /**
  21846. *
  21847. * A Track of keyframe values that represent color.
  21848. *
  21849. *
  21850. * @author Ben Houston / http://clara.io/
  21851. * @author David Sarno / http://lighthaus.us/
  21852. * @author tschw
  21853. */
  21854. function ColorKeyframeTrack(name, times, values, interpolation) {
  21855. KeyframeTrack.call(this, name, times, values, interpolation);
  21856. }
  21857. ColorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21858. constructor: ColorKeyframeTrack,
  21859. ValueTypeName: 'color' // ValueBufferType is inherited
  21860. // DefaultInterpolation is inherited
  21861. // Note: Very basic implementation and nothing special yet.
  21862. // However, this is the place for color space parameterization.
  21863. });
  21864. /**
  21865. *
  21866. * A Track of numeric keyframe values.
  21867. *
  21868. * @author Ben Houston / http://clara.io/
  21869. * @author David Sarno / http://lighthaus.us/
  21870. * @author tschw
  21871. */
  21872. function NumberKeyframeTrack(name, times, values, interpolation) {
  21873. KeyframeTrack.call(this, name, times, values, interpolation);
  21874. }
  21875. NumberKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21876. constructor: NumberKeyframeTrack,
  21877. ValueTypeName: 'number' // ValueBufferType is inherited
  21878. // DefaultInterpolation is inherited
  21879. });
  21880. /**
  21881. * Spherical linear unit quaternion interpolant.
  21882. *
  21883. * @author tschw
  21884. */
  21885. function QuaternionLinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21886. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21887. }
  21888. QuaternionLinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21889. constructor: QuaternionLinearInterpolant,
  21890. interpolate_: function (i1, t0, t, t1) {
  21891. var result = this.resultBuffer,
  21892. values = this.sampleValues,
  21893. stride = this.valueSize,
  21894. offset = i1 * stride,
  21895. alpha = (t - t0) / (t1 - t0);
  21896. for (var end = offset + stride; offset !== end; offset += 4) {
  21897. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  21898. }
  21899. return result;
  21900. }
  21901. });
  21902. /**
  21903. *
  21904. * A Track of quaternion keyframe values.
  21905. *
  21906. * @author Ben Houston / http://clara.io/
  21907. * @author David Sarno / http://lighthaus.us/
  21908. * @author tschw
  21909. */
  21910. function QuaternionKeyframeTrack(name, times, values, interpolation) {
  21911. KeyframeTrack.call(this, name, times, values, interpolation);
  21912. }
  21913. QuaternionKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21914. constructor: QuaternionKeyframeTrack,
  21915. ValueTypeName: 'quaternion',
  21916. // ValueBufferType is inherited
  21917. DefaultInterpolation: InterpolateLinear,
  21918. InterpolantFactoryMethodLinear: function (result) {
  21919. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  21920. },
  21921. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  21922. });
  21923. /**
  21924. *
  21925. * A Track that interpolates Strings
  21926. *
  21927. *
  21928. * @author Ben Houston / http://clara.io/
  21929. * @author David Sarno / http://lighthaus.us/
  21930. * @author tschw
  21931. */
  21932. function StringKeyframeTrack(name, times, values, interpolation) {
  21933. KeyframeTrack.call(this, name, times, values, interpolation);
  21934. }
  21935. StringKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21936. constructor: StringKeyframeTrack,
  21937. ValueTypeName: 'string',
  21938. ValueBufferType: Array,
  21939. DefaultInterpolation: InterpolateDiscrete,
  21940. InterpolantFactoryMethodLinear: undefined,
  21941. InterpolantFactoryMethodSmooth: undefined
  21942. });
  21943. /**
  21944. *
  21945. * A Track of vectored keyframe values.
  21946. *
  21947. *
  21948. * @author Ben Houston / http://clara.io/
  21949. * @author David Sarno / http://lighthaus.us/
  21950. * @author tschw
  21951. */
  21952. function VectorKeyframeTrack(name, times, values, interpolation) {
  21953. KeyframeTrack.call(this, name, times, values, interpolation);
  21954. }
  21955. VectorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21956. constructor: VectorKeyframeTrack,
  21957. ValueTypeName: 'vector' // ValueBufferType is inherited
  21958. // DefaultInterpolation is inherited
  21959. });
  21960. /**
  21961. *
  21962. * Reusable set of Tracks that represent an animation.
  21963. *
  21964. * @author Ben Houston / http://clara.io/
  21965. * @author David Sarno / http://lighthaus.us/
  21966. */
  21967. function AnimationClip(name, duration, tracks) {
  21968. this.name = name;
  21969. this.tracks = tracks;
  21970. this.duration = duration !== undefined ? duration : -1;
  21971. this.uuid = _Math.generateUUID(); // this means it should figure out its duration by scanning the tracks
  21972. if (this.duration < 0) {
  21973. this.resetDuration();
  21974. }
  21975. }
  21976. function getTrackTypeForValueTypeName(typeName) {
  21977. switch (typeName.toLowerCase()) {
  21978. case 'scalar':
  21979. case 'double':
  21980. case 'float':
  21981. case 'number':
  21982. case 'integer':
  21983. return NumberKeyframeTrack;
  21984. case 'vector':
  21985. case 'vector2':
  21986. case 'vector3':
  21987. case 'vector4':
  21988. return VectorKeyframeTrack;
  21989. case 'color':
  21990. return ColorKeyframeTrack;
  21991. case 'quaternion':
  21992. return QuaternionKeyframeTrack;
  21993. case 'bool':
  21994. case 'boolean':
  21995. return BooleanKeyframeTrack;
  21996. case 'string':
  21997. return StringKeyframeTrack;
  21998. }
  21999. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  22000. }
  22001. function parseKeyframeTrack(json) {
  22002. if (json.type === undefined) {
  22003. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  22004. }
  22005. var trackType = getTrackTypeForValueTypeName(json.type);
  22006. if (json.times === undefined) {
  22007. var times = [],
  22008. values = [];
  22009. AnimationUtils.flattenJSON(json.keys, times, values, 'value');
  22010. json.times = times;
  22011. json.values = values;
  22012. } // derived classes can define a static parse method
  22013. if (trackType.parse !== undefined) {
  22014. return trackType.parse(json);
  22015. } else {
  22016. // by default, we assume a constructor compatible with the base
  22017. return new trackType(json.name, json.times, json.values, json.interpolation);
  22018. }
  22019. }
  22020. Object.assign(AnimationClip, {
  22021. parse: function (json) {
  22022. var tracks = [],
  22023. jsonTracks = json.tracks,
  22024. frameTime = 1.0 / (json.fps || 1.0);
  22025. for (var i = 0, n = jsonTracks.length; i !== n; ++i) {
  22026. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  22027. }
  22028. return new AnimationClip(json.name, json.duration, tracks);
  22029. },
  22030. toJSON: function (clip) {
  22031. var tracks = [],
  22032. clipTracks = clip.tracks;
  22033. var json = {
  22034. 'name': clip.name,
  22035. 'duration': clip.duration,
  22036. 'tracks': tracks,
  22037. 'uuid': clip.uuid
  22038. };
  22039. for (var i = 0, n = clipTracks.length; i !== n; ++i) {
  22040. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  22041. }
  22042. return json;
  22043. },
  22044. CreateFromMorphTargetSequence: function (name, morphTargetSequence, fps, noLoop) {
  22045. var numMorphTargets = morphTargetSequence.length;
  22046. var tracks = [];
  22047. for (var i = 0; i < numMorphTargets; i++) {
  22048. var times = [];
  22049. var values = [];
  22050. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  22051. values.push(0, 1, 0);
  22052. var order = AnimationUtils.getKeyframeOrder(times);
  22053. times = AnimationUtils.sortedArray(times, 1, order);
  22054. values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  22055. // last frame as well for perfect loop.
  22056. if (!noLoop && times[0] === 0) {
  22057. times.push(numMorphTargets);
  22058. values.push(values[0]);
  22059. }
  22060. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  22061. }
  22062. return new AnimationClip(name, -1, tracks);
  22063. },
  22064. findByName: function (objectOrClipArray, name) {
  22065. var clipArray = objectOrClipArray;
  22066. if (!Array.isArray(objectOrClipArray)) {
  22067. var o = objectOrClipArray;
  22068. clipArray = o.geometry && o.geometry.animations || o.animations;
  22069. }
  22070. for (var i = 0; i < clipArray.length; i++) {
  22071. if (clipArray[i].name === name) {
  22072. return clipArray[i];
  22073. }
  22074. }
  22075. return null;
  22076. },
  22077. CreateClipsFromMorphTargetSequences: function (morphTargets, fps, noLoop) {
  22078. var animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  22079. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  22080. var pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  22081. // patterns like Walk_001, Walk_002, Run_001, Run_002
  22082. for (var i = 0, il = morphTargets.length; i < il; i++) {
  22083. var morphTarget = morphTargets[i];
  22084. var parts = morphTarget.name.match(pattern);
  22085. if (parts && parts.length > 1) {
  22086. var name = parts[1];
  22087. var animationMorphTargets = animationToMorphTargets[name];
  22088. if (!animationMorphTargets) {
  22089. animationToMorphTargets[name] = animationMorphTargets = [];
  22090. }
  22091. animationMorphTargets.push(morphTarget);
  22092. }
  22093. }
  22094. var clips = [];
  22095. for (var name in animationToMorphTargets) {
  22096. clips.push(AnimationClip.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  22097. }
  22098. return clips;
  22099. },
  22100. // parse the animation.hierarchy format
  22101. parseAnimation: function (animation, bones) {
  22102. if (!animation) {
  22103. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  22104. return null;
  22105. }
  22106. var addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  22107. // only return track if there are actually keys.
  22108. if (animationKeys.length !== 0) {
  22109. var times = [];
  22110. var values = [];
  22111. AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  22112. if (times.length !== 0) {
  22113. destTracks.push(new trackType(trackName, times, values));
  22114. }
  22115. }
  22116. };
  22117. var tracks = [];
  22118. var clipName = animation.name || 'default'; // automatic length determination in AnimationClip.
  22119. var duration = animation.length || -1;
  22120. var fps = animation.fps || 30;
  22121. var hierarchyTracks = animation.hierarchy || [];
  22122. for (var h = 0; h < hierarchyTracks.length; h++) {
  22123. var animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  22124. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  22125. if (animationKeys[0].morphTargets) {
  22126. // figure out all morph targets used in this track
  22127. var morphTargetNames = {};
  22128. for (var k = 0; k < animationKeys.length; k++) {
  22129. if (animationKeys[k].morphTargets) {
  22130. for (var m = 0; m < animationKeys[k].morphTargets.length; m++) {
  22131. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  22132. }
  22133. }
  22134. } // create a track for each morph target with all zero
  22135. // morphTargetInfluences except for the keys in which
  22136. // the morphTarget is named.
  22137. for (var morphTargetName in morphTargetNames) {
  22138. var times = [];
  22139. var values = [];
  22140. for (var m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  22141. var animationKey = animationKeys[k];
  22142. times.push(animationKey.time);
  22143. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  22144. }
  22145. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  22146. }
  22147. duration = morphTargetNames.length * (fps || 1.0);
  22148. } else {
  22149. // ...assume skeletal animation
  22150. var boneName = '.bones[' + bones[h].name + ']';
  22151. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  22152. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  22153. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  22154. }
  22155. }
  22156. if (tracks.length === 0) {
  22157. return null;
  22158. }
  22159. var clip = new AnimationClip(clipName, duration, tracks);
  22160. return clip;
  22161. }
  22162. });
  22163. Object.assign(AnimationClip.prototype, {
  22164. resetDuration: function () {
  22165. var tracks = this.tracks,
  22166. duration = 0;
  22167. for (var i = 0, n = tracks.length; i !== n; ++i) {
  22168. var track = this.tracks[i];
  22169. duration = Math.max(duration, track.times[track.times.length - 1]);
  22170. }
  22171. this.duration = duration;
  22172. return this;
  22173. },
  22174. trim: function () {
  22175. for (var i = 0; i < this.tracks.length; i++) {
  22176. this.tracks[i].trim(0, this.duration);
  22177. }
  22178. return this;
  22179. },
  22180. validate: function () {
  22181. var valid = true;
  22182. for (var i = 0; i < this.tracks.length; i++) {
  22183. valid = valid && this.tracks[i].validate();
  22184. }
  22185. return valid;
  22186. },
  22187. optimize: function () {
  22188. for (var i = 0; i < this.tracks.length; i++) {
  22189. this.tracks[i].optimize();
  22190. }
  22191. return this;
  22192. },
  22193. clone: function () {
  22194. var tracks = [];
  22195. for (var i = 0; i < this.tracks.length; i++) {
  22196. tracks.push(this.tracks[i].clone());
  22197. }
  22198. return new AnimationClip(this.name, this.duration, tracks);
  22199. }
  22200. });
  22201. /**
  22202. * @author mrdoob / http://mrdoob.com/
  22203. */
  22204. var Cache = {
  22205. enabled: false,
  22206. files: {},
  22207. add: function (key, file) {
  22208. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  22209. this.files[key] = file;
  22210. },
  22211. get: function (key) {
  22212. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  22213. return this.files[key];
  22214. },
  22215. remove: function (key) {
  22216. delete this.files[key];
  22217. },
  22218. clear: function () {
  22219. this.files = {};
  22220. }
  22221. };
  22222. /**
  22223. * @author mrdoob / http://mrdoob.com/
  22224. */
  22225. exports.Cache = Cache;
  22226. function LoadingManager(onLoad, onProgress, onError) {
  22227. var scope = this;
  22228. var isLoading = false;
  22229. var itemsLoaded = 0;
  22230. var itemsTotal = 0;
  22231. var urlModifier = undefined;
  22232. var handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  22233. // in the constructor
  22234. this.onStart = undefined;
  22235. this.onLoad = onLoad;
  22236. this.onProgress = onProgress;
  22237. this.onError = onError;
  22238. this.itemStart = function (url) {
  22239. itemsTotal++;
  22240. if (isLoading === false) {
  22241. if (scope.onStart !== undefined) {
  22242. scope.onStart(url, itemsLoaded, itemsTotal);
  22243. }
  22244. }
  22245. isLoading = true;
  22246. };
  22247. this.itemEnd = function (url) {
  22248. itemsLoaded++;
  22249. if (scope.onProgress !== undefined) {
  22250. scope.onProgress(url, itemsLoaded, itemsTotal);
  22251. }
  22252. if (itemsLoaded === itemsTotal) {
  22253. isLoading = false;
  22254. if (scope.onLoad !== undefined) {
  22255. scope.onLoad();
  22256. }
  22257. }
  22258. };
  22259. this.itemError = function (url) {
  22260. if (scope.onError !== undefined) {
  22261. scope.onError(url);
  22262. }
  22263. };
  22264. this.resolveURL = function (url) {
  22265. if (urlModifier) {
  22266. return urlModifier(url);
  22267. }
  22268. return url;
  22269. };
  22270. this.setURLModifier = function (transform) {
  22271. urlModifier = transform;
  22272. return this;
  22273. };
  22274. this.addHandler = function (regex, loader) {
  22275. handlers.push(regex, loader);
  22276. return this;
  22277. };
  22278. this.removeHandler = function (regex) {
  22279. var index = handlers.indexOf(regex);
  22280. if (index !== -1) {
  22281. handlers.splice(index, 2);
  22282. }
  22283. return this;
  22284. };
  22285. this.getHandler = function (file) {
  22286. for (var i = 0, l = handlers.length; i < l; i += 2) {
  22287. var regex = handlers[i];
  22288. var loader = handlers[i + 1];
  22289. if (regex.test(file)) {
  22290. return loader;
  22291. }
  22292. }
  22293. return null;
  22294. };
  22295. }
  22296. var DefaultLoadingManager = new LoadingManager();
  22297. /**
  22298. * @author alteredq / http://alteredqualia.com/
  22299. */
  22300. exports.DefaultLoadingManager = DefaultLoadingManager;
  22301. function Loader(manager) {
  22302. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  22303. this.crossOrigin = 'anonymous';
  22304. this.path = '';
  22305. this.resourcePath = '';
  22306. }
  22307. Object.assign(Loader.prototype, {
  22308. load: function ()
  22309. /* url, onLoad, onProgress, onError */
  22310. {},
  22311. parse: function ()
  22312. /* data */
  22313. {},
  22314. setCrossOrigin: function (crossOrigin) {
  22315. this.crossOrigin = crossOrigin;
  22316. return this;
  22317. },
  22318. setPath: function (path) {
  22319. this.path = path;
  22320. return this;
  22321. },
  22322. setResourcePath: function (resourcePath) {
  22323. this.resourcePath = resourcePath;
  22324. return this;
  22325. }
  22326. });
  22327. /**
  22328. * @author mrdoob / http://mrdoob.com/
  22329. */
  22330. var loading = {};
  22331. function FileLoader(manager) {
  22332. Loader.call(this, manager);
  22333. }
  22334. FileLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22335. constructor: FileLoader,
  22336. load: function (url, onLoad, onProgress, onError) {
  22337. if (url === undefined) url = '';
  22338. if (this.path !== undefined) url = this.path + url;
  22339. url = this.manager.resolveURL(url);
  22340. var scope = this;
  22341. var cached = Cache.get(url);
  22342. if (cached !== undefined) {
  22343. scope.manager.itemStart(url);
  22344. setTimeout(function () {
  22345. if (onLoad) onLoad(cached);
  22346. scope.manager.itemEnd(url);
  22347. }, 0);
  22348. return cached;
  22349. } // Check if request is duplicate
  22350. if (loading[url] !== undefined) {
  22351. loading[url].push({
  22352. onLoad: onLoad,
  22353. onProgress: onProgress,
  22354. onError: onError
  22355. });
  22356. return;
  22357. } // Check for data: URI
  22358. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  22359. var dataUriRegexResult = url.match(dataUriRegex); // Safari can not handle Data URIs through XMLHttpRequest so process manually
  22360. if (dataUriRegexResult) {
  22361. var mimeType = dataUriRegexResult[1];
  22362. var isBase64 = !!dataUriRegexResult[2];
  22363. var data = dataUriRegexResult[3];
  22364. data = decodeURIComponent(data);
  22365. if (isBase64) data = atob(data);
  22366. try {
  22367. var response;
  22368. var responseType = (this.responseType || '').toLowerCase();
  22369. switch (responseType) {
  22370. case 'arraybuffer':
  22371. case 'blob':
  22372. var view = new Uint8Array(data.length);
  22373. for (var i = 0; i < data.length; i++) {
  22374. view[i] = data.charCodeAt(i);
  22375. }
  22376. if (responseType === 'blob') {
  22377. response = new Blob([view.buffer], {
  22378. type: mimeType
  22379. });
  22380. } else {
  22381. response = view.buffer;
  22382. }
  22383. break;
  22384. case 'document':
  22385. var parser = new DOMParser();
  22386. response = parser.parseFromString(data, mimeType);
  22387. break;
  22388. case 'json':
  22389. response = JSON.parse(data);
  22390. break;
  22391. default:
  22392. // 'text' or other
  22393. response = data;
  22394. break;
  22395. } // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22396. setTimeout(function () {
  22397. if (onLoad) onLoad(response);
  22398. scope.manager.itemEnd(url);
  22399. }, 0);
  22400. } catch (error) {
  22401. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22402. setTimeout(function () {
  22403. if (onError) onError(error);
  22404. scope.manager.itemError(url);
  22405. scope.manager.itemEnd(url);
  22406. }, 0);
  22407. }
  22408. } else {
  22409. // Initialise array for duplicate requests
  22410. loading[url] = [];
  22411. loading[url].push({
  22412. onLoad: onLoad,
  22413. onProgress: onProgress,
  22414. onError: onError
  22415. });
  22416. var request = new XMLHttpRequest();
  22417. request.open('GET', url, true);
  22418. request.addEventListener('load', function (event) {
  22419. var response = this.response;
  22420. Cache.add(url, response);
  22421. var callbacks = loading[url];
  22422. delete loading[url];
  22423. if (this.status === 200 || this.status === 0) {
  22424. // Some browsers return HTTP Status 0 when using non-http protocol
  22425. // e.g. 'file://' or 'data://'. Handle as success.
  22426. if (this.status === 0) console.warn('THREE.FileLoader: HTTP Status 0 received.');
  22427. for (var i = 0, il = callbacks.length; i < il; i++) {
  22428. var callback = callbacks[i];
  22429. if (callback.onLoad) callback.onLoad(response);
  22430. }
  22431. scope.manager.itemEnd(url);
  22432. } else {
  22433. for (var i = 0, il = callbacks.length; i < il; i++) {
  22434. var callback = callbacks[i];
  22435. if (callback.onError) callback.onError(event);
  22436. }
  22437. scope.manager.itemError(url);
  22438. scope.manager.itemEnd(url);
  22439. }
  22440. }, false);
  22441. request.addEventListener('progress', function (event) {
  22442. var callbacks = loading[url];
  22443. for (var i = 0, il = callbacks.length; i < il; i++) {
  22444. var callback = callbacks[i];
  22445. if (callback.onProgress) callback.onProgress(event);
  22446. }
  22447. }, false);
  22448. request.addEventListener('error', function (event) {
  22449. var callbacks = loading[url];
  22450. delete loading[url];
  22451. for (var i = 0, il = callbacks.length; i < il; i++) {
  22452. var callback = callbacks[i];
  22453. if (callback.onError) callback.onError(event);
  22454. }
  22455. scope.manager.itemError(url);
  22456. scope.manager.itemEnd(url);
  22457. }, false);
  22458. request.addEventListener('abort', function (event) {
  22459. var callbacks = loading[url];
  22460. delete loading[url];
  22461. for (var i = 0, il = callbacks.length; i < il; i++) {
  22462. var callback = callbacks[i];
  22463. if (callback.onError) callback.onError(event);
  22464. }
  22465. scope.manager.itemError(url);
  22466. scope.manager.itemEnd(url);
  22467. }, false);
  22468. if (this.responseType !== undefined) request.responseType = this.responseType;
  22469. if (this.withCredentials !== undefined) request.withCredentials = this.withCredentials;
  22470. if (request.overrideMimeType) request.overrideMimeType(this.mimeType !== undefined ? this.mimeType : 'text/plain');
  22471. for (var header in this.requestHeader) {
  22472. request.setRequestHeader(header, this.requestHeader[header]);
  22473. }
  22474. request.send(null);
  22475. }
  22476. scope.manager.itemStart(url);
  22477. return request;
  22478. },
  22479. setResponseType: function (value) {
  22480. this.responseType = value;
  22481. return this;
  22482. },
  22483. setWithCredentials: function (value) {
  22484. this.withCredentials = value;
  22485. return this;
  22486. },
  22487. setMimeType: function (value) {
  22488. this.mimeType = value;
  22489. return this;
  22490. },
  22491. setRequestHeader: function (value) {
  22492. this.requestHeader = value;
  22493. return this;
  22494. }
  22495. });
  22496. /**
  22497. * @author bhouston / http://clara.io/
  22498. */
  22499. function AnimationLoader(manager) {
  22500. Loader.call(this, manager);
  22501. }
  22502. AnimationLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22503. constructor: AnimationLoader,
  22504. load: function (url, onLoad, onProgress, onError) {
  22505. var scope = this;
  22506. var loader = new FileLoader(scope.manager);
  22507. loader.setPath(scope.path);
  22508. loader.load(url, function (text) {
  22509. onLoad(scope.parse(JSON.parse(text)));
  22510. }, onProgress, onError);
  22511. },
  22512. parse: function (json) {
  22513. var animations = [];
  22514. for (var i = 0; i < json.length; i++) {
  22515. var clip = AnimationClip.parse(json[i]);
  22516. animations.push(clip);
  22517. }
  22518. return animations;
  22519. }
  22520. });
  22521. /**
  22522. * @author mrdoob / http://mrdoob.com/
  22523. *
  22524. * Abstract Base class to block based textures loader (dds, pvr, ...)
  22525. *
  22526. * Sub classes have to implement the parse() method which will be used in load().
  22527. */
  22528. function CompressedTextureLoader(manager) {
  22529. Loader.call(this, manager);
  22530. }
  22531. CompressedTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22532. constructor: CompressedTextureLoader,
  22533. load: function (url, onLoad, onProgress, onError) {
  22534. var scope = this;
  22535. var images = [];
  22536. var texture = new CompressedTexture();
  22537. texture.image = images;
  22538. var loader = new FileLoader(this.manager);
  22539. loader.setPath(this.path);
  22540. loader.setResponseType('arraybuffer');
  22541. function loadTexture(i) {
  22542. loader.load(url[i], function (buffer) {
  22543. var texDatas = scope.parse(buffer, true);
  22544. images[i] = {
  22545. width: texDatas.width,
  22546. height: texDatas.height,
  22547. format: texDatas.format,
  22548. mipmaps: texDatas.mipmaps
  22549. };
  22550. loaded += 1;
  22551. if (loaded === 6) {
  22552. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  22553. texture.format = texDatas.format;
  22554. texture.needsUpdate = true;
  22555. if (onLoad) onLoad(texture);
  22556. }
  22557. }, onProgress, onError);
  22558. }
  22559. if (Array.isArray(url)) {
  22560. var loaded = 0;
  22561. for (var i = 0, il = url.length; i < il; ++i) {
  22562. loadTexture(i);
  22563. }
  22564. } else {
  22565. // compressed cubemap texture stored in a single DDS file
  22566. loader.load(url, function (buffer) {
  22567. var texDatas = scope.parse(buffer, true);
  22568. if (texDatas.isCubemap) {
  22569. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  22570. for (var f = 0; f < faces; f++) {
  22571. images[f] = {
  22572. mipmaps: []
  22573. };
  22574. for (var i = 0; i < texDatas.mipmapCount; i++) {
  22575. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  22576. images[f].format = texDatas.format;
  22577. images[f].width = texDatas.width;
  22578. images[f].height = texDatas.height;
  22579. }
  22580. }
  22581. } else {
  22582. texture.image.width = texDatas.width;
  22583. texture.image.height = texDatas.height;
  22584. texture.mipmaps = texDatas.mipmaps;
  22585. }
  22586. if (texDatas.mipmapCount === 1) {
  22587. texture.minFilter = LinearFilter;
  22588. }
  22589. texture.format = texDatas.format;
  22590. texture.needsUpdate = true;
  22591. if (onLoad) onLoad(texture);
  22592. }, onProgress, onError);
  22593. }
  22594. return texture;
  22595. }
  22596. });
  22597. /**
  22598. * @author Nikos M. / https://github.com/foo123/
  22599. *
  22600. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  22601. *
  22602. * Sub classes have to implement the parse() method which will be used in load().
  22603. */
  22604. function DataTextureLoader(manager) {
  22605. Loader.call(this, manager);
  22606. }
  22607. DataTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22608. constructor: DataTextureLoader,
  22609. load: function (url, onLoad, onProgress, onError) {
  22610. var scope = this;
  22611. var texture = new DataTexture();
  22612. var loader = new FileLoader(this.manager);
  22613. loader.setResponseType('arraybuffer');
  22614. loader.setPath(this.path);
  22615. loader.load(url, function (buffer) {
  22616. var texData = scope.parse(buffer);
  22617. if (!texData) return;
  22618. if (texData.image !== undefined) {
  22619. texture.image = texData.image;
  22620. } else if (texData.data !== undefined) {
  22621. texture.image.width = texData.width;
  22622. texture.image.height = texData.height;
  22623. texture.image.data = texData.data;
  22624. }
  22625. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  22626. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  22627. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  22628. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearMipmapLinearFilter;
  22629. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  22630. if (texData.format !== undefined) {
  22631. texture.format = texData.format;
  22632. }
  22633. if (texData.type !== undefined) {
  22634. texture.type = texData.type;
  22635. }
  22636. if (texData.mipmaps !== undefined) {
  22637. texture.mipmaps = texData.mipmaps;
  22638. }
  22639. if (texData.mipmapCount === 1) {
  22640. texture.minFilter = LinearFilter;
  22641. }
  22642. texture.needsUpdate = true;
  22643. if (onLoad) onLoad(texture, texData);
  22644. }, onProgress, onError);
  22645. return texture;
  22646. }
  22647. });
  22648. /**
  22649. * @author mrdoob / http://mrdoob.com/
  22650. */
  22651. function ImageLoader(manager) {
  22652. Loader.call(this, manager);
  22653. }
  22654. ImageLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22655. constructor: ImageLoader,
  22656. load: function (url, onLoad, onProgress, onError) {
  22657. if (this.path !== undefined) url = this.path + url;
  22658. url = this.manager.resolveURL(url);
  22659. var scope = this;
  22660. var cached = Cache.get(url);
  22661. if (cached !== undefined) {
  22662. scope.manager.itemStart(url);
  22663. setTimeout(function () {
  22664. if (onLoad) onLoad(cached);
  22665. scope.manager.itemEnd(url);
  22666. }, 0);
  22667. return cached;
  22668. }
  22669. var image = document.createElementNS('http://www.w3.org/1999/xhtml', 'img');
  22670. function onImageLoad() {
  22671. image.removeEventListener('load', onImageLoad, false);
  22672. image.removeEventListener('error', onImageError, false);
  22673. Cache.add(url, this);
  22674. if (onLoad) onLoad(this);
  22675. scope.manager.itemEnd(url);
  22676. }
  22677. function onImageError(event) {
  22678. image.removeEventListener('load', onImageLoad, false);
  22679. image.removeEventListener('error', onImageError, false);
  22680. if (onError) onError(event);
  22681. scope.manager.itemError(url);
  22682. scope.manager.itemEnd(url);
  22683. }
  22684. image.addEventListener('load', onImageLoad, false);
  22685. image.addEventListener('error', onImageError, false);
  22686. if (url.substr(0, 5) !== 'data:') {
  22687. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  22688. }
  22689. scope.manager.itemStart(url);
  22690. image.src = url;
  22691. return image;
  22692. }
  22693. });
  22694. /**
  22695. * @author mrdoob / http://mrdoob.com/
  22696. */
  22697. function CubeTextureLoader(manager) {
  22698. Loader.call(this, manager);
  22699. }
  22700. CubeTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22701. constructor: CubeTextureLoader,
  22702. load: function (urls, onLoad, onProgress, onError) {
  22703. var texture = new CubeTexture();
  22704. var loader = new ImageLoader(this.manager);
  22705. loader.setCrossOrigin(this.crossOrigin);
  22706. loader.setPath(this.path);
  22707. var loaded = 0;
  22708. function loadTexture(i) {
  22709. loader.load(urls[i], function (image) {
  22710. texture.images[i] = image;
  22711. loaded++;
  22712. if (loaded === 6) {
  22713. texture.needsUpdate = true;
  22714. if (onLoad) onLoad(texture);
  22715. }
  22716. }, undefined, onError);
  22717. }
  22718. for (var i = 0; i < urls.length; ++i) {
  22719. loadTexture(i);
  22720. }
  22721. return texture;
  22722. }
  22723. });
  22724. /**
  22725. * @author mrdoob / http://mrdoob.com/
  22726. */
  22727. function TextureLoader(manager) {
  22728. Loader.call(this, manager);
  22729. }
  22730. TextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22731. constructor: TextureLoader,
  22732. load: function (url, onLoad, onProgress, onError) {
  22733. var texture = new Texture();
  22734. var loader = new ImageLoader(this.manager);
  22735. loader.setCrossOrigin(this.crossOrigin);
  22736. loader.setPath(this.path);
  22737. loader.load(url, function (image) {
  22738. texture.image = image; // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  22739. var isJPEG = url.search(/\.jpe?g($|\?)/i) > 0 || url.search(/^data\:image\/jpeg/) === 0;
  22740. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  22741. texture.needsUpdate = true;
  22742. if (onLoad !== undefined) {
  22743. onLoad(texture);
  22744. }
  22745. }, onProgress, onError);
  22746. return texture;
  22747. }
  22748. });
  22749. /**
  22750. * @author zz85 / http://www.lab4games.net/zz85/blog
  22751. * Extensible curve object
  22752. *
  22753. * Some common of curve methods:
  22754. * .getPoint( t, optionalTarget ), .getTangent( t )
  22755. * .getPointAt( u, optionalTarget ), .getTangentAt( u )
  22756. * .getPoints(), .getSpacedPoints()
  22757. * .getLength()
  22758. * .updateArcLengths()
  22759. *
  22760. * This following curves inherit from THREE.Curve:
  22761. *
  22762. * -- 2D curves --
  22763. * THREE.ArcCurve
  22764. * THREE.CubicBezierCurve
  22765. * THREE.EllipseCurve
  22766. * THREE.LineCurve
  22767. * THREE.QuadraticBezierCurve
  22768. * THREE.SplineCurve
  22769. *
  22770. * -- 3D curves --
  22771. * THREE.CatmullRomCurve3
  22772. * THREE.CubicBezierCurve3
  22773. * THREE.LineCurve3
  22774. * THREE.QuadraticBezierCurve3
  22775. *
  22776. * A series of curves can be represented as a THREE.CurvePath.
  22777. *
  22778. **/
  22779. /**************************************************************
  22780. * Abstract Curve base class
  22781. **************************************************************/
  22782. function Curve() {
  22783. this.type = 'Curve';
  22784. this.arcLengthDivisions = 200;
  22785. }
  22786. Object.assign(Curve.prototype, {
  22787. // Virtual base class method to overwrite and implement in subclasses
  22788. // - t [0 .. 1]
  22789. getPoint: function ()
  22790. /* t, optionalTarget */
  22791. {
  22792. console.warn('THREE.Curve: .getPoint() not implemented.');
  22793. return null;
  22794. },
  22795. // Get point at relative position in curve according to arc length
  22796. // - u [0 .. 1]
  22797. getPointAt: function (u, optionalTarget) {
  22798. var t = this.getUtoTmapping(u);
  22799. return this.getPoint(t, optionalTarget);
  22800. },
  22801. // Get sequence of points using getPoint( t )
  22802. getPoints: function (divisions) {
  22803. if (divisions === undefined) divisions = 5;
  22804. var points = [];
  22805. for (var d = 0; d <= divisions; d++) {
  22806. points.push(this.getPoint(d / divisions));
  22807. }
  22808. return points;
  22809. },
  22810. // Get sequence of points using getPointAt( u )
  22811. getSpacedPoints: function (divisions) {
  22812. if (divisions === undefined) divisions = 5;
  22813. var points = [];
  22814. for (var d = 0; d <= divisions; d++) {
  22815. points.push(this.getPointAt(d / divisions));
  22816. }
  22817. return points;
  22818. },
  22819. // Get total curve arc length
  22820. getLength: function () {
  22821. var lengths = this.getLengths();
  22822. return lengths[lengths.length - 1];
  22823. },
  22824. // Get list of cumulative segment lengths
  22825. getLengths: function (divisions) {
  22826. if (divisions === undefined) divisions = this.arcLengthDivisions;
  22827. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  22828. return this.cacheArcLengths;
  22829. }
  22830. this.needsUpdate = false;
  22831. var cache = [];
  22832. var current,
  22833. last = this.getPoint(0);
  22834. var p,
  22835. sum = 0;
  22836. cache.push(0);
  22837. for (p = 1; p <= divisions; p++) {
  22838. current = this.getPoint(p / divisions);
  22839. sum += current.distanceTo(last);
  22840. cache.push(sum);
  22841. last = current;
  22842. }
  22843. this.cacheArcLengths = cache;
  22844. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  22845. },
  22846. updateArcLengths: function () {
  22847. this.needsUpdate = true;
  22848. this.getLengths();
  22849. },
  22850. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  22851. getUtoTmapping: function (u, distance) {
  22852. var arcLengths = this.getLengths();
  22853. var i = 0,
  22854. il = arcLengths.length;
  22855. var targetArcLength; // The targeted u distance value to get
  22856. if (distance) {
  22857. targetArcLength = distance;
  22858. } else {
  22859. targetArcLength = u * arcLengths[il - 1];
  22860. } // binary search for the index with largest value smaller than target u distance
  22861. var low = 0,
  22862. high = il - 1,
  22863. comparison;
  22864. while (low <= high) {
  22865. 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
  22866. comparison = arcLengths[i] - targetArcLength;
  22867. if (comparison < 0) {
  22868. low = i + 1;
  22869. } else if (comparison > 0) {
  22870. high = i - 1;
  22871. } else {
  22872. high = i;
  22873. break; // DONE
  22874. }
  22875. }
  22876. i = high;
  22877. if (arcLengths[i] === targetArcLength) {
  22878. return i / (il - 1);
  22879. } // we could get finer grain at lengths, or use simple interpolation between two points
  22880. var lengthBefore = arcLengths[i];
  22881. var lengthAfter = arcLengths[i + 1];
  22882. var segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  22883. var segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  22884. var t = (i + segmentFraction) / (il - 1);
  22885. return t;
  22886. },
  22887. // Returns a unit vector tangent at t
  22888. // In case any sub curve does not implement its tangent derivation,
  22889. // 2 points a small delta apart will be used to find its gradient
  22890. // which seems to give a reasonable approximation
  22891. getTangent: function (t) {
  22892. var delta = 0.0001;
  22893. var t1 = t - delta;
  22894. var t2 = t + delta; // Capping in case of danger
  22895. if (t1 < 0) t1 = 0;
  22896. if (t2 > 1) t2 = 1;
  22897. var pt1 = this.getPoint(t1);
  22898. var pt2 = this.getPoint(t2);
  22899. var vec = pt2.clone().sub(pt1);
  22900. return vec.normalize();
  22901. },
  22902. getTangentAt: function (u) {
  22903. var t = this.getUtoTmapping(u);
  22904. return this.getTangent(t);
  22905. },
  22906. computeFrenetFrames: function (segments, closed) {
  22907. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  22908. var normal = new Vector3();
  22909. var tangents = [];
  22910. var normals = [];
  22911. var binormals = [];
  22912. var vec = new Vector3();
  22913. var mat = new Matrix4();
  22914. var i, u, theta; // compute the tangent vectors for each segment on the curve
  22915. for (i = 0; i <= segments; i++) {
  22916. u = i / segments;
  22917. tangents[i] = this.getTangentAt(u);
  22918. tangents[i].normalize();
  22919. } // select an initial normal vector perpendicular to the first tangent vector,
  22920. // and in the direction of the minimum tangent xyz component
  22921. normals[0] = new Vector3();
  22922. binormals[0] = new Vector3();
  22923. var min = Number.MAX_VALUE;
  22924. var tx = Math.abs(tangents[0].x);
  22925. var ty = Math.abs(tangents[0].y);
  22926. var tz = Math.abs(tangents[0].z);
  22927. if (tx <= min) {
  22928. min = tx;
  22929. normal.set(1, 0, 0);
  22930. }
  22931. if (ty <= min) {
  22932. min = ty;
  22933. normal.set(0, 1, 0);
  22934. }
  22935. if (tz <= min) {
  22936. normal.set(0, 0, 1);
  22937. }
  22938. vec.crossVectors(tangents[0], normal).normalize();
  22939. normals[0].crossVectors(tangents[0], vec);
  22940. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  22941. for (i = 1; i <= segments; i++) {
  22942. normals[i] = normals[i - 1].clone();
  22943. binormals[i] = binormals[i - 1].clone();
  22944. vec.crossVectors(tangents[i - 1], tangents[i]);
  22945. if (vec.length() > Number.EPSILON) {
  22946. vec.normalize();
  22947. theta = Math.acos(_Math.clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  22948. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  22949. }
  22950. binormals[i].crossVectors(tangents[i], normals[i]);
  22951. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  22952. if (closed === true) {
  22953. theta = Math.acos(_Math.clamp(normals[0].dot(normals[segments]), -1, 1));
  22954. theta /= segments;
  22955. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  22956. theta = -theta;
  22957. }
  22958. for (i = 1; i <= segments; i++) {
  22959. // twist a little...
  22960. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  22961. binormals[i].crossVectors(tangents[i], normals[i]);
  22962. }
  22963. }
  22964. return {
  22965. tangents: tangents,
  22966. normals: normals,
  22967. binormals: binormals
  22968. };
  22969. },
  22970. clone: function () {
  22971. return new this.constructor().copy(this);
  22972. },
  22973. copy: function (source) {
  22974. this.arcLengthDivisions = source.arcLengthDivisions;
  22975. return this;
  22976. },
  22977. toJSON: function () {
  22978. var data = {
  22979. metadata: {
  22980. version: 4.5,
  22981. type: 'Curve',
  22982. generator: 'Curve.toJSON'
  22983. }
  22984. };
  22985. data.arcLengthDivisions = this.arcLengthDivisions;
  22986. data.type = this.type;
  22987. return data;
  22988. },
  22989. fromJSON: function (json) {
  22990. this.arcLengthDivisions = json.arcLengthDivisions;
  22991. return this;
  22992. }
  22993. });
  22994. function EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  22995. Curve.call(this);
  22996. this.type = 'EllipseCurve';
  22997. this.aX = aX || 0;
  22998. this.aY = aY || 0;
  22999. this.xRadius = xRadius || 1;
  23000. this.yRadius = yRadius || 1;
  23001. this.aStartAngle = aStartAngle || 0;
  23002. this.aEndAngle = aEndAngle || 2 * Math.PI;
  23003. this.aClockwise = aClockwise || false;
  23004. this.aRotation = aRotation || 0;
  23005. }
  23006. EllipseCurve.prototype = Object.create(Curve.prototype);
  23007. EllipseCurve.prototype.constructor = EllipseCurve;
  23008. EllipseCurve.prototype.isEllipseCurve = true;
  23009. EllipseCurve.prototype.getPoint = function (t, optionalTarget) {
  23010. var point = optionalTarget || new Vector2();
  23011. var twoPi = Math.PI * 2;
  23012. var deltaAngle = this.aEndAngle - this.aStartAngle;
  23013. var samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  23014. while (deltaAngle < 0) deltaAngle += twoPi;
  23015. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  23016. if (deltaAngle < Number.EPSILON) {
  23017. if (samePoints) {
  23018. deltaAngle = 0;
  23019. } else {
  23020. deltaAngle = twoPi;
  23021. }
  23022. }
  23023. if (this.aClockwise === true && !samePoints) {
  23024. if (deltaAngle === twoPi) {
  23025. deltaAngle = -twoPi;
  23026. } else {
  23027. deltaAngle = deltaAngle - twoPi;
  23028. }
  23029. }
  23030. var angle = this.aStartAngle + t * deltaAngle;
  23031. var x = this.aX + this.xRadius * Math.cos(angle);
  23032. var y = this.aY + this.yRadius * Math.sin(angle);
  23033. if (this.aRotation !== 0) {
  23034. var cos = Math.cos(this.aRotation);
  23035. var sin = Math.sin(this.aRotation);
  23036. var tx = x - this.aX;
  23037. var ty = y - this.aY; // Rotate the point about the center of the ellipse.
  23038. x = tx * cos - ty * sin + this.aX;
  23039. y = tx * sin + ty * cos + this.aY;
  23040. }
  23041. return point.set(x, y);
  23042. };
  23043. EllipseCurve.prototype.copy = function (source) {
  23044. Curve.prototype.copy.call(this, source);
  23045. this.aX = source.aX;
  23046. this.aY = source.aY;
  23047. this.xRadius = source.xRadius;
  23048. this.yRadius = source.yRadius;
  23049. this.aStartAngle = source.aStartAngle;
  23050. this.aEndAngle = source.aEndAngle;
  23051. this.aClockwise = source.aClockwise;
  23052. this.aRotation = source.aRotation;
  23053. return this;
  23054. };
  23055. EllipseCurve.prototype.toJSON = function () {
  23056. var data = Curve.prototype.toJSON.call(this);
  23057. data.aX = this.aX;
  23058. data.aY = this.aY;
  23059. data.xRadius = this.xRadius;
  23060. data.yRadius = this.yRadius;
  23061. data.aStartAngle = this.aStartAngle;
  23062. data.aEndAngle = this.aEndAngle;
  23063. data.aClockwise = this.aClockwise;
  23064. data.aRotation = this.aRotation;
  23065. return data;
  23066. };
  23067. EllipseCurve.prototype.fromJSON = function (json) {
  23068. Curve.prototype.fromJSON.call(this, json);
  23069. this.aX = json.aX;
  23070. this.aY = json.aY;
  23071. this.xRadius = json.xRadius;
  23072. this.yRadius = json.yRadius;
  23073. this.aStartAngle = json.aStartAngle;
  23074. this.aEndAngle = json.aEndAngle;
  23075. this.aClockwise = json.aClockwise;
  23076. this.aRotation = json.aRotation;
  23077. return this;
  23078. };
  23079. function ArcCurve(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  23080. EllipseCurve.call(this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  23081. this.type = 'ArcCurve';
  23082. }
  23083. ArcCurve.prototype = Object.create(EllipseCurve.prototype);
  23084. ArcCurve.prototype.constructor = ArcCurve;
  23085. ArcCurve.prototype.isArcCurve = true;
  23086. /**
  23087. * @author zz85 https://github.com/zz85
  23088. *
  23089. * Centripetal CatmullRom Curve - which is useful for avoiding
  23090. * cusps and self-intersections in non-uniform catmull rom curves.
  23091. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  23092. *
  23093. * curve.type accepts centripetal(default), chordal and catmullrom
  23094. * curve.tension is used for catmullrom which defaults to 0.5
  23095. */
  23096. /*
  23097. Based on an optimized c++ solution in
  23098. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  23099. - http://ideone.com/NoEbVM
  23100. This CubicPoly class could be used for reusing some variables and calculations,
  23101. but for three.js curve use, it could be possible inlined and flatten into a single function call
  23102. which can be placed in CurveUtils.
  23103. */
  23104. function CubicPoly() {
  23105. var c0 = 0,
  23106. c1 = 0,
  23107. c2 = 0,
  23108. c3 = 0;
  23109. /*
  23110. * Compute coefficients for a cubic polynomial
  23111. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  23112. * such that
  23113. * p(0) = x0, p(1) = x1
  23114. * and
  23115. * p'(0) = t0, p'(1) = t1.
  23116. */
  23117. function init(x0, x1, t0, t1) {
  23118. c0 = x0;
  23119. c1 = t0;
  23120. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  23121. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  23122. }
  23123. return {
  23124. initCatmullRom: function (x0, x1, x2, x3, tension) {
  23125. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  23126. },
  23127. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  23128. // compute tangents when parameterized in [t1,t2]
  23129. var t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  23130. var t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  23131. t1 *= dt1;
  23132. t2 *= dt1;
  23133. init(x1, x2, t1, t2);
  23134. },
  23135. calc: function (t) {
  23136. var t2 = t * t;
  23137. var t3 = t2 * t;
  23138. return c0 + c1 * t + c2 * t2 + c3 * t3;
  23139. }
  23140. };
  23141. } //
  23142. var tmp = new Vector3();
  23143. var px = new CubicPoly(),
  23144. py = new CubicPoly(),
  23145. pz = new CubicPoly();
  23146. function CatmullRomCurve3(points, closed, curveType, tension) {
  23147. Curve.call(this);
  23148. this.type = 'CatmullRomCurve3';
  23149. this.points = points || [];
  23150. this.closed = closed || false;
  23151. this.curveType = curveType || 'centripetal';
  23152. this.tension = tension || 0.5;
  23153. }
  23154. CatmullRomCurve3.prototype = Object.create(Curve.prototype);
  23155. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  23156. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  23157. CatmullRomCurve3.prototype.getPoint = function (t, optionalTarget) {
  23158. var point = optionalTarget || new Vector3();
  23159. var points = this.points;
  23160. var l = points.length;
  23161. var p = (l - (this.closed ? 0 : 1)) * t;
  23162. var intPoint = Math.floor(p);
  23163. var weight = p - intPoint;
  23164. if (this.closed) {
  23165. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  23166. } else if (weight === 0 && intPoint === l - 1) {
  23167. intPoint = l - 2;
  23168. weight = 1;
  23169. }
  23170. var p0, p1, p2, p3; // 4 points
  23171. if (this.closed || intPoint > 0) {
  23172. p0 = points[(intPoint - 1) % l];
  23173. } else {
  23174. // extrapolate first point
  23175. tmp.subVectors(points[0], points[1]).add(points[0]);
  23176. p0 = tmp;
  23177. }
  23178. p1 = points[intPoint % l];
  23179. p2 = points[(intPoint + 1) % l];
  23180. if (this.closed || intPoint + 2 < l) {
  23181. p3 = points[(intPoint + 2) % l];
  23182. } else {
  23183. // extrapolate last point
  23184. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  23185. p3 = tmp;
  23186. }
  23187. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  23188. // init Centripetal / Chordal Catmull-Rom
  23189. var pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  23190. var dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  23191. var dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  23192. var dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  23193. if (dt1 < 1e-4) dt1 = 1.0;
  23194. if (dt0 < 1e-4) dt0 = dt1;
  23195. if (dt2 < 1e-4) dt2 = dt1;
  23196. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  23197. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  23198. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  23199. } else if (this.curveType === 'catmullrom') {
  23200. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  23201. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  23202. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  23203. }
  23204. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  23205. return point;
  23206. };
  23207. CatmullRomCurve3.prototype.copy = function (source) {
  23208. Curve.prototype.copy.call(this, source);
  23209. this.points = [];
  23210. for (var i = 0, l = source.points.length; i < l; i++) {
  23211. var point = source.points[i];
  23212. this.points.push(point.clone());
  23213. }
  23214. this.closed = source.closed;
  23215. this.curveType = source.curveType;
  23216. this.tension = source.tension;
  23217. return this;
  23218. };
  23219. CatmullRomCurve3.prototype.toJSON = function () {
  23220. var data = Curve.prototype.toJSON.call(this);
  23221. data.points = [];
  23222. for (var i = 0, l = this.points.length; i < l; i++) {
  23223. var point = this.points[i];
  23224. data.points.push(point.toArray());
  23225. }
  23226. data.closed = this.closed;
  23227. data.curveType = this.curveType;
  23228. data.tension = this.tension;
  23229. return data;
  23230. };
  23231. CatmullRomCurve3.prototype.fromJSON = function (json) {
  23232. Curve.prototype.fromJSON.call(this, json);
  23233. this.points = [];
  23234. for (var i = 0, l = json.points.length; i < l; i++) {
  23235. var point = json.points[i];
  23236. this.points.push(new Vector3().fromArray(point));
  23237. }
  23238. this.closed = json.closed;
  23239. this.curveType = json.curveType;
  23240. this.tension = json.tension;
  23241. return this;
  23242. };
  23243. /**
  23244. * @author zz85 / http://www.lab4games.net/zz85/blog
  23245. *
  23246. * Bezier Curves formulas obtained from
  23247. * http://en.wikipedia.org/wiki/Bézier_curve
  23248. */
  23249. function CatmullRom(t, p0, p1, p2, p3) {
  23250. var v0 = (p2 - p0) * 0.5;
  23251. var v1 = (p3 - p1) * 0.5;
  23252. var t2 = t * t;
  23253. var t3 = t * t2;
  23254. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  23255. } //
  23256. function QuadraticBezierP0(t, p) {
  23257. var k = 1 - t;
  23258. return k * k * p;
  23259. }
  23260. function QuadraticBezierP1(t, p) {
  23261. return 2 * (1 - t) * t * p;
  23262. }
  23263. function QuadraticBezierP2(t, p) {
  23264. return t * t * p;
  23265. }
  23266. function QuadraticBezier(t, p0, p1, p2) {
  23267. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  23268. } //
  23269. function CubicBezierP0(t, p) {
  23270. var k = 1 - t;
  23271. return k * k * k * p;
  23272. }
  23273. function CubicBezierP1(t, p) {
  23274. var k = 1 - t;
  23275. return 3 * k * k * t * p;
  23276. }
  23277. function CubicBezierP2(t, p) {
  23278. return 3 * (1 - t) * t * t * p;
  23279. }
  23280. function CubicBezierP3(t, p) {
  23281. return t * t * t * p;
  23282. }
  23283. function CubicBezier(t, p0, p1, p2, p3) {
  23284. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  23285. }
  23286. function CubicBezierCurve(v0, v1, v2, v3) {
  23287. Curve.call(this);
  23288. this.type = 'CubicBezierCurve';
  23289. this.v0 = v0 || new Vector2();
  23290. this.v1 = v1 || new Vector2();
  23291. this.v2 = v2 || new Vector2();
  23292. this.v3 = v3 || new Vector2();
  23293. }
  23294. CubicBezierCurve.prototype = Object.create(Curve.prototype);
  23295. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  23296. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  23297. CubicBezierCurve.prototype.getPoint = function (t, optionalTarget) {
  23298. var point = optionalTarget || new Vector2();
  23299. var v0 = this.v0,
  23300. v1 = this.v1,
  23301. v2 = this.v2,
  23302. v3 = this.v3;
  23303. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  23304. return point;
  23305. };
  23306. CubicBezierCurve.prototype.copy = function (source) {
  23307. Curve.prototype.copy.call(this, source);
  23308. this.v0.copy(source.v0);
  23309. this.v1.copy(source.v1);
  23310. this.v2.copy(source.v2);
  23311. this.v3.copy(source.v3);
  23312. return this;
  23313. };
  23314. CubicBezierCurve.prototype.toJSON = function () {
  23315. var data = Curve.prototype.toJSON.call(this);
  23316. data.v0 = this.v0.toArray();
  23317. data.v1 = this.v1.toArray();
  23318. data.v2 = this.v2.toArray();
  23319. data.v3 = this.v3.toArray();
  23320. return data;
  23321. };
  23322. CubicBezierCurve.prototype.fromJSON = function (json) {
  23323. Curve.prototype.fromJSON.call(this, json);
  23324. this.v0.fromArray(json.v0);
  23325. this.v1.fromArray(json.v1);
  23326. this.v2.fromArray(json.v2);
  23327. this.v3.fromArray(json.v3);
  23328. return this;
  23329. };
  23330. function CubicBezierCurve3(v0, v1, v2, v3) {
  23331. Curve.call(this);
  23332. this.type = 'CubicBezierCurve3';
  23333. this.v0 = v0 || new Vector3();
  23334. this.v1 = v1 || new Vector3();
  23335. this.v2 = v2 || new Vector3();
  23336. this.v3 = v3 || new Vector3();
  23337. }
  23338. CubicBezierCurve3.prototype = Object.create(Curve.prototype);
  23339. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  23340. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  23341. CubicBezierCurve3.prototype.getPoint = function (t, optionalTarget) {
  23342. var point = optionalTarget || new Vector3();
  23343. var v0 = this.v0,
  23344. v1 = this.v1,
  23345. v2 = this.v2,
  23346. v3 = this.v3;
  23347. 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));
  23348. return point;
  23349. };
  23350. CubicBezierCurve3.prototype.copy = function (source) {
  23351. Curve.prototype.copy.call(this, source);
  23352. this.v0.copy(source.v0);
  23353. this.v1.copy(source.v1);
  23354. this.v2.copy(source.v2);
  23355. this.v3.copy(source.v3);
  23356. return this;
  23357. };
  23358. CubicBezierCurve3.prototype.toJSON = function () {
  23359. var data = Curve.prototype.toJSON.call(this);
  23360. data.v0 = this.v0.toArray();
  23361. data.v1 = this.v1.toArray();
  23362. data.v2 = this.v2.toArray();
  23363. data.v3 = this.v3.toArray();
  23364. return data;
  23365. };
  23366. CubicBezierCurve3.prototype.fromJSON = function (json) {
  23367. Curve.prototype.fromJSON.call(this, json);
  23368. this.v0.fromArray(json.v0);
  23369. this.v1.fromArray(json.v1);
  23370. this.v2.fromArray(json.v2);
  23371. this.v3.fromArray(json.v3);
  23372. return this;
  23373. };
  23374. function LineCurve(v1, v2) {
  23375. Curve.call(this);
  23376. this.type = 'LineCurve';
  23377. this.v1 = v1 || new Vector2();
  23378. this.v2 = v2 || new Vector2();
  23379. }
  23380. LineCurve.prototype = Object.create(Curve.prototype);
  23381. LineCurve.prototype.constructor = LineCurve;
  23382. LineCurve.prototype.isLineCurve = true;
  23383. LineCurve.prototype.getPoint = function (t, optionalTarget) {
  23384. var point = optionalTarget || new Vector2();
  23385. if (t === 1) {
  23386. point.copy(this.v2);
  23387. } else {
  23388. point.copy(this.v2).sub(this.v1);
  23389. point.multiplyScalar(t).add(this.v1);
  23390. }
  23391. return point;
  23392. }; // Line curve is linear, so we can overwrite default getPointAt
  23393. LineCurve.prototype.getPointAt = function (u, optionalTarget) {
  23394. return this.getPoint(u, optionalTarget);
  23395. };
  23396. LineCurve.prototype.getTangent = function ()
  23397. /* t */
  23398. {
  23399. var tangent = this.v2.clone().sub(this.v1);
  23400. return tangent.normalize();
  23401. };
  23402. LineCurve.prototype.copy = function (source) {
  23403. Curve.prototype.copy.call(this, source);
  23404. this.v1.copy(source.v1);
  23405. this.v2.copy(source.v2);
  23406. return this;
  23407. };
  23408. LineCurve.prototype.toJSON = function () {
  23409. var data = Curve.prototype.toJSON.call(this);
  23410. data.v1 = this.v1.toArray();
  23411. data.v2 = this.v2.toArray();
  23412. return data;
  23413. };
  23414. LineCurve.prototype.fromJSON = function (json) {
  23415. Curve.prototype.fromJSON.call(this, json);
  23416. this.v1.fromArray(json.v1);
  23417. this.v2.fromArray(json.v2);
  23418. return this;
  23419. };
  23420. function LineCurve3(v1, v2) {
  23421. Curve.call(this);
  23422. this.type = 'LineCurve3';
  23423. this.v1 = v1 || new Vector3();
  23424. this.v2 = v2 || new Vector3();
  23425. }
  23426. LineCurve3.prototype = Object.create(Curve.prototype);
  23427. LineCurve3.prototype.constructor = LineCurve3;
  23428. LineCurve3.prototype.isLineCurve3 = true;
  23429. LineCurve3.prototype.getPoint = function (t, optionalTarget) {
  23430. var point = optionalTarget || new Vector3();
  23431. if (t === 1) {
  23432. point.copy(this.v2);
  23433. } else {
  23434. point.copy(this.v2).sub(this.v1);
  23435. point.multiplyScalar(t).add(this.v1);
  23436. }
  23437. return point;
  23438. }; // Line curve is linear, so we can overwrite default getPointAt
  23439. LineCurve3.prototype.getPointAt = function (u, optionalTarget) {
  23440. return this.getPoint(u, optionalTarget);
  23441. };
  23442. LineCurve3.prototype.copy = function (source) {
  23443. Curve.prototype.copy.call(this, source);
  23444. this.v1.copy(source.v1);
  23445. this.v2.copy(source.v2);
  23446. return this;
  23447. };
  23448. LineCurve3.prototype.toJSON = function () {
  23449. var data = Curve.prototype.toJSON.call(this);
  23450. data.v1 = this.v1.toArray();
  23451. data.v2 = this.v2.toArray();
  23452. return data;
  23453. };
  23454. LineCurve3.prototype.fromJSON = function (json) {
  23455. Curve.prototype.fromJSON.call(this, json);
  23456. this.v1.fromArray(json.v1);
  23457. this.v2.fromArray(json.v2);
  23458. return this;
  23459. };
  23460. function QuadraticBezierCurve(v0, v1, v2) {
  23461. Curve.call(this);
  23462. this.type = 'QuadraticBezierCurve';
  23463. this.v0 = v0 || new Vector2();
  23464. this.v1 = v1 || new Vector2();
  23465. this.v2 = v2 || new Vector2();
  23466. }
  23467. QuadraticBezierCurve.prototype = Object.create(Curve.prototype);
  23468. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  23469. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  23470. QuadraticBezierCurve.prototype.getPoint = function (t, optionalTarget) {
  23471. var point = optionalTarget || new Vector2();
  23472. var v0 = this.v0,
  23473. v1 = this.v1,
  23474. v2 = this.v2;
  23475. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  23476. return point;
  23477. };
  23478. QuadraticBezierCurve.prototype.copy = function (source) {
  23479. Curve.prototype.copy.call(this, source);
  23480. this.v0.copy(source.v0);
  23481. this.v1.copy(source.v1);
  23482. this.v2.copy(source.v2);
  23483. return this;
  23484. };
  23485. QuadraticBezierCurve.prototype.toJSON = function () {
  23486. var data = Curve.prototype.toJSON.call(this);
  23487. data.v0 = this.v0.toArray();
  23488. data.v1 = this.v1.toArray();
  23489. data.v2 = this.v2.toArray();
  23490. return data;
  23491. };
  23492. QuadraticBezierCurve.prototype.fromJSON = function (json) {
  23493. Curve.prototype.fromJSON.call(this, json);
  23494. this.v0.fromArray(json.v0);
  23495. this.v1.fromArray(json.v1);
  23496. this.v2.fromArray(json.v2);
  23497. return this;
  23498. };
  23499. function QuadraticBezierCurve3(v0, v1, v2) {
  23500. Curve.call(this);
  23501. this.type = 'QuadraticBezierCurve3';
  23502. this.v0 = v0 || new Vector3();
  23503. this.v1 = v1 || new Vector3();
  23504. this.v2 = v2 || new Vector3();
  23505. }
  23506. QuadraticBezierCurve3.prototype = Object.create(Curve.prototype);
  23507. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  23508. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  23509. QuadraticBezierCurve3.prototype.getPoint = function (t, optionalTarget) {
  23510. var point = optionalTarget || new Vector3();
  23511. var v0 = this.v0,
  23512. v1 = this.v1,
  23513. v2 = this.v2;
  23514. 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));
  23515. return point;
  23516. };
  23517. QuadraticBezierCurve3.prototype.copy = function (source) {
  23518. Curve.prototype.copy.call(this, source);
  23519. this.v0.copy(source.v0);
  23520. this.v1.copy(source.v1);
  23521. this.v2.copy(source.v2);
  23522. return this;
  23523. };
  23524. QuadraticBezierCurve3.prototype.toJSON = function () {
  23525. var data = Curve.prototype.toJSON.call(this);
  23526. data.v0 = this.v0.toArray();
  23527. data.v1 = this.v1.toArray();
  23528. data.v2 = this.v2.toArray();
  23529. return data;
  23530. };
  23531. QuadraticBezierCurve3.prototype.fromJSON = function (json) {
  23532. Curve.prototype.fromJSON.call(this, json);
  23533. this.v0.fromArray(json.v0);
  23534. this.v1.fromArray(json.v1);
  23535. this.v2.fromArray(json.v2);
  23536. return this;
  23537. };
  23538. function SplineCurve(points
  23539. /* array of Vector2 */
  23540. ) {
  23541. Curve.call(this);
  23542. this.type = 'SplineCurve';
  23543. this.points = points || [];
  23544. }
  23545. SplineCurve.prototype = Object.create(Curve.prototype);
  23546. SplineCurve.prototype.constructor = SplineCurve;
  23547. SplineCurve.prototype.isSplineCurve = true;
  23548. SplineCurve.prototype.getPoint = function (t, optionalTarget) {
  23549. var point = optionalTarget || new Vector2();
  23550. var points = this.points;
  23551. var p = (points.length - 1) * t;
  23552. var intPoint = Math.floor(p);
  23553. var weight = p - intPoint;
  23554. var p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  23555. var p1 = points[intPoint];
  23556. var p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  23557. var p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  23558. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  23559. return point;
  23560. };
  23561. SplineCurve.prototype.copy = function (source) {
  23562. Curve.prototype.copy.call(this, source);
  23563. this.points = [];
  23564. for (var i = 0, l = source.points.length; i < l; i++) {
  23565. var point = source.points[i];
  23566. this.points.push(point.clone());
  23567. }
  23568. return this;
  23569. };
  23570. SplineCurve.prototype.toJSON = function () {
  23571. var data = Curve.prototype.toJSON.call(this);
  23572. data.points = [];
  23573. for (var i = 0, l = this.points.length; i < l; i++) {
  23574. var point = this.points[i];
  23575. data.points.push(point.toArray());
  23576. }
  23577. return data;
  23578. };
  23579. SplineCurve.prototype.fromJSON = function (json) {
  23580. Curve.prototype.fromJSON.call(this, json);
  23581. this.points = [];
  23582. for (var i = 0, l = json.points.length; i < l; i++) {
  23583. var point = json.points[i];
  23584. this.points.push(new Vector2().fromArray(point));
  23585. }
  23586. return this;
  23587. };
  23588. var Curves =
  23589. /*#__PURE__*/
  23590. Object.freeze({
  23591. ArcCurve: ArcCurve,
  23592. CatmullRomCurve3: CatmullRomCurve3,
  23593. CubicBezierCurve: CubicBezierCurve,
  23594. CubicBezierCurve3: CubicBezierCurve3,
  23595. EllipseCurve: EllipseCurve,
  23596. LineCurve: LineCurve,
  23597. LineCurve3: LineCurve3,
  23598. QuadraticBezierCurve: QuadraticBezierCurve,
  23599. QuadraticBezierCurve3: QuadraticBezierCurve3,
  23600. SplineCurve: SplineCurve
  23601. });
  23602. /**
  23603. * @author zz85 / http://www.lab4games.net/zz85/blog
  23604. *
  23605. **/
  23606. /**************************************************************
  23607. * Curved Path - a curve path is simply a array of connected
  23608. * curves, but retains the api of a curve
  23609. **************************************************************/
  23610. function CurvePath() {
  23611. Curve.call(this);
  23612. this.type = 'CurvePath';
  23613. this.curves = [];
  23614. this.autoClose = false; // Automatically closes the path
  23615. }
  23616. CurvePath.prototype = Object.assign(Object.create(Curve.prototype), {
  23617. constructor: CurvePath,
  23618. add: function (curve) {
  23619. this.curves.push(curve);
  23620. },
  23621. closePath: function () {
  23622. // Add a line curve if start and end of lines are not connected
  23623. var startPoint = this.curves[0].getPoint(0);
  23624. var endPoint = this.curves[this.curves.length - 1].getPoint(1);
  23625. if (!startPoint.equals(endPoint)) {
  23626. this.curves.push(new LineCurve(endPoint, startPoint));
  23627. }
  23628. },
  23629. // To get accurate point with reference to
  23630. // entire path distance at time t,
  23631. // following has to be done:
  23632. // 1. Length of each sub path have to be known
  23633. // 2. Locate and identify type of curve
  23634. // 3. Get t for the curve
  23635. // 4. Return curve.getPointAt(t')
  23636. getPoint: function (t) {
  23637. var d = t * this.getLength();
  23638. var curveLengths = this.getCurveLengths();
  23639. var i = 0; // To think about boundaries points.
  23640. while (i < curveLengths.length) {
  23641. if (curveLengths[i] >= d) {
  23642. var diff = curveLengths[i] - d;
  23643. var curve = this.curves[i];
  23644. var segmentLength = curve.getLength();
  23645. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  23646. return curve.getPointAt(u);
  23647. }
  23648. i++;
  23649. }
  23650. return null; // loop where sum != 0, sum > d , sum+1 <d
  23651. },
  23652. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  23653. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  23654. // getPoint() depends on getLength
  23655. getLength: function () {
  23656. var lens = this.getCurveLengths();
  23657. return lens[lens.length - 1];
  23658. },
  23659. // cacheLengths must be recalculated.
  23660. updateArcLengths: function () {
  23661. this.needsUpdate = true;
  23662. this.cacheLengths = null;
  23663. this.getCurveLengths();
  23664. },
  23665. // Compute lengths and cache them
  23666. // We cannot overwrite getLengths() because UtoT mapping uses it.
  23667. getCurveLengths: function () {
  23668. // We use cache values if curves and cache array are same length
  23669. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  23670. return this.cacheLengths;
  23671. } // Get length of sub-curve
  23672. // Push sums into cached array
  23673. var lengths = [],
  23674. sums = 0;
  23675. for (var i = 0, l = this.curves.length; i < l; i++) {
  23676. sums += this.curves[i].getLength();
  23677. lengths.push(sums);
  23678. }
  23679. this.cacheLengths = lengths;
  23680. return lengths;
  23681. },
  23682. getSpacedPoints: function (divisions) {
  23683. if (divisions === undefined) divisions = 40;
  23684. var points = [];
  23685. for (var i = 0; i <= divisions; i++) {
  23686. points.push(this.getPoint(i / divisions));
  23687. }
  23688. if (this.autoClose) {
  23689. points.push(points[0]);
  23690. }
  23691. return points;
  23692. },
  23693. getPoints: function (divisions) {
  23694. divisions = divisions || 12;
  23695. var points = [],
  23696. last;
  23697. for (var i = 0, curves = this.curves; i < curves.length; i++) {
  23698. var curve = curves[i];
  23699. var resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
  23700. var pts = curve.getPoints(resolution);
  23701. for (var j = 0; j < pts.length; j++) {
  23702. var point = pts[j];
  23703. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  23704. points.push(point);
  23705. last = point;
  23706. }
  23707. }
  23708. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  23709. points.push(points[0]);
  23710. }
  23711. return points;
  23712. },
  23713. copy: function (source) {
  23714. Curve.prototype.copy.call(this, source);
  23715. this.curves = [];
  23716. for (var i = 0, l = source.curves.length; i < l; i++) {
  23717. var curve = source.curves[i];
  23718. this.curves.push(curve.clone());
  23719. }
  23720. this.autoClose = source.autoClose;
  23721. return this;
  23722. },
  23723. toJSON: function () {
  23724. var data = Curve.prototype.toJSON.call(this);
  23725. data.autoClose = this.autoClose;
  23726. data.curves = [];
  23727. for (var i = 0, l = this.curves.length; i < l; i++) {
  23728. var curve = this.curves[i];
  23729. data.curves.push(curve.toJSON());
  23730. }
  23731. return data;
  23732. },
  23733. fromJSON: function (json) {
  23734. Curve.prototype.fromJSON.call(this, json);
  23735. this.autoClose = json.autoClose;
  23736. this.curves = [];
  23737. for (var i = 0, l = json.curves.length; i < l; i++) {
  23738. var curve = json.curves[i];
  23739. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  23740. }
  23741. return this;
  23742. }
  23743. });
  23744. /**
  23745. * @author zz85 / http://www.lab4games.net/zz85/blog
  23746. * Creates free form 2d path using series of points, lines or curves.
  23747. **/
  23748. function Path(points) {
  23749. CurvePath.call(this);
  23750. this.type = 'Path';
  23751. this.currentPoint = new Vector2();
  23752. if (points) {
  23753. this.setFromPoints(points);
  23754. }
  23755. }
  23756. Path.prototype = Object.assign(Object.create(CurvePath.prototype), {
  23757. constructor: Path,
  23758. setFromPoints: function (points) {
  23759. this.moveTo(points[0].x, points[0].y);
  23760. for (var i = 1, l = points.length; i < l; i++) {
  23761. this.lineTo(points[i].x, points[i].y);
  23762. }
  23763. },
  23764. moveTo: function (x, y) {
  23765. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  23766. },
  23767. lineTo: function (x, y) {
  23768. var curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  23769. this.curves.push(curve);
  23770. this.currentPoint.set(x, y);
  23771. },
  23772. quadraticCurveTo: function (aCPx, aCPy, aX, aY) {
  23773. var curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  23774. this.curves.push(curve);
  23775. this.currentPoint.set(aX, aY);
  23776. },
  23777. bezierCurveTo: function (aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  23778. var curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  23779. this.curves.push(curve);
  23780. this.currentPoint.set(aX, aY);
  23781. },
  23782. splineThru: function (pts
  23783. /*Array of Vector*/
  23784. ) {
  23785. var npts = [this.currentPoint.clone()].concat(pts);
  23786. var curve = new SplineCurve(npts);
  23787. this.curves.push(curve);
  23788. this.currentPoint.copy(pts[pts.length - 1]);
  23789. },
  23790. arc: function (aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  23791. var x0 = this.currentPoint.x;
  23792. var y0 = this.currentPoint.y;
  23793. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  23794. },
  23795. absarc: function (aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  23796. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  23797. },
  23798. ellipse: function (aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  23799. var x0 = this.currentPoint.x;
  23800. var y0 = this.currentPoint.y;
  23801. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  23802. },
  23803. absellipse: function (aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  23804. var curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  23805. if (this.curves.length > 0) {
  23806. // if a previous curve is present, attempt to join
  23807. var firstPoint = curve.getPoint(0);
  23808. if (!firstPoint.equals(this.currentPoint)) {
  23809. this.lineTo(firstPoint.x, firstPoint.y);
  23810. }
  23811. }
  23812. this.curves.push(curve);
  23813. var lastPoint = curve.getPoint(1);
  23814. this.currentPoint.copy(lastPoint);
  23815. },
  23816. copy: function (source) {
  23817. CurvePath.prototype.copy.call(this, source);
  23818. this.currentPoint.copy(source.currentPoint);
  23819. return this;
  23820. },
  23821. toJSON: function () {
  23822. var data = CurvePath.prototype.toJSON.call(this);
  23823. data.currentPoint = this.currentPoint.toArray();
  23824. return data;
  23825. },
  23826. fromJSON: function (json) {
  23827. CurvePath.prototype.fromJSON.call(this, json);
  23828. this.currentPoint.fromArray(json.currentPoint);
  23829. return this;
  23830. }
  23831. });
  23832. /**
  23833. * @author zz85 / http://www.lab4games.net/zz85/blog
  23834. * Defines a 2d shape plane using paths.
  23835. **/
  23836. // STEP 1 Create a path.
  23837. // STEP 2 Turn path into shape.
  23838. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  23839. // STEP 3a - Extract points from each shape, turn to vertices
  23840. // STEP 3b - Triangulate each shape, add faces.
  23841. function Shape(points) {
  23842. Path.call(this, points);
  23843. this.uuid = _Math.generateUUID();
  23844. this.type = 'Shape';
  23845. this.holes = [];
  23846. }
  23847. Shape.prototype = Object.assign(Object.create(Path.prototype), {
  23848. constructor: Shape,
  23849. getPointsHoles: function (divisions) {
  23850. var holesPts = [];
  23851. for (var i = 0, l = this.holes.length; i < l; i++) {
  23852. holesPts[i] = this.holes[i].getPoints(divisions);
  23853. }
  23854. return holesPts;
  23855. },
  23856. // get points of shape and holes (keypoints based on segments parameter)
  23857. extractPoints: function (divisions) {
  23858. return {
  23859. shape: this.getPoints(divisions),
  23860. holes: this.getPointsHoles(divisions)
  23861. };
  23862. },
  23863. copy: function (source) {
  23864. Path.prototype.copy.call(this, source);
  23865. this.holes = [];
  23866. for (var i = 0, l = source.holes.length; i < l; i++) {
  23867. var hole = source.holes[i];
  23868. this.holes.push(hole.clone());
  23869. }
  23870. return this;
  23871. },
  23872. toJSON: function () {
  23873. var data = Path.prototype.toJSON.call(this);
  23874. data.uuid = this.uuid;
  23875. data.holes = [];
  23876. for (var i = 0, l = this.holes.length; i < l; i++) {
  23877. var hole = this.holes[i];
  23878. data.holes.push(hole.toJSON());
  23879. }
  23880. return data;
  23881. },
  23882. fromJSON: function (json) {
  23883. Path.prototype.fromJSON.call(this, json);
  23884. this.uuid = json.uuid;
  23885. this.holes = [];
  23886. for (var i = 0, l = json.holes.length; i < l; i++) {
  23887. var hole = json.holes[i];
  23888. this.holes.push(new Path().fromJSON(hole));
  23889. }
  23890. return this;
  23891. }
  23892. });
  23893. /**
  23894. * @author mrdoob / http://mrdoob.com/
  23895. * @author alteredq / http://alteredqualia.com/
  23896. */
  23897. function Light(color, intensity) {
  23898. Object3D.call(this);
  23899. this.type = 'Light';
  23900. this.color = new Color(color);
  23901. this.intensity = intensity !== undefined ? intensity : 1;
  23902. this.receiveShadow = undefined;
  23903. }
  23904. Light.prototype = Object.assign(Object.create(Object3D.prototype), {
  23905. constructor: Light,
  23906. isLight: true,
  23907. copy: function (source) {
  23908. Object3D.prototype.copy.call(this, source);
  23909. this.color.copy(source.color);
  23910. this.intensity = source.intensity;
  23911. return this;
  23912. },
  23913. toJSON: function (meta) {
  23914. var data = Object3D.prototype.toJSON.call(this, meta);
  23915. data.object.color = this.color.getHex();
  23916. data.object.intensity = this.intensity;
  23917. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  23918. if (this.distance !== undefined) data.object.distance = this.distance;
  23919. if (this.angle !== undefined) data.object.angle = this.angle;
  23920. if (this.decay !== undefined) data.object.decay = this.decay;
  23921. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  23922. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  23923. return data;
  23924. }
  23925. });
  23926. /**
  23927. * @author alteredq / http://alteredqualia.com/
  23928. */
  23929. function HemisphereLight(skyColor, groundColor, intensity) {
  23930. Light.call(this, skyColor, intensity);
  23931. this.type = 'HemisphereLight';
  23932. this.castShadow = undefined;
  23933. this.position.copy(Object3D.DefaultUp);
  23934. this.updateMatrix();
  23935. this.groundColor = new Color(groundColor);
  23936. }
  23937. HemisphereLight.prototype = Object.assign(Object.create(Light.prototype), {
  23938. constructor: HemisphereLight,
  23939. isHemisphereLight: true,
  23940. copy: function (source) {
  23941. Light.prototype.copy.call(this, source);
  23942. this.groundColor.copy(source.groundColor);
  23943. return this;
  23944. }
  23945. });
  23946. /**
  23947. * @author mrdoob / http://mrdoob.com/
  23948. */
  23949. function LightShadow(camera) {
  23950. this.camera = camera;
  23951. this.bias = 0;
  23952. this.radius = 1;
  23953. this.mapSize = new Vector2(512, 512);
  23954. this.map = null;
  23955. this.mapPass = null;
  23956. this.matrix = new Matrix4();
  23957. this._frustum = new Frustum();
  23958. this._frameExtents = new Vector2(1, 1);
  23959. this._viewportCount = 1;
  23960. this._viewports = [new Vector4(0, 0, 1, 1)];
  23961. }
  23962. Object.assign(LightShadow.prototype, {
  23963. _projScreenMatrix: new Matrix4(),
  23964. _lightPositionWorld: new Vector3(),
  23965. _lookTarget: new Vector3(),
  23966. getViewportCount: function () {
  23967. return this._viewportCount;
  23968. },
  23969. getFrustum: function () {
  23970. return this._frustum;
  23971. },
  23972. updateMatrices: function (light) {
  23973. var shadowCamera = this.camera,
  23974. shadowMatrix = this.matrix,
  23975. projScreenMatrix = this._projScreenMatrix,
  23976. lookTarget = this._lookTarget,
  23977. lightPositionWorld = this._lightPositionWorld;
  23978. lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  23979. shadowCamera.position.copy(lightPositionWorld);
  23980. lookTarget.setFromMatrixPosition(light.target.matrixWorld);
  23981. shadowCamera.lookAt(lookTarget);
  23982. shadowCamera.updateMatrixWorld();
  23983. projScreenMatrix.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  23984. this._frustum.setFromMatrix(projScreenMatrix);
  23985. 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);
  23986. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  23987. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  23988. },
  23989. getViewport: function (viewportIndex) {
  23990. return this._viewports[viewportIndex];
  23991. },
  23992. getFrameExtents: function () {
  23993. return this._frameExtents;
  23994. },
  23995. copy: function (source) {
  23996. this.camera = source.camera.clone();
  23997. this.bias = source.bias;
  23998. this.radius = source.radius;
  23999. this.mapSize.copy(source.mapSize);
  24000. return this;
  24001. },
  24002. clone: function () {
  24003. return new this.constructor().copy(this);
  24004. },
  24005. toJSON: function () {
  24006. var object = {};
  24007. if (this.bias !== 0) object.bias = this.bias;
  24008. if (this.radius !== 1) object.radius = this.radius;
  24009. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  24010. object.camera = this.camera.toJSON(false).object;
  24011. delete object.camera.matrix;
  24012. return object;
  24013. }
  24014. });
  24015. /**
  24016. * @author mrdoob / http://mrdoob.com/
  24017. */
  24018. function SpotLightShadow() {
  24019. LightShadow.call(this, new PerspectiveCamera(50, 1, 0.5, 500));
  24020. }
  24021. SpotLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  24022. constructor: SpotLightShadow,
  24023. isSpotLightShadow: true,
  24024. updateMatrices: function (light, viewCamera, viewportIndex) {
  24025. var camera = this.camera;
  24026. var fov = _Math.RAD2DEG * 2 * light.angle;
  24027. var aspect = this.mapSize.width / this.mapSize.height;
  24028. var far = light.distance || camera.far;
  24029. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  24030. camera.fov = fov;
  24031. camera.aspect = aspect;
  24032. camera.far = far;
  24033. camera.updateProjectionMatrix();
  24034. }
  24035. LightShadow.prototype.updateMatrices.call(this, light, viewCamera, viewportIndex);
  24036. }
  24037. });
  24038. /**
  24039. * @author alteredq / http://alteredqualia.com/
  24040. */
  24041. function SpotLight(color, intensity, distance, angle, penumbra, decay) {
  24042. Light.call(this, color, intensity);
  24043. this.type = 'SpotLight';
  24044. this.position.copy(Object3D.DefaultUp);
  24045. this.updateMatrix();
  24046. this.target = new Object3D();
  24047. Object.defineProperty(this, 'power', {
  24048. get: function () {
  24049. // intensity = power per solid angle.
  24050. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24051. return this.intensity * Math.PI;
  24052. },
  24053. set: function (power) {
  24054. // intensity = power per solid angle.
  24055. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24056. this.intensity = power / Math.PI;
  24057. }
  24058. });
  24059. this.distance = distance !== undefined ? distance : 0;
  24060. this.angle = angle !== undefined ? angle : Math.PI / 3;
  24061. this.penumbra = penumbra !== undefined ? penumbra : 0;
  24062. this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
  24063. this.shadow = new SpotLightShadow();
  24064. }
  24065. SpotLight.prototype = Object.assign(Object.create(Light.prototype), {
  24066. constructor: SpotLight,
  24067. isSpotLight: true,
  24068. copy: function (source) {
  24069. Light.prototype.copy.call(this, source);
  24070. this.distance = source.distance;
  24071. this.angle = source.angle;
  24072. this.penumbra = source.penumbra;
  24073. this.decay = source.decay;
  24074. this.target = source.target.clone();
  24075. this.shadow = source.shadow.clone();
  24076. return this;
  24077. }
  24078. });
  24079. function PointLightShadow() {
  24080. LightShadow.call(this, new PerspectiveCamera(90, 1, 0.5, 500));
  24081. this._frameExtents = new Vector2(4, 2);
  24082. this._viewportCount = 6;
  24083. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  24084. // following orientation:
  24085. //
  24086. // xzXZ
  24087. // y Y
  24088. //
  24089. // X - Positive x direction
  24090. // x - Negative x direction
  24091. // Y - Positive y direction
  24092. // y - Negative y direction
  24093. // Z - Positive z direction
  24094. // z - Negative z direction
  24095. // positive X
  24096. new Vector4(2, 1, 1, 1), // negative X
  24097. new Vector4(0, 1, 1, 1), // positive Z
  24098. new Vector4(3, 1, 1, 1), // negative Z
  24099. new Vector4(1, 1, 1, 1), // positive Y
  24100. new Vector4(3, 0, 1, 1), // negative Y
  24101. new Vector4(1, 0, 1, 1)];
  24102. 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)];
  24103. 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)];
  24104. }
  24105. PointLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  24106. constructor: PointLightShadow,
  24107. isPointLightShadow: true,
  24108. updateMatrices: function (light, viewCamera, viewportIndex) {
  24109. var camera = this.camera,
  24110. shadowMatrix = this.matrix,
  24111. lightPositionWorld = this._lightPositionWorld,
  24112. lookTarget = this._lookTarget,
  24113. projScreenMatrix = this._projScreenMatrix;
  24114. lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  24115. camera.position.copy(lightPositionWorld);
  24116. lookTarget.copy(camera.position);
  24117. lookTarget.add(this._cubeDirections[viewportIndex]);
  24118. camera.up.copy(this._cubeUps[viewportIndex]);
  24119. camera.lookAt(lookTarget);
  24120. camera.updateMatrixWorld();
  24121. shadowMatrix.makeTranslation(-lightPositionWorld.x, -lightPositionWorld.y, -lightPositionWorld.z);
  24122. projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  24123. this._frustum.setFromMatrix(projScreenMatrix);
  24124. }
  24125. });
  24126. /**
  24127. * @author mrdoob / http://mrdoob.com/
  24128. */
  24129. function PointLight(color, intensity, distance, decay) {
  24130. Light.call(this, color, intensity);
  24131. this.type = 'PointLight';
  24132. Object.defineProperty(this, 'power', {
  24133. get: function () {
  24134. // intensity = power per solid angle.
  24135. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24136. return this.intensity * 4 * Math.PI;
  24137. },
  24138. set: function (power) {
  24139. // intensity = power per solid angle.
  24140. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24141. this.intensity = power / (4 * Math.PI);
  24142. }
  24143. });
  24144. this.distance = distance !== undefined ? distance : 0;
  24145. this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
  24146. this.shadow = new PointLightShadow();
  24147. }
  24148. PointLight.prototype = Object.assign(Object.create(Light.prototype), {
  24149. constructor: PointLight,
  24150. isPointLight: true,
  24151. copy: function (source) {
  24152. Light.prototype.copy.call(this, source);
  24153. this.distance = source.distance;
  24154. this.decay = source.decay;
  24155. this.shadow = source.shadow.clone();
  24156. return this;
  24157. }
  24158. });
  24159. /**
  24160. * @author alteredq / http://alteredqualia.com/
  24161. * @author arose / http://github.com/arose
  24162. */
  24163. function OrthographicCamera(left, right, top, bottom, near, far) {
  24164. Camera.call(this);
  24165. this.type = 'OrthographicCamera';
  24166. this.zoom = 1;
  24167. this.view = null;
  24168. this.left = left !== undefined ? left : -1;
  24169. this.right = right !== undefined ? right : 1;
  24170. this.top = top !== undefined ? top : 1;
  24171. this.bottom = bottom !== undefined ? bottom : -1;
  24172. this.near = near !== undefined ? near : 0.1;
  24173. this.far = far !== undefined ? far : 2000;
  24174. this.updateProjectionMatrix();
  24175. }
  24176. OrthographicCamera.prototype = Object.assign(Object.create(Camera.prototype), {
  24177. constructor: OrthographicCamera,
  24178. isOrthographicCamera: true,
  24179. copy: function (source, recursive) {
  24180. Camera.prototype.copy.call(this, source, recursive);
  24181. this.left = source.left;
  24182. this.right = source.right;
  24183. this.top = source.top;
  24184. this.bottom = source.bottom;
  24185. this.near = source.near;
  24186. this.far = source.far;
  24187. this.zoom = source.zoom;
  24188. this.view = source.view === null ? null : Object.assign({}, source.view);
  24189. return this;
  24190. },
  24191. setViewOffset: function (fullWidth, fullHeight, x, y, width, height) {
  24192. if (this.view === null) {
  24193. this.view = {
  24194. enabled: true,
  24195. fullWidth: 1,
  24196. fullHeight: 1,
  24197. offsetX: 0,
  24198. offsetY: 0,
  24199. width: 1,
  24200. height: 1
  24201. };
  24202. }
  24203. this.view.enabled = true;
  24204. this.view.fullWidth = fullWidth;
  24205. this.view.fullHeight = fullHeight;
  24206. this.view.offsetX = x;
  24207. this.view.offsetY = y;
  24208. this.view.width = width;
  24209. this.view.height = height;
  24210. this.updateProjectionMatrix();
  24211. },
  24212. clearViewOffset: function () {
  24213. if (this.view !== null) {
  24214. this.view.enabled = false;
  24215. }
  24216. this.updateProjectionMatrix();
  24217. },
  24218. updateProjectionMatrix: function () {
  24219. var dx = (this.right - this.left) / (2 * this.zoom);
  24220. var dy = (this.top - this.bottom) / (2 * this.zoom);
  24221. var cx = (this.right + this.left) / 2;
  24222. var cy = (this.top + this.bottom) / 2;
  24223. var left = cx - dx;
  24224. var right = cx + dx;
  24225. var top = cy + dy;
  24226. var bottom = cy - dy;
  24227. if (this.view !== null && this.view.enabled) {
  24228. var zoomW = this.zoom / (this.view.width / this.view.fullWidth);
  24229. var zoomH = this.zoom / (this.view.height / this.view.fullHeight);
  24230. var scaleW = (this.right - this.left) / this.view.width;
  24231. var scaleH = (this.top - this.bottom) / this.view.height;
  24232. left += scaleW * (this.view.offsetX / zoomW);
  24233. right = left + scaleW * (this.view.width / zoomW);
  24234. top -= scaleH * (this.view.offsetY / zoomH);
  24235. bottom = top - scaleH * (this.view.height / zoomH);
  24236. }
  24237. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  24238. this.projectionMatrixInverse.getInverse(this.projectionMatrix);
  24239. },
  24240. toJSON: function (meta) {
  24241. var data = Object3D.prototype.toJSON.call(this, meta);
  24242. data.object.zoom = this.zoom;
  24243. data.object.left = this.left;
  24244. data.object.right = this.right;
  24245. data.object.top = this.top;
  24246. data.object.bottom = this.bottom;
  24247. data.object.near = this.near;
  24248. data.object.far = this.far;
  24249. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  24250. return data;
  24251. }
  24252. });
  24253. /**
  24254. * @author mrdoob / http://mrdoob.com/
  24255. */
  24256. function DirectionalLightShadow() {
  24257. LightShadow.call(this, new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  24258. }
  24259. DirectionalLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  24260. constructor: DirectionalLightShadow,
  24261. isDirectionalLightShadow: true,
  24262. updateMatrices: function (light, viewCamera, viewportIndex) {
  24263. LightShadow.prototype.updateMatrices.call(this, light, viewCamera, viewportIndex);
  24264. }
  24265. });
  24266. /**
  24267. * @author mrdoob / http://mrdoob.com/
  24268. * @author alteredq / http://alteredqualia.com/
  24269. */
  24270. function DirectionalLight(color, intensity) {
  24271. Light.call(this, color, intensity);
  24272. this.type = 'DirectionalLight';
  24273. this.position.copy(Object3D.DefaultUp);
  24274. this.updateMatrix();
  24275. this.target = new Object3D();
  24276. this.shadow = new DirectionalLightShadow();
  24277. }
  24278. DirectionalLight.prototype = Object.assign(Object.create(Light.prototype), {
  24279. constructor: DirectionalLight,
  24280. isDirectionalLight: true,
  24281. copy: function (source) {
  24282. Light.prototype.copy.call(this, source);
  24283. this.target = source.target.clone();
  24284. this.shadow = source.shadow.clone();
  24285. return this;
  24286. }
  24287. });
  24288. /**
  24289. * @author mrdoob / http://mrdoob.com/
  24290. */
  24291. function AmbientLight(color, intensity) {
  24292. Light.call(this, color, intensity);
  24293. this.type = 'AmbientLight';
  24294. this.castShadow = undefined;
  24295. }
  24296. AmbientLight.prototype = Object.assign(Object.create(Light.prototype), {
  24297. constructor: AmbientLight,
  24298. isAmbientLight: true
  24299. });
  24300. /**
  24301. * @author abelnation / http://github.com/abelnation
  24302. */
  24303. function RectAreaLight(color, intensity, width, height) {
  24304. Light.call(this, color, intensity);
  24305. this.type = 'RectAreaLight';
  24306. this.width = width !== undefined ? width : 10;
  24307. this.height = height !== undefined ? height : 10;
  24308. }
  24309. RectAreaLight.prototype = Object.assign(Object.create(Light.prototype), {
  24310. constructor: RectAreaLight,
  24311. isRectAreaLight: true,
  24312. copy: function (source) {
  24313. Light.prototype.copy.call(this, source);
  24314. this.width = source.width;
  24315. this.height = source.height;
  24316. return this;
  24317. },
  24318. toJSON: function (meta) {
  24319. var data = Light.prototype.toJSON.call(this, meta);
  24320. data.object.width = this.width;
  24321. data.object.height = this.height;
  24322. return data;
  24323. }
  24324. });
  24325. /**
  24326. * @author mrdoob / http://mrdoob.com/
  24327. */
  24328. function MaterialLoader(manager) {
  24329. Loader.call(this, manager);
  24330. this.textures = {};
  24331. }
  24332. MaterialLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24333. constructor: MaterialLoader,
  24334. load: function (url, onLoad, onProgress, onError) {
  24335. var scope = this;
  24336. var loader = new FileLoader(scope.manager);
  24337. loader.setPath(scope.path);
  24338. loader.load(url, function (text) {
  24339. onLoad(scope.parse(JSON.parse(text)));
  24340. }, onProgress, onError);
  24341. },
  24342. parse: function (json) {
  24343. var textures = this.textures;
  24344. function getTexture(name) {
  24345. if (textures[name] === undefined) {
  24346. console.warn('THREE.MaterialLoader: Undefined texture', name);
  24347. }
  24348. return textures[name];
  24349. }
  24350. var material = new Materials[json.type]();
  24351. if (json.uuid !== undefined) material.uuid = json.uuid;
  24352. if (json.name !== undefined) material.name = json.name;
  24353. if (json.color !== undefined) material.color.setHex(json.color);
  24354. if (json.roughness !== undefined) material.roughness = json.roughness;
  24355. if (json.metalness !== undefined) material.metalness = json.metalness;
  24356. if (json.sheen !== undefined) material.sheen = new Color().setHex(json.sheen);
  24357. if (json.emissive !== undefined) material.emissive.setHex(json.emissive);
  24358. if (json.specular !== undefined) material.specular.setHex(json.specular);
  24359. if (json.shininess !== undefined) material.shininess = json.shininess;
  24360. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  24361. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  24362. if (json.vertexColors !== undefined) material.vertexColors = json.vertexColors;
  24363. if (json.fog !== undefined) material.fog = json.fog;
  24364. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  24365. if (json.blending !== undefined) material.blending = json.blending;
  24366. if (json.combine !== undefined) material.combine = json.combine;
  24367. if (json.side !== undefined) material.side = json.side;
  24368. if (json.opacity !== undefined) material.opacity = json.opacity;
  24369. if (json.transparent !== undefined) material.transparent = json.transparent;
  24370. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  24371. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  24372. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  24373. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  24374. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  24375. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  24376. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  24377. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  24378. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  24379. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  24380. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  24381. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  24382. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  24383. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  24384. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  24385. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  24386. if (json.rotation !== undefined) material.rotation = json.rotation;
  24387. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  24388. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  24389. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  24390. if (json.scale !== undefined) material.scale = json.scale;
  24391. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  24392. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  24393. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  24394. if (json.skinning !== undefined) material.skinning = json.skinning;
  24395. if (json.morphTargets !== undefined) material.morphTargets = json.morphTargets;
  24396. if (json.morphNormals !== undefined) material.morphNormals = json.morphNormals;
  24397. if (json.dithering !== undefined) material.dithering = json.dithering;
  24398. if (json.visible !== undefined) material.visible = json.visible;
  24399. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  24400. if (json.userData !== undefined) material.userData = json.userData; // Shader Material
  24401. if (json.uniforms !== undefined) {
  24402. for (var name in json.uniforms) {
  24403. var uniform = json.uniforms[name];
  24404. material.uniforms[name] = {};
  24405. switch (uniform.type) {
  24406. case 't':
  24407. material.uniforms[name].value = getTexture(uniform.value);
  24408. break;
  24409. case 'c':
  24410. material.uniforms[name].value = new Color().setHex(uniform.value);
  24411. break;
  24412. case 'v2':
  24413. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  24414. break;
  24415. case 'v3':
  24416. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  24417. break;
  24418. case 'v4':
  24419. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  24420. break;
  24421. case 'm3':
  24422. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  24423. case 'm4':
  24424. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  24425. break;
  24426. default:
  24427. material.uniforms[name].value = uniform.value;
  24428. }
  24429. }
  24430. }
  24431. if (json.defines !== undefined) material.defines = json.defines;
  24432. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  24433. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  24434. if (json.extensions !== undefined) {
  24435. for (var key in json.extensions) {
  24436. material.extensions[key] = json.extensions[key];
  24437. }
  24438. } // Deprecated
  24439. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  24440. // for PointsMaterial
  24441. if (json.size !== undefined) material.size = json.size;
  24442. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  24443. if (json.map !== undefined) material.map = getTexture(json.map);
  24444. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  24445. if (json.alphaMap !== undefined) {
  24446. material.alphaMap = getTexture(json.alphaMap);
  24447. material.transparent = true;
  24448. }
  24449. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  24450. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  24451. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  24452. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  24453. if (json.normalScale !== undefined) {
  24454. var normalScale = json.normalScale;
  24455. if (Array.isArray(normalScale) === false) {
  24456. // Blender exporter used to export a scalar. See #7459
  24457. normalScale = [normalScale, normalScale];
  24458. }
  24459. material.normalScale = new Vector2().fromArray(normalScale);
  24460. }
  24461. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  24462. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  24463. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  24464. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  24465. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  24466. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  24467. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  24468. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  24469. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  24470. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  24471. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  24472. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  24473. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  24474. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  24475. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  24476. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  24477. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  24478. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  24479. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  24480. return material;
  24481. },
  24482. setTextures: function (value) {
  24483. this.textures = value;
  24484. return this;
  24485. }
  24486. });
  24487. /**
  24488. * @author Don McCurdy / https://www.donmccurdy.com
  24489. */
  24490. var LoaderUtils = {
  24491. decodeText: function (array) {
  24492. if (typeof TextDecoder !== 'undefined') {
  24493. return new TextDecoder().decode(array);
  24494. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  24495. // throws a "maximum call stack size exceeded" error for large arrays.
  24496. var s = '';
  24497. for (var i = 0, il = array.length; i < il; i++) {
  24498. // Implicitly assumes little-endian.
  24499. s += String.fromCharCode(array[i]);
  24500. }
  24501. try {
  24502. // merges multi-byte utf-8 characters.
  24503. return decodeURIComponent(escape(s));
  24504. } catch (e) {
  24505. // see #16358
  24506. return s;
  24507. }
  24508. },
  24509. extractUrlBase: function (url) {
  24510. var index = url.lastIndexOf('/');
  24511. if (index === -1) return './';
  24512. return url.substr(0, index + 1);
  24513. }
  24514. };
  24515. /**
  24516. * @author benaadams / https://twitter.com/ben_a_adams
  24517. */
  24518. exports.LoaderUtils = LoaderUtils;
  24519. function InstancedBufferGeometry() {
  24520. BufferGeometry.call(this);
  24521. this.type = 'InstancedBufferGeometry';
  24522. this.maxInstancedCount = undefined;
  24523. }
  24524. InstancedBufferGeometry.prototype = Object.assign(Object.create(BufferGeometry.prototype), {
  24525. constructor: InstancedBufferGeometry,
  24526. isInstancedBufferGeometry: true,
  24527. copy: function (source) {
  24528. BufferGeometry.prototype.copy.call(this, source);
  24529. this.maxInstancedCount = source.maxInstancedCount;
  24530. return this;
  24531. },
  24532. clone: function () {
  24533. return new this.constructor().copy(this);
  24534. },
  24535. toJSON: function () {
  24536. var data = BufferGeometry.prototype.toJSON.call(this);
  24537. data.maxInstancedCount = this.maxInstancedCount;
  24538. data.isInstancedBufferGeometry = true;
  24539. return data;
  24540. }
  24541. });
  24542. /**
  24543. * @author benaadams / https://twitter.com/ben_a_adams
  24544. */
  24545. function InstancedBufferAttribute(array, itemSize, normalized, meshPerAttribute) {
  24546. if (typeof normalized === 'number') {
  24547. meshPerAttribute = normalized;
  24548. normalized = false;
  24549. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  24550. }
  24551. BufferAttribute.call(this, array, itemSize, normalized);
  24552. this.meshPerAttribute = meshPerAttribute || 1;
  24553. }
  24554. InstancedBufferAttribute.prototype = Object.assign(Object.create(BufferAttribute.prototype), {
  24555. constructor: InstancedBufferAttribute,
  24556. isInstancedBufferAttribute: true,
  24557. copy: function (source) {
  24558. BufferAttribute.prototype.copy.call(this, source);
  24559. this.meshPerAttribute = source.meshPerAttribute;
  24560. return this;
  24561. },
  24562. toJSON: function () {
  24563. var data = BufferAttribute.prototype.toJSON.call(this);
  24564. data.meshPerAttribute = this.meshPerAttribute;
  24565. data.isInstancedBufferAttribute = true;
  24566. return data;
  24567. }
  24568. });
  24569. /**
  24570. * @author mrdoob / http://mrdoob.com/
  24571. */
  24572. function BufferGeometryLoader(manager) {
  24573. Loader.call(this, manager);
  24574. }
  24575. BufferGeometryLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24576. constructor: BufferGeometryLoader,
  24577. load: function (url, onLoad, onProgress, onError) {
  24578. var scope = this;
  24579. var loader = new FileLoader(scope.manager);
  24580. loader.setPath(scope.path);
  24581. loader.load(url, function (text) {
  24582. onLoad(scope.parse(JSON.parse(text)));
  24583. }, onProgress, onError);
  24584. },
  24585. parse: function (json) {
  24586. var geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  24587. var index = json.data.index;
  24588. if (index !== undefined) {
  24589. var typedArray = new TYPED_ARRAYS[index.type](index.array);
  24590. geometry.setIndex(new BufferAttribute(typedArray, 1));
  24591. }
  24592. var attributes = json.data.attributes;
  24593. for (var key in attributes) {
  24594. var attribute = attributes[key];
  24595. var typedArray = new TYPED_ARRAYS[attribute.type](attribute.array);
  24596. var bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  24597. var bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  24598. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  24599. geometry.addAttribute(key, bufferAttribute);
  24600. }
  24601. var morphAttributes = json.data.morphAttributes;
  24602. if (morphAttributes) {
  24603. for (var key in morphAttributes) {
  24604. var attributeArray = morphAttributes[key];
  24605. var array = [];
  24606. for (var i = 0, il = attributeArray.length; i < il; i++) {
  24607. var attribute = attributeArray[i];
  24608. var typedArray = new TYPED_ARRAYS[attribute.type](attribute.array);
  24609. var bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  24610. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  24611. array.push(bufferAttribute);
  24612. }
  24613. geometry.morphAttributes[key] = array;
  24614. }
  24615. }
  24616. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  24617. if (groups !== undefined) {
  24618. for (var i = 0, n = groups.length; i !== n; ++i) {
  24619. var group = groups[i];
  24620. geometry.addGroup(group.start, group.count, group.materialIndex);
  24621. }
  24622. }
  24623. var boundingSphere = json.data.boundingSphere;
  24624. if (boundingSphere !== undefined) {
  24625. var center = new Vector3();
  24626. if (boundingSphere.center !== undefined) {
  24627. center.fromArray(boundingSphere.center);
  24628. }
  24629. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  24630. }
  24631. if (json.name) geometry.name = json.name;
  24632. if (json.userData) geometry.userData = json.userData;
  24633. return geometry;
  24634. }
  24635. });
  24636. var TYPED_ARRAYS = {
  24637. Int8Array: Int8Array,
  24638. Uint8Array: Uint8Array,
  24639. // Workaround for IE11 pre KB2929437. See #11440
  24640. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  24641. Int16Array: Int16Array,
  24642. Uint16Array: Uint16Array,
  24643. Int32Array: Int32Array,
  24644. Uint32Array: Uint32Array,
  24645. Float32Array: Float32Array,
  24646. Float64Array: Float64Array
  24647. };
  24648. /**
  24649. * @author mrdoob / http://mrdoob.com/
  24650. */
  24651. function ObjectLoader(manager) {
  24652. Loader.call(this, manager);
  24653. }
  24654. ObjectLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24655. constructor: ObjectLoader,
  24656. load: function (url, onLoad, onProgress, onError) {
  24657. var scope = this;
  24658. var path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  24659. this.resourcePath = this.resourcePath || path;
  24660. var loader = new FileLoader(scope.manager);
  24661. loader.setPath(this.path);
  24662. loader.load(url, function (text) {
  24663. var json = null;
  24664. try {
  24665. json = JSON.parse(text);
  24666. } catch (error) {
  24667. if (onError !== undefined) onError(error);
  24668. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  24669. return;
  24670. }
  24671. var metadata = json.metadata;
  24672. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  24673. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  24674. return;
  24675. }
  24676. scope.parse(json, onLoad);
  24677. }, onProgress, onError);
  24678. },
  24679. parse: function (json, onLoad) {
  24680. var shapes = this.parseShape(json.shapes);
  24681. var geometries = this.parseGeometries(json.geometries, shapes);
  24682. var images = this.parseImages(json.images, function () {
  24683. if (onLoad !== undefined) onLoad(object);
  24684. });
  24685. var textures = this.parseTextures(json.textures, images);
  24686. var materials = this.parseMaterials(json.materials, textures);
  24687. var object = this.parseObject(json.object, geometries, materials);
  24688. if (json.animations) {
  24689. object.animations = this.parseAnimations(json.animations);
  24690. }
  24691. if (json.images === undefined || json.images.length === 0) {
  24692. if (onLoad !== undefined) onLoad(object);
  24693. }
  24694. return object;
  24695. },
  24696. parseShape: function (json) {
  24697. var shapes = {};
  24698. if (json !== undefined) {
  24699. for (var i = 0, l = json.length; i < l; i++) {
  24700. var shape = new Shape().fromJSON(json[i]);
  24701. shapes[shape.uuid] = shape;
  24702. }
  24703. }
  24704. return shapes;
  24705. },
  24706. parseGeometries: function (json, shapes) {
  24707. var geometries = {};
  24708. if (json !== undefined) {
  24709. var bufferGeometryLoader = new BufferGeometryLoader();
  24710. for (var i = 0, l = json.length; i < l; i++) {
  24711. var geometry;
  24712. var data = json[i];
  24713. switch (data.type) {
  24714. case 'PlaneGeometry':
  24715. case 'PlaneBufferGeometry':
  24716. geometry = new Geometries[data.type](data.width, data.height, data.widthSegments, data.heightSegments);
  24717. break;
  24718. case 'BoxGeometry':
  24719. case 'BoxBufferGeometry':
  24720. case 'CubeGeometry':
  24721. // backwards compatible
  24722. geometry = new Geometries[data.type](data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  24723. break;
  24724. case 'CircleGeometry':
  24725. case 'CircleBufferGeometry':
  24726. geometry = new Geometries[data.type](data.radius, data.segments, data.thetaStart, data.thetaLength);
  24727. break;
  24728. case 'CylinderGeometry':
  24729. case 'CylinderBufferGeometry':
  24730. geometry = new Geometries[data.type](data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  24731. break;
  24732. case 'ConeGeometry':
  24733. case 'ConeBufferGeometry':
  24734. geometry = new Geometries[data.type](data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  24735. break;
  24736. case 'SphereGeometry':
  24737. case 'SphereBufferGeometry':
  24738. geometry = new Geometries[data.type](data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  24739. break;
  24740. case 'DodecahedronGeometry':
  24741. case 'DodecahedronBufferGeometry':
  24742. case 'IcosahedronGeometry':
  24743. case 'IcosahedronBufferGeometry':
  24744. case 'OctahedronGeometry':
  24745. case 'OctahedronBufferGeometry':
  24746. case 'TetrahedronGeometry':
  24747. case 'TetrahedronBufferGeometry':
  24748. geometry = new Geometries[data.type](data.radius, data.detail);
  24749. break;
  24750. case 'RingGeometry':
  24751. case 'RingBufferGeometry':
  24752. geometry = new Geometries[data.type](data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  24753. break;
  24754. case 'TorusGeometry':
  24755. case 'TorusBufferGeometry':
  24756. geometry = new Geometries[data.type](data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  24757. break;
  24758. case 'TorusKnotGeometry':
  24759. case 'TorusKnotBufferGeometry':
  24760. geometry = new Geometries[data.type](data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  24761. break;
  24762. case 'TubeGeometry':
  24763. case 'TubeBufferGeometry':
  24764. // This only works for built-in curves (e.g. CatmullRomCurve3).
  24765. // User defined curves or instances of CurvePath will not be deserialized.
  24766. geometry = new Geometries[data.type](new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  24767. break;
  24768. case 'LatheGeometry':
  24769. case 'LatheBufferGeometry':
  24770. geometry = new Geometries[data.type](data.points, data.segments, data.phiStart, data.phiLength);
  24771. break;
  24772. case 'PolyhedronGeometry':
  24773. case 'PolyhedronBufferGeometry':
  24774. geometry = new Geometries[data.type](data.vertices, data.indices, data.radius, data.details);
  24775. break;
  24776. case 'ShapeGeometry':
  24777. case 'ShapeBufferGeometry':
  24778. var geometryShapes = [];
  24779. for (var j = 0, jl = data.shapes.length; j < jl; j++) {
  24780. var shape = shapes[data.shapes[j]];
  24781. geometryShapes.push(shape);
  24782. }
  24783. geometry = new Geometries[data.type](geometryShapes, data.curveSegments);
  24784. break;
  24785. case 'ExtrudeGeometry':
  24786. case 'ExtrudeBufferGeometry':
  24787. var geometryShapes = [];
  24788. for (var j = 0, jl = data.shapes.length; j < jl; j++) {
  24789. var shape = shapes[data.shapes[j]];
  24790. geometryShapes.push(shape);
  24791. }
  24792. var extrudePath = data.options.extrudePath;
  24793. if (extrudePath !== undefined) {
  24794. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  24795. }
  24796. geometry = new Geometries[data.type](geometryShapes, data.options);
  24797. break;
  24798. case 'BufferGeometry':
  24799. case 'InstancedBufferGeometry':
  24800. geometry = bufferGeometryLoader.parse(data);
  24801. break;
  24802. case 'Geometry':
  24803. if ('THREE' in window && 'LegacyJSONLoader' in THREE) {
  24804. var geometryLoader = new THREE.LegacyJSONLoader();
  24805. geometry = geometryLoader.parse(data, this.resourcePath).geometry;
  24806. } else {
  24807. console.error('THREE.ObjectLoader: You have to import LegacyJSONLoader in order load geometry data of type "Geometry".');
  24808. }
  24809. break;
  24810. default:
  24811. console.warn('THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"');
  24812. continue;
  24813. }
  24814. geometry.uuid = data.uuid;
  24815. if (data.name !== undefined) geometry.name = data.name;
  24816. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  24817. geometries[data.uuid] = geometry;
  24818. }
  24819. }
  24820. return geometries;
  24821. },
  24822. parseMaterials: function (json, textures) {
  24823. var cache = {}; // MultiMaterial
  24824. var materials = {};
  24825. if (json !== undefined) {
  24826. var loader = new MaterialLoader();
  24827. loader.setTextures(textures);
  24828. for (var i = 0, l = json.length; i < l; i++) {
  24829. var data = json[i];
  24830. if (data.type === 'MultiMaterial') {
  24831. // Deprecated
  24832. var array = [];
  24833. for (var j = 0; j < data.materials.length; j++) {
  24834. var material = data.materials[j];
  24835. if (cache[material.uuid] === undefined) {
  24836. cache[material.uuid] = loader.parse(material);
  24837. }
  24838. array.push(cache[material.uuid]);
  24839. }
  24840. materials[data.uuid] = array;
  24841. } else {
  24842. if (cache[data.uuid] === undefined) {
  24843. cache[data.uuid] = loader.parse(data);
  24844. }
  24845. materials[data.uuid] = cache[data.uuid];
  24846. }
  24847. }
  24848. }
  24849. return materials;
  24850. },
  24851. parseAnimations: function (json) {
  24852. var animations = [];
  24853. for (var i = 0; i < json.length; i++) {
  24854. var data = json[i];
  24855. var clip = AnimationClip.parse(data);
  24856. if (data.uuid !== undefined) clip.uuid = data.uuid;
  24857. animations.push(clip);
  24858. }
  24859. return animations;
  24860. },
  24861. parseImages: function (json, onLoad) {
  24862. var scope = this;
  24863. var images = {};
  24864. function loadImage(url) {
  24865. scope.manager.itemStart(url);
  24866. return loader.load(url, function () {
  24867. scope.manager.itemEnd(url);
  24868. }, undefined, function () {
  24869. scope.manager.itemError(url);
  24870. scope.manager.itemEnd(url);
  24871. });
  24872. }
  24873. if (json !== undefined && json.length > 0) {
  24874. var manager = new LoadingManager(onLoad);
  24875. var loader = new ImageLoader(manager);
  24876. loader.setCrossOrigin(this.crossOrigin);
  24877. for (var i = 0, il = json.length; i < il; i++) {
  24878. var image = json[i];
  24879. var url = image.url;
  24880. if (Array.isArray(url)) {
  24881. // load array of images e.g CubeTexture
  24882. images[image.uuid] = [];
  24883. for (var j = 0, jl = url.length; j < jl; j++) {
  24884. var currentUrl = url[j];
  24885. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(currentUrl) ? currentUrl : scope.resourcePath + currentUrl;
  24886. images[image.uuid].push(loadImage(path));
  24887. }
  24888. } else {
  24889. // load single image
  24890. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(image.url) ? image.url : scope.resourcePath + image.url;
  24891. images[image.uuid] = loadImage(path);
  24892. }
  24893. }
  24894. }
  24895. return images;
  24896. },
  24897. parseTextures: function (json, images) {
  24898. function parseConstant(value, type) {
  24899. if (typeof value === 'number') return value;
  24900. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  24901. return type[value];
  24902. }
  24903. var textures = {};
  24904. if (json !== undefined) {
  24905. for (var i = 0, l = json.length; i < l; i++) {
  24906. var data = json[i];
  24907. if (data.image === undefined) {
  24908. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  24909. }
  24910. if (images[data.image] === undefined) {
  24911. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  24912. }
  24913. var texture;
  24914. if (Array.isArray(images[data.image])) {
  24915. texture = new CubeTexture(images[data.image]);
  24916. } else {
  24917. texture = new Texture(images[data.image]);
  24918. }
  24919. texture.needsUpdate = true;
  24920. texture.uuid = data.uuid;
  24921. if (data.name !== undefined) texture.name = data.name;
  24922. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  24923. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  24924. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  24925. if (data.center !== undefined) texture.center.fromArray(data.center);
  24926. if (data.rotation !== undefined) texture.rotation = data.rotation;
  24927. if (data.wrap !== undefined) {
  24928. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  24929. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  24930. }
  24931. if (data.format !== undefined) texture.format = data.format;
  24932. if (data.type !== undefined) texture.type = data.type;
  24933. if (data.encoding !== undefined) texture.encoding = data.encoding;
  24934. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  24935. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  24936. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  24937. if (data.flipY !== undefined) texture.flipY = data.flipY;
  24938. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  24939. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  24940. textures[data.uuid] = texture;
  24941. }
  24942. }
  24943. return textures;
  24944. },
  24945. parseObject: function (data, geometries, materials) {
  24946. var object;
  24947. function getGeometry(name) {
  24948. if (geometries[name] === undefined) {
  24949. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  24950. }
  24951. return geometries[name];
  24952. }
  24953. function getMaterial(name) {
  24954. if (name === undefined) return undefined;
  24955. if (Array.isArray(name)) {
  24956. var array = [];
  24957. for (var i = 0, l = name.length; i < l; i++) {
  24958. var uuid = name[i];
  24959. if (materials[uuid] === undefined) {
  24960. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  24961. }
  24962. array.push(materials[uuid]);
  24963. }
  24964. return array;
  24965. }
  24966. if (materials[name] === undefined) {
  24967. console.warn('THREE.ObjectLoader: Undefined material', name);
  24968. }
  24969. return materials[name];
  24970. }
  24971. switch (data.type) {
  24972. case 'Scene':
  24973. object = new Scene();
  24974. if (data.background !== undefined) {
  24975. if (Number.isInteger(data.background)) {
  24976. object.background = new Color(data.background);
  24977. }
  24978. }
  24979. if (data.fog !== undefined) {
  24980. if (data.fog.type === 'Fog') {
  24981. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  24982. } else if (data.fog.type === 'FogExp2') {
  24983. object.fog = new FogExp2(data.fog.color, data.fog.density);
  24984. }
  24985. }
  24986. break;
  24987. case 'PerspectiveCamera':
  24988. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  24989. if (data.focus !== undefined) object.focus = data.focus;
  24990. if (data.zoom !== undefined) object.zoom = data.zoom;
  24991. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  24992. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  24993. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24994. break;
  24995. case 'OrthographicCamera':
  24996. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  24997. if (data.zoom !== undefined) object.zoom = data.zoom;
  24998. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24999. break;
  25000. case 'AmbientLight':
  25001. object = new AmbientLight(data.color, data.intensity);
  25002. break;
  25003. case 'DirectionalLight':
  25004. object = new DirectionalLight(data.color, data.intensity);
  25005. break;
  25006. case 'PointLight':
  25007. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  25008. break;
  25009. case 'RectAreaLight':
  25010. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  25011. break;
  25012. case 'SpotLight':
  25013. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  25014. break;
  25015. case 'HemisphereLight':
  25016. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  25017. break;
  25018. case 'SkinnedMesh':
  25019. console.warn('THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.');
  25020. case 'Mesh':
  25021. var geometry = getGeometry(data.geometry);
  25022. var material = getMaterial(data.material);
  25023. if (geometry.bones && geometry.bones.length > 0) {
  25024. object = new SkinnedMesh(geometry, material);
  25025. } else {
  25026. object = new Mesh(geometry, material);
  25027. }
  25028. if (data.drawMode !== undefined) object.setDrawMode(data.drawMode);
  25029. break;
  25030. case 'LOD':
  25031. object = new LOD();
  25032. break;
  25033. case 'Line':
  25034. object = new Line(getGeometry(data.geometry), getMaterial(data.material), data.mode);
  25035. break;
  25036. case 'LineLoop':
  25037. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  25038. break;
  25039. case 'LineSegments':
  25040. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  25041. break;
  25042. case 'PointCloud':
  25043. case 'Points':
  25044. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  25045. break;
  25046. case 'Sprite':
  25047. object = new Sprite(getMaterial(data.material));
  25048. break;
  25049. case 'Group':
  25050. object = new Group();
  25051. break;
  25052. default:
  25053. object = new Object3D();
  25054. }
  25055. object.uuid = data.uuid;
  25056. if (data.name !== undefined) object.name = data.name;
  25057. if (data.matrix !== undefined) {
  25058. object.matrix.fromArray(data.matrix);
  25059. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  25060. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  25061. } else {
  25062. if (data.position !== undefined) object.position.fromArray(data.position);
  25063. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  25064. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  25065. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  25066. }
  25067. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  25068. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  25069. if (data.shadow) {
  25070. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  25071. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  25072. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  25073. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  25074. }
  25075. if (data.visible !== undefined) object.visible = data.visible;
  25076. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  25077. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  25078. if (data.userData !== undefined) object.userData = data.userData;
  25079. if (data.layers !== undefined) object.layers.mask = data.layers;
  25080. if (data.children !== undefined) {
  25081. var children = data.children;
  25082. for (var i = 0; i < children.length; i++) {
  25083. object.add(this.parseObject(children[i], geometries, materials));
  25084. }
  25085. }
  25086. if (data.type === 'LOD') {
  25087. var levels = data.levels;
  25088. for (var l = 0; l < levels.length; l++) {
  25089. var level = levels[l];
  25090. var child = object.getObjectByProperty('uuid', level.object);
  25091. if (child !== undefined) {
  25092. object.addLevel(child, level.distance);
  25093. }
  25094. }
  25095. }
  25096. return object;
  25097. }
  25098. });
  25099. var TEXTURE_MAPPING = {
  25100. UVMapping: UVMapping,
  25101. CubeReflectionMapping: CubeReflectionMapping,
  25102. CubeRefractionMapping: CubeRefractionMapping,
  25103. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  25104. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  25105. SphericalReflectionMapping: SphericalReflectionMapping,
  25106. CubeUVReflectionMapping: CubeUVReflectionMapping,
  25107. CubeUVRefractionMapping: CubeUVRefractionMapping
  25108. };
  25109. var TEXTURE_WRAPPING = {
  25110. RepeatWrapping: RepeatWrapping,
  25111. ClampToEdgeWrapping: ClampToEdgeWrapping,
  25112. MirroredRepeatWrapping: MirroredRepeatWrapping
  25113. };
  25114. var TEXTURE_FILTER = {
  25115. NearestFilter: NearestFilter,
  25116. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  25117. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  25118. LinearFilter: LinearFilter,
  25119. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  25120. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  25121. };
  25122. /**
  25123. * @author thespite / http://clicktorelease.com/
  25124. */
  25125. function ImageBitmapLoader(manager) {
  25126. if (typeof createImageBitmap === 'undefined') {
  25127. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  25128. }
  25129. if (typeof fetch === 'undefined') {
  25130. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  25131. }
  25132. Loader.call(this, manager);
  25133. this.options = undefined;
  25134. }
  25135. ImageBitmapLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  25136. constructor: ImageBitmapLoader,
  25137. setOptions: function setOptions(options) {
  25138. this.options = options;
  25139. return this;
  25140. },
  25141. load: function (url, onLoad, onProgress, onError) {
  25142. if (url === undefined) url = '';
  25143. if (this.path !== undefined) url = this.path + url;
  25144. url = this.manager.resolveURL(url);
  25145. var scope = this;
  25146. var cached = Cache.get(url);
  25147. if (cached !== undefined) {
  25148. scope.manager.itemStart(url);
  25149. setTimeout(function () {
  25150. if (onLoad) onLoad(cached);
  25151. scope.manager.itemEnd(url);
  25152. }, 0);
  25153. return cached;
  25154. }
  25155. fetch(url).then(function (res) {
  25156. return res.blob();
  25157. }).then(function (blob) {
  25158. if (scope.options === undefined) {
  25159. // Workaround for FireFox. It causes an error if you pass options.
  25160. return createImageBitmap(blob);
  25161. } else {
  25162. return createImageBitmap(blob, scope.options);
  25163. }
  25164. }).then(function (imageBitmap) {
  25165. Cache.add(url, imageBitmap);
  25166. if (onLoad) onLoad(imageBitmap);
  25167. scope.manager.itemEnd(url);
  25168. }).catch(function (e) {
  25169. if (onError) onError(e);
  25170. scope.manager.itemError(url);
  25171. scope.manager.itemEnd(url);
  25172. });
  25173. scope.manager.itemStart(url);
  25174. }
  25175. });
  25176. /**
  25177. * @author zz85 / http://www.lab4games.net/zz85/blog
  25178. * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  25179. **/
  25180. function ShapePath() {
  25181. this.type = 'ShapePath';
  25182. this.color = new Color();
  25183. this.subPaths = [];
  25184. this.currentPath = null;
  25185. }
  25186. Object.assign(ShapePath.prototype, {
  25187. moveTo: function (x, y) {
  25188. this.currentPath = new Path();
  25189. this.subPaths.push(this.currentPath);
  25190. this.currentPath.moveTo(x, y);
  25191. },
  25192. lineTo: function (x, y) {
  25193. this.currentPath.lineTo(x, y);
  25194. },
  25195. quadraticCurveTo: function (aCPx, aCPy, aX, aY) {
  25196. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  25197. },
  25198. bezierCurveTo: function (aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  25199. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  25200. },
  25201. splineThru: function (pts) {
  25202. this.currentPath.splineThru(pts);
  25203. },
  25204. toShapes: function (isCCW, noHoles) {
  25205. function toShapesNoHoles(inSubpaths) {
  25206. var shapes = [];
  25207. for (var i = 0, l = inSubpaths.length; i < l; i++) {
  25208. var tmpPath = inSubpaths[i];
  25209. var tmpShape = new Shape();
  25210. tmpShape.curves = tmpPath.curves;
  25211. shapes.push(tmpShape);
  25212. }
  25213. return shapes;
  25214. }
  25215. function isPointInsidePolygon(inPt, inPolygon) {
  25216. var polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  25217. // toggling of inside/outside at every single! intersection point of an edge
  25218. // with the horizontal line through inPt, left of inPt
  25219. // not counting lowerY endpoints of edges and whole edges on that line
  25220. var inside = false;
  25221. for (var p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  25222. var edgeLowPt = inPolygon[p];
  25223. var edgeHighPt = inPolygon[q];
  25224. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  25225. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  25226. if (Math.abs(edgeDy) > Number.EPSILON) {
  25227. // not parallel
  25228. if (edgeDy < 0) {
  25229. edgeLowPt = inPolygon[q];
  25230. edgeDx = -edgeDx;
  25231. edgeHighPt = inPolygon[p];
  25232. edgeDy = -edgeDy;
  25233. }
  25234. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  25235. if (inPt.y === edgeLowPt.y) {
  25236. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  25237. // continue; // no intersection or edgeLowPt => doesn't count !!!
  25238. } else {
  25239. var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  25240. if (perpEdge === 0) return true; // inPt is on contour ?
  25241. if (perpEdge < 0) continue;
  25242. inside = !inside; // true intersection left of inPt
  25243. }
  25244. } else {
  25245. // parallel or collinear
  25246. if (inPt.y !== edgeLowPt.y) continue; // parallel
  25247. // edge lies on the same horizontal line as inPt
  25248. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  25249. // continue;
  25250. }
  25251. }
  25252. return inside;
  25253. }
  25254. var isClockWise = ShapeUtils.isClockWise;
  25255. var subPaths = this.subPaths;
  25256. if (subPaths.length === 0) return [];
  25257. if (noHoles === true) return toShapesNoHoles(subPaths);
  25258. var solid,
  25259. tmpPath,
  25260. tmpShape,
  25261. shapes = [];
  25262. if (subPaths.length === 1) {
  25263. tmpPath = subPaths[0];
  25264. tmpShape = new Shape();
  25265. tmpShape.curves = tmpPath.curves;
  25266. shapes.push(tmpShape);
  25267. return shapes;
  25268. }
  25269. var holesFirst = !isClockWise(subPaths[0].getPoints());
  25270. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  25271. var betterShapeHoles = [];
  25272. var newShapes = [];
  25273. var newShapeHoles = [];
  25274. var mainIdx = 0;
  25275. var tmpPoints;
  25276. newShapes[mainIdx] = undefined;
  25277. newShapeHoles[mainIdx] = [];
  25278. for (var i = 0, l = subPaths.length; i < l; i++) {
  25279. tmpPath = subPaths[i];
  25280. tmpPoints = tmpPath.getPoints();
  25281. solid = isClockWise(tmpPoints);
  25282. solid = isCCW ? !solid : solid;
  25283. if (solid) {
  25284. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  25285. newShapes[mainIdx] = {
  25286. s: new Shape(),
  25287. p: tmpPoints
  25288. };
  25289. newShapes[mainIdx].s.curves = tmpPath.curves;
  25290. if (holesFirst) mainIdx++;
  25291. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  25292. } else {
  25293. newShapeHoles[mainIdx].push({
  25294. h: tmpPath,
  25295. p: tmpPoints[0]
  25296. }); //console.log('ccw', i);
  25297. }
  25298. } // only Holes? -> probably all Shapes with wrong orientation
  25299. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  25300. if (newShapes.length > 1) {
  25301. var ambiguous = false;
  25302. var toChange = [];
  25303. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  25304. betterShapeHoles[sIdx] = [];
  25305. }
  25306. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  25307. var sho = newShapeHoles[sIdx];
  25308. for (var hIdx = 0; hIdx < sho.length; hIdx++) {
  25309. var ho = sho[hIdx];
  25310. var hole_unassigned = true;
  25311. for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  25312. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  25313. if (sIdx !== s2Idx) toChange.push({
  25314. froms: sIdx,
  25315. tos: s2Idx,
  25316. hole: hIdx
  25317. });
  25318. if (hole_unassigned) {
  25319. hole_unassigned = false;
  25320. betterShapeHoles[s2Idx].push(ho);
  25321. } else {
  25322. ambiguous = true;
  25323. }
  25324. }
  25325. }
  25326. if (hole_unassigned) {
  25327. betterShapeHoles[sIdx].push(ho);
  25328. }
  25329. }
  25330. } // console.log("ambiguous: ", ambiguous);
  25331. if (toChange.length > 0) {
  25332. // console.log("to change: ", toChange);
  25333. if (!ambiguous) newShapeHoles = betterShapeHoles;
  25334. }
  25335. }
  25336. var tmpHoles;
  25337. for (var i = 0, il = newShapes.length; i < il; i++) {
  25338. tmpShape = newShapes[i].s;
  25339. shapes.push(tmpShape);
  25340. tmpHoles = newShapeHoles[i];
  25341. for (var j = 0, jl = tmpHoles.length; j < jl; j++) {
  25342. tmpShape.holes.push(tmpHoles[j].h);
  25343. }
  25344. } //console.log("shape", shapes);
  25345. return shapes;
  25346. }
  25347. });
  25348. /**
  25349. * @author zz85 / http://www.lab4games.net/zz85/blog
  25350. * @author mrdoob / http://mrdoob.com/
  25351. */
  25352. function Font(data) {
  25353. this.type = 'Font';
  25354. this.data = data;
  25355. }
  25356. Object.assign(Font.prototype, {
  25357. isFont: true,
  25358. generateShapes: function (text, size) {
  25359. if (size === undefined) size = 100;
  25360. var shapes = [];
  25361. var paths = createPaths(text, size, this.data);
  25362. for (var p = 0, pl = paths.length; p < pl; p++) {
  25363. Array.prototype.push.apply(shapes, paths[p].toShapes());
  25364. }
  25365. return shapes;
  25366. }
  25367. });
  25368. function createPaths(text, size, data) {
  25369. var chars = Array.from ? Array.from(text) : String(text).split(''); // see #13988
  25370. var scale = size / data.resolution;
  25371. var line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale;
  25372. var paths = [];
  25373. var offsetX = 0,
  25374. offsetY = 0;
  25375. for (var i = 0; i < chars.length; i++) {
  25376. var char = chars[i];
  25377. if (char === '\n') {
  25378. offsetX = 0;
  25379. offsetY -= line_height;
  25380. } else {
  25381. var ret = createPath(char, scale, offsetX, offsetY, data);
  25382. offsetX += ret.offsetX;
  25383. paths.push(ret.path);
  25384. }
  25385. }
  25386. return paths;
  25387. }
  25388. function createPath(char, scale, offsetX, offsetY, data) {
  25389. var glyph = data.glyphs[char] || data.glyphs['?'];
  25390. if (!glyph) {
  25391. console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.');
  25392. return;
  25393. }
  25394. var path = new ShapePath();
  25395. var x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  25396. if (glyph.o) {
  25397. var outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(' '));
  25398. for (var i = 0, l = outline.length; i < l;) {
  25399. var action = outline[i++];
  25400. switch (action) {
  25401. case 'm':
  25402. // moveTo
  25403. x = outline[i++] * scale + offsetX;
  25404. y = outline[i++] * scale + offsetY;
  25405. path.moveTo(x, y);
  25406. break;
  25407. case 'l':
  25408. // lineTo
  25409. x = outline[i++] * scale + offsetX;
  25410. y = outline[i++] * scale + offsetY;
  25411. path.lineTo(x, y);
  25412. break;
  25413. case 'q':
  25414. // quadraticCurveTo
  25415. cpx = outline[i++] * scale + offsetX;
  25416. cpy = outline[i++] * scale + offsetY;
  25417. cpx1 = outline[i++] * scale + offsetX;
  25418. cpy1 = outline[i++] * scale + offsetY;
  25419. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  25420. break;
  25421. case 'b':
  25422. // bezierCurveTo
  25423. cpx = outline[i++] * scale + offsetX;
  25424. cpy = outline[i++] * scale + offsetY;
  25425. cpx1 = outline[i++] * scale + offsetX;
  25426. cpy1 = outline[i++] * scale + offsetY;
  25427. cpx2 = outline[i++] * scale + offsetX;
  25428. cpy2 = outline[i++] * scale + offsetY;
  25429. path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);
  25430. break;
  25431. }
  25432. }
  25433. }
  25434. return {
  25435. offsetX: glyph.ha * scale,
  25436. path: path
  25437. };
  25438. }
  25439. /**
  25440. * @author mrdoob / http://mrdoob.com/
  25441. */
  25442. function FontLoader(manager) {
  25443. Loader.call(this, manager);
  25444. }
  25445. FontLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  25446. constructor: FontLoader,
  25447. load: function (url, onLoad, onProgress, onError) {
  25448. var scope = this;
  25449. var loader = new FileLoader(this.manager);
  25450. loader.setPath(this.path);
  25451. loader.load(url, function (text) {
  25452. var json;
  25453. try {
  25454. json = JSON.parse(text);
  25455. } catch (e) {
  25456. console.warn('THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.');
  25457. json = JSON.parse(text.substring(65, text.length - 2));
  25458. }
  25459. var font = scope.parse(json);
  25460. if (onLoad) onLoad(font);
  25461. }, onProgress, onError);
  25462. },
  25463. parse: function (json) {
  25464. return new Font(json);
  25465. }
  25466. });
  25467. /**
  25468. * @author mrdoob / http://mrdoob.com/
  25469. */
  25470. var _context;
  25471. var AudioContext = {
  25472. getContext: function () {
  25473. if (_context === undefined) {
  25474. _context = new (window.AudioContext || window.webkitAudioContext)();
  25475. }
  25476. return _context;
  25477. },
  25478. setContext: function (value) {
  25479. _context = value;
  25480. }
  25481. };
  25482. /**
  25483. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  25484. */
  25485. exports.AudioContext = AudioContext;
  25486. function AudioLoader(manager) {
  25487. Loader.call(this, manager);
  25488. }
  25489. AudioLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  25490. constructor: AudioLoader,
  25491. load: function (url, onLoad, onProgress, onError) {
  25492. var loader = new FileLoader(this.manager);
  25493. loader.setResponseType('arraybuffer');
  25494. loader.setPath(this.path);
  25495. loader.load(url, function (buffer) {
  25496. // Create a copy of the buffer. The `decodeAudioData` method
  25497. // detaches the buffer when complete, preventing reuse.
  25498. var bufferCopy = buffer.slice(0);
  25499. var context = AudioContext.getContext();
  25500. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  25501. onLoad(audioBuffer);
  25502. });
  25503. }, onProgress, onError);
  25504. }
  25505. });
  25506. /**
  25507. * @author bhouston / http://clara.io
  25508. * @author WestLangley / http://github.com/WestLangley
  25509. *
  25510. * Primary reference:
  25511. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  25512. *
  25513. * Secondary reference:
  25514. * https://www.ppsloan.org/publications/StupidSH36.pdf
  25515. */
  25516. // 3-band SH defined by 9 coefficients
  25517. function SphericalHarmonics3() {
  25518. this.coefficients = [];
  25519. for (var i = 0; i < 9; i++) {
  25520. this.coefficients.push(new Vector3());
  25521. }
  25522. }
  25523. Object.assign(SphericalHarmonics3.prototype, {
  25524. isSphericalHarmonics3: true,
  25525. set: function (coefficients) {
  25526. for (var i = 0; i < 9; i++) {
  25527. this.coefficients[i].copy(coefficients[i]);
  25528. }
  25529. return this;
  25530. },
  25531. zero: function () {
  25532. for (var i = 0; i < 9; i++) {
  25533. this.coefficients[i].set(0, 0, 0);
  25534. }
  25535. return this;
  25536. },
  25537. // get the radiance in the direction of the normal
  25538. // target is a Vector3
  25539. getAt: function (normal, target) {
  25540. // normal is assumed to be unit length
  25541. var x = normal.x,
  25542. y = normal.y,
  25543. z = normal.z;
  25544. var coeff = this.coefficients; // band 0
  25545. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  25546. target.addScale(coeff[1], 0.488603 * y);
  25547. target.addScale(coeff[2], 0.488603 * z);
  25548. target.addScale(coeff[3], 0.488603 * x); // band 2
  25549. target.addScale(coeff[4], 1.092548 * (x * y));
  25550. target.addScale(coeff[5], 1.092548 * (y * z));
  25551. target.addScale(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  25552. target.addScale(coeff[7], 1.092548 * (x * z));
  25553. target.addScale(coeff[8], 0.546274 * (x * x - y * y));
  25554. return target;
  25555. },
  25556. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  25557. // target is a Vector3
  25558. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  25559. getIrradianceAt: function (normal, target) {
  25560. // normal is assumed to be unit length
  25561. var x = normal.x,
  25562. y = normal.y,
  25563. z = normal.z;
  25564. var coeff = this.coefficients; // band 0
  25565. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  25566. // band 1
  25567. target.addScale(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  25568. target.addScale(coeff[2], 2.0 * 0.511664 * z);
  25569. target.addScale(coeff[3], 2.0 * 0.511664 * x); // band 2
  25570. target.addScale(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  25571. target.addScale(coeff[5], 2.0 * 0.429043 * y * z);
  25572. target.addScale(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  25573. target.addScale(coeff[7], 2.0 * 0.429043 * x * z);
  25574. target.addScale(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  25575. return target;
  25576. },
  25577. add: function (sh) {
  25578. for (var i = 0; i < 9; i++) {
  25579. this.coefficients[i].add(sh.coefficients[i]);
  25580. }
  25581. return this;
  25582. },
  25583. scale: function (s) {
  25584. for (var i = 0; i < 9; i++) {
  25585. this.coefficients[i].multiplyScalar(s);
  25586. }
  25587. return this;
  25588. },
  25589. lerp: function (sh, alpha) {
  25590. for (var i = 0; i < 9; i++) {
  25591. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  25592. }
  25593. return this;
  25594. },
  25595. equals: function (sh) {
  25596. for (var i = 0; i < 9; i++) {
  25597. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  25598. return false;
  25599. }
  25600. }
  25601. return true;
  25602. },
  25603. copy: function (sh) {
  25604. return this.set(sh.coefficients);
  25605. },
  25606. clone: function () {
  25607. return new this.constructor().copy(this);
  25608. },
  25609. fromArray: function (array, offset) {
  25610. if (offset === undefined) offset = 0;
  25611. var coefficients = this.coefficients;
  25612. for (var i = 0; i < 9; i++) {
  25613. coefficients[i].fromArray(array, offset + i * 3);
  25614. }
  25615. return this;
  25616. },
  25617. toArray: function (array, offset) {
  25618. if (array === undefined) array = [];
  25619. if (offset === undefined) offset = 0;
  25620. var coefficients = this.coefficients;
  25621. for (var i = 0; i < 9; i++) {
  25622. coefficients[i].toArray(array, offset + i * 3);
  25623. }
  25624. return array;
  25625. }
  25626. });
  25627. Object.assign(SphericalHarmonics3, {
  25628. // evaluate the basis functions
  25629. // shBasis is an Array[ 9 ]
  25630. getBasisAt: function (normal, shBasis) {
  25631. // normal is assumed to be unit length
  25632. var x = normal.x,
  25633. y = normal.y,
  25634. z = normal.z; // band 0
  25635. shBasis[0] = 0.282095; // band 1
  25636. shBasis[1] = 0.488603 * y;
  25637. shBasis[2] = 0.488603 * z;
  25638. shBasis[3] = 0.488603 * x; // band 2
  25639. shBasis[4] = 1.092548 * x * y;
  25640. shBasis[5] = 1.092548 * y * z;
  25641. shBasis[6] = 0.315392 * (3 * z * z - 1);
  25642. shBasis[7] = 1.092548 * x * z;
  25643. shBasis[8] = 0.546274 * (x * x - y * y);
  25644. }
  25645. });
  25646. /**
  25647. * @author WestLangley / http://github.com/WestLangley
  25648. *
  25649. * A LightProbe is a source of indirect-diffuse light
  25650. */
  25651. function LightProbe(sh, intensity) {
  25652. Light.call(this, undefined, intensity);
  25653. this.sh = sh !== undefined ? sh : new SphericalHarmonics3();
  25654. }
  25655. LightProbe.prototype = Object.assign(Object.create(Light.prototype), {
  25656. constructor: LightProbe,
  25657. isLightProbe: true,
  25658. copy: function (source) {
  25659. Light.prototype.copy.call(this, source);
  25660. this.sh.copy(source.sh);
  25661. this.intensity = source.intensity;
  25662. return this;
  25663. },
  25664. toJSON: function (meta) {
  25665. var data = Light.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  25666. return data;
  25667. }
  25668. });
  25669. /**
  25670. * @author WestLangley / http://github.com/WestLangley
  25671. */
  25672. function HemisphereLightProbe(skyColor, groundColor, intensity) {
  25673. LightProbe.call(this, undefined, intensity);
  25674. var color1 = new Color().set(skyColor);
  25675. var color2 = new Color().set(groundColor);
  25676. var sky = new Vector3(color1.r, color1.g, color1.b);
  25677. var ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  25678. var c0 = Math.sqrt(Math.PI);
  25679. var c1 = c0 * Math.sqrt(0.75);
  25680. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  25681. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  25682. }
  25683. HemisphereLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
  25684. constructor: HemisphereLightProbe,
  25685. isHemisphereLightProbe: true,
  25686. copy: function (source) {
  25687. // modifying colors not currently supported
  25688. LightProbe.prototype.copy.call(this, source);
  25689. return this;
  25690. },
  25691. toJSON: function (meta) {
  25692. var data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  25693. return data;
  25694. }
  25695. });
  25696. /**
  25697. * @author WestLangley / http://github.com/WestLangley
  25698. */
  25699. function AmbientLightProbe(color, intensity) {
  25700. LightProbe.call(this, undefined, intensity);
  25701. var color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  25702. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  25703. }
  25704. AmbientLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
  25705. constructor: AmbientLightProbe,
  25706. isAmbientLightProbe: true,
  25707. copy: function (source) {
  25708. // modifying color not currently supported
  25709. LightProbe.prototype.copy.call(this, source);
  25710. return this;
  25711. },
  25712. toJSON: function (meta) {
  25713. var data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  25714. return data;
  25715. }
  25716. });
  25717. var _eyeRight = new Matrix4();
  25718. var _eyeLeft = new Matrix4();
  25719. /**
  25720. * @author mrdoob / http://mrdoob.com/
  25721. */
  25722. function StereoCamera() {
  25723. this.type = 'StereoCamera';
  25724. this.aspect = 1;
  25725. this.eyeSep = 0.064;
  25726. this.cameraL = new PerspectiveCamera();
  25727. this.cameraL.layers.enable(1);
  25728. this.cameraL.matrixAutoUpdate = false;
  25729. this.cameraR = new PerspectiveCamera();
  25730. this.cameraR.layers.enable(2);
  25731. this.cameraR.matrixAutoUpdate = false;
  25732. this._cache = {
  25733. focus: null,
  25734. fov: null,
  25735. aspect: null,
  25736. near: null,
  25737. far: null,
  25738. zoom: null,
  25739. eyeSep: null
  25740. };
  25741. }
  25742. Object.assign(StereoCamera.prototype, {
  25743. update: function (camera) {
  25744. var cache = this._cache;
  25745. 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;
  25746. if (needsUpdate) {
  25747. cache.focus = camera.focus;
  25748. cache.fov = camera.fov;
  25749. cache.aspect = camera.aspect * this.aspect;
  25750. cache.near = camera.near;
  25751. cache.far = camera.far;
  25752. cache.zoom = camera.zoom;
  25753. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  25754. // http://paulbourke.net/stereographics/stereorender/
  25755. var projectionMatrix = camera.projectionMatrix.clone();
  25756. var eyeSepHalf = cache.eyeSep / 2;
  25757. var eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  25758. var ymax = cache.near * Math.tan(_Math.DEG2RAD * cache.fov * 0.5) / cache.zoom;
  25759. var xmin, xmax; // translate xOffset
  25760. _eyeLeft.elements[12] = -eyeSepHalf;
  25761. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  25762. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  25763. xmax = ymax * cache.aspect + eyeSepOnProjection;
  25764. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  25765. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  25766. this.cameraL.projectionMatrix.copy(projectionMatrix); // for right eye
  25767. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  25768. xmax = ymax * cache.aspect - eyeSepOnProjection;
  25769. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  25770. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  25771. this.cameraR.projectionMatrix.copy(projectionMatrix);
  25772. }
  25773. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  25774. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  25775. }
  25776. });
  25777. /**
  25778. * @author alteredq / http://alteredqualia.com/
  25779. */
  25780. function Clock(autoStart) {
  25781. this.autoStart = autoStart !== undefined ? autoStart : true;
  25782. this.startTime = 0;
  25783. this.oldTime = 0;
  25784. this.elapsedTime = 0;
  25785. this.running = false;
  25786. }
  25787. Object.assign(Clock.prototype, {
  25788. start: function () {
  25789. this.startTime = (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  25790. this.oldTime = this.startTime;
  25791. this.elapsedTime = 0;
  25792. this.running = true;
  25793. },
  25794. stop: function () {
  25795. this.getElapsedTime();
  25796. this.running = false;
  25797. this.autoStart = false;
  25798. },
  25799. getElapsedTime: function () {
  25800. this.getDelta();
  25801. return this.elapsedTime;
  25802. },
  25803. getDelta: function () {
  25804. var diff = 0;
  25805. if (this.autoStart && !this.running) {
  25806. this.start();
  25807. return 0;
  25808. }
  25809. if (this.running) {
  25810. var newTime = (typeof performance === 'undefined' ? Date : performance).now();
  25811. diff = (newTime - this.oldTime) / 1000;
  25812. this.oldTime = newTime;
  25813. this.elapsedTime += diff;
  25814. }
  25815. return diff;
  25816. }
  25817. });
  25818. /**
  25819. * @author mrdoob / http://mrdoob.com/
  25820. */
  25821. var _position$2 = new Vector3();
  25822. var _quaternion$3 = new Quaternion();
  25823. var _scale$1 = new Vector3();
  25824. var _orientation = new Vector3();
  25825. function AudioListener() {
  25826. Object3D.call(this);
  25827. this.type = 'AudioListener';
  25828. this.context = AudioContext.getContext();
  25829. this.gain = this.context.createGain();
  25830. this.gain.connect(this.context.destination);
  25831. this.filter = null;
  25832. this.timeDelta = 0; // private
  25833. this._clock = new Clock();
  25834. }
  25835. AudioListener.prototype = Object.assign(Object.create(Object3D.prototype), {
  25836. constructor: AudioListener,
  25837. getInput: function () {
  25838. return this.gain;
  25839. },
  25840. removeFilter: function () {
  25841. if (this.filter !== null) {
  25842. this.gain.disconnect(this.filter);
  25843. this.filter.disconnect(this.context.destination);
  25844. this.gain.connect(this.context.destination);
  25845. this.filter = null;
  25846. }
  25847. return this;
  25848. },
  25849. getFilter: function () {
  25850. return this.filter;
  25851. },
  25852. setFilter: function (value) {
  25853. if (this.filter !== null) {
  25854. this.gain.disconnect(this.filter);
  25855. this.filter.disconnect(this.context.destination);
  25856. } else {
  25857. this.gain.disconnect(this.context.destination);
  25858. }
  25859. this.filter = value;
  25860. this.gain.connect(this.filter);
  25861. this.filter.connect(this.context.destination);
  25862. return this;
  25863. },
  25864. getMasterVolume: function () {
  25865. return this.gain.gain.value;
  25866. },
  25867. setMasterVolume: function (value) {
  25868. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25869. return this;
  25870. },
  25871. updateMatrixWorld: function (force) {
  25872. Object3D.prototype.updateMatrixWorld.call(this, force);
  25873. var listener = this.context.listener;
  25874. var up = this.up;
  25875. this.timeDelta = this._clock.getDelta();
  25876. this.matrixWorld.decompose(_position$2, _quaternion$3, _scale$1);
  25877. _orientation.set(0, 0, -1).applyQuaternion(_quaternion$3);
  25878. if (listener.positionX) {
  25879. // code path for Chrome (see #14393)
  25880. var endTime = this.context.currentTime + this.timeDelta;
  25881. listener.positionX.linearRampToValueAtTime(_position$2.x, endTime);
  25882. listener.positionY.linearRampToValueAtTime(_position$2.y, endTime);
  25883. listener.positionZ.linearRampToValueAtTime(_position$2.z, endTime);
  25884. listener.forwardX.linearRampToValueAtTime(_orientation.x, endTime);
  25885. listener.forwardY.linearRampToValueAtTime(_orientation.y, endTime);
  25886. listener.forwardZ.linearRampToValueAtTime(_orientation.z, endTime);
  25887. listener.upX.linearRampToValueAtTime(up.x, endTime);
  25888. listener.upY.linearRampToValueAtTime(up.y, endTime);
  25889. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  25890. } else {
  25891. listener.setPosition(_position$2.x, _position$2.y, _position$2.z);
  25892. listener.setOrientation(_orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z);
  25893. }
  25894. }
  25895. });
  25896. /**
  25897. * @author mrdoob / http://mrdoob.com/
  25898. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  25899. */
  25900. function Audio(listener) {
  25901. Object3D.call(this);
  25902. this.type = 'Audio';
  25903. this.listener = listener;
  25904. this.context = listener.context;
  25905. this.gain = this.context.createGain();
  25906. this.gain.connect(listener.getInput());
  25907. this.autoplay = false;
  25908. this.buffer = null;
  25909. this.detune = 0;
  25910. this.loop = false;
  25911. this.startTime = 0;
  25912. this.offset = 0;
  25913. this.duration = undefined;
  25914. this.playbackRate = 1;
  25915. this.isPlaying = false;
  25916. this.hasPlaybackControl = true;
  25917. this.sourceType = 'empty';
  25918. this.filters = [];
  25919. }
  25920. Audio.prototype = Object.assign(Object.create(Object3D.prototype), {
  25921. constructor: Audio,
  25922. getOutput: function () {
  25923. return this.gain;
  25924. },
  25925. setNodeSource: function (audioNode) {
  25926. this.hasPlaybackControl = false;
  25927. this.sourceType = 'audioNode';
  25928. this.source = audioNode;
  25929. this.connect();
  25930. return this;
  25931. },
  25932. setMediaElementSource: function (mediaElement) {
  25933. this.hasPlaybackControl = false;
  25934. this.sourceType = 'mediaNode';
  25935. this.source = this.context.createMediaElementSource(mediaElement);
  25936. this.connect();
  25937. return this;
  25938. },
  25939. setMediaStreamSource: function (mediaStream) {
  25940. this.hasPlaybackControl = false;
  25941. this.sourceType = 'mediaStreamNode';
  25942. this.source = this.context.createMediaStreamSource(mediaStream);
  25943. this.connect();
  25944. return this;
  25945. },
  25946. setBuffer: function (audioBuffer) {
  25947. this.buffer = audioBuffer;
  25948. this.sourceType = 'buffer';
  25949. if (this.autoplay) this.play();
  25950. return this;
  25951. },
  25952. play: function () {
  25953. if (this.isPlaying === true) {
  25954. console.warn('THREE.Audio: Audio is already playing.');
  25955. return;
  25956. }
  25957. if (this.hasPlaybackControl === false) {
  25958. console.warn('THREE.Audio: this Audio has no playback control.');
  25959. return;
  25960. }
  25961. var source = this.context.createBufferSource();
  25962. source.buffer = this.buffer;
  25963. source.loop = this.loop;
  25964. source.onended = this.onEnded.bind(this);
  25965. this.startTime = this.context.currentTime;
  25966. source.start(this.startTime, this.offset, this.duration);
  25967. this.isPlaying = true;
  25968. this.source = source;
  25969. this.setDetune(this.detune);
  25970. this.setPlaybackRate(this.playbackRate);
  25971. return this.connect();
  25972. },
  25973. pause: function () {
  25974. if (this.hasPlaybackControl === false) {
  25975. console.warn('THREE.Audio: this Audio has no playback control.');
  25976. return;
  25977. }
  25978. if (this.isPlaying === true) {
  25979. this.source.stop();
  25980. this.source.onended = null;
  25981. this.offset += (this.context.currentTime - this.startTime) * this.playbackRate;
  25982. this.isPlaying = false;
  25983. }
  25984. return this;
  25985. },
  25986. stop: function () {
  25987. if (this.hasPlaybackControl === false) {
  25988. console.warn('THREE.Audio: this Audio has no playback control.');
  25989. return;
  25990. }
  25991. this.source.stop();
  25992. this.source.onended = null;
  25993. this.offset = 0;
  25994. this.isPlaying = false;
  25995. return this;
  25996. },
  25997. connect: function () {
  25998. if (this.filters.length > 0) {
  25999. this.source.connect(this.filters[0]);
  26000. for (var i = 1, l = this.filters.length; i < l; i++) {
  26001. this.filters[i - 1].connect(this.filters[i]);
  26002. }
  26003. this.filters[this.filters.length - 1].connect(this.getOutput());
  26004. } else {
  26005. this.source.connect(this.getOutput());
  26006. }
  26007. return this;
  26008. },
  26009. disconnect: function () {
  26010. if (this.filters.length > 0) {
  26011. this.source.disconnect(this.filters[0]);
  26012. for (var i = 1, l = this.filters.length; i < l; i++) {
  26013. this.filters[i - 1].disconnect(this.filters[i]);
  26014. }
  26015. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  26016. } else {
  26017. this.source.disconnect(this.getOutput());
  26018. }
  26019. return this;
  26020. },
  26021. getFilters: function () {
  26022. return this.filters;
  26023. },
  26024. setFilters: function (value) {
  26025. if (!value) value = [];
  26026. if (this.isPlaying === true) {
  26027. this.disconnect();
  26028. this.filters = value;
  26029. this.connect();
  26030. } else {
  26031. this.filters = value;
  26032. }
  26033. return this;
  26034. },
  26035. setDetune: function (value) {
  26036. this.detune = value;
  26037. if (this.source.detune === undefined) return; // only set detune when available
  26038. if (this.isPlaying === true) {
  26039. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  26040. }
  26041. return this;
  26042. },
  26043. getDetune: function () {
  26044. return this.detune;
  26045. },
  26046. getFilter: function () {
  26047. return this.getFilters()[0];
  26048. },
  26049. setFilter: function (filter) {
  26050. return this.setFilters(filter ? [filter] : []);
  26051. },
  26052. setPlaybackRate: function (value) {
  26053. if (this.hasPlaybackControl === false) {
  26054. console.warn('THREE.Audio: this Audio has no playback control.');
  26055. return;
  26056. }
  26057. this.playbackRate = value;
  26058. if (this.isPlaying === true) {
  26059. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  26060. }
  26061. return this;
  26062. },
  26063. getPlaybackRate: function () {
  26064. return this.playbackRate;
  26065. },
  26066. onEnded: function () {
  26067. this.isPlaying = false;
  26068. },
  26069. getLoop: function () {
  26070. if (this.hasPlaybackControl === false) {
  26071. console.warn('THREE.Audio: this Audio has no playback control.');
  26072. return false;
  26073. }
  26074. return this.loop;
  26075. },
  26076. setLoop: function (value) {
  26077. if (this.hasPlaybackControl === false) {
  26078. console.warn('THREE.Audio: this Audio has no playback control.');
  26079. return;
  26080. }
  26081. this.loop = value;
  26082. if (this.isPlaying === true) {
  26083. this.source.loop = this.loop;
  26084. }
  26085. return this;
  26086. },
  26087. getVolume: function () {
  26088. return this.gain.gain.value;
  26089. },
  26090. setVolume: function (value) {
  26091. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  26092. return this;
  26093. }
  26094. });
  26095. /**
  26096. * @author mrdoob / http://mrdoob.com/
  26097. */
  26098. var _position$3 = new Vector3();
  26099. var _quaternion$4 = new Quaternion();
  26100. var _scale$2 = new Vector3();
  26101. var _orientation$1 = new Vector3();
  26102. function PositionalAudio(listener) {
  26103. Audio.call(this, listener);
  26104. this.panner = this.context.createPanner();
  26105. this.panner.panningModel = 'HRTF';
  26106. this.panner.connect(this.gain);
  26107. }
  26108. PositionalAudio.prototype = Object.assign(Object.create(Audio.prototype), {
  26109. constructor: PositionalAudio,
  26110. getOutput: function () {
  26111. return this.panner;
  26112. },
  26113. getRefDistance: function () {
  26114. return this.panner.refDistance;
  26115. },
  26116. setRefDistance: function (value) {
  26117. this.panner.refDistance = value;
  26118. return this;
  26119. },
  26120. getRolloffFactor: function () {
  26121. return this.panner.rolloffFactor;
  26122. },
  26123. setRolloffFactor: function (value) {
  26124. this.panner.rolloffFactor = value;
  26125. return this;
  26126. },
  26127. getDistanceModel: function () {
  26128. return this.panner.distanceModel;
  26129. },
  26130. setDistanceModel: function (value) {
  26131. this.panner.distanceModel = value;
  26132. return this;
  26133. },
  26134. getMaxDistance: function () {
  26135. return this.panner.maxDistance;
  26136. },
  26137. setMaxDistance: function (value) {
  26138. this.panner.maxDistance = value;
  26139. return this;
  26140. },
  26141. setDirectionalCone: function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  26142. this.panner.coneInnerAngle = coneInnerAngle;
  26143. this.panner.coneOuterAngle = coneOuterAngle;
  26144. this.panner.coneOuterGain = coneOuterGain;
  26145. return this;
  26146. },
  26147. updateMatrixWorld: function (force) {
  26148. Object3D.prototype.updateMatrixWorld.call(this, force);
  26149. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  26150. this.matrixWorld.decompose(_position$3, _quaternion$4, _scale$2);
  26151. _orientation$1.set(0, 0, 1).applyQuaternion(_quaternion$4);
  26152. var panner = this.panner;
  26153. if (panner.positionX) {
  26154. // code path for Chrome and Firefox (see #14393)
  26155. var endTime = this.context.currentTime + this.listener.timeDelta;
  26156. panner.positionX.linearRampToValueAtTime(_position$3.x, endTime);
  26157. panner.positionY.linearRampToValueAtTime(_position$3.y, endTime);
  26158. panner.positionZ.linearRampToValueAtTime(_position$3.z, endTime);
  26159. panner.orientationX.linearRampToValueAtTime(_orientation$1.x, endTime);
  26160. panner.orientationY.linearRampToValueAtTime(_orientation$1.y, endTime);
  26161. panner.orientationZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  26162. } else {
  26163. panner.setPosition(_position$3.x, _position$3.y, _position$3.z);
  26164. panner.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z);
  26165. }
  26166. }
  26167. });
  26168. /**
  26169. * @author mrdoob / http://mrdoob.com/
  26170. */
  26171. function AudioAnalyser(audio, fftSize) {
  26172. this.analyser = audio.context.createAnalyser();
  26173. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  26174. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  26175. audio.getOutput().connect(this.analyser);
  26176. }
  26177. Object.assign(AudioAnalyser.prototype, {
  26178. getFrequencyData: function () {
  26179. this.analyser.getByteFrequencyData(this.data);
  26180. return this.data;
  26181. },
  26182. getAverageFrequency: function () {
  26183. var value = 0,
  26184. data = this.getFrequencyData();
  26185. for (var i = 0; i < data.length; i++) {
  26186. value += data[i];
  26187. }
  26188. return value / data.length;
  26189. }
  26190. });
  26191. /**
  26192. *
  26193. * Buffered scene graph property that allows weighted accumulation.
  26194. *
  26195. *
  26196. * @author Ben Houston / http://clara.io/
  26197. * @author David Sarno / http://lighthaus.us/
  26198. * @author tschw
  26199. */
  26200. function PropertyMixer(binding, typeName, valueSize) {
  26201. this.binding = binding;
  26202. this.valueSize = valueSize;
  26203. var bufferType = Float64Array,
  26204. mixFunction;
  26205. switch (typeName) {
  26206. case 'quaternion':
  26207. mixFunction = this._slerp;
  26208. break;
  26209. case 'string':
  26210. case 'bool':
  26211. bufferType = Array;
  26212. mixFunction = this._select;
  26213. break;
  26214. default:
  26215. mixFunction = this._lerp;
  26216. }
  26217. this.buffer = new bufferType(valueSize * 4); // layout: [ incoming | accu0 | accu1 | orig ]
  26218. //
  26219. // interpolators can use .buffer as their .result
  26220. // the data then goes to 'incoming'
  26221. //
  26222. // 'accu0' and 'accu1' are used frame-interleaved for
  26223. // the cumulative result and are compared to detect
  26224. // changes
  26225. //
  26226. // 'orig' stores the original state of the property
  26227. this._mixBufferRegion = mixFunction;
  26228. this.cumulativeWeight = 0;
  26229. this.useCount = 0;
  26230. this.referenceCount = 0;
  26231. }
  26232. Object.assign(PropertyMixer.prototype, {
  26233. // accumulate data in the 'incoming' region into 'accu<i>'
  26234. accumulate: function (accuIndex, weight) {
  26235. // note: happily accumulating nothing when weight = 0, the caller knows
  26236. // the weight and shouldn't have made the call in the first place
  26237. var buffer = this.buffer,
  26238. stride = this.valueSize,
  26239. offset = accuIndex * stride + stride,
  26240. currentWeight = this.cumulativeWeight;
  26241. if (currentWeight === 0) {
  26242. // accuN := incoming * weight
  26243. for (var i = 0; i !== stride; ++i) {
  26244. buffer[offset + i] = buffer[i];
  26245. }
  26246. currentWeight = weight;
  26247. } else {
  26248. // accuN := accuN + incoming * weight
  26249. currentWeight += weight;
  26250. var mix = weight / currentWeight;
  26251. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  26252. }
  26253. this.cumulativeWeight = currentWeight;
  26254. },
  26255. // apply the state of 'accu<i>' to the binding when accus differ
  26256. apply: function (accuIndex) {
  26257. var stride = this.valueSize,
  26258. buffer = this.buffer,
  26259. offset = accuIndex * stride + stride,
  26260. weight = this.cumulativeWeight,
  26261. binding = this.binding;
  26262. this.cumulativeWeight = 0;
  26263. if (weight < 1) {
  26264. // accuN := accuN + original * ( 1 - cumulativeWeight )
  26265. var originalValueOffset = stride * 3;
  26266. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  26267. }
  26268. for (var i = stride, e = stride + stride; i !== e; ++i) {
  26269. if (buffer[i] !== buffer[i + stride]) {
  26270. // value has changed -> update scene graph
  26271. binding.setValue(buffer, offset);
  26272. break;
  26273. }
  26274. }
  26275. },
  26276. // remember the state of the bound property and copy it to both accus
  26277. saveOriginalState: function () {
  26278. var binding = this.binding;
  26279. var buffer = this.buffer,
  26280. stride = this.valueSize,
  26281. originalValueOffset = stride * 3;
  26282. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  26283. for (var i = stride, e = originalValueOffset; i !== e; ++i) {
  26284. buffer[i] = buffer[originalValueOffset + i % stride];
  26285. }
  26286. this.cumulativeWeight = 0;
  26287. },
  26288. // apply the state previously taken via 'saveOriginalState' to the binding
  26289. restoreOriginalState: function () {
  26290. var originalValueOffset = this.valueSize * 3;
  26291. this.binding.setValue(this.buffer, originalValueOffset);
  26292. },
  26293. // mix functions
  26294. _select: function (buffer, dstOffset, srcOffset, t, stride) {
  26295. if (t >= 0.5) {
  26296. for (var i = 0; i !== stride; ++i) {
  26297. buffer[dstOffset + i] = buffer[srcOffset + i];
  26298. }
  26299. }
  26300. },
  26301. _slerp: function (buffer, dstOffset, srcOffset, t) {
  26302. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  26303. },
  26304. _lerp: function (buffer, dstOffset, srcOffset, t, stride) {
  26305. var s = 1 - t;
  26306. for (var i = 0; i !== stride; ++i) {
  26307. var j = dstOffset + i;
  26308. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  26309. }
  26310. }
  26311. });
  26312. /**
  26313. *
  26314. * A reference to a real property in the scene graph.
  26315. *
  26316. *
  26317. * @author Ben Houston / http://clara.io/
  26318. * @author David Sarno / http://lighthaus.us/
  26319. * @author tschw
  26320. */
  26321. // Characters [].:/ are reserved for track binding syntax.
  26322. var _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  26323. var _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  26324. // only latin characters, and the unicode \p{L} is not yet supported. So
  26325. // instead, we exclude reserved characters and match everything else.
  26326. var _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  26327. var _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  26328. // be matched to parse the rest of the track name.
  26329. var _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  26330. var _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  26331. // characters. Accessor may contain any character except closing bracket.
  26332. var _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  26333. // contain any non-bracket characters.
  26334. var _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  26335. var _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  26336. var _supportedObjectNames = ['material', 'materials', 'bones'];
  26337. function Composite(targetGroup, path, optionalParsedPath) {
  26338. var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  26339. this._targetGroup = targetGroup;
  26340. this._bindings = targetGroup.subscribe_(path, parsedPath);
  26341. }
  26342. Object.assign(Composite.prototype, {
  26343. getValue: function (array, offset) {
  26344. this.bind(); // bind all binding
  26345. var firstValidIndex = this._targetGroup.nCachedObjects_,
  26346. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  26347. if (binding !== undefined) binding.getValue(array, offset);
  26348. },
  26349. setValue: function (array, offset) {
  26350. var bindings = this._bindings;
  26351. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  26352. bindings[i].setValue(array, offset);
  26353. }
  26354. },
  26355. bind: function () {
  26356. var bindings = this._bindings;
  26357. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  26358. bindings[i].bind();
  26359. }
  26360. },
  26361. unbind: function () {
  26362. var bindings = this._bindings;
  26363. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  26364. bindings[i].unbind();
  26365. }
  26366. }
  26367. });
  26368. function PropertyBinding(rootNode, path, parsedPath) {
  26369. this.path = path;
  26370. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  26371. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  26372. this.rootNode = rootNode;
  26373. }
  26374. Object.assign(PropertyBinding, {
  26375. Composite: Composite,
  26376. create: function (root, path, parsedPath) {
  26377. if (!(root && root.isAnimationObjectGroup)) {
  26378. return new PropertyBinding(root, path, parsedPath);
  26379. } else {
  26380. return new PropertyBinding.Composite(root, path, parsedPath);
  26381. }
  26382. },
  26383. /**
  26384. * Replaces spaces with underscores and removes unsupported characters from
  26385. * node names, to ensure compatibility with parseTrackName().
  26386. *
  26387. * @param {string} name Node name to be sanitized.
  26388. * @return {string}
  26389. */
  26390. sanitizeNodeName: function (name) {
  26391. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  26392. },
  26393. parseTrackName: function (trackName) {
  26394. var matches = _trackRe.exec(trackName);
  26395. if (!matches) {
  26396. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  26397. }
  26398. var results = {
  26399. // directoryName: matches[ 1 ], // (tschw) currently unused
  26400. nodeName: matches[2],
  26401. objectName: matches[3],
  26402. objectIndex: matches[4],
  26403. propertyName: matches[5],
  26404. // required
  26405. propertyIndex: matches[6]
  26406. };
  26407. var lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  26408. if (lastDot !== undefined && lastDot !== -1) {
  26409. var objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against a whitelist. Otherwise, there
  26410. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  26411. // 'bar' could be the objectName, or part of a nodeName (which can
  26412. // include '.' characters).
  26413. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  26414. results.nodeName = results.nodeName.substring(0, lastDot);
  26415. results.objectName = objectName;
  26416. }
  26417. }
  26418. if (results.propertyName === null || results.propertyName.length === 0) {
  26419. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  26420. }
  26421. return results;
  26422. },
  26423. findNode: function (root, nodeName) {
  26424. if (!nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  26425. return root;
  26426. } // search into skeleton bones.
  26427. if (root.skeleton) {
  26428. var bone = root.skeleton.getBoneByName(nodeName);
  26429. if (bone !== undefined) {
  26430. return bone;
  26431. }
  26432. } // search into node subtree.
  26433. if (root.children) {
  26434. var searchNodeSubtree = function (children) {
  26435. for (var i = 0; i < children.length; i++) {
  26436. var childNode = children[i];
  26437. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  26438. return childNode;
  26439. }
  26440. var result = searchNodeSubtree(childNode.children);
  26441. if (result) return result;
  26442. }
  26443. return null;
  26444. };
  26445. var subTreeNode = searchNodeSubtree(root.children);
  26446. if (subTreeNode) {
  26447. return subTreeNode;
  26448. }
  26449. }
  26450. return null;
  26451. }
  26452. });
  26453. Object.assign(PropertyBinding.prototype, {
  26454. // prototype, continued
  26455. // these are used to "bind" a nonexistent property
  26456. _getValue_unavailable: function () {},
  26457. _setValue_unavailable: function () {},
  26458. BindingType: {
  26459. Direct: 0,
  26460. EntireArray: 1,
  26461. ArrayElement: 2,
  26462. HasFromToArray: 3
  26463. },
  26464. Versioning: {
  26465. None: 0,
  26466. NeedsUpdate: 1,
  26467. MatrixWorldNeedsUpdate: 2
  26468. },
  26469. GetterByBindingType: [function getValue_direct(buffer, offset) {
  26470. buffer[offset] = this.node[this.propertyName];
  26471. }, function getValue_array(buffer, offset) {
  26472. var source = this.resolvedProperty;
  26473. for (var i = 0, n = source.length; i !== n; ++i) {
  26474. buffer[offset++] = source[i];
  26475. }
  26476. }, function getValue_arrayElement(buffer, offset) {
  26477. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  26478. }, function getValue_toArray(buffer, offset) {
  26479. this.resolvedProperty.toArray(buffer, offset);
  26480. }],
  26481. SetterByBindingTypeAndVersioning: [[// Direct
  26482. function setValue_direct(buffer, offset) {
  26483. this.targetObject[this.propertyName] = buffer[offset];
  26484. }, function setValue_direct_setNeedsUpdate(buffer, offset) {
  26485. this.targetObject[this.propertyName] = buffer[offset];
  26486. this.targetObject.needsUpdate = true;
  26487. }, function setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  26488. this.targetObject[this.propertyName] = buffer[offset];
  26489. this.targetObject.matrixWorldNeedsUpdate = true;
  26490. }], [// EntireArray
  26491. function setValue_array(buffer, offset) {
  26492. var dest = this.resolvedProperty;
  26493. for (var i = 0, n = dest.length; i !== n; ++i) {
  26494. dest[i] = buffer[offset++];
  26495. }
  26496. }, function setValue_array_setNeedsUpdate(buffer, offset) {
  26497. var dest = this.resolvedProperty;
  26498. for (var i = 0, n = dest.length; i !== n; ++i) {
  26499. dest[i] = buffer[offset++];
  26500. }
  26501. this.targetObject.needsUpdate = true;
  26502. }, function setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  26503. var dest = this.resolvedProperty;
  26504. for (var i = 0, n = dest.length; i !== n; ++i) {
  26505. dest[i] = buffer[offset++];
  26506. }
  26507. this.targetObject.matrixWorldNeedsUpdate = true;
  26508. }], [// ArrayElement
  26509. function setValue_arrayElement(buffer, offset) {
  26510. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  26511. }, function setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  26512. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  26513. this.targetObject.needsUpdate = true;
  26514. }, function setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  26515. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  26516. this.targetObject.matrixWorldNeedsUpdate = true;
  26517. }], [// HasToFromArray
  26518. function setValue_fromArray(buffer, offset) {
  26519. this.resolvedProperty.fromArray(buffer, offset);
  26520. }, function setValue_fromArray_setNeedsUpdate(buffer, offset) {
  26521. this.resolvedProperty.fromArray(buffer, offset);
  26522. this.targetObject.needsUpdate = true;
  26523. }, function setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  26524. this.resolvedProperty.fromArray(buffer, offset);
  26525. this.targetObject.matrixWorldNeedsUpdate = true;
  26526. }]],
  26527. getValue: function getValue_unbound(targetArray, offset) {
  26528. this.bind();
  26529. this.getValue(targetArray, offset); // Note: This class uses a State pattern on a per-method basis:
  26530. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  26531. // prototype version of these methods with one that represents
  26532. // the bound state. When the property is not found, the methods
  26533. // become no-ops.
  26534. },
  26535. setValue: function getValue_unbound(sourceArray, offset) {
  26536. this.bind();
  26537. this.setValue(sourceArray, offset);
  26538. },
  26539. // create getter / setter pair for a property in the scene graph
  26540. bind: function () {
  26541. var targetObject = this.node,
  26542. parsedPath = this.parsedPath,
  26543. objectName = parsedPath.objectName,
  26544. propertyName = parsedPath.propertyName,
  26545. propertyIndex = parsedPath.propertyIndex;
  26546. if (!targetObject) {
  26547. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  26548. this.node = targetObject;
  26549. } // set fail state so we can just 'return' on error
  26550. this.getValue = this._getValue_unavailable;
  26551. this.setValue = this._setValue_unavailable; // ensure there is a value node
  26552. if (!targetObject) {
  26553. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  26554. return;
  26555. }
  26556. if (objectName) {
  26557. var objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  26558. switch (objectName) {
  26559. case 'materials':
  26560. if (!targetObject.material) {
  26561. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  26562. return;
  26563. }
  26564. if (!targetObject.material.materials) {
  26565. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  26566. return;
  26567. }
  26568. targetObject = targetObject.material.materials;
  26569. break;
  26570. case 'bones':
  26571. if (!targetObject.skeleton) {
  26572. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  26573. return;
  26574. } // potential future optimization: skip this if propertyIndex is already an integer
  26575. // and convert the integer string to a true integer.
  26576. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  26577. for (var i = 0; i < targetObject.length; i++) {
  26578. if (targetObject[i].name === objectIndex) {
  26579. objectIndex = i;
  26580. break;
  26581. }
  26582. }
  26583. break;
  26584. default:
  26585. if (targetObject[objectName] === undefined) {
  26586. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  26587. return;
  26588. }
  26589. targetObject = targetObject[objectName];
  26590. }
  26591. if (objectIndex !== undefined) {
  26592. if (targetObject[objectIndex] === undefined) {
  26593. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  26594. return;
  26595. }
  26596. targetObject = targetObject[objectIndex];
  26597. }
  26598. } // resolve property
  26599. var nodeProperty = targetObject[propertyName];
  26600. if (nodeProperty === undefined) {
  26601. var nodeName = parsedPath.nodeName;
  26602. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  26603. return;
  26604. } // determine versioning scheme
  26605. var versioning = this.Versioning.None;
  26606. this.targetObject = targetObject;
  26607. if (targetObject.needsUpdate !== undefined) {
  26608. // material
  26609. versioning = this.Versioning.NeedsUpdate;
  26610. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  26611. // node transform
  26612. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  26613. } // determine how the property gets bound
  26614. var bindingType = this.BindingType.Direct;
  26615. if (propertyIndex !== undefined) {
  26616. // access a sub element of the property array (only primitives are supported right now)
  26617. if (propertyName === "morphTargetInfluences") {
  26618. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  26619. // support resolving morphTarget names into indices.
  26620. if (!targetObject.geometry) {
  26621. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  26622. return;
  26623. }
  26624. if (targetObject.geometry.isBufferGeometry) {
  26625. if (!targetObject.geometry.morphAttributes) {
  26626. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  26627. return;
  26628. }
  26629. for (var i = 0; i < this.node.geometry.morphAttributes.position.length; i++) {
  26630. if (targetObject.geometry.morphAttributes.position[i].name === propertyIndex) {
  26631. propertyIndex = i;
  26632. break;
  26633. }
  26634. }
  26635. } else {
  26636. if (!targetObject.geometry.morphTargets) {
  26637. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.', this);
  26638. return;
  26639. }
  26640. for (var i = 0; i < this.node.geometry.morphTargets.length; i++) {
  26641. if (targetObject.geometry.morphTargets[i].name === propertyIndex) {
  26642. propertyIndex = i;
  26643. break;
  26644. }
  26645. }
  26646. }
  26647. }
  26648. bindingType = this.BindingType.ArrayElement;
  26649. this.resolvedProperty = nodeProperty;
  26650. this.propertyIndex = propertyIndex;
  26651. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  26652. // must use copy for Object3D.Euler/Quaternion
  26653. bindingType = this.BindingType.HasFromToArray;
  26654. this.resolvedProperty = nodeProperty;
  26655. } else if (Array.isArray(nodeProperty)) {
  26656. bindingType = this.BindingType.EntireArray;
  26657. this.resolvedProperty = nodeProperty;
  26658. } else {
  26659. this.propertyName = propertyName;
  26660. } // select getter / setter
  26661. this.getValue = this.GetterByBindingType[bindingType];
  26662. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  26663. },
  26664. unbind: function () {
  26665. this.node = null; // back to the prototype version of getValue / setValue
  26666. // note: avoiding to mutate the shape of 'this' via 'delete'
  26667. this.getValue = this._getValue_unbound;
  26668. this.setValue = this._setValue_unbound;
  26669. }
  26670. }); //!\ DECLARE ALIAS AFTER assign prototype !
  26671. Object.assign(PropertyBinding.prototype, {
  26672. // initial state of these methods that calls 'bind'
  26673. _getValue_unbound: PropertyBinding.prototype.getValue,
  26674. _setValue_unbound: PropertyBinding.prototype.setValue
  26675. });
  26676. /**
  26677. *
  26678. * A group of objects that receives a shared animation state.
  26679. *
  26680. * Usage:
  26681. *
  26682. * - Add objects you would otherwise pass as 'root' to the
  26683. * constructor or the .clipAction method of AnimationMixer.
  26684. *
  26685. * - Instead pass this object as 'root'.
  26686. *
  26687. * - You can also add and remove objects later when the mixer
  26688. * is running.
  26689. *
  26690. * Note:
  26691. *
  26692. * Objects of this class appear as one object to the mixer,
  26693. * so cache control of the individual objects must be done
  26694. * on the group.
  26695. *
  26696. * Limitation:
  26697. *
  26698. * - The animated properties must be compatible among the
  26699. * all objects in the group.
  26700. *
  26701. * - A single property can either be controlled through a
  26702. * target group or directly, but not both.
  26703. *
  26704. * @author tschw
  26705. */
  26706. function AnimationObjectGroup() {
  26707. this.uuid = _Math.generateUUID(); // cached objects followed by the active ones
  26708. this._objects = Array.prototype.slice.call(arguments);
  26709. this.nCachedObjects_ = 0; // threshold
  26710. // note: read by PropertyBinding.Composite
  26711. var indices = {};
  26712. this._indicesByUUID = indices; // for bookkeeping
  26713. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26714. indices[arguments[i].uuid] = i;
  26715. }
  26716. this._paths = []; // inside: string
  26717. this._parsedPaths = []; // inside: { we don't care, here }
  26718. this._bindings = []; // inside: Array< PropertyBinding >
  26719. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  26720. var scope = this;
  26721. this.stats = {
  26722. objects: {
  26723. get total() {
  26724. return scope._objects.length;
  26725. },
  26726. get inUse() {
  26727. return this.total - scope.nCachedObjects_;
  26728. }
  26729. },
  26730. get bindingsPerObject() {
  26731. return scope._bindings.length;
  26732. }
  26733. };
  26734. }
  26735. Object.assign(AnimationObjectGroup.prototype, {
  26736. isAnimationObjectGroup: true,
  26737. add: function () {
  26738. var objects = this._objects,
  26739. nObjects = objects.length,
  26740. nCachedObjects = this.nCachedObjects_,
  26741. indicesByUUID = this._indicesByUUID,
  26742. paths = this._paths,
  26743. parsedPaths = this._parsedPaths,
  26744. bindings = this._bindings,
  26745. nBindings = bindings.length,
  26746. knownObject = undefined;
  26747. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26748. var object = arguments[i],
  26749. uuid = object.uuid,
  26750. index = indicesByUUID[uuid];
  26751. if (index === undefined) {
  26752. // unknown object -> add it to the ACTIVE region
  26753. index = nObjects++;
  26754. indicesByUUID[uuid] = index;
  26755. objects.push(object); // accounting is done, now do the same for all bindings
  26756. for (var j = 0, m = nBindings; j !== m; ++j) {
  26757. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  26758. }
  26759. } else if (index < nCachedObjects) {
  26760. knownObject = objects[index]; // move existing object to the ACTIVE region
  26761. var firstActiveIndex = --nCachedObjects,
  26762. lastCachedObject = objects[firstActiveIndex];
  26763. indicesByUUID[lastCachedObject.uuid] = index;
  26764. objects[index] = lastCachedObject;
  26765. indicesByUUID[uuid] = firstActiveIndex;
  26766. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  26767. for (var j = 0, m = nBindings; j !== m; ++j) {
  26768. var bindingsForPath = bindings[j],
  26769. lastCached = bindingsForPath[firstActiveIndex],
  26770. binding = bindingsForPath[index];
  26771. bindingsForPath[index] = lastCached;
  26772. if (binding === undefined) {
  26773. // since we do not bother to create new bindings
  26774. // for objects that are cached, the binding may
  26775. // or may not exist
  26776. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  26777. }
  26778. bindingsForPath[firstActiveIndex] = binding;
  26779. }
  26780. } else if (objects[index] !== knownObject) {
  26781. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  26782. } // else the object is already where we want it to be
  26783. } // for arguments
  26784. this.nCachedObjects_ = nCachedObjects;
  26785. },
  26786. remove: function () {
  26787. var objects = this._objects,
  26788. nCachedObjects = this.nCachedObjects_,
  26789. indicesByUUID = this._indicesByUUID,
  26790. bindings = this._bindings,
  26791. nBindings = bindings.length;
  26792. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26793. var object = arguments[i],
  26794. uuid = object.uuid,
  26795. index = indicesByUUID[uuid];
  26796. if (index !== undefined && index >= nCachedObjects) {
  26797. // move existing object into the CACHED region
  26798. var lastCachedIndex = nCachedObjects++,
  26799. firstActiveObject = objects[lastCachedIndex];
  26800. indicesByUUID[firstActiveObject.uuid] = index;
  26801. objects[index] = firstActiveObject;
  26802. indicesByUUID[uuid] = lastCachedIndex;
  26803. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  26804. for (var j = 0, m = nBindings; j !== m; ++j) {
  26805. var bindingsForPath = bindings[j],
  26806. firstActive = bindingsForPath[lastCachedIndex],
  26807. binding = bindingsForPath[index];
  26808. bindingsForPath[index] = firstActive;
  26809. bindingsForPath[lastCachedIndex] = binding;
  26810. }
  26811. }
  26812. } // for arguments
  26813. this.nCachedObjects_ = nCachedObjects;
  26814. },
  26815. // remove & forget
  26816. uncache: function () {
  26817. var objects = this._objects,
  26818. nObjects = objects.length,
  26819. nCachedObjects = this.nCachedObjects_,
  26820. indicesByUUID = this._indicesByUUID,
  26821. bindings = this._bindings,
  26822. nBindings = bindings.length;
  26823. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26824. var object = arguments[i],
  26825. uuid = object.uuid,
  26826. index = indicesByUUID[uuid];
  26827. if (index !== undefined) {
  26828. delete indicesByUUID[uuid];
  26829. if (index < nCachedObjects) {
  26830. // object is cached, shrink the CACHED region
  26831. var firstActiveIndex = --nCachedObjects,
  26832. lastCachedObject = objects[firstActiveIndex],
  26833. lastIndex = --nObjects,
  26834. lastObject = objects[lastIndex]; // last cached object takes this object's place
  26835. indicesByUUID[lastCachedObject.uuid] = index;
  26836. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  26837. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  26838. objects[firstActiveIndex] = lastObject;
  26839. objects.pop(); // accounting is done, now do the same for all bindings
  26840. for (var j = 0, m = nBindings; j !== m; ++j) {
  26841. var bindingsForPath = bindings[j],
  26842. lastCached = bindingsForPath[firstActiveIndex],
  26843. last = bindingsForPath[lastIndex];
  26844. bindingsForPath[index] = lastCached;
  26845. bindingsForPath[firstActiveIndex] = last;
  26846. bindingsForPath.pop();
  26847. }
  26848. } else {
  26849. // object is active, just swap with the last and pop
  26850. var lastIndex = --nObjects,
  26851. lastObject = objects[lastIndex];
  26852. indicesByUUID[lastObject.uuid] = index;
  26853. objects[index] = lastObject;
  26854. objects.pop(); // accounting is done, now do the same for all bindings
  26855. for (var j = 0, m = nBindings; j !== m; ++j) {
  26856. var bindingsForPath = bindings[j];
  26857. bindingsForPath[index] = bindingsForPath[lastIndex];
  26858. bindingsForPath.pop();
  26859. }
  26860. } // cached or active
  26861. } // if object is known
  26862. } // for arguments
  26863. this.nCachedObjects_ = nCachedObjects;
  26864. },
  26865. // Internal interface used by befriended PropertyBinding.Composite:
  26866. subscribe_: function (path, parsedPath) {
  26867. // returns an array of bindings for the given path that is changed
  26868. // according to the contained objects in the group
  26869. var indicesByPath = this._bindingsIndicesByPath,
  26870. index = indicesByPath[path],
  26871. bindings = this._bindings;
  26872. if (index !== undefined) return bindings[index];
  26873. var paths = this._paths,
  26874. parsedPaths = this._parsedPaths,
  26875. objects = this._objects,
  26876. nObjects = objects.length,
  26877. nCachedObjects = this.nCachedObjects_,
  26878. bindingsForPath = new Array(nObjects);
  26879. index = bindings.length;
  26880. indicesByPath[path] = index;
  26881. paths.push(path);
  26882. parsedPaths.push(parsedPath);
  26883. bindings.push(bindingsForPath);
  26884. for (var i = nCachedObjects, n = objects.length; i !== n; ++i) {
  26885. var object = objects[i];
  26886. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  26887. }
  26888. return bindingsForPath;
  26889. },
  26890. unsubscribe_: function (path) {
  26891. // tells the group to forget about a property path and no longer
  26892. // update the array previously obtained with 'subscribe_'
  26893. var indicesByPath = this._bindingsIndicesByPath,
  26894. index = indicesByPath[path];
  26895. if (index !== undefined) {
  26896. var paths = this._paths,
  26897. parsedPaths = this._parsedPaths,
  26898. bindings = this._bindings,
  26899. lastBindingsIndex = bindings.length - 1,
  26900. lastBindings = bindings[lastBindingsIndex],
  26901. lastBindingsPath = path[lastBindingsIndex];
  26902. indicesByPath[lastBindingsPath] = index;
  26903. bindings[index] = lastBindings;
  26904. bindings.pop();
  26905. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  26906. parsedPaths.pop();
  26907. paths[index] = paths[lastBindingsIndex];
  26908. paths.pop();
  26909. }
  26910. }
  26911. });
  26912. /**
  26913. *
  26914. * Action provided by AnimationMixer for scheduling clip playback on specific
  26915. * objects.
  26916. *
  26917. * @author Ben Houston / http://clara.io/
  26918. * @author David Sarno / http://lighthaus.us/
  26919. * @author tschw
  26920. *
  26921. */
  26922. function AnimationAction(mixer, clip, localRoot) {
  26923. this._mixer = mixer;
  26924. this._clip = clip;
  26925. this._localRoot = localRoot || null;
  26926. var tracks = clip.tracks,
  26927. nTracks = tracks.length,
  26928. interpolants = new Array(nTracks);
  26929. var interpolantSettings = {
  26930. endingStart: ZeroCurvatureEnding,
  26931. endingEnd: ZeroCurvatureEnding
  26932. };
  26933. for (var i = 0; i !== nTracks; ++i) {
  26934. var interpolant = tracks[i].createInterpolant(null);
  26935. interpolants[i] = interpolant;
  26936. interpolant.settings = interpolantSettings;
  26937. }
  26938. this._interpolantSettings = interpolantSettings;
  26939. this._interpolants = interpolants; // bound by the mixer
  26940. // inside: PropertyMixer (managed by the mixer)
  26941. this._propertyBindings = new Array(nTracks);
  26942. this._cacheIndex = null; // for the memory manager
  26943. this._byClipCacheIndex = null; // for the memory manager
  26944. this._timeScaleInterpolant = null;
  26945. this._weightInterpolant = null;
  26946. this.loop = LoopRepeat;
  26947. this._loopCount = -1; // global mixer time when the action is to be started
  26948. // it's set back to 'null' upon start of the action
  26949. this._startTime = null; // scaled local time of the action
  26950. // gets clamped or wrapped to 0..clip.duration according to loop
  26951. this.time = 0;
  26952. this.timeScale = 1;
  26953. this._effectiveTimeScale = 1;
  26954. this.weight = 1;
  26955. this._effectiveWeight = 1;
  26956. this.repetitions = Infinity; // no. of repetitions when looping
  26957. this.paused = false; // true -> zero effective time scale
  26958. this.enabled = true; // false -> zero effective weight
  26959. this.clampWhenFinished = false; // keep feeding the last frame?
  26960. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  26961. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  26962. }
  26963. Object.assign(AnimationAction.prototype, {
  26964. // State & Scheduling
  26965. play: function () {
  26966. this._mixer._activateAction(this);
  26967. return this;
  26968. },
  26969. stop: function () {
  26970. this._mixer._deactivateAction(this);
  26971. return this.reset();
  26972. },
  26973. reset: function () {
  26974. this.paused = false;
  26975. this.enabled = true;
  26976. this.time = 0; // restart clip
  26977. this._loopCount = -1; // forget previous loops
  26978. this._startTime = null; // forget scheduling
  26979. return this.stopFading().stopWarping();
  26980. },
  26981. isRunning: function () {
  26982. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  26983. },
  26984. // return true when play has been called
  26985. isScheduled: function () {
  26986. return this._mixer._isActiveAction(this);
  26987. },
  26988. startAt: function (time) {
  26989. this._startTime = time;
  26990. return this;
  26991. },
  26992. setLoop: function (mode, repetitions) {
  26993. this.loop = mode;
  26994. this.repetitions = repetitions;
  26995. return this;
  26996. },
  26997. // Weight
  26998. // set the weight stopping any scheduled fading
  26999. // although .enabled = false yields an effective weight of zero, this
  27000. // method does *not* change .enabled, because it would be confusing
  27001. setEffectiveWeight: function (weight) {
  27002. this.weight = weight; // note: same logic as when updated at runtime
  27003. this._effectiveWeight = this.enabled ? weight : 0;
  27004. return this.stopFading();
  27005. },
  27006. // return the weight considering fading and .enabled
  27007. getEffectiveWeight: function () {
  27008. return this._effectiveWeight;
  27009. },
  27010. fadeIn: function (duration) {
  27011. return this._scheduleFading(duration, 0, 1);
  27012. },
  27013. fadeOut: function (duration) {
  27014. return this._scheduleFading(duration, 1, 0);
  27015. },
  27016. crossFadeFrom: function (fadeOutAction, duration, warp) {
  27017. fadeOutAction.fadeOut(duration);
  27018. this.fadeIn(duration);
  27019. if (warp) {
  27020. var fadeInDuration = this._clip.duration,
  27021. fadeOutDuration = fadeOutAction._clip.duration,
  27022. startEndRatio = fadeOutDuration / fadeInDuration,
  27023. endStartRatio = fadeInDuration / fadeOutDuration;
  27024. fadeOutAction.warp(1.0, startEndRatio, duration);
  27025. this.warp(endStartRatio, 1.0, duration);
  27026. }
  27027. return this;
  27028. },
  27029. crossFadeTo: function (fadeInAction, duration, warp) {
  27030. return fadeInAction.crossFadeFrom(this, duration, warp);
  27031. },
  27032. stopFading: function () {
  27033. var weightInterpolant = this._weightInterpolant;
  27034. if (weightInterpolant !== null) {
  27035. this._weightInterpolant = null;
  27036. this._mixer._takeBackControlInterpolant(weightInterpolant);
  27037. }
  27038. return this;
  27039. },
  27040. // Time Scale Control
  27041. // set the time scale stopping any scheduled warping
  27042. // although .paused = true yields an effective time scale of zero, this
  27043. // method does *not* change .paused, because it would be confusing
  27044. setEffectiveTimeScale: function (timeScale) {
  27045. this.timeScale = timeScale;
  27046. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  27047. return this.stopWarping();
  27048. },
  27049. // return the time scale considering warping and .paused
  27050. getEffectiveTimeScale: function () {
  27051. return this._effectiveTimeScale;
  27052. },
  27053. setDuration: function (duration) {
  27054. this.timeScale = this._clip.duration / duration;
  27055. return this.stopWarping();
  27056. },
  27057. syncWith: function (action) {
  27058. this.time = action.time;
  27059. this.timeScale = action.timeScale;
  27060. return this.stopWarping();
  27061. },
  27062. halt: function (duration) {
  27063. return this.warp(this._effectiveTimeScale, 0, duration);
  27064. },
  27065. warp: function (startTimeScale, endTimeScale, duration) {
  27066. var mixer = this._mixer,
  27067. now = mixer.time,
  27068. interpolant = this._timeScaleInterpolant,
  27069. timeScale = this.timeScale;
  27070. if (interpolant === null) {
  27071. interpolant = mixer._lendControlInterpolant();
  27072. this._timeScaleInterpolant = interpolant;
  27073. }
  27074. var times = interpolant.parameterPositions,
  27075. values = interpolant.sampleValues;
  27076. times[0] = now;
  27077. times[1] = now + duration;
  27078. values[0] = startTimeScale / timeScale;
  27079. values[1] = endTimeScale / timeScale;
  27080. return this;
  27081. },
  27082. stopWarping: function () {
  27083. var timeScaleInterpolant = this._timeScaleInterpolant;
  27084. if (timeScaleInterpolant !== null) {
  27085. this._timeScaleInterpolant = null;
  27086. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  27087. }
  27088. return this;
  27089. },
  27090. // Object Accessors
  27091. getMixer: function () {
  27092. return this._mixer;
  27093. },
  27094. getClip: function () {
  27095. return this._clip;
  27096. },
  27097. getRoot: function () {
  27098. return this._localRoot || this._mixer._root;
  27099. },
  27100. // Interna
  27101. _update: function (time, deltaTime, timeDirection, accuIndex) {
  27102. // called by the mixer
  27103. if (!this.enabled) {
  27104. // call ._updateWeight() to update ._effectiveWeight
  27105. this._updateWeight(time);
  27106. return;
  27107. }
  27108. var startTime = this._startTime;
  27109. if (startTime !== null) {
  27110. // check for scheduled start of action
  27111. var timeRunning = (time - startTime) * timeDirection;
  27112. if (timeRunning < 0 || timeDirection === 0) {
  27113. return; // yet to come / don't decide when delta = 0
  27114. } // start
  27115. this._startTime = null; // unschedule
  27116. deltaTime = timeDirection * timeRunning;
  27117. } // apply time scale and advance time
  27118. deltaTime *= this._updateTimeScale(time);
  27119. var clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  27120. // an effective weight of 0
  27121. var weight = this._updateWeight(time);
  27122. if (weight > 0) {
  27123. var interpolants = this._interpolants;
  27124. var propertyMixers = this._propertyBindings;
  27125. for (var j = 0, m = interpolants.length; j !== m; ++j) {
  27126. interpolants[j].evaluate(clipTime);
  27127. propertyMixers[j].accumulate(accuIndex, weight);
  27128. }
  27129. }
  27130. },
  27131. _updateWeight: function (time) {
  27132. var weight = 0;
  27133. if (this.enabled) {
  27134. weight = this.weight;
  27135. var interpolant = this._weightInterpolant;
  27136. if (interpolant !== null) {
  27137. var interpolantValue = interpolant.evaluate(time)[0];
  27138. weight *= interpolantValue;
  27139. if (time > interpolant.parameterPositions[1]) {
  27140. this.stopFading();
  27141. if (interpolantValue === 0) {
  27142. // faded out, disable
  27143. this.enabled = false;
  27144. }
  27145. }
  27146. }
  27147. }
  27148. this._effectiveWeight = weight;
  27149. return weight;
  27150. },
  27151. _updateTimeScale: function (time) {
  27152. var timeScale = 0;
  27153. if (!this.paused) {
  27154. timeScale = this.timeScale;
  27155. var interpolant = this._timeScaleInterpolant;
  27156. if (interpolant !== null) {
  27157. var interpolantValue = interpolant.evaluate(time)[0];
  27158. timeScale *= interpolantValue;
  27159. if (time > interpolant.parameterPositions[1]) {
  27160. this.stopWarping();
  27161. if (timeScale === 0) {
  27162. // motion has halted, pause
  27163. this.paused = true;
  27164. } else {
  27165. // warp done - apply final time scale
  27166. this.timeScale = timeScale;
  27167. }
  27168. }
  27169. }
  27170. }
  27171. this._effectiveTimeScale = timeScale;
  27172. return timeScale;
  27173. },
  27174. _updateTime: function (deltaTime) {
  27175. var time = this.time + deltaTime;
  27176. var duration = this._clip.duration;
  27177. var loop = this.loop;
  27178. var loopCount = this._loopCount;
  27179. var pingPong = loop === LoopPingPong;
  27180. if (deltaTime === 0) {
  27181. if (loopCount === -1) return time;
  27182. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  27183. }
  27184. if (loop === LoopOnce) {
  27185. if (loopCount === -1) {
  27186. // just started
  27187. this._loopCount = 0;
  27188. this._setEndings(true, true, false);
  27189. }
  27190. handle_stop: {
  27191. if (time >= duration) {
  27192. time = duration;
  27193. } else if (time < 0) {
  27194. time = 0;
  27195. } else {
  27196. this.time = time;
  27197. break handle_stop;
  27198. }
  27199. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  27200. this.time = time;
  27201. this._mixer.dispatchEvent({
  27202. type: 'finished',
  27203. action: this,
  27204. direction: deltaTime < 0 ? -1 : 1
  27205. });
  27206. }
  27207. } else {
  27208. // repetitive Repeat or PingPong
  27209. if (loopCount === -1) {
  27210. // just started
  27211. if (deltaTime >= 0) {
  27212. loopCount = 0;
  27213. this._setEndings(true, this.repetitions === 0, pingPong);
  27214. } else {
  27215. // when looping in reverse direction, the initial
  27216. // transition through zero counts as a repetition,
  27217. // so leave loopCount at -1
  27218. this._setEndings(this.repetitions === 0, true, pingPong);
  27219. }
  27220. }
  27221. if (time >= duration || time < 0) {
  27222. // wrap around
  27223. var loopDelta = Math.floor(time / duration); // signed
  27224. time -= duration * loopDelta;
  27225. loopCount += Math.abs(loopDelta);
  27226. var pending = this.repetitions - loopCount;
  27227. if (pending <= 0) {
  27228. // have to stop (switch state, clamp time, fire event)
  27229. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  27230. time = deltaTime > 0 ? duration : 0;
  27231. this.time = time;
  27232. this._mixer.dispatchEvent({
  27233. type: 'finished',
  27234. action: this,
  27235. direction: deltaTime > 0 ? 1 : -1
  27236. });
  27237. } else {
  27238. // keep running
  27239. if (pending === 1) {
  27240. // entering the last round
  27241. var atStart = deltaTime < 0;
  27242. this._setEndings(atStart, !atStart, pingPong);
  27243. } else {
  27244. this._setEndings(false, false, pingPong);
  27245. }
  27246. this._loopCount = loopCount;
  27247. this.time = time;
  27248. this._mixer.dispatchEvent({
  27249. type: 'loop',
  27250. action: this,
  27251. loopDelta: loopDelta
  27252. });
  27253. }
  27254. } else {
  27255. this.time = time;
  27256. }
  27257. if (pingPong && (loopCount & 1) === 1) {
  27258. // invert time for the "pong round"
  27259. return duration - time;
  27260. }
  27261. }
  27262. return time;
  27263. },
  27264. _setEndings: function (atStart, atEnd, pingPong) {
  27265. var settings = this._interpolantSettings;
  27266. if (pingPong) {
  27267. settings.endingStart = ZeroSlopeEnding;
  27268. settings.endingEnd = ZeroSlopeEnding;
  27269. } else {
  27270. // assuming for LoopOnce atStart == atEnd == true
  27271. if (atStart) {
  27272. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27273. } else {
  27274. settings.endingStart = WrapAroundEnding;
  27275. }
  27276. if (atEnd) {
  27277. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27278. } else {
  27279. settings.endingEnd = WrapAroundEnding;
  27280. }
  27281. }
  27282. },
  27283. _scheduleFading: function (duration, weightNow, weightThen) {
  27284. var mixer = this._mixer,
  27285. now = mixer.time,
  27286. interpolant = this._weightInterpolant;
  27287. if (interpolant === null) {
  27288. interpolant = mixer._lendControlInterpolant();
  27289. this._weightInterpolant = interpolant;
  27290. }
  27291. var times = interpolant.parameterPositions,
  27292. values = interpolant.sampleValues;
  27293. times[0] = now;
  27294. values[0] = weightNow;
  27295. times[1] = now + duration;
  27296. values[1] = weightThen;
  27297. return this;
  27298. }
  27299. });
  27300. /**
  27301. *
  27302. * Player for AnimationClips.
  27303. *
  27304. *
  27305. * @author Ben Houston / http://clara.io/
  27306. * @author David Sarno / http://lighthaus.us/
  27307. * @author tschw
  27308. */
  27309. function AnimationMixer(root) {
  27310. this._root = root;
  27311. this._initMemoryManager();
  27312. this._accuIndex = 0;
  27313. this.time = 0;
  27314. this.timeScale = 1.0;
  27315. }
  27316. AnimationMixer.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  27317. constructor: AnimationMixer,
  27318. _bindAction: function (action, prototypeAction) {
  27319. var root = action._localRoot || this._root,
  27320. tracks = action._clip.tracks,
  27321. nTracks = tracks.length,
  27322. bindings = action._propertyBindings,
  27323. interpolants = action._interpolants,
  27324. rootUuid = root.uuid,
  27325. bindingsByRoot = this._bindingsByRootAndName,
  27326. bindingsByName = bindingsByRoot[rootUuid];
  27327. if (bindingsByName === undefined) {
  27328. bindingsByName = {};
  27329. bindingsByRoot[rootUuid] = bindingsByName;
  27330. }
  27331. for (var i = 0; i !== nTracks; ++i) {
  27332. var track = tracks[i],
  27333. trackName = track.name,
  27334. binding = bindingsByName[trackName];
  27335. if (binding !== undefined) {
  27336. bindings[i] = binding;
  27337. } else {
  27338. binding = bindings[i];
  27339. if (binding !== undefined) {
  27340. // existing binding, make sure the cache knows
  27341. if (binding._cacheIndex === null) {
  27342. ++binding.referenceCount;
  27343. this._addInactiveBinding(binding, rootUuid, trackName);
  27344. }
  27345. continue;
  27346. }
  27347. var path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  27348. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  27349. ++binding.referenceCount;
  27350. this._addInactiveBinding(binding, rootUuid, trackName);
  27351. bindings[i] = binding;
  27352. }
  27353. interpolants[i].resultBuffer = binding.buffer;
  27354. }
  27355. },
  27356. _activateAction: function (action) {
  27357. if (!this._isActiveAction(action)) {
  27358. if (action._cacheIndex === null) {
  27359. // this action has been forgotten by the cache, but the user
  27360. // appears to be still using it -> rebind
  27361. var rootUuid = (action._localRoot || this._root).uuid,
  27362. clipUuid = action._clip.uuid,
  27363. actionsForClip = this._actionsByClip[clipUuid];
  27364. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  27365. this._addInactiveAction(action, clipUuid, rootUuid);
  27366. }
  27367. var bindings = action._propertyBindings; // increment reference counts / sort out state
  27368. for (var i = 0, n = bindings.length; i !== n; ++i) {
  27369. var binding = bindings[i];
  27370. if (binding.useCount++ === 0) {
  27371. this._lendBinding(binding);
  27372. binding.saveOriginalState();
  27373. }
  27374. }
  27375. this._lendAction(action);
  27376. }
  27377. },
  27378. _deactivateAction: function (action) {
  27379. if (this._isActiveAction(action)) {
  27380. var bindings = action._propertyBindings; // decrement reference counts / sort out state
  27381. for (var i = 0, n = bindings.length; i !== n; ++i) {
  27382. var binding = bindings[i];
  27383. if (--binding.useCount === 0) {
  27384. binding.restoreOriginalState();
  27385. this._takeBackBinding(binding);
  27386. }
  27387. }
  27388. this._takeBackAction(action);
  27389. }
  27390. },
  27391. // Memory manager
  27392. _initMemoryManager: function () {
  27393. this._actions = []; // 'nActiveActions' followed by inactive ones
  27394. this._nActiveActions = 0;
  27395. this._actionsByClip = {}; // inside:
  27396. // {
  27397. // knownActions: Array< AnimationAction > - used as prototypes
  27398. // actionByRoot: AnimationAction - lookup
  27399. // }
  27400. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  27401. this._nActiveBindings = 0;
  27402. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  27403. this._controlInterpolants = []; // same game as above
  27404. this._nActiveControlInterpolants = 0;
  27405. var scope = this;
  27406. this.stats = {
  27407. actions: {
  27408. get total() {
  27409. return scope._actions.length;
  27410. },
  27411. get inUse() {
  27412. return scope._nActiveActions;
  27413. }
  27414. },
  27415. bindings: {
  27416. get total() {
  27417. return scope._bindings.length;
  27418. },
  27419. get inUse() {
  27420. return scope._nActiveBindings;
  27421. }
  27422. },
  27423. controlInterpolants: {
  27424. get total() {
  27425. return scope._controlInterpolants.length;
  27426. },
  27427. get inUse() {
  27428. return scope._nActiveControlInterpolants;
  27429. }
  27430. }
  27431. };
  27432. },
  27433. // Memory management for AnimationAction objects
  27434. _isActiveAction: function (action) {
  27435. var index = action._cacheIndex;
  27436. return index !== null && index < this._nActiveActions;
  27437. },
  27438. _addInactiveAction: function (action, clipUuid, rootUuid) {
  27439. var actions = this._actions,
  27440. actionsByClip = this._actionsByClip,
  27441. actionsForClip = actionsByClip[clipUuid];
  27442. if (actionsForClip === undefined) {
  27443. actionsForClip = {
  27444. knownActions: [action],
  27445. actionByRoot: {}
  27446. };
  27447. action._byClipCacheIndex = 0;
  27448. actionsByClip[clipUuid] = actionsForClip;
  27449. } else {
  27450. var knownActions = actionsForClip.knownActions;
  27451. action._byClipCacheIndex = knownActions.length;
  27452. knownActions.push(action);
  27453. }
  27454. action._cacheIndex = actions.length;
  27455. actions.push(action);
  27456. actionsForClip.actionByRoot[rootUuid] = action;
  27457. },
  27458. _removeInactiveAction: function (action) {
  27459. var actions = this._actions,
  27460. lastInactiveAction = actions[actions.length - 1],
  27461. cacheIndex = action._cacheIndex;
  27462. lastInactiveAction._cacheIndex = cacheIndex;
  27463. actions[cacheIndex] = lastInactiveAction;
  27464. actions.pop();
  27465. action._cacheIndex = null;
  27466. var clipUuid = action._clip.uuid,
  27467. actionsByClip = this._actionsByClip,
  27468. actionsForClip = actionsByClip[clipUuid],
  27469. knownActionsForClip = actionsForClip.knownActions,
  27470. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  27471. byClipCacheIndex = action._byClipCacheIndex;
  27472. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  27473. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  27474. knownActionsForClip.pop();
  27475. action._byClipCacheIndex = null;
  27476. var actionByRoot = actionsForClip.actionByRoot,
  27477. rootUuid = (action._localRoot || this._root).uuid;
  27478. delete actionByRoot[rootUuid];
  27479. if (knownActionsForClip.length === 0) {
  27480. delete actionsByClip[clipUuid];
  27481. }
  27482. this._removeInactiveBindingsForAction(action);
  27483. },
  27484. _removeInactiveBindingsForAction: function (action) {
  27485. var bindings = action._propertyBindings;
  27486. for (var i = 0, n = bindings.length; i !== n; ++i) {
  27487. var binding = bindings[i];
  27488. if (--binding.referenceCount === 0) {
  27489. this._removeInactiveBinding(binding);
  27490. }
  27491. }
  27492. },
  27493. _lendAction: function (action) {
  27494. // [ active actions | inactive actions ]
  27495. // [ active actions >| inactive actions ]
  27496. // s a
  27497. // <-swap->
  27498. // a s
  27499. var actions = this._actions,
  27500. prevIndex = action._cacheIndex,
  27501. lastActiveIndex = this._nActiveActions++,
  27502. firstInactiveAction = actions[lastActiveIndex];
  27503. action._cacheIndex = lastActiveIndex;
  27504. actions[lastActiveIndex] = action;
  27505. firstInactiveAction._cacheIndex = prevIndex;
  27506. actions[prevIndex] = firstInactiveAction;
  27507. },
  27508. _takeBackAction: function (action) {
  27509. // [ active actions | inactive actions ]
  27510. // [ active actions |< inactive actions ]
  27511. // a s
  27512. // <-swap->
  27513. // s a
  27514. var actions = this._actions,
  27515. prevIndex = action._cacheIndex,
  27516. firstInactiveIndex = --this._nActiveActions,
  27517. lastActiveAction = actions[firstInactiveIndex];
  27518. action._cacheIndex = firstInactiveIndex;
  27519. actions[firstInactiveIndex] = action;
  27520. lastActiveAction._cacheIndex = prevIndex;
  27521. actions[prevIndex] = lastActiveAction;
  27522. },
  27523. // Memory management for PropertyMixer objects
  27524. _addInactiveBinding: function (binding, rootUuid, trackName) {
  27525. var bindingsByRoot = this._bindingsByRootAndName,
  27526. bindingByName = bindingsByRoot[rootUuid],
  27527. bindings = this._bindings;
  27528. if (bindingByName === undefined) {
  27529. bindingByName = {};
  27530. bindingsByRoot[rootUuid] = bindingByName;
  27531. }
  27532. bindingByName[trackName] = binding;
  27533. binding._cacheIndex = bindings.length;
  27534. bindings.push(binding);
  27535. },
  27536. _removeInactiveBinding: function (binding) {
  27537. var bindings = this._bindings,
  27538. propBinding = binding.binding,
  27539. rootUuid = propBinding.rootNode.uuid,
  27540. trackName = propBinding.path,
  27541. bindingsByRoot = this._bindingsByRootAndName,
  27542. bindingByName = bindingsByRoot[rootUuid],
  27543. lastInactiveBinding = bindings[bindings.length - 1],
  27544. cacheIndex = binding._cacheIndex;
  27545. lastInactiveBinding._cacheIndex = cacheIndex;
  27546. bindings[cacheIndex] = lastInactiveBinding;
  27547. bindings.pop();
  27548. delete bindingByName[trackName];
  27549. if (Object.keys(bindingByName).length === 0) {
  27550. delete bindingsByRoot[rootUuid];
  27551. }
  27552. },
  27553. _lendBinding: function (binding) {
  27554. var bindings = this._bindings,
  27555. prevIndex = binding._cacheIndex,
  27556. lastActiveIndex = this._nActiveBindings++,
  27557. firstInactiveBinding = bindings[lastActiveIndex];
  27558. binding._cacheIndex = lastActiveIndex;
  27559. bindings[lastActiveIndex] = binding;
  27560. firstInactiveBinding._cacheIndex = prevIndex;
  27561. bindings[prevIndex] = firstInactiveBinding;
  27562. },
  27563. _takeBackBinding: function (binding) {
  27564. var bindings = this._bindings,
  27565. prevIndex = binding._cacheIndex,
  27566. firstInactiveIndex = --this._nActiveBindings,
  27567. lastActiveBinding = bindings[firstInactiveIndex];
  27568. binding._cacheIndex = firstInactiveIndex;
  27569. bindings[firstInactiveIndex] = binding;
  27570. lastActiveBinding._cacheIndex = prevIndex;
  27571. bindings[prevIndex] = lastActiveBinding;
  27572. },
  27573. // Memory management of Interpolants for weight and time scale
  27574. _lendControlInterpolant: function () {
  27575. var interpolants = this._controlInterpolants,
  27576. lastActiveIndex = this._nActiveControlInterpolants++,
  27577. interpolant = interpolants[lastActiveIndex];
  27578. if (interpolant === undefined) {
  27579. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
  27580. interpolant.__cacheIndex = lastActiveIndex;
  27581. interpolants[lastActiveIndex] = interpolant;
  27582. }
  27583. return interpolant;
  27584. },
  27585. _takeBackControlInterpolant: function (interpolant) {
  27586. var interpolants = this._controlInterpolants,
  27587. prevIndex = interpolant.__cacheIndex,
  27588. firstInactiveIndex = --this._nActiveControlInterpolants,
  27589. lastActiveInterpolant = interpolants[firstInactiveIndex];
  27590. interpolant.__cacheIndex = firstInactiveIndex;
  27591. interpolants[firstInactiveIndex] = interpolant;
  27592. lastActiveInterpolant.__cacheIndex = prevIndex;
  27593. interpolants[prevIndex] = lastActiveInterpolant;
  27594. },
  27595. _controlInterpolantsResultBuffer: new Float32Array(1),
  27596. // return an action for a clip optionally using a custom root target
  27597. // object (this method allocates a lot of dynamic memory in case a
  27598. // previously unknown clip/root combination is specified)
  27599. clipAction: function (clip, optionalRoot) {
  27600. var root = optionalRoot || this._root,
  27601. rootUuid = root.uuid,
  27602. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  27603. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  27604. actionsForClip = this._actionsByClip[clipUuid],
  27605. prototypeAction = null;
  27606. if (actionsForClip !== undefined) {
  27607. var existingAction = actionsForClip.actionByRoot[rootUuid];
  27608. if (existingAction !== undefined) {
  27609. return existingAction;
  27610. } // we know the clip, so we don't have to parse all
  27611. // the bindings again but can just copy
  27612. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  27613. if (clipObject === null) clipObject = prototypeAction._clip;
  27614. } // clip must be known when specified via string
  27615. if (clipObject === null) return null; // allocate all resources required to run it
  27616. var newAction = new AnimationAction(this, clipObject, optionalRoot);
  27617. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  27618. this._addInactiveAction(newAction, clipUuid, rootUuid);
  27619. return newAction;
  27620. },
  27621. // get an existing action
  27622. existingAction: function (clip, optionalRoot) {
  27623. var root = optionalRoot || this._root,
  27624. rootUuid = root.uuid,
  27625. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  27626. clipUuid = clipObject ? clipObject.uuid : clip,
  27627. actionsForClip = this._actionsByClip[clipUuid];
  27628. if (actionsForClip !== undefined) {
  27629. return actionsForClip.actionByRoot[rootUuid] || null;
  27630. }
  27631. return null;
  27632. },
  27633. // deactivates all previously scheduled actions
  27634. stopAllAction: function () {
  27635. var actions = this._actions,
  27636. nActions = this._nActiveActions,
  27637. bindings = this._bindings,
  27638. nBindings = this._nActiveBindings;
  27639. this._nActiveActions = 0;
  27640. this._nActiveBindings = 0;
  27641. for (var i = 0; i !== nActions; ++i) {
  27642. actions[i].reset();
  27643. }
  27644. for (var i = 0; i !== nBindings; ++i) {
  27645. bindings[i].useCount = 0;
  27646. }
  27647. return this;
  27648. },
  27649. // advance the time and update apply the animation
  27650. update: function (deltaTime) {
  27651. deltaTime *= this.timeScale;
  27652. var actions = this._actions,
  27653. nActions = this._nActiveActions,
  27654. time = this.time += deltaTime,
  27655. timeDirection = Math.sign(deltaTime),
  27656. accuIndex = this._accuIndex ^= 1; // run active actions
  27657. for (var i = 0; i !== nActions; ++i) {
  27658. var action = actions[i];
  27659. action._update(time, deltaTime, timeDirection, accuIndex);
  27660. } // update scene graph
  27661. var bindings = this._bindings,
  27662. nBindings = this._nActiveBindings;
  27663. for (var i = 0; i !== nBindings; ++i) {
  27664. bindings[i].apply(accuIndex);
  27665. }
  27666. return this;
  27667. },
  27668. // Allows you to seek to a specific time in an animation.
  27669. setTime: function (timeInSeconds) {
  27670. this.time = 0; // Zero out time attribute for AnimationMixer object;
  27671. for (var i = 0; i < this._actions.length; i++) {
  27672. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  27673. }
  27674. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  27675. },
  27676. // return this mixer's root target object
  27677. getRoot: function () {
  27678. return this._root;
  27679. },
  27680. // free all resources specific to a particular clip
  27681. uncacheClip: function (clip) {
  27682. var actions = this._actions,
  27683. clipUuid = clip.uuid,
  27684. actionsByClip = this._actionsByClip,
  27685. actionsForClip = actionsByClip[clipUuid];
  27686. if (actionsForClip !== undefined) {
  27687. // note: just calling _removeInactiveAction would mess up the
  27688. // iteration state and also require updating the state we can
  27689. // just throw away
  27690. var actionsToRemove = actionsForClip.knownActions;
  27691. for (var i = 0, n = actionsToRemove.length; i !== n; ++i) {
  27692. var action = actionsToRemove[i];
  27693. this._deactivateAction(action);
  27694. var cacheIndex = action._cacheIndex,
  27695. lastInactiveAction = actions[actions.length - 1];
  27696. action._cacheIndex = null;
  27697. action._byClipCacheIndex = null;
  27698. lastInactiveAction._cacheIndex = cacheIndex;
  27699. actions[cacheIndex] = lastInactiveAction;
  27700. actions.pop();
  27701. this._removeInactiveBindingsForAction(action);
  27702. }
  27703. delete actionsByClip[clipUuid];
  27704. }
  27705. },
  27706. // free all resources specific to a particular root target object
  27707. uncacheRoot: function (root) {
  27708. var rootUuid = root.uuid,
  27709. actionsByClip = this._actionsByClip;
  27710. for (var clipUuid in actionsByClip) {
  27711. var actionByRoot = actionsByClip[clipUuid].actionByRoot,
  27712. action = actionByRoot[rootUuid];
  27713. if (action !== undefined) {
  27714. this._deactivateAction(action);
  27715. this._removeInactiveAction(action);
  27716. }
  27717. }
  27718. var bindingsByRoot = this._bindingsByRootAndName,
  27719. bindingByName = bindingsByRoot[rootUuid];
  27720. if (bindingByName !== undefined) {
  27721. for (var trackName in bindingByName) {
  27722. var binding = bindingByName[trackName];
  27723. binding.restoreOriginalState();
  27724. this._removeInactiveBinding(binding);
  27725. }
  27726. }
  27727. },
  27728. // remove a targeted clip from the cache
  27729. uncacheAction: function (clip, optionalRoot) {
  27730. var action = this.existingAction(clip, optionalRoot);
  27731. if (action !== null) {
  27732. this._deactivateAction(action);
  27733. this._removeInactiveAction(action);
  27734. }
  27735. }
  27736. });
  27737. /**
  27738. * @author mrdoob / http://mrdoob.com/
  27739. */
  27740. function Uniform(value) {
  27741. if (typeof value === 'string') {
  27742. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  27743. value = arguments[1];
  27744. }
  27745. this.value = value;
  27746. }
  27747. Uniform.prototype.clone = function () {
  27748. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  27749. };
  27750. /**
  27751. * @author benaadams / https://twitter.com/ben_a_adams
  27752. */
  27753. function InstancedInterleavedBuffer(array, stride, meshPerAttribute) {
  27754. InterleavedBuffer.call(this, array, stride);
  27755. this.meshPerAttribute = meshPerAttribute || 1;
  27756. }
  27757. InstancedInterleavedBuffer.prototype = Object.assign(Object.create(InterleavedBuffer.prototype), {
  27758. constructor: InstancedInterleavedBuffer,
  27759. isInstancedInterleavedBuffer: true,
  27760. copy: function (source) {
  27761. InterleavedBuffer.prototype.copy.call(this, source);
  27762. this.meshPerAttribute = source.meshPerAttribute;
  27763. return this;
  27764. }
  27765. });
  27766. /**
  27767. * @author mrdoob / http://mrdoob.com/
  27768. * @author bhouston / http://clara.io/
  27769. * @author stephomi / http://stephaneginier.com/
  27770. */
  27771. function Raycaster(origin, direction, near, far) {
  27772. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  27773. this.near = near || 0;
  27774. this.far = far || Infinity;
  27775. this.camera = null;
  27776. this.params = {
  27777. Mesh: {},
  27778. Line: {},
  27779. LOD: {},
  27780. Points: {
  27781. threshold: 1
  27782. },
  27783. Sprite: {}
  27784. };
  27785. Object.defineProperties(this.params, {
  27786. PointCloud: {
  27787. get: function () {
  27788. console.warn('THREE.Raycaster: params.PointCloud has been renamed to params.Points.');
  27789. return this.Points;
  27790. }
  27791. }
  27792. });
  27793. }
  27794. function ascSort(a, b) {
  27795. return a.distance - b.distance;
  27796. }
  27797. function intersectObject(object, raycaster, intersects, recursive) {
  27798. if (object.visible === false) return;
  27799. object.raycast(raycaster, intersects);
  27800. if (recursive === true) {
  27801. var children = object.children;
  27802. for (var i = 0, l = children.length; i < l; i++) {
  27803. intersectObject(children[i], raycaster, intersects, true);
  27804. }
  27805. }
  27806. }
  27807. Object.assign(Raycaster.prototype, {
  27808. linePrecision: 1,
  27809. set: function (origin, direction) {
  27810. // direction is assumed to be normalized (for accurate distance calculations)
  27811. this.ray.set(origin, direction);
  27812. },
  27813. setFromCamera: function (coords, camera) {
  27814. if (camera && camera.isPerspectiveCamera) {
  27815. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  27816. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  27817. this.camera = camera;
  27818. } else if (camera && camera.isOrthographicCamera) {
  27819. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  27820. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  27821. this.camera = camera;
  27822. } else {
  27823. console.error('THREE.Raycaster: Unsupported camera type.');
  27824. }
  27825. },
  27826. intersectObject: function (object, recursive, optionalTarget) {
  27827. var intersects = optionalTarget || [];
  27828. intersectObject(object, this, intersects, recursive);
  27829. intersects.sort(ascSort);
  27830. return intersects;
  27831. },
  27832. intersectObjects: function (objects, recursive, optionalTarget) {
  27833. var intersects = optionalTarget || [];
  27834. if (Array.isArray(objects) === false) {
  27835. console.warn('THREE.Raycaster.intersectObjects: objects is not an Array.');
  27836. return intersects;
  27837. }
  27838. for (var i = 0, l = objects.length; i < l; i++) {
  27839. intersectObject(objects[i], this, intersects, recursive);
  27840. }
  27841. intersects.sort(ascSort);
  27842. return intersects;
  27843. }
  27844. });
  27845. /**
  27846. * @author bhouston / http://clara.io
  27847. * @author WestLangley / http://github.com/WestLangley
  27848. *
  27849. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  27850. *
  27851. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  27852. * The azimuthal angle (theta) is measured from the positive z-axiz.
  27853. */
  27854. function Spherical(radius, phi, theta) {
  27855. this.radius = radius !== undefined ? radius : 1.0;
  27856. this.phi = phi !== undefined ? phi : 0; // polar angle
  27857. this.theta = theta !== undefined ? theta : 0; // azimuthal angle
  27858. return this;
  27859. }
  27860. Object.assign(Spherical.prototype, {
  27861. set: function (radius, phi, theta) {
  27862. this.radius = radius;
  27863. this.phi = phi;
  27864. this.theta = theta;
  27865. return this;
  27866. },
  27867. clone: function () {
  27868. return new this.constructor().copy(this);
  27869. },
  27870. copy: function (other) {
  27871. this.radius = other.radius;
  27872. this.phi = other.phi;
  27873. this.theta = other.theta;
  27874. return this;
  27875. },
  27876. // restrict phi to be betwee EPS and PI-EPS
  27877. makeSafe: function () {
  27878. var EPS = 0.000001;
  27879. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  27880. return this;
  27881. },
  27882. setFromVector3: function (v) {
  27883. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27884. },
  27885. setFromCartesianCoords: function (x, y, z) {
  27886. this.radius = Math.sqrt(x * x + y * y + z * z);
  27887. if (this.radius === 0) {
  27888. this.theta = 0;
  27889. this.phi = 0;
  27890. } else {
  27891. this.theta = Math.atan2(x, z);
  27892. this.phi = Math.acos(_Math.clamp(y / this.radius, -1, 1));
  27893. }
  27894. return this;
  27895. }
  27896. });
  27897. /**
  27898. * @author Mugen87 / https://github.com/Mugen87
  27899. *
  27900. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  27901. *
  27902. */
  27903. function Cylindrical(radius, theta, y) {
  27904. this.radius = radius !== undefined ? radius : 1.0; // distance from the origin to a point in the x-z plane
  27905. this.theta = theta !== undefined ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  27906. this.y = y !== undefined ? y : 0; // height above the x-z plane
  27907. return this;
  27908. }
  27909. Object.assign(Cylindrical.prototype, {
  27910. set: function (radius, theta, y) {
  27911. this.radius = radius;
  27912. this.theta = theta;
  27913. this.y = y;
  27914. return this;
  27915. },
  27916. clone: function () {
  27917. return new this.constructor().copy(this);
  27918. },
  27919. copy: function (other) {
  27920. this.radius = other.radius;
  27921. this.theta = other.theta;
  27922. this.y = other.y;
  27923. return this;
  27924. },
  27925. setFromVector3: function (v) {
  27926. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27927. },
  27928. setFromCartesianCoords: function (x, y, z) {
  27929. this.radius = Math.sqrt(x * x + z * z);
  27930. this.theta = Math.atan2(x, z);
  27931. this.y = y;
  27932. return this;
  27933. }
  27934. });
  27935. /**
  27936. * @author bhouston / http://clara.io
  27937. */
  27938. var _vector$6 = new Vector2();
  27939. function Box2(min, max) {
  27940. this.min = min !== undefined ? min : new Vector2(+Infinity, +Infinity);
  27941. this.max = max !== undefined ? max : new Vector2(-Infinity, -Infinity);
  27942. }
  27943. Object.assign(Box2.prototype, {
  27944. set: function (min, max) {
  27945. this.min.copy(min);
  27946. this.max.copy(max);
  27947. return this;
  27948. },
  27949. setFromPoints: function (points) {
  27950. this.makeEmpty();
  27951. for (var i = 0, il = points.length; i < il; i++) {
  27952. this.expandByPoint(points[i]);
  27953. }
  27954. return this;
  27955. },
  27956. setFromCenterAndSize: function (center, size) {
  27957. var halfSize = _vector$6.copy(size).multiplyScalar(0.5);
  27958. this.min.copy(center).sub(halfSize);
  27959. this.max.copy(center).add(halfSize);
  27960. return this;
  27961. },
  27962. clone: function () {
  27963. return new this.constructor().copy(this);
  27964. },
  27965. copy: function (box) {
  27966. this.min.copy(box.min);
  27967. this.max.copy(box.max);
  27968. return this;
  27969. },
  27970. makeEmpty: function () {
  27971. this.min.x = this.min.y = +Infinity;
  27972. this.max.x = this.max.y = -Infinity;
  27973. return this;
  27974. },
  27975. isEmpty: function () {
  27976. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  27977. return this.max.x < this.min.x || this.max.y < this.min.y;
  27978. },
  27979. getCenter: function (target) {
  27980. if (target === undefined) {
  27981. console.warn('THREE.Box2: .getCenter() target is now required');
  27982. target = new Vector2();
  27983. }
  27984. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  27985. },
  27986. getSize: function (target) {
  27987. if (target === undefined) {
  27988. console.warn('THREE.Box2: .getSize() target is now required');
  27989. target = new Vector2();
  27990. }
  27991. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  27992. },
  27993. expandByPoint: function (point) {
  27994. this.min.min(point);
  27995. this.max.max(point);
  27996. return this;
  27997. },
  27998. expandByVector: function (vector) {
  27999. this.min.sub(vector);
  28000. this.max.add(vector);
  28001. return this;
  28002. },
  28003. expandByScalar: function (scalar) {
  28004. this.min.addScalar(-scalar);
  28005. this.max.addScalar(scalar);
  28006. return this;
  28007. },
  28008. containsPoint: function (point) {
  28009. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  28010. },
  28011. containsBox: function (box) {
  28012. 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;
  28013. },
  28014. getParameter: function (point, target) {
  28015. // This can potentially have a divide by zero if the box
  28016. // has a size dimension of 0.
  28017. if (target === undefined) {
  28018. console.warn('THREE.Box2: .getParameter() target is now required');
  28019. target = new Vector2();
  28020. }
  28021. 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));
  28022. },
  28023. intersectsBox: function (box) {
  28024. // using 4 splitting planes to rule out intersections
  28025. 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;
  28026. },
  28027. clampPoint: function (point, target) {
  28028. if (target === undefined) {
  28029. console.warn('THREE.Box2: .clampPoint() target is now required');
  28030. target = new Vector2();
  28031. }
  28032. return target.copy(point).clamp(this.min, this.max);
  28033. },
  28034. distanceToPoint: function (point) {
  28035. var clampedPoint = _vector$6.copy(point).clamp(this.min, this.max);
  28036. return clampedPoint.sub(point).length();
  28037. },
  28038. intersect: function (box) {
  28039. this.min.max(box.min);
  28040. this.max.min(box.max);
  28041. return this;
  28042. },
  28043. union: function (box) {
  28044. this.min.min(box.min);
  28045. this.max.max(box.max);
  28046. return this;
  28047. },
  28048. translate: function (offset) {
  28049. this.min.add(offset);
  28050. this.max.add(offset);
  28051. return this;
  28052. },
  28053. equals: function (box) {
  28054. return box.min.equals(this.min) && box.max.equals(this.max);
  28055. }
  28056. });
  28057. /**
  28058. * @author bhouston / http://clara.io
  28059. */
  28060. var _startP = new Vector3();
  28061. var _startEnd = new Vector3();
  28062. function Line3(start, end) {
  28063. this.start = start !== undefined ? start : new Vector3();
  28064. this.end = end !== undefined ? end : new Vector3();
  28065. }
  28066. Object.assign(Line3.prototype, {
  28067. set: function (start, end) {
  28068. this.start.copy(start);
  28069. this.end.copy(end);
  28070. return this;
  28071. },
  28072. clone: function () {
  28073. return new this.constructor().copy(this);
  28074. },
  28075. copy: function (line) {
  28076. this.start.copy(line.start);
  28077. this.end.copy(line.end);
  28078. return this;
  28079. },
  28080. getCenter: function (target) {
  28081. if (target === undefined) {
  28082. console.warn('THREE.Line3: .getCenter() target is now required');
  28083. target = new Vector3();
  28084. }
  28085. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  28086. },
  28087. delta: function (target) {
  28088. if (target === undefined) {
  28089. console.warn('THREE.Line3: .delta() target is now required');
  28090. target = new Vector3();
  28091. }
  28092. return target.subVectors(this.end, this.start);
  28093. },
  28094. distanceSq: function () {
  28095. return this.start.distanceToSquared(this.end);
  28096. },
  28097. distance: function () {
  28098. return this.start.distanceTo(this.end);
  28099. },
  28100. at: function (t, target) {
  28101. if (target === undefined) {
  28102. console.warn('THREE.Line3: .at() target is now required');
  28103. target = new Vector3();
  28104. }
  28105. return this.delta(target).multiplyScalar(t).add(this.start);
  28106. },
  28107. closestPointToPointParameter: function (point, clampToLine) {
  28108. _startP.subVectors(point, this.start);
  28109. _startEnd.subVectors(this.end, this.start);
  28110. var startEnd2 = _startEnd.dot(_startEnd);
  28111. var startEnd_startP = _startEnd.dot(_startP);
  28112. var t = startEnd_startP / startEnd2;
  28113. if (clampToLine) {
  28114. t = _Math.clamp(t, 0, 1);
  28115. }
  28116. return t;
  28117. },
  28118. closestPointToPoint: function (point, clampToLine, target) {
  28119. var t = this.closestPointToPointParameter(point, clampToLine);
  28120. if (target === undefined) {
  28121. console.warn('THREE.Line3: .closestPointToPoint() target is now required');
  28122. target = new Vector3();
  28123. }
  28124. return this.delta(target).multiplyScalar(t).add(this.start);
  28125. },
  28126. applyMatrix4: function (matrix) {
  28127. this.start.applyMatrix4(matrix);
  28128. this.end.applyMatrix4(matrix);
  28129. return this;
  28130. },
  28131. equals: function (line) {
  28132. return line.start.equals(this.start) && line.end.equals(this.end);
  28133. }
  28134. });
  28135. /**
  28136. * @author alteredq / http://alteredqualia.com/
  28137. */
  28138. function ImmediateRenderObject(material) {
  28139. Object3D.call(this);
  28140. this.material = material;
  28141. this.render = function ()
  28142. /* renderCallback */
  28143. {};
  28144. }
  28145. ImmediateRenderObject.prototype = Object.create(Object3D.prototype);
  28146. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  28147. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  28148. /**
  28149. * @author mrdoob / http://mrdoob.com/
  28150. * @author WestLangley / http://github.com/WestLangley
  28151. */
  28152. var _v1$5 = new Vector3();
  28153. var _v2$3 = new Vector3();
  28154. var _normalMatrix$1 = new Matrix3();
  28155. var _keys = ['a', 'b', 'c'];
  28156. function VertexNormalsHelper(object, size, hex, linewidth) {
  28157. this.object = object;
  28158. this.size = size !== undefined ? size : 1;
  28159. var color = hex !== undefined ? hex : 0xff0000;
  28160. var width = linewidth !== undefined ? linewidth : 1; //
  28161. var nNormals = 0;
  28162. var objGeometry = this.object.geometry;
  28163. if (objGeometry && objGeometry.isGeometry) {
  28164. nNormals = objGeometry.faces.length * 3;
  28165. } else if (objGeometry && objGeometry.isBufferGeometry) {
  28166. nNormals = objGeometry.attributes.normal.count;
  28167. } //
  28168. var geometry = new BufferGeometry();
  28169. var positions = new Float32BufferAttribute(nNormals * 2 * 3, 3);
  28170. geometry.addAttribute('position', positions);
  28171. LineSegments.call(this, geometry, new LineBasicMaterial({
  28172. color: color,
  28173. linewidth: width
  28174. })); //
  28175. this.matrixAutoUpdate = false;
  28176. this.update();
  28177. }
  28178. VertexNormalsHelper.prototype = Object.create(LineSegments.prototype);
  28179. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  28180. VertexNormalsHelper.prototype.update = function () {
  28181. this.object.updateMatrixWorld(true);
  28182. _normalMatrix$1.getNormalMatrix(this.object.matrixWorld);
  28183. var matrixWorld = this.object.matrixWorld;
  28184. var position = this.geometry.attributes.position; //
  28185. var objGeometry = this.object.geometry;
  28186. if (objGeometry && objGeometry.isGeometry) {
  28187. var vertices = objGeometry.vertices;
  28188. var faces = objGeometry.faces;
  28189. var idx = 0;
  28190. for (var i = 0, l = faces.length; i < l; i++) {
  28191. var face = faces[i];
  28192. for (var j = 0, jl = face.vertexNormals.length; j < jl; j++) {
  28193. var vertex = vertices[face[_keys[j]]];
  28194. var normal = face.vertexNormals[j];
  28195. _v1$5.copy(vertex).applyMatrix4(matrixWorld);
  28196. _v2$3.copy(normal).applyMatrix3(_normalMatrix$1).normalize().multiplyScalar(this.size).add(_v1$5);
  28197. position.setXYZ(idx, _v1$5.x, _v1$5.y, _v1$5.z);
  28198. idx = idx + 1;
  28199. position.setXYZ(idx, _v2$3.x, _v2$3.y, _v2$3.z);
  28200. idx = idx + 1;
  28201. }
  28202. }
  28203. } else if (objGeometry && objGeometry.isBufferGeometry) {
  28204. var objPos = objGeometry.attributes.position;
  28205. var objNorm = objGeometry.attributes.normal;
  28206. var idx = 0; // for simplicity, ignore index and drawcalls, and render every normal
  28207. for (var j = 0, jl = objPos.count; j < jl; j++) {
  28208. _v1$5.set(objPos.getX(j), objPos.getY(j), objPos.getZ(j)).applyMatrix4(matrixWorld);
  28209. _v2$3.set(objNorm.getX(j), objNorm.getY(j), objNorm.getZ(j));
  28210. _v2$3.applyMatrix3(_normalMatrix$1).normalize().multiplyScalar(this.size).add(_v1$5);
  28211. position.setXYZ(idx, _v1$5.x, _v1$5.y, _v1$5.z);
  28212. idx = idx + 1;
  28213. position.setXYZ(idx, _v2$3.x, _v2$3.y, _v2$3.z);
  28214. idx = idx + 1;
  28215. }
  28216. }
  28217. position.needsUpdate = true;
  28218. };
  28219. /**
  28220. * @author alteredq / http://alteredqualia.com/
  28221. * @author mrdoob / http://mrdoob.com/
  28222. * @author WestLangley / http://github.com/WestLangley
  28223. */
  28224. var _vector$7 = new Vector3();
  28225. function SpotLightHelper(light, color) {
  28226. Object3D.call(this);
  28227. this.light = light;
  28228. this.light.updateMatrixWorld();
  28229. this.matrix = light.matrixWorld;
  28230. this.matrixAutoUpdate = false;
  28231. this.color = color;
  28232. var geometry = new BufferGeometry();
  28233. 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];
  28234. for (var i = 0, j = 1, l = 32; i < l; i++, j++) {
  28235. var p1 = i / l * Math.PI * 2;
  28236. var p2 = j / l * Math.PI * 2;
  28237. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  28238. }
  28239. geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));
  28240. var material = new LineBasicMaterial({
  28241. fog: false
  28242. });
  28243. this.cone = new LineSegments(geometry, material);
  28244. this.add(this.cone);
  28245. this.update();
  28246. }
  28247. SpotLightHelper.prototype = Object.create(Object3D.prototype);
  28248. SpotLightHelper.prototype.constructor = SpotLightHelper;
  28249. SpotLightHelper.prototype.dispose = function () {
  28250. this.cone.geometry.dispose();
  28251. this.cone.material.dispose();
  28252. };
  28253. SpotLightHelper.prototype.update = function () {
  28254. this.light.updateMatrixWorld();
  28255. var coneLength = this.light.distance ? this.light.distance : 1000;
  28256. var coneWidth = coneLength * Math.tan(this.light.angle);
  28257. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  28258. _vector$7.setFromMatrixPosition(this.light.target.matrixWorld);
  28259. this.cone.lookAt(_vector$7);
  28260. if (this.color !== undefined) {
  28261. this.cone.material.color.set(this.color);
  28262. } else {
  28263. this.cone.material.color.copy(this.light.color);
  28264. }
  28265. };
  28266. /**
  28267. * @author Sean Griffin / http://twitter.com/sgrif
  28268. * @author Michael Guerrero / http://realitymeltdown.com
  28269. * @author mrdoob / http://mrdoob.com/
  28270. * @author ikerr / http://verold.com
  28271. * @author Mugen87 / https://github.com/Mugen87
  28272. */
  28273. var _vector$8 = new Vector3();
  28274. var _boneMatrix = new Matrix4();
  28275. var _matrixWorldInv = new Matrix4();
  28276. function getBoneList(object) {
  28277. var boneList = [];
  28278. if (object && object.isBone) {
  28279. boneList.push(object);
  28280. }
  28281. for (var i = 0; i < object.children.length; i++) {
  28282. boneList.push.apply(boneList, getBoneList(object.children[i]));
  28283. }
  28284. return boneList;
  28285. }
  28286. function SkeletonHelper(object) {
  28287. var bones = getBoneList(object);
  28288. var geometry = new BufferGeometry();
  28289. var vertices = [];
  28290. var colors = [];
  28291. var color1 = new Color(0, 0, 1);
  28292. var color2 = new Color(0, 1, 0);
  28293. for (var i = 0; i < bones.length; i++) {
  28294. var bone = bones[i];
  28295. if (bone.parent && bone.parent.isBone) {
  28296. vertices.push(0, 0, 0);
  28297. vertices.push(0, 0, 0);
  28298. colors.push(color1.r, color1.g, color1.b);
  28299. colors.push(color2.r, color2.g, color2.b);
  28300. }
  28301. }
  28302. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  28303. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  28304. var material = new LineBasicMaterial({
  28305. vertexColors: VertexColors,
  28306. depthTest: false,
  28307. depthWrite: false,
  28308. transparent: true
  28309. });
  28310. LineSegments.call(this, geometry, material);
  28311. this.root = object;
  28312. this.bones = bones;
  28313. this.matrix = object.matrixWorld;
  28314. this.matrixAutoUpdate = false;
  28315. }
  28316. SkeletonHelper.prototype = Object.create(LineSegments.prototype);
  28317. SkeletonHelper.prototype.constructor = SkeletonHelper;
  28318. SkeletonHelper.prototype.updateMatrixWorld = function (force) {
  28319. var bones = this.bones;
  28320. var geometry = this.geometry;
  28321. var position = geometry.getAttribute('position');
  28322. _matrixWorldInv.getInverse(this.root.matrixWorld);
  28323. for (var i = 0, j = 0; i < bones.length; i++) {
  28324. var bone = bones[i];
  28325. if (bone.parent && bone.parent.isBone) {
  28326. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  28327. _vector$8.setFromMatrixPosition(_boneMatrix);
  28328. position.setXYZ(j, _vector$8.x, _vector$8.y, _vector$8.z);
  28329. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  28330. _vector$8.setFromMatrixPosition(_boneMatrix);
  28331. position.setXYZ(j + 1, _vector$8.x, _vector$8.y, _vector$8.z);
  28332. j += 2;
  28333. }
  28334. }
  28335. geometry.getAttribute('position').needsUpdate = true;
  28336. Object3D.prototype.updateMatrixWorld.call(this, force);
  28337. };
  28338. /**
  28339. * @author alteredq / http://alteredqualia.com/
  28340. * @author mrdoob / http://mrdoob.com/
  28341. */
  28342. function PointLightHelper(light, sphereSize, color) {
  28343. this.light = light;
  28344. this.light.updateMatrixWorld();
  28345. this.color = color;
  28346. var geometry = new SphereBufferGeometry(sphereSize, 4, 2);
  28347. var material = new MeshBasicMaterial({
  28348. wireframe: true,
  28349. fog: false
  28350. });
  28351. Mesh.call(this, geometry, material);
  28352. this.matrix = this.light.matrixWorld;
  28353. this.matrixAutoUpdate = false;
  28354. this.update();
  28355. /*
  28356. var distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  28357. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  28358. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  28359. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  28360. var d = light.distance;
  28361. if ( d === 0.0 ) {
  28362. this.lightDistance.visible = false;
  28363. } else {
  28364. this.lightDistance.scale.set( d, d, d );
  28365. }
  28366. this.add( this.lightDistance );
  28367. */
  28368. }
  28369. PointLightHelper.prototype = Object.create(Mesh.prototype);
  28370. PointLightHelper.prototype.constructor = PointLightHelper;
  28371. PointLightHelper.prototype.dispose = function () {
  28372. this.geometry.dispose();
  28373. this.material.dispose();
  28374. };
  28375. PointLightHelper.prototype.update = function () {
  28376. if (this.color !== undefined) {
  28377. this.material.color.set(this.color);
  28378. } else {
  28379. this.material.color.copy(this.light.color);
  28380. }
  28381. /*
  28382. var d = this.light.distance;
  28383. if ( d === 0.0 ) {
  28384. this.lightDistance.visible = false;
  28385. } else {
  28386. this.lightDistance.visible = true;
  28387. this.lightDistance.scale.set( d, d, d );
  28388. }
  28389. */
  28390. };
  28391. /**
  28392. * @author abelnation / http://github.com/abelnation
  28393. * @author Mugen87 / http://github.com/Mugen87
  28394. * @author WestLangley / http://github.com/WestLangley
  28395. *
  28396. * This helper must be added as a child of the light
  28397. */
  28398. function RectAreaLightHelper(light, color) {
  28399. this.type = 'RectAreaLightHelper';
  28400. this.light = light;
  28401. this.color = color; // optional hardwired color for the helper
  28402. var positions = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, -1, 0, 1, 1, 0];
  28403. var geometry = new BufferGeometry();
  28404. geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));
  28405. geometry.computeBoundingSphere();
  28406. var material = new LineBasicMaterial({
  28407. fog: false
  28408. });
  28409. Line.call(this, geometry, material); //
  28410. var positions2 = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0];
  28411. var geometry2 = new BufferGeometry();
  28412. geometry2.addAttribute('position', new Float32BufferAttribute(positions2, 3));
  28413. geometry2.computeBoundingSphere();
  28414. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  28415. side: BackSide,
  28416. fog: false
  28417. })));
  28418. this.update();
  28419. }
  28420. RectAreaLightHelper.prototype = Object.create(Line.prototype);
  28421. RectAreaLightHelper.prototype.constructor = RectAreaLightHelper;
  28422. RectAreaLightHelper.prototype.update = function () {
  28423. this.scale.set(0.5 * this.light.width, 0.5 * this.light.height, 1);
  28424. if (this.color !== undefined) {
  28425. this.material.color.set(this.color);
  28426. this.children[0].material.color.set(this.color);
  28427. } else {
  28428. this.material.color.copy(this.light.color).multiplyScalar(this.light.intensity); // prevent hue shift
  28429. var c = this.material.color;
  28430. var max = Math.max(c.r, c.g, c.b);
  28431. if (max > 1) c.multiplyScalar(1 / max);
  28432. this.children[0].material.color.copy(this.material.color);
  28433. }
  28434. };
  28435. RectAreaLightHelper.prototype.dispose = function () {
  28436. this.geometry.dispose();
  28437. this.material.dispose();
  28438. this.children[0].geometry.dispose();
  28439. this.children[0].material.dispose();
  28440. };
  28441. /**
  28442. * @author alteredq / http://alteredqualia.com/
  28443. * @author mrdoob / http://mrdoob.com/
  28444. * @author Mugen87 / https://github.com/Mugen87
  28445. */
  28446. var _vector$9 = new Vector3();
  28447. var _color1 = new Color();
  28448. var _color2 = new Color();
  28449. function HemisphereLightHelper(light, size, color) {
  28450. Object3D.call(this);
  28451. this.light = light;
  28452. this.light.updateMatrixWorld();
  28453. this.matrix = light.matrixWorld;
  28454. this.matrixAutoUpdate = false;
  28455. this.color = color;
  28456. var geometry = new OctahedronBufferGeometry(size);
  28457. geometry.rotateY(Math.PI * 0.5);
  28458. this.material = new MeshBasicMaterial({
  28459. wireframe: true,
  28460. fog: false
  28461. });
  28462. if (this.color === undefined) this.material.vertexColors = VertexColors;
  28463. var position = geometry.getAttribute('position');
  28464. var colors = new Float32Array(position.count * 3);
  28465. geometry.addAttribute('color', new BufferAttribute(colors, 3));
  28466. this.add(new Mesh(geometry, this.material));
  28467. this.update();
  28468. }
  28469. HemisphereLightHelper.prototype = Object.create(Object3D.prototype);
  28470. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  28471. HemisphereLightHelper.prototype.dispose = function () {
  28472. this.children[0].geometry.dispose();
  28473. this.children[0].material.dispose();
  28474. };
  28475. HemisphereLightHelper.prototype.update = function () {
  28476. var mesh = this.children[0];
  28477. if (this.color !== undefined) {
  28478. this.material.color.set(this.color);
  28479. } else {
  28480. var colors = mesh.geometry.getAttribute('color');
  28481. _color1.copy(this.light.color);
  28482. _color2.copy(this.light.groundColor);
  28483. for (var i = 0, l = colors.count; i < l; i++) {
  28484. var color = i < l / 2 ? _color1 : _color2;
  28485. colors.setXYZ(i, color.r, color.g, color.b);
  28486. }
  28487. colors.needsUpdate = true;
  28488. }
  28489. mesh.lookAt(_vector$9.setFromMatrixPosition(this.light.matrixWorld).negate());
  28490. };
  28491. /**
  28492. * @author WestLangley / http://github.com/WestLangley
  28493. */
  28494. function LightProbeHelper(lightProbe, size) {
  28495. this.lightProbe = lightProbe;
  28496. this.size = size;
  28497. var defines = {};
  28498. defines['GAMMA_OUTPUT'] = ""; // material
  28499. var material = new ShaderMaterial({
  28500. defines: defines,
  28501. uniforms: {
  28502. sh: {
  28503. value: this.lightProbe.sh.coefficients
  28504. },
  28505. // by reference
  28506. intensity: {
  28507. value: this.lightProbe.intensity
  28508. }
  28509. },
  28510. vertexShader: ['varying vec3 vNormal;', 'void main() {', ' vNormal = normalize( normalMatrix * normal );', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'),
  28511. 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')
  28512. });
  28513. var geometry = new SphereBufferGeometry(1, 32, 16);
  28514. Mesh.call(this, geometry, material);
  28515. this.onBeforeRender();
  28516. }
  28517. LightProbeHelper.prototype = Object.create(Mesh.prototype);
  28518. LightProbeHelper.prototype.constructor = LightProbeHelper;
  28519. LightProbeHelper.prototype.dispose = function () {
  28520. this.geometry.dispose();
  28521. this.material.dispose();
  28522. };
  28523. LightProbeHelper.prototype.onBeforeRender = function () {
  28524. this.position.copy(this.lightProbe.position);
  28525. this.scale.set(1, 1, 1).multiplyScalar(this.size);
  28526. this.material.uniforms.intensity.value = this.lightProbe.intensity;
  28527. };
  28528. /**
  28529. * @author mrdoob / http://mrdoob.com/
  28530. */
  28531. function GridHelper(size, divisions, color1, color2) {
  28532. size = size || 10;
  28533. divisions = divisions || 10;
  28534. color1 = new Color(color1 !== undefined ? color1 : 0x444444);
  28535. color2 = new Color(color2 !== undefined ? color2 : 0x888888);
  28536. var center = divisions / 2;
  28537. var step = size / divisions;
  28538. var halfSize = size / 2;
  28539. var vertices = [],
  28540. colors = [];
  28541. for (var i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  28542. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  28543. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  28544. var color = i === center ? color1 : color2;
  28545. color.toArray(colors, j);
  28546. j += 3;
  28547. color.toArray(colors, j);
  28548. j += 3;
  28549. color.toArray(colors, j);
  28550. j += 3;
  28551. color.toArray(colors, j);
  28552. j += 3;
  28553. }
  28554. var geometry = new BufferGeometry();
  28555. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  28556. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  28557. var material = new LineBasicMaterial({
  28558. vertexColors: VertexColors
  28559. });
  28560. LineSegments.call(this, geometry, material);
  28561. }
  28562. GridHelper.prototype = Object.assign(Object.create(LineSegments.prototype), {
  28563. constructor: GridHelper,
  28564. copy: function (source) {
  28565. LineSegments.prototype.copy.call(this, source);
  28566. this.geometry.copy(source.geometry);
  28567. this.material.copy(source.material);
  28568. return this;
  28569. },
  28570. clone: function () {
  28571. return new this.constructor().copy(this);
  28572. }
  28573. });
  28574. /**
  28575. * @author mrdoob / http://mrdoob.com/
  28576. * @author Mugen87 / http://github.com/Mugen87
  28577. * @author Hectate / http://www.github.com/Hectate
  28578. */
  28579. function PolarGridHelper(radius, radials, circles, divisions, color1, color2) {
  28580. radius = radius || 10;
  28581. radials = radials || 16;
  28582. circles = circles || 8;
  28583. divisions = divisions || 64;
  28584. color1 = new Color(color1 !== undefined ? color1 : 0x444444);
  28585. color2 = new Color(color2 !== undefined ? color2 : 0x888888);
  28586. var vertices = [];
  28587. var colors = [];
  28588. var x, z;
  28589. var v, i, j, r, color; // create the radials
  28590. for (i = 0; i <= radials; i++) {
  28591. v = i / radials * (Math.PI * 2);
  28592. x = Math.sin(v) * radius;
  28593. z = Math.cos(v) * radius;
  28594. vertices.push(0, 0, 0);
  28595. vertices.push(x, 0, z);
  28596. color = i & 1 ? color1 : color2;
  28597. colors.push(color.r, color.g, color.b);
  28598. colors.push(color.r, color.g, color.b);
  28599. } // create the circles
  28600. for (i = 0; i <= circles; i++) {
  28601. color = i & 1 ? color1 : color2;
  28602. r = radius - radius / circles * i;
  28603. for (j = 0; j < divisions; j++) {
  28604. // first vertex
  28605. v = j / divisions * (Math.PI * 2);
  28606. x = Math.sin(v) * r;
  28607. z = Math.cos(v) * r;
  28608. vertices.push(x, 0, z);
  28609. colors.push(color.r, color.g, color.b); // second vertex
  28610. v = (j + 1) / divisions * (Math.PI * 2);
  28611. x = Math.sin(v) * r;
  28612. z = Math.cos(v) * r;
  28613. vertices.push(x, 0, z);
  28614. colors.push(color.r, color.g, color.b);
  28615. }
  28616. }
  28617. var geometry = new BufferGeometry();
  28618. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  28619. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  28620. var material = new LineBasicMaterial({
  28621. vertexColors: VertexColors
  28622. });
  28623. LineSegments.call(this, geometry, material);
  28624. }
  28625. PolarGridHelper.prototype = Object.create(LineSegments.prototype);
  28626. PolarGridHelper.prototype.constructor = PolarGridHelper;
  28627. /**
  28628. * @author Mugen87 / http://github.com/Mugen87
  28629. */
  28630. function PositionalAudioHelper(audio, range, divisionsInnerAngle, divisionsOuterAngle) {
  28631. this.audio = audio;
  28632. this.range = range || 1;
  28633. this.divisionsInnerAngle = divisionsInnerAngle || 16;
  28634. this.divisionsOuterAngle = divisionsOuterAngle || 2;
  28635. var geometry = new BufferGeometry();
  28636. var divisions = this.divisionsInnerAngle + this.divisionsOuterAngle * 2;
  28637. var positions = new Float32Array((divisions * 3 + 3) * 3);
  28638. geometry.addAttribute('position', new BufferAttribute(positions, 3));
  28639. var materialInnerAngle = new LineBasicMaterial({
  28640. color: 0x00ff00
  28641. });
  28642. var materialOuterAngle = new LineBasicMaterial({
  28643. color: 0xffff00
  28644. });
  28645. Line.call(this, geometry, [materialOuterAngle, materialInnerAngle]);
  28646. this.update();
  28647. }
  28648. PositionalAudioHelper.prototype = Object.create(Line.prototype);
  28649. PositionalAudioHelper.prototype.constructor = PositionalAudioHelper;
  28650. PositionalAudioHelper.prototype.update = function () {
  28651. var audio = this.audio;
  28652. var range = this.range;
  28653. var divisionsInnerAngle = this.divisionsInnerAngle;
  28654. var divisionsOuterAngle = this.divisionsOuterAngle;
  28655. var coneInnerAngle = _Math.degToRad(audio.panner.coneInnerAngle);
  28656. var coneOuterAngle = _Math.degToRad(audio.panner.coneOuterAngle);
  28657. var halfConeInnerAngle = coneInnerAngle / 2;
  28658. var halfConeOuterAngle = coneOuterAngle / 2;
  28659. var start = 0;
  28660. var count = 0;
  28661. var i, stride;
  28662. var geometry = this.geometry;
  28663. var positionAttribute = geometry.attributes.position;
  28664. geometry.clearGroups(); //
  28665. function generateSegment(from, to, divisions, materialIndex) {
  28666. var step = (to - from) / divisions;
  28667. positionAttribute.setXYZ(start, 0, 0, 0);
  28668. count++;
  28669. for (i = from; i < to; i += step) {
  28670. stride = start + count;
  28671. positionAttribute.setXYZ(stride, Math.sin(i) * range, 0, Math.cos(i) * range);
  28672. positionAttribute.setXYZ(stride + 1, Math.sin(Math.min(i + step, to)) * range, 0, Math.cos(Math.min(i + step, to)) * range);
  28673. positionAttribute.setXYZ(stride + 2, 0, 0, 0);
  28674. count += 3;
  28675. }
  28676. geometry.addGroup(start, count, materialIndex);
  28677. start += count;
  28678. count = 0;
  28679. } //
  28680. generateSegment(-halfConeOuterAngle, -halfConeInnerAngle, divisionsOuterAngle, 0);
  28681. generateSegment(-halfConeInnerAngle, halfConeInnerAngle, divisionsInnerAngle, 1);
  28682. generateSegment(halfConeInnerAngle, halfConeOuterAngle, divisionsOuterAngle, 0); //
  28683. positionAttribute.needsUpdate = true;
  28684. if (coneInnerAngle === coneOuterAngle) this.material[0].visible = false;
  28685. };
  28686. PositionalAudioHelper.prototype.dispose = function () {
  28687. this.geometry.dispose();
  28688. this.material[0].dispose();
  28689. this.material[1].dispose();
  28690. };
  28691. /**
  28692. * @author mrdoob / http://mrdoob.com/
  28693. * @author WestLangley / http://github.com/WestLangley
  28694. */
  28695. var _v1$6 = new Vector3();
  28696. var _v2$4 = new Vector3();
  28697. var _normalMatrix$2 = new Matrix3();
  28698. function FaceNormalsHelper(object, size, hex, linewidth) {
  28699. // FaceNormalsHelper only supports THREE.Geometry
  28700. this.object = object;
  28701. this.size = size !== undefined ? size : 1;
  28702. var color = hex !== undefined ? hex : 0xffff00;
  28703. var width = linewidth !== undefined ? linewidth : 1; //
  28704. var nNormals = 0;
  28705. var objGeometry = this.object.geometry;
  28706. if (objGeometry && objGeometry.isGeometry) {
  28707. nNormals = objGeometry.faces.length;
  28708. } else {
  28709. console.warn('THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.');
  28710. } //
  28711. var geometry = new BufferGeometry();
  28712. var positions = new Float32BufferAttribute(nNormals * 2 * 3, 3);
  28713. geometry.addAttribute('position', positions);
  28714. LineSegments.call(this, geometry, new LineBasicMaterial({
  28715. color: color,
  28716. linewidth: width
  28717. })); //
  28718. this.matrixAutoUpdate = false;
  28719. this.update();
  28720. }
  28721. FaceNormalsHelper.prototype = Object.create(LineSegments.prototype);
  28722. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  28723. FaceNormalsHelper.prototype.update = function () {
  28724. this.object.updateMatrixWorld(true);
  28725. _normalMatrix$2.getNormalMatrix(this.object.matrixWorld);
  28726. var matrixWorld = this.object.matrixWorld;
  28727. var position = this.geometry.attributes.position; //
  28728. var objGeometry = this.object.geometry;
  28729. var vertices = objGeometry.vertices;
  28730. var faces = objGeometry.faces;
  28731. var idx = 0;
  28732. for (var i = 0, l = faces.length; i < l; i++) {
  28733. var face = faces[i];
  28734. var normal = face.normal;
  28735. _v1$6.copy(vertices[face.a]).add(vertices[face.b]).add(vertices[face.c]).divideScalar(3).applyMatrix4(matrixWorld);
  28736. _v2$4.copy(normal).applyMatrix3(_normalMatrix$2).normalize().multiplyScalar(this.size).add(_v1$6);
  28737. position.setXYZ(idx, _v1$6.x, _v1$6.y, _v1$6.z);
  28738. idx = idx + 1;
  28739. position.setXYZ(idx, _v2$4.x, _v2$4.y, _v2$4.z);
  28740. idx = idx + 1;
  28741. }
  28742. position.needsUpdate = true;
  28743. };
  28744. /**
  28745. * @author alteredq / http://alteredqualia.com/
  28746. * @author mrdoob / http://mrdoob.com/
  28747. * @author WestLangley / http://github.com/WestLangley
  28748. */
  28749. var _v1$7 = new Vector3();
  28750. var _v2$5 = new Vector3();
  28751. var _v3$1 = new Vector3();
  28752. function DirectionalLightHelper(light, size, color) {
  28753. Object3D.call(this);
  28754. this.light = light;
  28755. this.light.updateMatrixWorld();
  28756. this.matrix = light.matrixWorld;
  28757. this.matrixAutoUpdate = false;
  28758. this.color = color;
  28759. if (size === undefined) size = 1;
  28760. var geometry = new BufferGeometry();
  28761. geometry.addAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  28762. var material = new LineBasicMaterial({
  28763. fog: false
  28764. });
  28765. this.lightPlane = new Line(geometry, material);
  28766. this.add(this.lightPlane);
  28767. geometry = new BufferGeometry();
  28768. geometry.addAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  28769. this.targetLine = new Line(geometry, material);
  28770. this.add(this.targetLine);
  28771. this.update();
  28772. }
  28773. DirectionalLightHelper.prototype = Object.create(Object3D.prototype);
  28774. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  28775. DirectionalLightHelper.prototype.dispose = function () {
  28776. this.lightPlane.geometry.dispose();
  28777. this.lightPlane.material.dispose();
  28778. this.targetLine.geometry.dispose();
  28779. this.targetLine.material.dispose();
  28780. };
  28781. DirectionalLightHelper.prototype.update = function () {
  28782. _v1$7.setFromMatrixPosition(this.light.matrixWorld);
  28783. _v2$5.setFromMatrixPosition(this.light.target.matrixWorld);
  28784. _v3$1.subVectors(_v2$5, _v1$7);
  28785. this.lightPlane.lookAt(_v2$5);
  28786. if (this.color !== undefined) {
  28787. this.lightPlane.material.color.set(this.color);
  28788. this.targetLine.material.color.set(this.color);
  28789. } else {
  28790. this.lightPlane.material.color.copy(this.light.color);
  28791. this.targetLine.material.color.copy(this.light.color);
  28792. }
  28793. this.targetLine.lookAt(_v2$5);
  28794. this.targetLine.scale.z = _v3$1.length();
  28795. };
  28796. /**
  28797. * @author alteredq / http://alteredqualia.com/
  28798. * @author Mugen87 / https://github.com/Mugen87
  28799. *
  28800. * - shows frustum, line of sight and up of the camera
  28801. * - suitable for fast updates
  28802. * - based on frustum visualization in lightgl.js shadowmap example
  28803. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  28804. */
  28805. var _vector$a = new Vector3();
  28806. var _camera = new Camera();
  28807. function CameraHelper(camera) {
  28808. var geometry = new BufferGeometry();
  28809. var material = new LineBasicMaterial({
  28810. color: 0xffffff,
  28811. vertexColors: FaceColors
  28812. });
  28813. var vertices = [];
  28814. var colors = [];
  28815. var pointMap = {}; // colors
  28816. var colorFrustum = new Color(0xffaa00);
  28817. var colorCone = new Color(0xff0000);
  28818. var colorUp = new Color(0x00aaff);
  28819. var colorTarget = new Color(0xffffff);
  28820. var colorCross = new Color(0x333333); // near
  28821. addLine('n1', 'n2', colorFrustum);
  28822. addLine('n2', 'n4', colorFrustum);
  28823. addLine('n4', 'n3', colorFrustum);
  28824. addLine('n3', 'n1', colorFrustum); // far
  28825. addLine('f1', 'f2', colorFrustum);
  28826. addLine('f2', 'f4', colorFrustum);
  28827. addLine('f4', 'f3', colorFrustum);
  28828. addLine('f3', 'f1', colorFrustum); // sides
  28829. addLine('n1', 'f1', colorFrustum);
  28830. addLine('n2', 'f2', colorFrustum);
  28831. addLine('n3', 'f3', colorFrustum);
  28832. addLine('n4', 'f4', colorFrustum); // cone
  28833. addLine('p', 'n1', colorCone);
  28834. addLine('p', 'n2', colorCone);
  28835. addLine('p', 'n3', colorCone);
  28836. addLine('p', 'n4', colorCone); // up
  28837. addLine('u1', 'u2', colorUp);
  28838. addLine('u2', 'u3', colorUp);
  28839. addLine('u3', 'u1', colorUp); // target
  28840. addLine('c', 't', colorTarget);
  28841. addLine('p', 'c', colorCross); // cross
  28842. addLine('cn1', 'cn2', colorCross);
  28843. addLine('cn3', 'cn4', colorCross);
  28844. addLine('cf1', 'cf2', colorCross);
  28845. addLine('cf3', 'cf4', colorCross);
  28846. function addLine(a, b, color) {
  28847. addPoint(a, color);
  28848. addPoint(b, color);
  28849. }
  28850. function addPoint(id, color) {
  28851. vertices.push(0, 0, 0);
  28852. colors.push(color.r, color.g, color.b);
  28853. if (pointMap[id] === undefined) {
  28854. pointMap[id] = [];
  28855. }
  28856. pointMap[id].push(vertices.length / 3 - 1);
  28857. }
  28858. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  28859. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  28860. LineSegments.call(this, geometry, material);
  28861. this.camera = camera;
  28862. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  28863. this.matrix = camera.matrixWorld;
  28864. this.matrixAutoUpdate = false;
  28865. this.pointMap = pointMap;
  28866. this.update();
  28867. }
  28868. CameraHelper.prototype = Object.create(LineSegments.prototype);
  28869. CameraHelper.prototype.constructor = CameraHelper;
  28870. CameraHelper.prototype.update = function () {
  28871. var geometry = this.geometry;
  28872. var pointMap = this.pointMap;
  28873. var w = 1,
  28874. h = 1; // we need just camera projection matrix inverse
  28875. // world matrix must be identity
  28876. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  28877. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  28878. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  28879. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  28880. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  28881. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  28882. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  28883. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  28884. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  28885. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  28886. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  28887. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  28888. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  28889. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  28890. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  28891. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  28892. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  28893. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  28894. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  28895. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  28896. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  28897. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  28898. geometry.getAttribute('position').needsUpdate = true;
  28899. };
  28900. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  28901. _vector$a.set(x, y, z).unproject(camera);
  28902. var points = pointMap[point];
  28903. if (points !== undefined) {
  28904. var position = geometry.getAttribute('position');
  28905. for (var i = 0, l = points.length; i < l; i++) {
  28906. position.setXYZ(points[i], _vector$a.x, _vector$a.y, _vector$a.z);
  28907. }
  28908. }
  28909. }
  28910. /**
  28911. * @author mrdoob / http://mrdoob.com/
  28912. * @author Mugen87 / http://github.com/Mugen87
  28913. */
  28914. var _box$2 = new Box3();
  28915. function BoxHelper(object, color) {
  28916. this.object = object;
  28917. if (color === undefined) color = 0xffff00;
  28918. 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]);
  28919. var positions = new Float32Array(8 * 3);
  28920. var geometry = new BufferGeometry();
  28921. geometry.setIndex(new BufferAttribute(indices, 1));
  28922. geometry.addAttribute('position', new BufferAttribute(positions, 3));
  28923. LineSegments.call(this, geometry, new LineBasicMaterial({
  28924. color: color
  28925. }));
  28926. this.matrixAutoUpdate = false;
  28927. this.update();
  28928. }
  28929. BoxHelper.prototype = Object.create(LineSegments.prototype);
  28930. BoxHelper.prototype.constructor = BoxHelper;
  28931. BoxHelper.prototype.update = function (object) {
  28932. if (object !== undefined) {
  28933. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  28934. }
  28935. if (this.object !== undefined) {
  28936. _box$2.setFromObject(this.object);
  28937. }
  28938. if (_box$2.isEmpty()) return;
  28939. var min = _box$2.min;
  28940. var max = _box$2.max;
  28941. /*
  28942. 5____4
  28943. 1/___0/|
  28944. | 6__|_7
  28945. 2/___3/
  28946. 0: max.x, max.y, max.z
  28947. 1: min.x, max.y, max.z
  28948. 2: min.x, min.y, max.z
  28949. 3: max.x, min.y, max.z
  28950. 4: max.x, max.y, min.z
  28951. 5: min.x, max.y, min.z
  28952. 6: min.x, min.y, min.z
  28953. 7: max.x, min.y, min.z
  28954. */
  28955. var position = this.geometry.attributes.position;
  28956. var array = position.array;
  28957. array[0] = max.x;
  28958. array[1] = max.y;
  28959. array[2] = max.z;
  28960. array[3] = min.x;
  28961. array[4] = max.y;
  28962. array[5] = max.z;
  28963. array[6] = min.x;
  28964. array[7] = min.y;
  28965. array[8] = max.z;
  28966. array[9] = max.x;
  28967. array[10] = min.y;
  28968. array[11] = max.z;
  28969. array[12] = max.x;
  28970. array[13] = max.y;
  28971. array[14] = min.z;
  28972. array[15] = min.x;
  28973. array[16] = max.y;
  28974. array[17] = min.z;
  28975. array[18] = min.x;
  28976. array[19] = min.y;
  28977. array[20] = min.z;
  28978. array[21] = max.x;
  28979. array[22] = min.y;
  28980. array[23] = min.z;
  28981. position.needsUpdate = true;
  28982. this.geometry.computeBoundingSphere();
  28983. };
  28984. BoxHelper.prototype.setFromObject = function (object) {
  28985. this.object = object;
  28986. this.update();
  28987. return this;
  28988. };
  28989. BoxHelper.prototype.copy = function (source) {
  28990. LineSegments.prototype.copy.call(this, source);
  28991. this.object = source.object;
  28992. return this;
  28993. };
  28994. BoxHelper.prototype.clone = function () {
  28995. return new this.constructor().copy(this);
  28996. };
  28997. /**
  28998. * @author WestLangley / http://github.com/WestLangley
  28999. */
  29000. function Box3Helper(box, color) {
  29001. this.type = 'Box3Helper';
  29002. this.box = box;
  29003. color = color || 0xffff00;
  29004. 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]);
  29005. 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];
  29006. var geometry = new BufferGeometry();
  29007. geometry.setIndex(new BufferAttribute(indices, 1));
  29008. geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));
  29009. LineSegments.call(this, geometry, new LineBasicMaterial({
  29010. color: color
  29011. }));
  29012. this.geometry.computeBoundingSphere();
  29013. }
  29014. Box3Helper.prototype = Object.create(LineSegments.prototype);
  29015. Box3Helper.prototype.constructor = Box3Helper;
  29016. Box3Helper.prototype.updateMatrixWorld = function (force) {
  29017. var box = this.box;
  29018. if (box.isEmpty()) return;
  29019. box.getCenter(this.position);
  29020. box.getSize(this.scale);
  29021. this.scale.multiplyScalar(0.5);
  29022. Object3D.prototype.updateMatrixWorld.call(this, force);
  29023. };
  29024. /**
  29025. * @author WestLangley / http://github.com/WestLangley
  29026. */
  29027. function PlaneHelper(plane, size, hex) {
  29028. this.type = 'PlaneHelper';
  29029. this.plane = plane;
  29030. this.size = size === undefined ? 1 : size;
  29031. var color = hex !== undefined ? hex : 0xffff00;
  29032. 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];
  29033. var geometry = new BufferGeometry();
  29034. geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));
  29035. geometry.computeBoundingSphere();
  29036. Line.call(this, geometry, new LineBasicMaterial({
  29037. color: color
  29038. })); //
  29039. var positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
  29040. var geometry2 = new BufferGeometry();
  29041. geometry2.addAttribute('position', new Float32BufferAttribute(positions2, 3));
  29042. geometry2.computeBoundingSphere();
  29043. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  29044. color: color,
  29045. opacity: 0.2,
  29046. transparent: true,
  29047. depthWrite: false
  29048. })));
  29049. }
  29050. PlaneHelper.prototype = Object.create(Line.prototype);
  29051. PlaneHelper.prototype.constructor = PlaneHelper;
  29052. PlaneHelper.prototype.updateMatrixWorld = function (force) {
  29053. var scale = -this.plane.constant;
  29054. if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
  29055. this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
  29056. this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  29057. this.lookAt(this.plane.normal);
  29058. Object3D.prototype.updateMatrixWorld.call(this, force);
  29059. };
  29060. /**
  29061. * @author WestLangley / http://github.com/WestLangley
  29062. * @author zz85 / http://github.com/zz85
  29063. * @author bhouston / http://clara.io
  29064. *
  29065. * Creates an arrow for visualizing directions
  29066. *
  29067. * Parameters:
  29068. * dir - Vector3
  29069. * origin - Vector3
  29070. * length - Number
  29071. * color - color in hex value
  29072. * headLength - Number
  29073. * headWidth - Number
  29074. */
  29075. var _axis = new Vector3();
  29076. var _lineGeometry, _coneGeometry;
  29077. function ArrowHelper(dir, origin, length, color, headLength, headWidth) {
  29078. // dir is assumed to be normalized
  29079. Object3D.call(this);
  29080. if (dir === undefined) dir = new Vector3(0, 0, 1);
  29081. if (origin === undefined) origin = new Vector3(0, 0, 0);
  29082. if (length === undefined) length = 1;
  29083. if (color === undefined) color = 0xffff00;
  29084. if (headLength === undefined) headLength = 0.2 * length;
  29085. if (headWidth === undefined) headWidth = 0.2 * headLength;
  29086. if (_lineGeometry === undefined) {
  29087. _lineGeometry = new BufferGeometry();
  29088. _lineGeometry.addAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  29089. _coneGeometry = new CylinderBufferGeometry(0, 0.5, 1, 5, 1);
  29090. _coneGeometry.translate(0, -0.5, 0);
  29091. }
  29092. this.position.copy(origin);
  29093. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  29094. color: color
  29095. }));
  29096. this.line.matrixAutoUpdate = false;
  29097. this.add(this.line);
  29098. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  29099. color: color
  29100. }));
  29101. this.cone.matrixAutoUpdate = false;
  29102. this.add(this.cone);
  29103. this.setDirection(dir);
  29104. this.setLength(length, headLength, headWidth);
  29105. }
  29106. ArrowHelper.prototype = Object.create(Object3D.prototype);
  29107. ArrowHelper.prototype.constructor = ArrowHelper;
  29108. ArrowHelper.prototype.setDirection = function (dir) {
  29109. // dir is assumed to be normalized
  29110. if (dir.y > 0.99999) {
  29111. this.quaternion.set(0, 0, 0, 1);
  29112. } else if (dir.y < -0.99999) {
  29113. this.quaternion.set(1, 0, 0, 0);
  29114. } else {
  29115. _axis.set(dir.z, 0, -dir.x).normalize();
  29116. var radians = Math.acos(dir.y);
  29117. this.quaternion.setFromAxisAngle(_axis, radians);
  29118. }
  29119. };
  29120. ArrowHelper.prototype.setLength = function (length, headLength, headWidth) {
  29121. if (headLength === undefined) headLength = 0.2 * length;
  29122. if (headWidth === undefined) headWidth = 0.2 * headLength;
  29123. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  29124. this.line.updateMatrix();
  29125. this.cone.scale.set(headWidth, headLength, headWidth);
  29126. this.cone.position.y = length;
  29127. this.cone.updateMatrix();
  29128. };
  29129. ArrowHelper.prototype.setColor = function (color) {
  29130. this.line.material.color.set(color);
  29131. this.cone.material.color.set(color);
  29132. };
  29133. ArrowHelper.prototype.copy = function (source) {
  29134. Object3D.prototype.copy.call(this, source, false);
  29135. this.line.copy(source.line);
  29136. this.cone.copy(source.cone);
  29137. return this;
  29138. };
  29139. ArrowHelper.prototype.clone = function () {
  29140. return new this.constructor().copy(this);
  29141. };
  29142. /**
  29143. * @author sroucheray / http://sroucheray.org/
  29144. * @author mrdoob / http://mrdoob.com/
  29145. */
  29146. function AxesHelper(size) {
  29147. size = size || 1;
  29148. var vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  29149. var colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  29150. var geometry = new BufferGeometry();
  29151. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  29152. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  29153. var material = new LineBasicMaterial({
  29154. vertexColors: VertexColors
  29155. });
  29156. LineSegments.call(this, geometry, material);
  29157. }
  29158. AxesHelper.prototype = Object.create(LineSegments.prototype);
  29159. AxesHelper.prototype.constructor = AxesHelper;
  29160. /**
  29161. * @author mrdoob / http://mrdoob.com/
  29162. */
  29163. function Face4(a, b, c, d, normal, color, materialIndex) {
  29164. console.warn('THREE.Face4 has been removed. A THREE.Face3 will be created instead.');
  29165. return new Face3(a, b, c, normal, color, materialIndex);
  29166. }
  29167. var LineStrip = 0;
  29168. exports.LineStrip = LineStrip;
  29169. var LinePieces = 1;
  29170. exports.LinePieces = LinePieces;
  29171. function MeshFaceMaterial(materials) {
  29172. console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
  29173. return materials;
  29174. }
  29175. function MultiMaterial(materials) {
  29176. if (materials === undefined) materials = [];
  29177. console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
  29178. materials.isMultiMaterial = true;
  29179. materials.materials = materials;
  29180. materials.clone = function () {
  29181. return materials.slice();
  29182. };
  29183. return materials;
  29184. }
  29185. function PointCloud(geometry, material) {
  29186. console.warn('THREE.PointCloud has been renamed to THREE.Points.');
  29187. return new Points(geometry, material);
  29188. }
  29189. function Particle(material) {
  29190. console.warn('THREE.Particle has been renamed to THREE.Sprite.');
  29191. return new Sprite(material);
  29192. }
  29193. function ParticleSystem(geometry, material) {
  29194. console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
  29195. return new Points(geometry, material);
  29196. }
  29197. function PointCloudMaterial(parameters) {
  29198. console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
  29199. return new PointsMaterial(parameters);
  29200. }
  29201. function ParticleBasicMaterial(parameters) {
  29202. console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
  29203. return new PointsMaterial(parameters);
  29204. }
  29205. function ParticleSystemMaterial(parameters) {
  29206. console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
  29207. return new PointsMaterial(parameters);
  29208. }
  29209. function Vertex(x, y, z) {
  29210. console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
  29211. return new Vector3(x, y, z);
  29212. } //
  29213. function DynamicBufferAttribute(array, itemSize) {
  29214. console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.');
  29215. return new BufferAttribute(array, itemSize).setDynamic(true);
  29216. }
  29217. function Int8Attribute(array, itemSize) {
  29218. console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
  29219. return new Int8BufferAttribute(array, itemSize);
  29220. }
  29221. function Uint8Attribute(array, itemSize) {
  29222. console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
  29223. return new Uint8BufferAttribute(array, itemSize);
  29224. }
  29225. function Uint8ClampedAttribute(array, itemSize) {
  29226. console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
  29227. return new Uint8ClampedBufferAttribute(array, itemSize);
  29228. }
  29229. function Int16Attribute(array, itemSize) {
  29230. console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
  29231. return new Int16BufferAttribute(array, itemSize);
  29232. }
  29233. function Uint16Attribute(array, itemSize) {
  29234. console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
  29235. return new Uint16BufferAttribute(array, itemSize);
  29236. }
  29237. function Int32Attribute(array, itemSize) {
  29238. console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
  29239. return new Int32BufferAttribute(array, itemSize);
  29240. }
  29241. function Uint32Attribute(array, itemSize) {
  29242. console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
  29243. return new Uint32BufferAttribute(array, itemSize);
  29244. }
  29245. function Float32Attribute(array, itemSize) {
  29246. console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
  29247. return new Float32BufferAttribute(array, itemSize);
  29248. }
  29249. function Float64Attribute(array, itemSize) {
  29250. console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
  29251. return new Float64BufferAttribute(array, itemSize);
  29252. } //
  29253. Curve.create = function (construct, getPoint) {
  29254. console.log('THREE.Curve.create() has been deprecated');
  29255. construct.prototype = Object.create(Curve.prototype);
  29256. construct.prototype.constructor = construct;
  29257. construct.prototype.getPoint = getPoint;
  29258. return construct;
  29259. }; //
  29260. Object.assign(CurvePath.prototype, {
  29261. createPointsGeometry: function (divisions) {
  29262. 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)
  29263. var pts = this.getPoints(divisions);
  29264. return this.createGeometry(pts);
  29265. },
  29266. createSpacedPointsGeometry: function (divisions) {
  29267. console.warn('THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.'); // generate geometry from equidistant sampling along the path
  29268. var pts = this.getSpacedPoints(divisions);
  29269. return this.createGeometry(pts);
  29270. },
  29271. createGeometry: function (points) {
  29272. console.warn('THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.');
  29273. var geometry = new Geometry();
  29274. for (var i = 0, l = points.length; i < l; i++) {
  29275. var point = points[i];
  29276. geometry.vertices.push(new Vector3(point.x, point.y, point.z || 0));
  29277. }
  29278. return geometry;
  29279. }
  29280. }); //
  29281. Object.assign(Path.prototype, {
  29282. fromPoints: function (points) {
  29283. console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
  29284. this.setFromPoints(points);
  29285. }
  29286. }); //
  29287. function ClosedSplineCurve3(points) {
  29288. console.warn('THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
  29289. CatmullRomCurve3.call(this, points);
  29290. this.type = 'catmullrom';
  29291. this.closed = true;
  29292. }
  29293. ClosedSplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
  29294. function SplineCurve3(points) {
  29295. console.warn('THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
  29296. CatmullRomCurve3.call(this, points);
  29297. this.type = 'catmullrom';
  29298. }
  29299. SplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
  29300. function Spline(points) {
  29301. console.warn('THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.');
  29302. CatmullRomCurve3.call(this, points);
  29303. this.type = 'catmullrom';
  29304. }
  29305. Spline.prototype = Object.create(CatmullRomCurve3.prototype);
  29306. Object.assign(Spline.prototype, {
  29307. initFromArray: function ()
  29308. /* a */
  29309. {
  29310. console.error('THREE.Spline: .initFromArray() has been removed.');
  29311. },
  29312. getControlPointsArray: function ()
  29313. /* optionalTarget */
  29314. {
  29315. console.error('THREE.Spline: .getControlPointsArray() has been removed.');
  29316. },
  29317. reparametrizeByArcLength: function ()
  29318. /* samplingCoef */
  29319. {
  29320. console.error('THREE.Spline: .reparametrizeByArcLength() has been removed.');
  29321. }
  29322. }); //
  29323. function AxisHelper(size) {
  29324. console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
  29325. return new AxesHelper(size);
  29326. }
  29327. function BoundingBoxHelper(object, color) {
  29328. console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
  29329. return new BoxHelper(object, color);
  29330. }
  29331. function EdgesHelper(object, hex) {
  29332. console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
  29333. return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
  29334. color: hex !== undefined ? hex : 0xffffff
  29335. }));
  29336. }
  29337. GridHelper.prototype.setColors = function () {
  29338. console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
  29339. };
  29340. SkeletonHelper.prototype.update = function () {
  29341. console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
  29342. };
  29343. function WireframeHelper(object, hex) {
  29344. console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
  29345. return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
  29346. color: hex !== undefined ? hex : 0xffffff
  29347. }));
  29348. } //
  29349. Object.assign(Loader.prototype, {
  29350. extractUrlBase: function (url) {
  29351. console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
  29352. return LoaderUtils.extractUrlBase(url);
  29353. }
  29354. });
  29355. Loader.Handlers = {
  29356. add: function ()
  29357. /* regex, loader */
  29358. {
  29359. console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
  29360. },
  29361. get: function ()
  29362. /* file */
  29363. {
  29364. console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
  29365. }
  29366. };
  29367. function XHRLoader(manager) {
  29368. console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
  29369. return new FileLoader(manager);
  29370. }
  29371. function BinaryTextureLoader(manager) {
  29372. console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
  29373. return new DataTextureLoader(manager);
  29374. }
  29375. Object.assign(ObjectLoader.prototype, {
  29376. setTexturePath: function (value) {
  29377. console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
  29378. return this.setResourcePath(value);
  29379. }
  29380. }); //
  29381. Object.assign(Box2.prototype, {
  29382. center: function (optionalTarget) {
  29383. console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
  29384. return this.getCenter(optionalTarget);
  29385. },
  29386. empty: function () {
  29387. console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
  29388. return this.isEmpty();
  29389. },
  29390. isIntersectionBox: function (box) {
  29391. console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
  29392. return this.intersectsBox(box);
  29393. },
  29394. size: function (optionalTarget) {
  29395. console.warn('THREE.Box2: .size() has been renamed to .getSize().');
  29396. return this.getSize(optionalTarget);
  29397. }
  29398. });
  29399. Object.assign(Box3.prototype, {
  29400. center: function (optionalTarget) {
  29401. console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
  29402. return this.getCenter(optionalTarget);
  29403. },
  29404. empty: function () {
  29405. console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
  29406. return this.isEmpty();
  29407. },
  29408. isIntersectionBox: function (box) {
  29409. console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
  29410. return this.intersectsBox(box);
  29411. },
  29412. isIntersectionSphere: function (sphere) {
  29413. console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  29414. return this.intersectsSphere(sphere);
  29415. },
  29416. size: function (optionalTarget) {
  29417. console.warn('THREE.Box3: .size() has been renamed to .getSize().');
  29418. return this.getSize(optionalTarget);
  29419. }
  29420. });
  29421. Line3.prototype.center = function (optionalTarget) {
  29422. console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
  29423. return this.getCenter(optionalTarget);
  29424. };
  29425. Object.assign(_Math, {
  29426. random16: function () {
  29427. console.warn('THREE.Math: .random16() has been deprecated. Use Math.random() instead.');
  29428. return Math.random();
  29429. },
  29430. nearestPowerOfTwo: function (value) {
  29431. console.warn('THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().');
  29432. return _Math.floorPowerOfTwo(value);
  29433. },
  29434. nextPowerOfTwo: function (value) {
  29435. console.warn('THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().');
  29436. return _Math.ceilPowerOfTwo(value);
  29437. }
  29438. });
  29439. Object.assign(Matrix3.prototype, {
  29440. flattenToArrayOffset: function (array, offset) {
  29441. console.warn("THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");
  29442. return this.toArray(array, offset);
  29443. },
  29444. multiplyVector3: function (vector) {
  29445. console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
  29446. return vector.applyMatrix3(this);
  29447. },
  29448. multiplyVector3Array: function ()
  29449. /* a */
  29450. {
  29451. console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
  29452. },
  29453. applyToBuffer: function (buffer
  29454. /*, offset, length */
  29455. ) {
  29456. console.warn('THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.');
  29457. return this.applyToBufferAttribute(buffer);
  29458. },
  29459. applyToVector3Array: function ()
  29460. /* array, offset, length */
  29461. {
  29462. console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
  29463. }
  29464. });
  29465. Object.assign(Matrix4.prototype, {
  29466. extractPosition: function (m) {
  29467. console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
  29468. return this.copyPosition(m);
  29469. },
  29470. flattenToArrayOffset: function (array, offset) {
  29471. console.warn("THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");
  29472. return this.toArray(array, offset);
  29473. },
  29474. getPosition: function () {
  29475. console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
  29476. return new Vector3().setFromMatrixColumn(this, 3);
  29477. },
  29478. setRotationFromQuaternion: function (q) {
  29479. console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
  29480. return this.makeRotationFromQuaternion(q);
  29481. },
  29482. multiplyToArray: function () {
  29483. console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
  29484. },
  29485. multiplyVector3: function (vector) {
  29486. console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29487. return vector.applyMatrix4(this);
  29488. },
  29489. multiplyVector4: function (vector) {
  29490. console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29491. return vector.applyMatrix4(this);
  29492. },
  29493. multiplyVector3Array: function ()
  29494. /* a */
  29495. {
  29496. console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
  29497. },
  29498. rotateAxis: function (v) {
  29499. console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
  29500. v.transformDirection(this);
  29501. },
  29502. crossVector: function (vector) {
  29503. console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29504. return vector.applyMatrix4(this);
  29505. },
  29506. translate: function () {
  29507. console.error('THREE.Matrix4: .translate() has been removed.');
  29508. },
  29509. rotateX: function () {
  29510. console.error('THREE.Matrix4: .rotateX() has been removed.');
  29511. },
  29512. rotateY: function () {
  29513. console.error('THREE.Matrix4: .rotateY() has been removed.');
  29514. },
  29515. rotateZ: function () {
  29516. console.error('THREE.Matrix4: .rotateZ() has been removed.');
  29517. },
  29518. rotateByAxis: function () {
  29519. console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
  29520. },
  29521. applyToBuffer: function (buffer
  29522. /*, offset, length */
  29523. ) {
  29524. console.warn('THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.');
  29525. return this.applyToBufferAttribute(buffer);
  29526. },
  29527. applyToVector3Array: function ()
  29528. /* array, offset, length */
  29529. {
  29530. console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
  29531. },
  29532. makeFrustum: function (left, right, bottom, top, near, far) {
  29533. console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
  29534. return this.makePerspective(left, right, top, bottom, near, far);
  29535. }
  29536. });
  29537. Plane.prototype.isIntersectionLine = function (line) {
  29538. console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
  29539. return this.intersectsLine(line);
  29540. };
  29541. Quaternion.prototype.multiplyVector3 = function (vector) {
  29542. console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
  29543. return vector.applyQuaternion(this);
  29544. };
  29545. Object.assign(Ray.prototype, {
  29546. isIntersectionBox: function (box) {
  29547. console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
  29548. return this.intersectsBox(box);
  29549. },
  29550. isIntersectionPlane: function (plane) {
  29551. console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
  29552. return this.intersectsPlane(plane);
  29553. },
  29554. isIntersectionSphere: function (sphere) {
  29555. console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  29556. return this.intersectsSphere(sphere);
  29557. }
  29558. });
  29559. Object.assign(Triangle.prototype, {
  29560. area: function () {
  29561. console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
  29562. return this.getArea();
  29563. },
  29564. barycoordFromPoint: function (point, target) {
  29565. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  29566. return this.getBarycoord(point, target);
  29567. },
  29568. midpoint: function (target) {
  29569. console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
  29570. return this.getMidpoint(target);
  29571. },
  29572. normal: function (target) {
  29573. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  29574. return this.getNormal(target);
  29575. },
  29576. plane: function (target) {
  29577. console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
  29578. return this.getPlane(target);
  29579. }
  29580. });
  29581. Object.assign(Triangle, {
  29582. barycoordFromPoint: function (point, a, b, c, target) {
  29583. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  29584. return Triangle.getBarycoord(point, a, b, c, target);
  29585. },
  29586. normal: function (a, b, c, target) {
  29587. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  29588. return Triangle.getNormal(a, b, c, target);
  29589. }
  29590. });
  29591. Object.assign(Shape.prototype, {
  29592. extractAllPoints: function (divisions) {
  29593. console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
  29594. return this.extractPoints(divisions);
  29595. },
  29596. extrude: function (options) {
  29597. console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
  29598. return new ExtrudeGeometry(this, options);
  29599. },
  29600. makeGeometry: function (options) {
  29601. console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
  29602. return new ShapeGeometry(this, options);
  29603. }
  29604. });
  29605. Object.assign(Vector2.prototype, {
  29606. fromAttribute: function (attribute, index, offset) {
  29607. console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29608. return this.fromBufferAttribute(attribute, index, offset);
  29609. },
  29610. distanceToManhattan: function (v) {
  29611. console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  29612. return this.manhattanDistanceTo(v);
  29613. },
  29614. lengthManhattan: function () {
  29615. console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
  29616. return this.manhattanLength();
  29617. }
  29618. });
  29619. Object.assign(Vector3.prototype, {
  29620. setEulerFromRotationMatrix: function () {
  29621. console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
  29622. },
  29623. setEulerFromQuaternion: function () {
  29624. console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
  29625. },
  29626. getPositionFromMatrix: function (m) {
  29627. console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
  29628. return this.setFromMatrixPosition(m);
  29629. },
  29630. getScaleFromMatrix: function (m) {
  29631. console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
  29632. return this.setFromMatrixScale(m);
  29633. },
  29634. getColumnFromMatrix: function (index, matrix) {
  29635. console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
  29636. return this.setFromMatrixColumn(matrix, index);
  29637. },
  29638. applyProjection: function (m) {
  29639. console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
  29640. return this.applyMatrix4(m);
  29641. },
  29642. fromAttribute: function (attribute, index, offset) {
  29643. console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29644. return this.fromBufferAttribute(attribute, index, offset);
  29645. },
  29646. distanceToManhattan: function (v) {
  29647. console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  29648. return this.manhattanDistanceTo(v);
  29649. },
  29650. lengthManhattan: function () {
  29651. console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
  29652. return this.manhattanLength();
  29653. }
  29654. });
  29655. Object.assign(Vector4.prototype, {
  29656. fromAttribute: function (attribute, index, offset) {
  29657. console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29658. return this.fromBufferAttribute(attribute, index, offset);
  29659. },
  29660. lengthManhattan: function () {
  29661. console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
  29662. return this.manhattanLength();
  29663. }
  29664. }); //
  29665. Object.assign(Geometry.prototype, {
  29666. computeTangents: function () {
  29667. console.error('THREE.Geometry: .computeTangents() has been removed.');
  29668. },
  29669. computeLineDistances: function () {
  29670. console.error('THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.');
  29671. }
  29672. });
  29673. Object.assign(Object3D.prototype, {
  29674. getChildByName: function (name) {
  29675. console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
  29676. return this.getObjectByName(name);
  29677. },
  29678. renderDepth: function () {
  29679. console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
  29680. },
  29681. translate: function (distance, axis) {
  29682. console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
  29683. return this.translateOnAxis(axis, distance);
  29684. },
  29685. getWorldRotation: function () {
  29686. console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
  29687. }
  29688. });
  29689. Object.defineProperties(Object3D.prototype, {
  29690. eulerOrder: {
  29691. get: function () {
  29692. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  29693. return this.rotation.order;
  29694. },
  29695. set: function (value) {
  29696. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  29697. this.rotation.order = value;
  29698. }
  29699. },
  29700. useQuaternion: {
  29701. get: function () {
  29702. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  29703. },
  29704. set: function () {
  29705. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  29706. }
  29707. }
  29708. });
  29709. Object.defineProperties(LOD.prototype, {
  29710. objects: {
  29711. get: function () {
  29712. console.warn('THREE.LOD: .objects has been renamed to .levels.');
  29713. return this.levels;
  29714. }
  29715. }
  29716. });
  29717. Object.defineProperty(Skeleton.prototype, 'useVertexTexture', {
  29718. get: function () {
  29719. console.warn('THREE.Skeleton: useVertexTexture has been removed.');
  29720. },
  29721. set: function () {
  29722. console.warn('THREE.Skeleton: useVertexTexture has been removed.');
  29723. }
  29724. });
  29725. SkinnedMesh.prototype.initBones = function () {
  29726. console.error('THREE.SkinnedMesh: initBones() has been removed.');
  29727. };
  29728. Object.defineProperty(Curve.prototype, '__arcLengthDivisions', {
  29729. get: function () {
  29730. console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
  29731. return this.arcLengthDivisions;
  29732. },
  29733. set: function (value) {
  29734. console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
  29735. this.arcLengthDivisions = value;
  29736. }
  29737. }); //
  29738. PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
  29739. console.warn("THREE.PerspectiveCamera.setLens is deprecated. " + "Use .setFocalLength and .filmGauge for a photographic setup.");
  29740. if (filmGauge !== undefined) this.filmGauge = filmGauge;
  29741. this.setFocalLength(focalLength);
  29742. }; //
  29743. Object.defineProperties(Light.prototype, {
  29744. onlyShadow: {
  29745. set: function () {
  29746. console.warn('THREE.Light: .onlyShadow has been removed.');
  29747. }
  29748. },
  29749. shadowCameraFov: {
  29750. set: function (value) {
  29751. console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
  29752. this.shadow.camera.fov = value;
  29753. }
  29754. },
  29755. shadowCameraLeft: {
  29756. set: function (value) {
  29757. console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
  29758. this.shadow.camera.left = value;
  29759. }
  29760. },
  29761. shadowCameraRight: {
  29762. set: function (value) {
  29763. console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
  29764. this.shadow.camera.right = value;
  29765. }
  29766. },
  29767. shadowCameraTop: {
  29768. set: function (value) {
  29769. console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
  29770. this.shadow.camera.top = value;
  29771. }
  29772. },
  29773. shadowCameraBottom: {
  29774. set: function (value) {
  29775. console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
  29776. this.shadow.camera.bottom = value;
  29777. }
  29778. },
  29779. shadowCameraNear: {
  29780. set: function (value) {
  29781. console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
  29782. this.shadow.camera.near = value;
  29783. }
  29784. },
  29785. shadowCameraFar: {
  29786. set: function (value) {
  29787. console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
  29788. this.shadow.camera.far = value;
  29789. }
  29790. },
  29791. shadowCameraVisible: {
  29792. set: function () {
  29793. console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
  29794. }
  29795. },
  29796. shadowBias: {
  29797. set: function (value) {
  29798. console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
  29799. this.shadow.bias = value;
  29800. }
  29801. },
  29802. shadowDarkness: {
  29803. set: function () {
  29804. console.warn('THREE.Light: .shadowDarkness has been removed.');
  29805. }
  29806. },
  29807. shadowMapWidth: {
  29808. set: function (value) {
  29809. console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
  29810. this.shadow.mapSize.width = value;
  29811. }
  29812. },
  29813. shadowMapHeight: {
  29814. set: function (value) {
  29815. console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
  29816. this.shadow.mapSize.height = value;
  29817. }
  29818. }
  29819. }); //
  29820. Object.defineProperties(BufferAttribute.prototype, {
  29821. length: {
  29822. get: function () {
  29823. console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
  29824. return this.array.length;
  29825. }
  29826. }
  29827. });
  29828. Object.assign(BufferAttribute.prototype, {
  29829. copyIndicesArray: function ()
  29830. /* indices */
  29831. {
  29832. console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
  29833. },
  29834. setArray: function (array) {
  29835. console.warn('THREE.BufferAttribute: .setArray has been deprecated. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  29836. this.count = array !== undefined ? array.length / this.itemSize : 0;
  29837. this.array = array;
  29838. return this;
  29839. }
  29840. });
  29841. Object.assign(BufferGeometry.prototype, {
  29842. addIndex: function (index) {
  29843. console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
  29844. this.setIndex(index);
  29845. },
  29846. addDrawCall: function (start, count, indexOffset) {
  29847. if (indexOffset !== undefined) {
  29848. console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
  29849. }
  29850. console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
  29851. this.addGroup(start, count);
  29852. },
  29853. clearDrawCalls: function () {
  29854. console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
  29855. this.clearGroups();
  29856. },
  29857. computeTangents: function () {
  29858. console.warn('THREE.BufferGeometry: .computeTangents() has been removed.');
  29859. },
  29860. computeOffsets: function () {
  29861. console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
  29862. }
  29863. });
  29864. Object.defineProperties(BufferGeometry.prototype, {
  29865. drawcalls: {
  29866. get: function () {
  29867. console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
  29868. return this.groups;
  29869. }
  29870. },
  29871. offsets: {
  29872. get: function () {
  29873. console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
  29874. return this.groups;
  29875. }
  29876. }
  29877. });
  29878. Object.assign(InterleavedBuffer.prototype, {
  29879. setArray: function (array) {
  29880. console.warn('THREE.InterleavedBuffer: .setArray has been deprecated. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  29881. this.count = array !== undefined ? array.length / this.stride : 0;
  29882. this.array = array;
  29883. return this;
  29884. }
  29885. }); //
  29886. Object.assign(ExtrudeBufferGeometry.prototype, {
  29887. getArrays: function () {
  29888. console.error('THREE.ExtrudeBufferGeometry: .getArrays() has been removed.');
  29889. },
  29890. addShapeList: function () {
  29891. console.error('THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.');
  29892. },
  29893. addShape: function () {
  29894. console.error('THREE.ExtrudeBufferGeometry: .addShape() has been removed.');
  29895. }
  29896. }); //
  29897. Object.defineProperties(Uniform.prototype, {
  29898. dynamic: {
  29899. set: function () {
  29900. console.warn('THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.');
  29901. }
  29902. },
  29903. onUpdate: {
  29904. value: function () {
  29905. console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
  29906. return this;
  29907. }
  29908. }
  29909. }); //
  29910. Object.defineProperties(Material.prototype, {
  29911. wrapAround: {
  29912. get: function () {
  29913. console.warn('THREE.Material: .wrapAround has been removed.');
  29914. },
  29915. set: function () {
  29916. console.warn('THREE.Material: .wrapAround has been removed.');
  29917. }
  29918. },
  29919. overdraw: {
  29920. get: function () {
  29921. console.warn('THREE.Material: .overdraw has been removed.');
  29922. },
  29923. set: function () {
  29924. console.warn('THREE.Material: .overdraw has been removed.');
  29925. }
  29926. },
  29927. wrapRGB: {
  29928. get: function () {
  29929. console.warn('THREE.Material: .wrapRGB has been removed.');
  29930. return new Color();
  29931. }
  29932. },
  29933. shading: {
  29934. get: function () {
  29935. console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  29936. },
  29937. set: function (value) {
  29938. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  29939. this.flatShading = value === FlatShading;
  29940. }
  29941. },
  29942. stencilMask: {
  29943. get: function () {
  29944. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  29945. return this.stencilFuncMask;
  29946. },
  29947. set: function (value) {
  29948. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  29949. this.stencilFuncMask = value;
  29950. }
  29951. }
  29952. });
  29953. Object.defineProperties(MeshPhongMaterial.prototype, {
  29954. metal: {
  29955. get: function () {
  29956. console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.');
  29957. return false;
  29958. },
  29959. set: function () {
  29960. console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead');
  29961. }
  29962. }
  29963. });
  29964. Object.defineProperties(ShaderMaterial.prototype, {
  29965. derivatives: {
  29966. get: function () {
  29967. console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  29968. return this.extensions.derivatives;
  29969. },
  29970. set: function (value) {
  29971. console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  29972. this.extensions.derivatives = value;
  29973. }
  29974. }
  29975. }); //
  29976. Object.assign(WebGLRenderer.prototype, {
  29977. clearTarget: function (renderTarget, color, depth, stencil) {
  29978. console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
  29979. this.setRenderTarget(renderTarget);
  29980. this.clear(color, depth, stencil);
  29981. },
  29982. animate: function (callback) {
  29983. console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
  29984. this.setAnimationLoop(callback);
  29985. },
  29986. getCurrentRenderTarget: function () {
  29987. console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
  29988. return this.getRenderTarget();
  29989. },
  29990. getMaxAnisotropy: function () {
  29991. console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
  29992. return this.capabilities.getMaxAnisotropy();
  29993. },
  29994. getPrecision: function () {
  29995. console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
  29996. return this.capabilities.precision;
  29997. },
  29998. resetGLState: function () {
  29999. console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
  30000. return this.state.reset();
  30001. },
  30002. supportsFloatTextures: function () {
  30003. console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
  30004. return this.extensions.get('OES_texture_float');
  30005. },
  30006. supportsHalfFloatTextures: function () {
  30007. console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
  30008. return this.extensions.get('OES_texture_half_float');
  30009. },
  30010. supportsStandardDerivatives: function () {
  30011. console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
  30012. return this.extensions.get('OES_standard_derivatives');
  30013. },
  30014. supportsCompressedTextureS3TC: function () {
  30015. console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
  30016. return this.extensions.get('WEBGL_compressed_texture_s3tc');
  30017. },
  30018. supportsCompressedTexturePVRTC: function () {
  30019. console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
  30020. return this.extensions.get('WEBGL_compressed_texture_pvrtc');
  30021. },
  30022. supportsBlendMinMax: function () {
  30023. console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
  30024. return this.extensions.get('EXT_blend_minmax');
  30025. },
  30026. supportsVertexTextures: function () {
  30027. console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
  30028. return this.capabilities.vertexTextures;
  30029. },
  30030. supportsInstancedArrays: function () {
  30031. console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
  30032. return this.extensions.get('ANGLE_instanced_arrays');
  30033. },
  30034. enableScissorTest: function (boolean) {
  30035. console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
  30036. this.setScissorTest(boolean);
  30037. },
  30038. initMaterial: function () {
  30039. console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
  30040. },
  30041. addPrePlugin: function () {
  30042. console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
  30043. },
  30044. addPostPlugin: function () {
  30045. console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
  30046. },
  30047. updateShadowMap: function () {
  30048. console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
  30049. },
  30050. setFaceCulling: function () {
  30051. console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
  30052. },
  30053. allocTextureUnit: function () {
  30054. console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
  30055. },
  30056. setTexture: function () {
  30057. console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
  30058. },
  30059. setTexture2D: function () {
  30060. console.warn('THREE.WebGLRenderer: .setTexture2D() has been removed.');
  30061. },
  30062. setTextureCube: function () {
  30063. console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
  30064. },
  30065. getActiveMipMapLevel: function () {
  30066. console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
  30067. return this.getActiveMipmapLevel();
  30068. }
  30069. });
  30070. Object.defineProperties(WebGLRenderer.prototype, {
  30071. shadowMapEnabled: {
  30072. get: function () {
  30073. return this.shadowMap.enabled;
  30074. },
  30075. set: function (value) {
  30076. console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
  30077. this.shadowMap.enabled = value;
  30078. }
  30079. },
  30080. shadowMapType: {
  30081. get: function () {
  30082. return this.shadowMap.type;
  30083. },
  30084. set: function (value) {
  30085. console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
  30086. this.shadowMap.type = value;
  30087. }
  30088. },
  30089. shadowMapCullFace: {
  30090. get: function () {
  30091. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  30092. return undefined;
  30093. },
  30094. set: function ()
  30095. /* value */
  30096. {
  30097. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  30098. }
  30099. },
  30100. context: {
  30101. get: function () {
  30102. console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
  30103. return this.getContext();
  30104. }
  30105. }
  30106. });
  30107. Object.defineProperties(WebGLShadowMap.prototype, {
  30108. cullFace: {
  30109. get: function () {
  30110. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  30111. return undefined;
  30112. },
  30113. set: function ()
  30114. /* cullFace */
  30115. {
  30116. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  30117. }
  30118. },
  30119. renderReverseSided: {
  30120. get: function () {
  30121. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  30122. return undefined;
  30123. },
  30124. set: function () {
  30125. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  30126. }
  30127. },
  30128. renderSingleSided: {
  30129. get: function () {
  30130. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  30131. return undefined;
  30132. },
  30133. set: function () {
  30134. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  30135. }
  30136. }
  30137. }); //
  30138. Object.defineProperties(WebGLRenderTargetCube.prototype, {
  30139. activeCubeFace: {
  30140. set: function ()
  30141. /* value */
  30142. {
  30143. console.warn('THREE.WebGLRenderTargetCube: .activeCubeFace has been removed. It is now the second parameter of WebGLRenderer.setRenderTarget().');
  30144. }
  30145. },
  30146. activeMipMapLevel: {
  30147. set: function ()
  30148. /* value */
  30149. {
  30150. console.warn('THREE.WebGLRenderTargetCube: .activeMipMapLevel has been removed. It is now the third parameter of WebGLRenderer.setRenderTarget().');
  30151. }
  30152. }
  30153. }); //
  30154. Object.defineProperties(WebGLRenderTarget.prototype, {
  30155. wrapS: {
  30156. get: function () {
  30157. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  30158. return this.texture.wrapS;
  30159. },
  30160. set: function (value) {
  30161. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  30162. this.texture.wrapS = value;
  30163. }
  30164. },
  30165. wrapT: {
  30166. get: function () {
  30167. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  30168. return this.texture.wrapT;
  30169. },
  30170. set: function (value) {
  30171. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  30172. this.texture.wrapT = value;
  30173. }
  30174. },
  30175. magFilter: {
  30176. get: function () {
  30177. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  30178. return this.texture.magFilter;
  30179. },
  30180. set: function (value) {
  30181. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  30182. this.texture.magFilter = value;
  30183. }
  30184. },
  30185. minFilter: {
  30186. get: function () {
  30187. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  30188. return this.texture.minFilter;
  30189. },
  30190. set: function (value) {
  30191. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  30192. this.texture.minFilter = value;
  30193. }
  30194. },
  30195. anisotropy: {
  30196. get: function () {
  30197. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  30198. return this.texture.anisotropy;
  30199. },
  30200. set: function (value) {
  30201. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  30202. this.texture.anisotropy = value;
  30203. }
  30204. },
  30205. offset: {
  30206. get: function () {
  30207. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  30208. return this.texture.offset;
  30209. },
  30210. set: function (value) {
  30211. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  30212. this.texture.offset = value;
  30213. }
  30214. },
  30215. repeat: {
  30216. get: function () {
  30217. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  30218. return this.texture.repeat;
  30219. },
  30220. set: function (value) {
  30221. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  30222. this.texture.repeat = value;
  30223. }
  30224. },
  30225. format: {
  30226. get: function () {
  30227. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  30228. return this.texture.format;
  30229. },
  30230. set: function (value) {
  30231. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  30232. this.texture.format = value;
  30233. }
  30234. },
  30235. type: {
  30236. get: function () {
  30237. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  30238. return this.texture.type;
  30239. },
  30240. set: function (value) {
  30241. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  30242. this.texture.type = value;
  30243. }
  30244. },
  30245. generateMipmaps: {
  30246. get: function () {
  30247. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  30248. return this.texture.generateMipmaps;
  30249. },
  30250. set: function (value) {
  30251. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  30252. this.texture.generateMipmaps = value;
  30253. }
  30254. }
  30255. }); //
  30256. Object.defineProperties(WebVRManager.prototype, {
  30257. standing: {
  30258. set: function ()
  30259. /* value */
  30260. {
  30261. console.warn('THREE.WebVRManager: .standing has been removed.');
  30262. }
  30263. },
  30264. userHeight: {
  30265. set: function ()
  30266. /* value */
  30267. {
  30268. console.warn('THREE.WebVRManager: .userHeight has been removed.');
  30269. }
  30270. }
  30271. }); //
  30272. Audio.prototype.load = function (file) {
  30273. console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
  30274. var scope = this;
  30275. var audioLoader = new AudioLoader();
  30276. audioLoader.load(file, function (buffer) {
  30277. scope.setBuffer(buffer);
  30278. });
  30279. return this;
  30280. };
  30281. AudioAnalyser.prototype.getData = function () {
  30282. console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
  30283. return this.getFrequencyData();
  30284. }; //
  30285. CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
  30286. console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
  30287. return this.update(renderer, scene);
  30288. }; //
  30289. var GeometryUtils = {
  30290. merge: function (geometry1, geometry2, materialIndexOffset) {
  30291. console.warn('THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.');
  30292. var matrix;
  30293. if (geometry2.isMesh) {
  30294. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  30295. matrix = geometry2.matrix;
  30296. geometry2 = geometry2.geometry;
  30297. }
  30298. geometry1.merge(geometry2, matrix, materialIndexOffset);
  30299. },
  30300. center: function (geometry) {
  30301. console.warn('THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.');
  30302. return geometry.center();
  30303. }
  30304. };
  30305. exports.GeometryUtils = GeometryUtils;
  30306. ImageUtils.crossOrigin = undefined;
  30307. ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
  30308. console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
  30309. var loader = new TextureLoader();
  30310. loader.setCrossOrigin(this.crossOrigin);
  30311. var texture = loader.load(url, onLoad, undefined, onError);
  30312. if (mapping) texture.mapping = mapping;
  30313. return texture;
  30314. };
  30315. ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
  30316. console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
  30317. var loader = new CubeTextureLoader();
  30318. loader.setCrossOrigin(this.crossOrigin);
  30319. var texture = loader.load(urls, onLoad, undefined, onError);
  30320. if (mapping) texture.mapping = mapping;
  30321. return texture;
  30322. };
  30323. ImageUtils.loadCompressedTexture = function () {
  30324. console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
  30325. };
  30326. ImageUtils.loadCompressedTextureCube = function () {
  30327. console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
  30328. }; //
  30329. function CanvasRenderer() {
  30330. console.error('THREE.CanvasRenderer has been removed');
  30331. } //
  30332. function JSONLoader() {
  30333. console.error('THREE.JSONLoader has been removed.');
  30334. } //
  30335. var SceneUtils = {
  30336. createMultiMaterialObject: function ()
  30337. /* geometry, materials */
  30338. {
  30339. console.error('THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js');
  30340. },
  30341. detach: function ()
  30342. /* child, parent, scene */
  30343. {
  30344. console.error('THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js');
  30345. },
  30346. attach: function ()
  30347. /* child, scene, parent */
  30348. {
  30349. console.error('THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js');
  30350. }
  30351. }; //
  30352. exports.SceneUtils = SceneUtils;
  30353. function LensFlare() {
  30354. console.error('THREE.LensFlare has been moved to /examples/js/objects/Lensflare.js');
  30355. }
  30356. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  30357. /* eslint-disable no-undef */
  30358. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  30359. detail: {
  30360. revision: REVISION
  30361. }
  30362. }));
  30363. /* eslint-enable no-undef */
  30364. }
  30365. },{}],"../node_modules/three/examples/jsm/loaders/GLTFLoader.js":[function(require,module,exports) {
  30366. "use strict";
  30367. Object.defineProperty(exports, "__esModule", {
  30368. value: true
  30369. });
  30370. exports.GLTFLoader = void 0;
  30371. var _threeModule = require("../../../build/three.module.js");
  30372. /**
  30373. * @author Rich Tibbett / https://github.com/richtr
  30374. * @author mrdoob / http://mrdoob.com/
  30375. * @author Tony Parisi / http://www.tonyparisi.com/
  30376. * @author Takahiro / https://github.com/takahirox
  30377. * @author Don McCurdy / https://www.donmccurdy.com
  30378. */
  30379. var GLTFLoader = function () {
  30380. function GLTFLoader(manager) {
  30381. _threeModule.Loader.call(this, manager);
  30382. this.dracoLoader = null;
  30383. this.ddsLoader = null;
  30384. }
  30385. GLTFLoader.prototype = Object.assign(Object.create(_threeModule.Loader.prototype), {
  30386. constructor: GLTFLoader,
  30387. load: function (url, onLoad, onProgress, onError) {
  30388. var scope = this;
  30389. var resourcePath;
  30390. if (this.resourcePath !== '') {
  30391. resourcePath = this.resourcePath;
  30392. } else if (this.path !== '') {
  30393. resourcePath = this.path;
  30394. } else {
  30395. resourcePath = _threeModule.LoaderUtils.extractUrlBase(url);
  30396. } // Tells the LoadingManager to track an extra item, which resolves after
  30397. // the model is fully loaded. This means the count of items loaded will
  30398. // be incorrect, but ensures manager.onLoad() does not fire early.
  30399. scope.manager.itemStart(url);
  30400. var _onError = function (e) {
  30401. if (onError) {
  30402. onError(e);
  30403. } else {
  30404. console.error(e);
  30405. }
  30406. scope.manager.itemError(url);
  30407. scope.manager.itemEnd(url);
  30408. };
  30409. var loader = new _threeModule.FileLoader(scope.manager);
  30410. loader.setPath(this.path);
  30411. loader.setResponseType('arraybuffer');
  30412. if (scope.crossOrigin === 'use-credentials') {
  30413. loader.setWithCredentials(true);
  30414. }
  30415. loader.load(url, function (data) {
  30416. try {
  30417. scope.parse(data, resourcePath, function (gltf) {
  30418. onLoad(gltf);
  30419. scope.manager.itemEnd(url);
  30420. }, _onError);
  30421. } catch (e) {
  30422. _onError(e);
  30423. }
  30424. }, onProgress, _onError);
  30425. },
  30426. setDRACOLoader: function (dracoLoader) {
  30427. this.dracoLoader = dracoLoader;
  30428. return this;
  30429. },
  30430. setDDSLoader: function (ddsLoader) {
  30431. this.ddsLoader = ddsLoader;
  30432. return this;
  30433. },
  30434. parse: function (data, path, onLoad, onError) {
  30435. var content;
  30436. var extensions = {};
  30437. if (typeof data === 'string') {
  30438. content = data;
  30439. } else {
  30440. var magic = _threeModule.LoaderUtils.decodeText(new Uint8Array(data, 0, 4));
  30441. if (magic === BINARY_EXTENSION_HEADER_MAGIC) {
  30442. try {
  30443. extensions[EXTENSIONS.KHR_BINARY_GLTF] = new GLTFBinaryExtension(data);
  30444. } catch (error) {
  30445. if (onError) onError(error);
  30446. return;
  30447. }
  30448. content = extensions[EXTENSIONS.KHR_BINARY_GLTF].content;
  30449. } else {
  30450. content = _threeModule.LoaderUtils.decodeText(new Uint8Array(data));
  30451. }
  30452. }
  30453. var json = JSON.parse(content);
  30454. if (json.asset === undefined || json.asset.version[0] < 2) {
  30455. if (onError) onError(new Error('THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported. Use LegacyGLTFLoader instead.'));
  30456. return;
  30457. }
  30458. if (json.extensionsUsed) {
  30459. for (var i = 0; i < json.extensionsUsed.length; ++i) {
  30460. var extensionName = json.extensionsUsed[i];
  30461. var extensionsRequired = json.extensionsRequired || [];
  30462. switch (extensionName) {
  30463. case EXTENSIONS.KHR_LIGHTS_PUNCTUAL:
  30464. extensions[extensionName] = new GLTFLightsExtension(json);
  30465. break;
  30466. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  30467. extensions[extensionName] = new GLTFMaterialsUnlitExtension();
  30468. break;
  30469. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  30470. extensions[extensionName] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  30471. break;
  30472. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  30473. extensions[extensionName] = new GLTFDracoMeshCompressionExtension(json, this.dracoLoader);
  30474. break;
  30475. case EXTENSIONS.MSFT_TEXTURE_DDS:
  30476. extensions[EXTENSIONS.MSFT_TEXTURE_DDS] = new GLTFTextureDDSExtension(this.ddsLoader);
  30477. break;
  30478. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  30479. extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] = new GLTFTextureTransformExtension();
  30480. break;
  30481. default:
  30482. if (extensionsRequired.indexOf(extensionName) >= 0) {
  30483. console.warn('THREE.GLTFLoader: Unknown extension "' + extensionName + '".');
  30484. }
  30485. }
  30486. }
  30487. }
  30488. var parser = new GLTFParser(json, extensions, {
  30489. path: path || this.resourcePath || '',
  30490. crossOrigin: this.crossOrigin,
  30491. manager: this.manager
  30492. });
  30493. parser.parse(onLoad, onError);
  30494. }
  30495. });
  30496. /* GLTFREGISTRY */
  30497. function GLTFRegistry() {
  30498. var objects = {};
  30499. return {
  30500. get: function (key) {
  30501. return objects[key];
  30502. },
  30503. add: function (key, object) {
  30504. objects[key] = object;
  30505. },
  30506. remove: function (key) {
  30507. delete objects[key];
  30508. },
  30509. removeAll: function () {
  30510. objects = {};
  30511. }
  30512. };
  30513. }
  30514. /*********************************/
  30515. /********** EXTENSIONS ***********/
  30516. /*********************************/
  30517. var EXTENSIONS = {
  30518. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  30519. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  30520. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  30521. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  30522. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  30523. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  30524. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  30525. };
  30526. /**
  30527. * DDS Texture Extension
  30528. *
  30529. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  30530. *
  30531. */
  30532. function GLTFTextureDDSExtension(ddsLoader) {
  30533. if (!ddsLoader) {
  30534. throw new Error('THREE.GLTFLoader: Attempting to load .dds texture without importing DDSLoader');
  30535. }
  30536. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  30537. this.ddsLoader = ddsLoader;
  30538. }
  30539. /**
  30540. * Punctual Lights Extension
  30541. *
  30542. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  30543. */
  30544. function GLTFLightsExtension(json) {
  30545. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  30546. var extension = json.extensions && json.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL] || {};
  30547. this.lightDefs = extension.lights || [];
  30548. }
  30549. GLTFLightsExtension.prototype.loadLight = function (lightIndex) {
  30550. var lightDef = this.lightDefs[lightIndex];
  30551. var lightNode;
  30552. var color = new _threeModule.Color(0xffffff);
  30553. if (lightDef.color !== undefined) color.fromArray(lightDef.color);
  30554. var range = lightDef.range !== undefined ? lightDef.range : 0;
  30555. switch (lightDef.type) {
  30556. case 'directional':
  30557. lightNode = new _threeModule.DirectionalLight(color);
  30558. lightNode.target.position.set(0, 0, -1);
  30559. lightNode.add(lightNode.target);
  30560. break;
  30561. case 'point':
  30562. lightNode = new _threeModule.PointLight(color);
  30563. lightNode.distance = range;
  30564. break;
  30565. case 'spot':
  30566. lightNode = new _threeModule.SpotLight(color);
  30567. lightNode.distance = range; // Handle spotlight properties.
  30568. lightDef.spot = lightDef.spot || {};
  30569. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  30570. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  30571. lightNode.angle = lightDef.spot.outerConeAngle;
  30572. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  30573. lightNode.target.position.set(0, 0, -1);
  30574. lightNode.add(lightNode.target);
  30575. break;
  30576. default:
  30577. throw new Error('THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".');
  30578. } // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  30579. // here, because node-level parsing will only override position if explicitly specified.
  30580. lightNode.position.set(0, 0, 0);
  30581. lightNode.decay = 2;
  30582. if (lightDef.intensity !== undefined) lightNode.intensity = lightDef.intensity;
  30583. lightNode.name = lightDef.name || 'light_' + lightIndex;
  30584. return Promise.resolve(lightNode);
  30585. };
  30586. /**
  30587. * Unlit Materials Extension
  30588. *
  30589. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  30590. */
  30591. function GLTFMaterialsUnlitExtension() {
  30592. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  30593. }
  30594. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () {
  30595. return _threeModule.MeshBasicMaterial;
  30596. };
  30597. GLTFMaterialsUnlitExtension.prototype.extendParams = function (materialParams, materialDef, parser) {
  30598. var pending = [];
  30599. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  30600. materialParams.opacity = 1.0;
  30601. var metallicRoughness = materialDef.pbrMetallicRoughness;
  30602. if (metallicRoughness) {
  30603. if (Array.isArray(metallicRoughness.baseColorFactor)) {
  30604. var array = metallicRoughness.baseColorFactor;
  30605. materialParams.color.fromArray(array);
  30606. materialParams.opacity = array[3];
  30607. }
  30608. if (metallicRoughness.baseColorTexture !== undefined) {
  30609. pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture));
  30610. }
  30611. }
  30612. return Promise.all(pending);
  30613. };
  30614. /* BINARY EXTENSION */
  30615. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  30616. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  30617. var BINARY_EXTENSION_CHUNK_TYPES = {
  30618. JSON: 0x4E4F534A,
  30619. BIN: 0x004E4942
  30620. };
  30621. function GLTFBinaryExtension(data) {
  30622. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  30623. this.content = null;
  30624. this.body = null;
  30625. var headerView = new DataView(data, 0, BINARY_EXTENSION_HEADER_LENGTH);
  30626. this.header = {
  30627. magic: _threeModule.LoaderUtils.decodeText(new Uint8Array(data.slice(0, 4))),
  30628. version: headerView.getUint32(4, true),
  30629. length: headerView.getUint32(8, true)
  30630. };
  30631. if (this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC) {
  30632. throw new Error('THREE.GLTFLoader: Unsupported glTF-Binary header.');
  30633. } else if (this.header.version < 2.0) {
  30634. throw new Error('THREE.GLTFLoader: Legacy binary file detected. Use LegacyGLTFLoader instead.');
  30635. }
  30636. var chunkView = new DataView(data, BINARY_EXTENSION_HEADER_LENGTH);
  30637. var chunkIndex = 0;
  30638. while (chunkIndex < chunkView.byteLength) {
  30639. var chunkLength = chunkView.getUint32(chunkIndex, true);
  30640. chunkIndex += 4;
  30641. var chunkType = chunkView.getUint32(chunkIndex, true);
  30642. chunkIndex += 4;
  30643. if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON) {
  30644. var contentArray = new Uint8Array(data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength);
  30645. this.content = _threeModule.LoaderUtils.decodeText(contentArray);
  30646. } else if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN) {
  30647. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  30648. this.body = data.slice(byteOffset, byteOffset + chunkLength);
  30649. } // Clients must ignore chunks with unknown types.
  30650. chunkIndex += chunkLength;
  30651. }
  30652. if (this.content === null) {
  30653. throw new Error('THREE.GLTFLoader: JSON content not found.');
  30654. }
  30655. }
  30656. /**
  30657. * DRACO Mesh Compression Extension
  30658. *
  30659. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  30660. */
  30661. function GLTFDracoMeshCompressionExtension(json, dracoLoader) {
  30662. if (!dracoLoader) {
  30663. throw new Error('THREE.GLTFLoader: No DRACOLoader instance provided.');
  30664. }
  30665. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  30666. this.json = json;
  30667. this.dracoLoader = dracoLoader;
  30668. }
  30669. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function (primitive, parser) {
  30670. var json = this.json;
  30671. var dracoLoader = this.dracoLoader;
  30672. var bufferViewIndex = primitive.extensions[this.name].bufferView;
  30673. var gltfAttributeMap = primitive.extensions[this.name].attributes;
  30674. var threeAttributeMap = {};
  30675. var attributeNormalizedMap = {};
  30676. var attributeTypeMap = {};
  30677. for (var attributeName in gltfAttributeMap) {
  30678. var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
  30679. threeAttributeMap[threeAttributeName] = gltfAttributeMap[attributeName];
  30680. }
  30681. for (attributeName in primitive.attributes) {
  30682. var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
  30683. if (gltfAttributeMap[attributeName] !== undefined) {
  30684. var accessorDef = json.accessors[primitive.attributes[attributeName]];
  30685. var componentType = WEBGL_COMPONENT_TYPES[accessorDef.componentType];
  30686. attributeTypeMap[threeAttributeName] = componentType;
  30687. attributeNormalizedMap[threeAttributeName] = accessorDef.normalized === true;
  30688. }
  30689. }
  30690. return parser.getDependency('bufferView', bufferViewIndex).then(function (bufferView) {
  30691. return new Promise(function (resolve) {
  30692. dracoLoader.decodeDracoFile(bufferView, function (geometry) {
  30693. for (var attributeName in geometry.attributes) {
  30694. var attribute = geometry.attributes[attributeName];
  30695. var normalized = attributeNormalizedMap[attributeName];
  30696. if (normalized !== undefined) attribute.normalized = normalized;
  30697. }
  30698. resolve(geometry);
  30699. }, threeAttributeMap, attributeTypeMap);
  30700. });
  30701. });
  30702. };
  30703. /**
  30704. * Texture Transform Extension
  30705. *
  30706. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
  30707. */
  30708. function GLTFTextureTransformExtension() {
  30709. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  30710. }
  30711. GLTFTextureTransformExtension.prototype.extendTexture = function (texture, transform) {
  30712. texture = texture.clone();
  30713. if (transform.offset !== undefined) {
  30714. texture.offset.fromArray(transform.offset);
  30715. }
  30716. if (transform.rotation !== undefined) {
  30717. texture.rotation = transform.rotation;
  30718. }
  30719. if (transform.scale !== undefined) {
  30720. texture.repeat.fromArray(transform.scale);
  30721. }
  30722. if (transform.texCoord !== undefined) {
  30723. console.warn('THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.');
  30724. }
  30725. texture.needsUpdate = true;
  30726. return texture;
  30727. };
  30728. /**
  30729. * Specular-Glossiness Extension
  30730. *
  30731. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  30732. */
  30733. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  30734. return {
  30735. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  30736. specularGlossinessParams: ['color', 'map', 'lightMap', 'lightMapIntensity', 'aoMap', 'aoMapIntensity', 'emissive', 'emissiveIntensity', 'emissiveMap', 'bumpMap', 'bumpScale', 'normalMap', 'displacementMap', 'displacementScale', 'displacementBias', 'specularMap', 'specular', 'glossinessMap', 'glossiness', 'alphaMap', 'envMap', 'envMapIntensity', 'refractionRatio'],
  30737. getMaterialType: function () {
  30738. return _threeModule.ShaderMaterial;
  30739. },
  30740. extendParams: function (materialParams, materialDef, parser) {
  30741. var pbrSpecularGlossiness = materialDef.extensions[this.name];
  30742. var shader = _threeModule.ShaderLib['standard'];
  30743. var uniforms = _threeModule.UniformsUtils.clone(shader.uniforms);
  30744. var specularMapParsFragmentChunk = ['#ifdef USE_SPECULARMAP', ' uniform sampler2D specularMap;', '#endif'].join('\n');
  30745. var glossinessMapParsFragmentChunk = ['#ifdef USE_GLOSSINESSMAP', ' uniform sampler2D glossinessMap;', '#endif'].join('\n');
  30746. 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');
  30747. 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');
  30748. var lightPhysicalFragmentChunk = ['PhysicalMaterial material;', 'material.diffuseColor = diffuseColor.rgb;', 'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );', 'material.specularColor = specularFactor.rgb;'].join('\n');
  30749. 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);
  30750. delete uniforms.roughness;
  30751. delete uniforms.metalness;
  30752. delete uniforms.roughnessMap;
  30753. delete uniforms.metalnessMap;
  30754. uniforms.specular = {
  30755. value: new _threeModule.Color().setHex(0x111111)
  30756. };
  30757. uniforms.glossiness = {
  30758. value: 0.5
  30759. };
  30760. uniforms.specularMap = {
  30761. value: null
  30762. };
  30763. uniforms.glossinessMap = {
  30764. value: null
  30765. };
  30766. materialParams.vertexShader = shader.vertexShader;
  30767. materialParams.fragmentShader = fragmentShader;
  30768. materialParams.uniforms = uniforms;
  30769. materialParams.defines = {
  30770. 'STANDARD': ''
  30771. };
  30772. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  30773. materialParams.opacity = 1.0;
  30774. var pending = [];
  30775. if (Array.isArray(pbrSpecularGlossiness.diffuseFactor)) {
  30776. var array = pbrSpecularGlossiness.diffuseFactor;
  30777. materialParams.color.fromArray(array);
  30778. materialParams.opacity = array[3];
  30779. }
  30780. if (pbrSpecularGlossiness.diffuseTexture !== undefined) {
  30781. pending.push(parser.assignTexture(materialParams, 'map', pbrSpecularGlossiness.diffuseTexture));
  30782. }
  30783. materialParams.emissive = new _threeModule.Color(0.0, 0.0, 0.0);
  30784. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  30785. materialParams.specular = new _threeModule.Color(1.0, 1.0, 1.0);
  30786. if (Array.isArray(pbrSpecularGlossiness.specularFactor)) {
  30787. materialParams.specular.fromArray(pbrSpecularGlossiness.specularFactor);
  30788. }
  30789. if (pbrSpecularGlossiness.specularGlossinessTexture !== undefined) {
  30790. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  30791. pending.push(parser.assignTexture(materialParams, 'glossinessMap', specGlossMapDef));
  30792. pending.push(parser.assignTexture(materialParams, 'specularMap', specGlossMapDef));
  30793. }
  30794. return Promise.all(pending);
  30795. },
  30796. createMaterial: function (params) {
  30797. // setup material properties based on MeshStandardMaterial for Specular-Glossiness
  30798. var material = new _threeModule.ShaderMaterial({
  30799. defines: params.defines,
  30800. vertexShader: params.vertexShader,
  30801. fragmentShader: params.fragmentShader,
  30802. uniforms: params.uniforms,
  30803. fog: true,
  30804. lights: true,
  30805. opacity: params.opacity,
  30806. transparent: params.transparent
  30807. });
  30808. material.isGLTFSpecularGlossinessMaterial = true;
  30809. material.color = params.color;
  30810. material.map = params.map === undefined ? null : params.map;
  30811. material.lightMap = null;
  30812. material.lightMapIntensity = 1.0;
  30813. material.aoMap = params.aoMap === undefined ? null : params.aoMap;
  30814. material.aoMapIntensity = 1.0;
  30815. material.emissive = params.emissive;
  30816. material.emissiveIntensity = 1.0;
  30817. material.emissiveMap = params.emissiveMap === undefined ? null : params.emissiveMap;
  30818. material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap;
  30819. material.bumpScale = 1;
  30820. material.normalMap = params.normalMap === undefined ? null : params.normalMap;
  30821. if (params.normalScale) material.normalScale = params.normalScale;
  30822. material.displacementMap = null;
  30823. material.displacementScale = 1;
  30824. material.displacementBias = 0;
  30825. material.specularMap = params.specularMap === undefined ? null : params.specularMap;
  30826. material.specular = params.specular;
  30827. material.glossinessMap = params.glossinessMap === undefined ? null : params.glossinessMap;
  30828. material.glossiness = params.glossiness;
  30829. material.alphaMap = null;
  30830. material.envMap = params.envMap === undefined ? null : params.envMap;
  30831. material.envMapIntensity = 1.0;
  30832. material.refractionRatio = 0.98;
  30833. material.extensions.derivatives = true;
  30834. return material;
  30835. },
  30836. /**
  30837. * Clones a GLTFSpecularGlossinessMaterial instance. The ShaderMaterial.copy() method can
  30838. * copy only properties it knows about or inherits, and misses many properties that would
  30839. * normally be defined by MeshStandardMaterial.
  30840. *
  30841. * This method allows GLTFSpecularGlossinessMaterials to be cloned in the process of
  30842. * loading a glTF model, but cloning later (e.g. by the user) would require these changes
  30843. * AND also updating `.onBeforeRender` on the parent mesh.
  30844. *
  30845. * @param {ShaderMaterial} source
  30846. * @return {ShaderMaterial}
  30847. */
  30848. cloneMaterial: function (source) {
  30849. var target = source.clone();
  30850. target.isGLTFSpecularGlossinessMaterial = true;
  30851. var params = this.specularGlossinessParams;
  30852. for (var i = 0, il = params.length; i < il; i++) {
  30853. var value = source[params[i]];
  30854. target[params[i]] = value && value.isColor ? value.clone() : value;
  30855. }
  30856. return target;
  30857. },
  30858. // Here's based on refreshUniformsCommon() and refreshUniformsStandard() in WebGLRenderer.
  30859. refreshUniforms: function (renderer, scene, camera, geometry, material) {
  30860. if (material.isGLTFSpecularGlossinessMaterial !== true) {
  30861. return;
  30862. }
  30863. var uniforms = material.uniforms;
  30864. var defines = material.defines;
  30865. uniforms.opacity.value = material.opacity;
  30866. uniforms.diffuse.value.copy(material.color);
  30867. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  30868. uniforms.map.value = material.map;
  30869. uniforms.specularMap.value = material.specularMap;
  30870. uniforms.alphaMap.value = material.alphaMap;
  30871. uniforms.lightMap.value = material.lightMap;
  30872. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  30873. uniforms.aoMap.value = material.aoMap;
  30874. uniforms.aoMapIntensity.value = material.aoMapIntensity; // uv repeat and offset setting priorities
  30875. // 1. color map
  30876. // 2. specular map
  30877. // 3. normal map
  30878. // 4. bump map
  30879. // 5. alpha map
  30880. // 6. emissive map
  30881. var uvScaleMap;
  30882. if (material.map) {
  30883. uvScaleMap = material.map;
  30884. } else if (material.specularMap) {
  30885. uvScaleMap = material.specularMap;
  30886. } else if (material.displacementMap) {
  30887. uvScaleMap = material.displacementMap;
  30888. } else if (material.normalMap) {
  30889. uvScaleMap = material.normalMap;
  30890. } else if (material.bumpMap) {
  30891. uvScaleMap = material.bumpMap;
  30892. } else if (material.glossinessMap) {
  30893. uvScaleMap = material.glossinessMap;
  30894. } else if (material.alphaMap) {
  30895. uvScaleMap = material.alphaMap;
  30896. } else if (material.emissiveMap) {
  30897. uvScaleMap = material.emissiveMap;
  30898. }
  30899. if (uvScaleMap !== undefined) {
  30900. // backwards compatibility
  30901. if (uvScaleMap.isWebGLRenderTarget) {
  30902. uvScaleMap = uvScaleMap.texture;
  30903. }
  30904. if (uvScaleMap.matrixAutoUpdate === true) {
  30905. uvScaleMap.updateMatrix();
  30906. }
  30907. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  30908. }
  30909. if (material.envMap) {
  30910. uniforms.envMap.value = material.envMap;
  30911. uniforms.envMapIntensity.value = material.envMapIntensity; // don't flip CubeTexture envMaps, flip everything else:
  30912. // WebGLRenderTargetCube will be flipped for backwards compatibility
  30913. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  30914. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  30915. uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? -1 : 1;
  30916. uniforms.reflectivity.value = material.reflectivity;
  30917. uniforms.refractionRatio.value = material.refractionRatio;
  30918. uniforms.maxMipLevel.value = renderer.properties.get(material.envMap).__maxMipLevel;
  30919. }
  30920. uniforms.specular.value.copy(material.specular);
  30921. uniforms.glossiness.value = material.glossiness;
  30922. uniforms.glossinessMap.value = material.glossinessMap;
  30923. uniforms.emissiveMap.value = material.emissiveMap;
  30924. uniforms.bumpMap.value = material.bumpMap;
  30925. uniforms.normalMap.value = material.normalMap;
  30926. uniforms.displacementMap.value = material.displacementMap;
  30927. uniforms.displacementScale.value = material.displacementScale;
  30928. uniforms.displacementBias.value = material.displacementBias;
  30929. if (uniforms.glossinessMap.value !== null && defines.USE_GLOSSINESSMAP === undefined) {
  30930. defines.USE_GLOSSINESSMAP = ''; // set USE_ROUGHNESSMAP to enable vUv
  30931. defines.USE_ROUGHNESSMAP = '';
  30932. }
  30933. if (uniforms.glossinessMap.value === null && defines.USE_GLOSSINESSMAP !== undefined) {
  30934. delete defines.USE_GLOSSINESSMAP;
  30935. delete defines.USE_ROUGHNESSMAP;
  30936. }
  30937. }
  30938. };
  30939. }
  30940. /*********************************/
  30941. /********** INTERPOLATION ********/
  30942. /*********************************/
  30943. // Spline Interpolation
  30944. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  30945. function GLTFCubicSplineInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  30946. _threeModule.Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  30947. }
  30948. GLTFCubicSplineInterpolant.prototype = Object.create(_threeModule.Interpolant.prototype);
  30949. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  30950. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function (index) {
  30951. // Copies a sample value to the result buffer. See description of glTF
  30952. // CUBICSPLINE values layout in interpolate_() function below.
  30953. var result = this.resultBuffer,
  30954. values = this.sampleValues,
  30955. valueSize = this.valueSize,
  30956. offset = index * valueSize * 3 + valueSize;
  30957. for (var i = 0; i !== valueSize; i++) {
  30958. result[i] = values[offset + i];
  30959. }
  30960. return result;
  30961. };
  30962. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  30963. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  30964. GLTFCubicSplineInterpolant.prototype.interpolate_ = function (i1, t0, t, t1) {
  30965. var result = this.resultBuffer;
  30966. var values = this.sampleValues;
  30967. var stride = this.valueSize;
  30968. var stride2 = stride * 2;
  30969. var stride3 = stride * 3;
  30970. var td = t1 - t0;
  30971. var p = (t - t0) / td;
  30972. var pp = p * p;
  30973. var ppp = pp * p;
  30974. var offset1 = i1 * stride3;
  30975. var offset0 = offset1 - stride3;
  30976. var s2 = -2 * ppp + 3 * pp;
  30977. var s3 = ppp - pp;
  30978. var s0 = 1 - s2;
  30979. var s1 = s3 - pp + p; // Layout of keyframe output values for CUBICSPLINE animations:
  30980. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  30981. for (var i = 0; i !== stride; i++) {
  30982. var p0 = values[offset0 + i + stride]; // splineVertex_k
  30983. var m0 = values[offset0 + i + stride2] * td; // outTangent_k * (t_k+1 - t_k)
  30984. var p1 = values[offset1 + i + stride]; // splineVertex_k+1
  30985. var m1 = values[offset1 + i] * td; // inTangent_k+1 * (t_k+1 - t_k)
  30986. result[i] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  30987. }
  30988. return result;
  30989. };
  30990. /*********************************/
  30991. /********** INTERNALS ************/
  30992. /*********************************/
  30993. /* CONSTANTS */
  30994. var WEBGL_CONSTANTS = {
  30995. FLOAT: 5126,
  30996. //FLOAT_MAT2: 35674,
  30997. FLOAT_MAT3: 35675,
  30998. FLOAT_MAT4: 35676,
  30999. FLOAT_VEC2: 35664,
  31000. FLOAT_VEC3: 35665,
  31001. FLOAT_VEC4: 35666,
  31002. LINEAR: 9729,
  31003. REPEAT: 10497,
  31004. SAMPLER_2D: 35678,
  31005. POINTS: 0,
  31006. LINES: 1,
  31007. LINE_LOOP: 2,
  31008. LINE_STRIP: 3,
  31009. TRIANGLES: 4,
  31010. TRIANGLE_STRIP: 5,
  31011. TRIANGLE_FAN: 6,
  31012. UNSIGNED_BYTE: 5121,
  31013. UNSIGNED_SHORT: 5123
  31014. };
  31015. var WEBGL_COMPONENT_TYPES = {
  31016. 5120: Int8Array,
  31017. 5121: Uint8Array,
  31018. 5122: Int16Array,
  31019. 5123: Uint16Array,
  31020. 5125: Uint32Array,
  31021. 5126: Float32Array
  31022. };
  31023. var WEBGL_FILTERS = {
  31024. 9728: _threeModule.NearestFilter,
  31025. 9729: _threeModule.LinearFilter,
  31026. 9984: _threeModule.NearestMipmapNearestFilter,
  31027. 9985: _threeModule.LinearMipmapNearestFilter,
  31028. 9986: _threeModule.NearestMipmapLinearFilter,
  31029. 9987: _threeModule.LinearMipmapLinearFilter
  31030. };
  31031. var WEBGL_WRAPPINGS = {
  31032. 33071: _threeModule.ClampToEdgeWrapping,
  31033. 33648: _threeModule.MirroredRepeatWrapping,
  31034. 10497: _threeModule.RepeatWrapping
  31035. };
  31036. var WEBGL_TYPE_SIZES = {
  31037. 'SCALAR': 1,
  31038. 'VEC2': 2,
  31039. 'VEC3': 3,
  31040. 'VEC4': 4,
  31041. 'MAT2': 4,
  31042. 'MAT3': 9,
  31043. 'MAT4': 16
  31044. };
  31045. var ATTRIBUTES = {
  31046. POSITION: 'position',
  31047. NORMAL: 'normal',
  31048. TANGENT: 'tangent',
  31049. TEXCOORD_0: 'uv',
  31050. TEXCOORD_1: 'uv2',
  31051. COLOR_0: 'color',
  31052. WEIGHTS_0: 'skinWeight',
  31053. JOINTS_0: 'skinIndex'
  31054. };
  31055. var PATH_PROPERTIES = {
  31056. scale: 'scale',
  31057. translation: 'position',
  31058. rotation: 'quaternion',
  31059. weights: 'morphTargetInfluences'
  31060. };
  31061. var INTERPOLATION = {
  31062. CUBICSPLINE: undefined,
  31063. // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  31064. // keyframe track will be initialized with a default interpolation type, then modified.
  31065. LINEAR: _threeModule.InterpolateLinear,
  31066. STEP: _threeModule.InterpolateDiscrete
  31067. };
  31068. var ALPHA_MODES = {
  31069. OPAQUE: 'OPAQUE',
  31070. MASK: 'MASK',
  31071. BLEND: 'BLEND'
  31072. };
  31073. var MIME_TYPE_FORMATS = {
  31074. 'image/png': _threeModule.RGBAFormat,
  31075. 'image/jpeg': _threeModule.RGBFormat
  31076. };
  31077. /* UTILITY FUNCTIONS */
  31078. function resolveURL(url, path) {
  31079. // Invalid URL
  31080. if (typeof url !== 'string' || url === '') return ''; // Host Relative URL
  31081. if (/^https?:\/\//i.test(path) && /^\//.test(url)) {
  31082. path = path.replace(/(^https?:\/\/[^\/]+).*/i, '$1');
  31083. } // Absolute URL http://,https://,//
  31084. if (/^(https?:)?\/\//i.test(url)) return url; // Data URI
  31085. if (/^data:.*,.*$/i.test(url)) return url; // Blob URL
  31086. if (/^blob:.*$/i.test(url)) return url; // Relative URL
  31087. return path + url;
  31088. }
  31089. var defaultMaterial;
  31090. /**
  31091. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  31092. */
  31093. function createDefaultMaterial() {
  31094. defaultMaterial = defaultMaterial || new _threeModule.MeshStandardMaterial({
  31095. color: 0xFFFFFF,
  31096. emissive: 0x000000,
  31097. metalness: 1,
  31098. roughness: 1,
  31099. transparent: false,
  31100. depthTest: true,
  31101. side: _threeModule.FrontSide
  31102. });
  31103. return defaultMaterial;
  31104. }
  31105. function addUnknownExtensionsToUserData(knownExtensions, object, objectDef) {
  31106. // Add unknown glTF extensions to an object's userData.
  31107. for (var name in objectDef.extensions) {
  31108. if (knownExtensions[name] === undefined) {
  31109. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  31110. object.userData.gltfExtensions[name] = objectDef.extensions[name];
  31111. }
  31112. }
  31113. }
  31114. /**
  31115. * @param {Object3D|Material|BufferGeometry} object
  31116. * @param {GLTF.definition} gltfDef
  31117. */
  31118. function assignExtrasToUserData(object, gltfDef) {
  31119. if (gltfDef.extras !== undefined) {
  31120. if (typeof gltfDef.extras === 'object') {
  31121. Object.assign(object.userData, gltfDef.extras);
  31122. } else {
  31123. console.warn('THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras);
  31124. }
  31125. }
  31126. }
  31127. /**
  31128. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  31129. *
  31130. * @param {BufferGeometry} geometry
  31131. * @param {Array<GLTF.Target>} targets
  31132. * @param {GLTFParser} parser
  31133. * @return {Promise<BufferGeometry>}
  31134. */
  31135. function addMorphTargets(geometry, targets, parser) {
  31136. var hasMorphPosition = false;
  31137. var hasMorphNormal = false;
  31138. for (var i = 0, il = targets.length; i < il; i++) {
  31139. var target = targets[i];
  31140. if (target.POSITION !== undefined) hasMorphPosition = true;
  31141. if (target.NORMAL !== undefined) hasMorphNormal = true;
  31142. if (hasMorphPosition && hasMorphNormal) break;
  31143. }
  31144. if (!hasMorphPosition && !hasMorphNormal) return Promise.resolve(geometry);
  31145. var pendingPositionAccessors = [];
  31146. var pendingNormalAccessors = [];
  31147. for (var i = 0, il = targets.length; i < il; i++) {
  31148. var target = targets[i];
  31149. if (hasMorphPosition) {
  31150. var pendingAccessor = target.POSITION !== undefined ? parser.getDependency('accessor', target.POSITION) : geometry.attributes.position;
  31151. pendingPositionAccessors.push(pendingAccessor);
  31152. }
  31153. if (hasMorphNormal) {
  31154. var pendingAccessor = target.NORMAL !== undefined ? parser.getDependency('accessor', target.NORMAL) : geometry.attributes.normal;
  31155. pendingNormalAccessors.push(pendingAccessor);
  31156. }
  31157. }
  31158. return Promise.all([Promise.all(pendingPositionAccessors), Promise.all(pendingNormalAccessors)]).then(function (accessors) {
  31159. var morphPositions = accessors[0];
  31160. var morphNormals = accessors[1]; // Clone morph target accessors before modifying them.
  31161. for (var i = 0, il = morphPositions.length; i < il; i++) {
  31162. if (geometry.attributes.position === morphPositions[i]) continue;
  31163. morphPositions[i] = cloneBufferAttribute(morphPositions[i]);
  31164. }
  31165. for (var i = 0, il = morphNormals.length; i < il; i++) {
  31166. if (geometry.attributes.normal === morphNormals[i]) continue;
  31167. morphNormals[i] = cloneBufferAttribute(morphNormals[i]);
  31168. }
  31169. for (var i = 0, il = targets.length; i < il; i++) {
  31170. var target = targets[i];
  31171. var attributeName = 'morphTarget' + i;
  31172. if (hasMorphPosition) {
  31173. // Three.js morph position is absolute value. The formula is
  31174. // basePosition
  31175. // + weight0 * ( morphPosition0 - basePosition )
  31176. // + weight1 * ( morphPosition1 - basePosition )
  31177. // ...
  31178. // while the glTF one is relative
  31179. // basePosition
  31180. // + weight0 * glTFmorphPosition0
  31181. // + weight1 * glTFmorphPosition1
  31182. // ...
  31183. // then we need to convert from relative to absolute here.
  31184. if (target.POSITION !== undefined) {
  31185. var positionAttribute = morphPositions[i];
  31186. positionAttribute.name = attributeName;
  31187. var position = geometry.attributes.position;
  31188. for (var j = 0, jl = positionAttribute.count; j < jl; j++) {
  31189. positionAttribute.setXYZ(j, positionAttribute.getX(j) + position.getX(j), positionAttribute.getY(j) + position.getY(j), positionAttribute.getZ(j) + position.getZ(j));
  31190. }
  31191. }
  31192. }
  31193. if (hasMorphNormal) {
  31194. // see target.POSITION's comment
  31195. if (target.NORMAL !== undefined) {
  31196. var normalAttribute = morphNormals[i];
  31197. normalAttribute.name = attributeName;
  31198. var normal = geometry.attributes.normal;
  31199. for (var j = 0, jl = normalAttribute.count; j < jl; j++) {
  31200. normalAttribute.setXYZ(j, normalAttribute.getX(j) + normal.getX(j), normalAttribute.getY(j) + normal.getY(j), normalAttribute.getZ(j) + normal.getZ(j));
  31201. }
  31202. }
  31203. }
  31204. }
  31205. if (hasMorphPosition) geometry.morphAttributes.position = morphPositions;
  31206. if (hasMorphNormal) geometry.morphAttributes.normal = morphNormals;
  31207. return geometry;
  31208. });
  31209. }
  31210. /**
  31211. * @param {Mesh} mesh
  31212. * @param {GLTF.Mesh} meshDef
  31213. */
  31214. function updateMorphTargets(mesh, meshDef) {
  31215. mesh.updateMorphTargets();
  31216. if (meshDef.weights !== undefined) {
  31217. for (var i = 0, il = meshDef.weights.length; i < il; i++) {
  31218. mesh.morphTargetInfluences[i] = meshDef.weights[i];
  31219. }
  31220. } // .extras has user-defined data, so check that .extras.targetNames is an array.
  31221. if (meshDef.extras && Array.isArray(meshDef.extras.targetNames)) {
  31222. var targetNames = meshDef.extras.targetNames;
  31223. if (mesh.morphTargetInfluences.length === targetNames.length) {
  31224. mesh.morphTargetDictionary = {};
  31225. for (var i = 0, il = targetNames.length; i < il; i++) {
  31226. mesh.morphTargetDictionary[targetNames[i]] = i;
  31227. }
  31228. } else {
  31229. console.warn('THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.');
  31230. }
  31231. }
  31232. }
  31233. function createPrimitiveKey(primitiveDef) {
  31234. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION];
  31235. var geometryKey;
  31236. if (dracoExtension) {
  31237. geometryKey = 'draco:' + dracoExtension.bufferView + ':' + dracoExtension.indices + ':' + createAttributesKey(dracoExtension.attributes);
  31238. } else {
  31239. geometryKey = primitiveDef.indices + ':' + createAttributesKey(primitiveDef.attributes) + ':' + primitiveDef.mode;
  31240. }
  31241. return geometryKey;
  31242. }
  31243. function createAttributesKey(attributes) {
  31244. var attributesKey = '';
  31245. var keys = Object.keys(attributes).sort();
  31246. for (var i = 0, il = keys.length; i < il; i++) {
  31247. attributesKey += keys[i] + ':' + attributes[keys[i]] + ';';
  31248. }
  31249. return attributesKey;
  31250. }
  31251. function cloneBufferAttribute(attribute) {
  31252. if (attribute.isInterleavedBufferAttribute) {
  31253. var count = attribute.count;
  31254. var itemSize = attribute.itemSize;
  31255. var array = attribute.array.slice(0, count * itemSize);
  31256. for (var i = 0, j = 0; i < count; ++i) {
  31257. array[j++] = attribute.getX(i);
  31258. if (itemSize >= 2) array[j++] = attribute.getY(i);
  31259. if (itemSize >= 3) array[j++] = attribute.getZ(i);
  31260. if (itemSize >= 4) array[j++] = attribute.getW(i);
  31261. }
  31262. return new _threeModule.BufferAttribute(array, itemSize, attribute.normalized);
  31263. }
  31264. return attribute.clone();
  31265. }
  31266. /* GLTF PARSER */
  31267. function GLTFParser(json, extensions, options) {
  31268. this.json = json || {};
  31269. this.extensions = extensions || {};
  31270. this.options = options || {}; // loader object cache
  31271. this.cache = new GLTFRegistry(); // BufferGeometry caching
  31272. this.primitiveCache = {};
  31273. this.textureLoader = new _threeModule.TextureLoader(this.options.manager);
  31274. this.textureLoader.setCrossOrigin(this.options.crossOrigin);
  31275. this.fileLoader = new _threeModule.FileLoader(this.options.manager);
  31276. this.fileLoader.setResponseType('arraybuffer');
  31277. if (this.options.crossOrigin === 'use-credentials') {
  31278. this.fileLoader.setWithCredentials(true);
  31279. }
  31280. }
  31281. GLTFParser.prototype.parse = function (onLoad, onError) {
  31282. var parser = this;
  31283. var json = this.json;
  31284. var extensions = this.extensions; // Clear the loader cache
  31285. this.cache.removeAll(); // Mark the special nodes/meshes in json for efficient parse
  31286. this.markDefs();
  31287. Promise.all([this.getDependencies('scene'), this.getDependencies('animation'), this.getDependencies('camera')]).then(function (dependencies) {
  31288. var result = {
  31289. scene: dependencies[0][json.scene || 0],
  31290. scenes: dependencies[0],
  31291. animations: dependencies[1],
  31292. cameras: dependencies[2],
  31293. asset: json.asset,
  31294. parser: parser,
  31295. userData: {}
  31296. };
  31297. addUnknownExtensionsToUserData(extensions, result, json);
  31298. assignExtrasToUserData(result, json);
  31299. onLoad(result);
  31300. }).catch(onError);
  31301. };
  31302. /**
  31303. * Marks the special nodes/meshes in json for efficient parse.
  31304. */
  31305. GLTFParser.prototype.markDefs = function () {
  31306. var nodeDefs = this.json.nodes || [];
  31307. var skinDefs = this.json.skins || [];
  31308. var meshDefs = this.json.meshes || [];
  31309. var meshReferences = {};
  31310. var meshUses = {}; // Nothing in the node definition indicates whether it is a Bone or an
  31311. // Object3D. Use the skins' joint references to mark bones.
  31312. for (var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex++) {
  31313. var joints = skinDefs[skinIndex].joints;
  31314. for (var i = 0, il = joints.length; i < il; i++) {
  31315. nodeDefs[joints[i]].isBone = true;
  31316. }
  31317. } // Meshes can (and should) be reused by multiple nodes in a glTF asset. To
  31318. // avoid having more than one Mesh with the same name, count
  31319. // references and rename instances below.
  31320. //
  31321. // Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  31322. for (var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) {
  31323. var nodeDef = nodeDefs[nodeIndex];
  31324. if (nodeDef.mesh !== undefined) {
  31325. if (meshReferences[nodeDef.mesh] === undefined) {
  31326. meshReferences[nodeDef.mesh] = meshUses[nodeDef.mesh] = 0;
  31327. }
  31328. meshReferences[nodeDef.mesh]++; // Nothing in the mesh definition indicates whether it is
  31329. // a SkinnedMesh or Mesh. Use the node's mesh reference
  31330. // to mark SkinnedMesh if node has skin.
  31331. if (nodeDef.skin !== undefined) {
  31332. meshDefs[nodeDef.mesh].isSkinnedMesh = true;
  31333. }
  31334. }
  31335. }
  31336. this.json.meshReferences = meshReferences;
  31337. this.json.meshUses = meshUses;
  31338. };
  31339. /**
  31340. * Requests the specified dependency asynchronously, with caching.
  31341. * @param {string} type
  31342. * @param {number} index
  31343. * @return {Promise<Object3D|Material|THREE.Texture|AnimationClip|ArrayBuffer|Object>}
  31344. */
  31345. GLTFParser.prototype.getDependency = function (type, index) {
  31346. var cacheKey = type + ':' + index;
  31347. var dependency = this.cache.get(cacheKey);
  31348. if (!dependency) {
  31349. switch (type) {
  31350. case 'scene':
  31351. dependency = this.loadScene(index);
  31352. break;
  31353. case 'node':
  31354. dependency = this.loadNode(index);
  31355. break;
  31356. case 'mesh':
  31357. dependency = this.loadMesh(index);
  31358. break;
  31359. case 'accessor':
  31360. dependency = this.loadAccessor(index);
  31361. break;
  31362. case 'bufferView':
  31363. dependency = this.loadBufferView(index);
  31364. break;
  31365. case 'buffer':
  31366. dependency = this.loadBuffer(index);
  31367. break;
  31368. case 'material':
  31369. dependency = this.loadMaterial(index);
  31370. break;
  31371. case 'texture':
  31372. dependency = this.loadTexture(index);
  31373. break;
  31374. case 'skin':
  31375. dependency = this.loadSkin(index);
  31376. break;
  31377. case 'animation':
  31378. dependency = this.loadAnimation(index);
  31379. break;
  31380. case 'camera':
  31381. dependency = this.loadCamera(index);
  31382. break;
  31383. case 'light':
  31384. dependency = this.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].loadLight(index);
  31385. break;
  31386. default:
  31387. throw new Error('Unknown type: ' + type);
  31388. }
  31389. this.cache.add(cacheKey, dependency);
  31390. }
  31391. return dependency;
  31392. };
  31393. /**
  31394. * Requests all dependencies of the specified type asynchronously, with caching.
  31395. * @param {string} type
  31396. * @return {Promise<Array<Object>>}
  31397. */
  31398. GLTFParser.prototype.getDependencies = function (type) {
  31399. var dependencies = this.cache.get(type);
  31400. if (!dependencies) {
  31401. var parser = this;
  31402. var defs = this.json[type + (type === 'mesh' ? 'es' : 's')] || [];
  31403. dependencies = Promise.all(defs.map(function (def, index) {
  31404. return parser.getDependency(type, index);
  31405. }));
  31406. this.cache.add(type, dependencies);
  31407. }
  31408. return dependencies;
  31409. };
  31410. /**
  31411. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  31412. * @param {number} bufferIndex
  31413. * @return {Promise<ArrayBuffer>}
  31414. */
  31415. GLTFParser.prototype.loadBuffer = function (bufferIndex) {
  31416. var bufferDef = this.json.buffers[bufferIndex];
  31417. var loader = this.fileLoader;
  31418. if (bufferDef.type && bufferDef.type !== 'arraybuffer') {
  31419. throw new Error('THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.');
  31420. } // If present, GLB container is required to be the first buffer.
  31421. if (bufferDef.uri === undefined && bufferIndex === 0) {
  31422. return Promise.resolve(this.extensions[EXTENSIONS.KHR_BINARY_GLTF].body);
  31423. }
  31424. var options = this.options;
  31425. return new Promise(function (resolve, reject) {
  31426. loader.load(resolveURL(bufferDef.uri, options.path), resolve, undefined, function () {
  31427. reject(new Error('THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".'));
  31428. });
  31429. });
  31430. };
  31431. /**
  31432. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  31433. * @param {number} bufferViewIndex
  31434. * @return {Promise<ArrayBuffer>}
  31435. */
  31436. GLTFParser.prototype.loadBufferView = function (bufferViewIndex) {
  31437. var bufferViewDef = this.json.bufferViews[bufferViewIndex];
  31438. return this.getDependency('buffer', bufferViewDef.buffer).then(function (buffer) {
  31439. var byteLength = bufferViewDef.byteLength || 0;
  31440. var byteOffset = bufferViewDef.byteOffset || 0;
  31441. return buffer.slice(byteOffset, byteOffset + byteLength);
  31442. });
  31443. };
  31444. /**
  31445. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  31446. * @param {number} accessorIndex
  31447. * @return {Promise<BufferAttribute|InterleavedBufferAttribute>}
  31448. */
  31449. GLTFParser.prototype.loadAccessor = function (accessorIndex) {
  31450. var parser = this;
  31451. var json = this.json;
  31452. var accessorDef = this.json.accessors[accessorIndex];
  31453. if (accessorDef.bufferView === undefined && accessorDef.sparse === undefined) {
  31454. // Ignore empty accessors, which may be used to declare runtime
  31455. // information about attributes coming from another source (e.g. Draco
  31456. // compression extension).
  31457. return Promise.resolve(null);
  31458. }
  31459. var pendingBufferViews = [];
  31460. if (accessorDef.bufferView !== undefined) {
  31461. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.bufferView));
  31462. } else {
  31463. pendingBufferViews.push(null);
  31464. }
  31465. if (accessorDef.sparse !== undefined) {
  31466. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.indices.bufferView));
  31467. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.values.bufferView));
  31468. }
  31469. return Promise.all(pendingBufferViews).then(function (bufferViews) {
  31470. var bufferView = bufferViews[0];
  31471. var itemSize = WEBGL_TYPE_SIZES[accessorDef.type];
  31472. var TypedArray = WEBGL_COMPONENT_TYPES[accessorDef.componentType]; // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  31473. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  31474. var itemBytes = elementBytes * itemSize;
  31475. var byteOffset = accessorDef.byteOffset || 0;
  31476. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[accessorDef.bufferView].byteStride : undefined;
  31477. var normalized = accessorDef.normalized === true;
  31478. var array, bufferAttribute; // The buffer is not interleaved if the stride is the item size in bytes.
  31479. if (byteStride && byteStride !== itemBytes) {
  31480. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
  31481. // This makes sure that IBA.count reflects accessor.count properly
  31482. var ibSlice = Math.floor(byteOffset / byteStride);
  31483. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
  31484. var ib = parser.cache.get(ibCacheKey);
  31485. if (!ib) {
  31486. array = new TypedArray(bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes); // Integer parameters to IB/IBA are in array elements, not bytes.
  31487. ib = new _threeModule.InterleavedBuffer(array, byteStride / elementBytes);
  31488. parser.cache.add(ibCacheKey, ib);
  31489. }
  31490. bufferAttribute = new _threeModule.InterleavedBufferAttribute(ib, itemSize, byteOffset % byteStride / elementBytes, normalized);
  31491. } else {
  31492. if (bufferView === null) {
  31493. array = new TypedArray(accessorDef.count * itemSize);
  31494. } else {
  31495. array = new TypedArray(bufferView, byteOffset, accessorDef.count * itemSize);
  31496. }
  31497. bufferAttribute = new _threeModule.BufferAttribute(array, itemSize, normalized);
  31498. } // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  31499. if (accessorDef.sparse !== undefined) {
  31500. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  31501. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[accessorDef.sparse.indices.componentType];
  31502. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  31503. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  31504. var sparseIndices = new TypedArrayIndices(bufferViews[1], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices);
  31505. var sparseValues = new TypedArray(bufferViews[2], byteOffsetValues, accessorDef.sparse.count * itemSize);
  31506. if (bufferView !== null) {
  31507. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  31508. bufferAttribute = new _threeModule.BufferAttribute(bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized);
  31509. }
  31510. for (var i = 0, il = sparseIndices.length; i < il; i++) {
  31511. var index = sparseIndices[i];
  31512. bufferAttribute.setX(index, sparseValues[i * itemSize]);
  31513. if (itemSize >= 2) bufferAttribute.setY(index, sparseValues[i * itemSize + 1]);
  31514. if (itemSize >= 3) bufferAttribute.setZ(index, sparseValues[i * itemSize + 2]);
  31515. if (itemSize >= 4) bufferAttribute.setW(index, sparseValues[i * itemSize + 3]);
  31516. if (itemSize >= 5) throw new Error('THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.');
  31517. }
  31518. }
  31519. return bufferAttribute;
  31520. });
  31521. };
  31522. /**
  31523. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  31524. * @param {number} textureIndex
  31525. * @return {Promise<THREE.Texture>}
  31526. */
  31527. GLTFParser.prototype.loadTexture = function (textureIndex) {
  31528. var parser = this;
  31529. var json = this.json;
  31530. var options = this.options;
  31531. var textureLoader = this.textureLoader;
  31532. var URL = window.URL || window.webkitURL;
  31533. var textureDef = json.textures[textureIndex];
  31534. var textureExtensions = textureDef.extensions || {};
  31535. var source;
  31536. if (textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS]) {
  31537. source = json.images[textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS].source];
  31538. } else {
  31539. source = json.images[textureDef.source];
  31540. }
  31541. var sourceURI = source.uri;
  31542. var isObjectURL = false;
  31543. if (source.bufferView !== undefined) {
  31544. // Load binary image data from bufferView, if provided.
  31545. sourceURI = parser.getDependency('bufferView', source.bufferView).then(function (bufferView) {
  31546. isObjectURL = true;
  31547. var blob = new Blob([bufferView], {
  31548. type: source.mimeType
  31549. });
  31550. sourceURI = URL.createObjectURL(blob);
  31551. return sourceURI;
  31552. });
  31553. }
  31554. return Promise.resolve(sourceURI).then(function (sourceURI) {
  31555. // Load Texture resource.
  31556. var loader = options.manager.getHandler(sourceURI);
  31557. if (!loader) {
  31558. loader = textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS] ? parser.extensions[EXTENSIONS.MSFT_TEXTURE_DDS].ddsLoader : textureLoader;
  31559. }
  31560. return new Promise(function (resolve, reject) {
  31561. loader.load(resolveURL(sourceURI, options.path), resolve, undefined, reject);
  31562. });
  31563. }).then(function (texture) {
  31564. // Clean up resources and configure Texture.
  31565. if (isObjectURL === true) {
  31566. URL.revokeObjectURL(sourceURI);
  31567. }
  31568. texture.flipY = false;
  31569. if (textureDef.name !== undefined) texture.name = textureDef.name; // Ignore unknown mime types, like DDS files.
  31570. if (source.mimeType in MIME_TYPE_FORMATS) {
  31571. texture.format = MIME_TYPE_FORMATS[source.mimeType];
  31572. }
  31573. var samplers = json.samplers || {};
  31574. var sampler = samplers[textureDef.sampler] || {};
  31575. texture.magFilter = WEBGL_FILTERS[sampler.magFilter] || _threeModule.LinearFilter;
  31576. texture.minFilter = WEBGL_FILTERS[sampler.minFilter] || _threeModule.LinearMipmapLinearFilter;
  31577. texture.wrapS = WEBGL_WRAPPINGS[sampler.wrapS] || _threeModule.RepeatWrapping;
  31578. texture.wrapT = WEBGL_WRAPPINGS[sampler.wrapT] || _threeModule.RepeatWrapping;
  31579. return texture;
  31580. });
  31581. };
  31582. /**
  31583. * Asynchronously assigns a texture to the given material parameters.
  31584. * @param {Object} materialParams
  31585. * @param {string} mapName
  31586. * @param {Object} mapDef
  31587. * @return {Promise}
  31588. */
  31589. GLTFParser.prototype.assignTexture = function (materialParams, mapName, mapDef) {
  31590. var parser = this;
  31591. return this.getDependency('texture', mapDef.index).then(function (texture) {
  31592. if (!texture.isCompressedTexture) {
  31593. switch (mapName) {
  31594. case 'aoMap':
  31595. case 'emissiveMap':
  31596. case 'metalnessMap':
  31597. case 'normalMap':
  31598. case 'roughnessMap':
  31599. texture.format = _threeModule.RGBFormat;
  31600. break;
  31601. }
  31602. }
  31603. if (parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM]) {
  31604. var transform = mapDef.extensions !== undefined ? mapDef.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] : undefined;
  31605. if (transform) {
  31606. texture = parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM].extendTexture(texture, transform);
  31607. }
  31608. }
  31609. materialParams[mapName] = texture;
  31610. });
  31611. };
  31612. /**
  31613. * Assigns final material to a Mesh, Line, or Points instance. The instance
  31614. * already has a material (generated from the glTF material options alone)
  31615. * but reuse of the same glTF material may require multiple threejs materials
  31616. * to accomodate different primitive types, defines, etc. New materials will
  31617. * be created if necessary, and reused from a cache.
  31618. * @param {Object3D} mesh Mesh, Line, or Points instance.
  31619. */
  31620. GLTFParser.prototype.assignFinalMaterial = function (mesh) {
  31621. var geometry = mesh.geometry;
  31622. var material = mesh.material;
  31623. var extensions = this.extensions;
  31624. var useVertexTangents = geometry.attributes.tangent !== undefined;
  31625. var useVertexColors = geometry.attributes.color !== undefined;
  31626. var useFlatShading = geometry.attributes.normal === undefined;
  31627. var useSkinning = mesh.isSkinnedMesh === true;
  31628. var useMorphTargets = Object.keys(geometry.morphAttributes).length > 0;
  31629. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  31630. if (mesh.isPoints) {
  31631. var cacheKey = 'PointsMaterial:' + material.uuid;
  31632. var pointsMaterial = this.cache.get(cacheKey);
  31633. if (!pointsMaterial) {
  31634. pointsMaterial = new _threeModule.PointsMaterial();
  31635. _threeModule.Material.prototype.copy.call(pointsMaterial, material);
  31636. pointsMaterial.color.copy(material.color);
  31637. pointsMaterial.map = material.map;
  31638. pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
  31639. this.cache.add(cacheKey, pointsMaterial);
  31640. }
  31641. material = pointsMaterial;
  31642. } else if (mesh.isLine) {
  31643. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  31644. var lineMaterial = this.cache.get(cacheKey);
  31645. if (!lineMaterial) {
  31646. lineMaterial = new _threeModule.LineBasicMaterial();
  31647. _threeModule.Material.prototype.copy.call(lineMaterial, material);
  31648. lineMaterial.color.copy(material.color);
  31649. this.cache.add(cacheKey, lineMaterial);
  31650. }
  31651. material = lineMaterial;
  31652. } // Clone the material if it will be modified
  31653. if (useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets) {
  31654. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  31655. if (material.isGLTFSpecularGlossinessMaterial) cacheKey += 'specular-glossiness:';
  31656. if (useSkinning) cacheKey += 'skinning:';
  31657. if (useVertexTangents) cacheKey += 'vertex-tangents:';
  31658. if (useVertexColors) cacheKey += 'vertex-colors:';
  31659. if (useFlatShading) cacheKey += 'flat-shading:';
  31660. if (useMorphTargets) cacheKey += 'morph-targets:';
  31661. if (useMorphNormals) cacheKey += 'morph-normals:';
  31662. var cachedMaterial = this.cache.get(cacheKey);
  31663. if (!cachedMaterial) {
  31664. cachedMaterial = material.isGLTFSpecularGlossinessMaterial ? extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].cloneMaterial(material) : material.clone();
  31665. if (useSkinning) cachedMaterial.skinning = true;
  31666. if (useVertexTangents) cachedMaterial.vertexTangents = true;
  31667. if (useVertexColors) cachedMaterial.vertexColors = _threeModule.VertexColors;
  31668. if (useFlatShading) cachedMaterial.flatShading = true;
  31669. if (useMorphTargets) cachedMaterial.morphTargets = true;
  31670. if (useMorphNormals) cachedMaterial.morphNormals = true;
  31671. this.cache.add(cacheKey, cachedMaterial);
  31672. }
  31673. material = cachedMaterial;
  31674. } // workarounds for mesh and geometry
  31675. if (material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined) {
  31676. console.log('THREE.GLTFLoader: Duplicating UVs to support aoMap.');
  31677. geometry.addAttribute('uv2', new _threeModule.BufferAttribute(geometry.attributes.uv.array, 2));
  31678. }
  31679. if (material.isGLTFSpecularGlossinessMaterial) {
  31680. // for GLTFSpecularGlossinessMaterial(ShaderMaterial) uniforms runtime update
  31681. mesh.onBeforeRender = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].refreshUniforms;
  31682. }
  31683. mesh.material = material;
  31684. };
  31685. /**
  31686. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  31687. * @param {number} materialIndex
  31688. * @return {Promise<Material>}
  31689. */
  31690. GLTFParser.prototype.loadMaterial = function (materialIndex) {
  31691. var parser = this;
  31692. var json = this.json;
  31693. var extensions = this.extensions;
  31694. var materialDef = json.materials[materialIndex];
  31695. var materialType;
  31696. var materialParams = {};
  31697. var materialExtensions = materialDef.extensions || {};
  31698. var pending = [];
  31699. if (materialExtensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS]) {
  31700. var sgExtension = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS];
  31701. materialType = sgExtension.getMaterialType();
  31702. pending.push(sgExtension.extendParams(materialParams, materialDef, parser));
  31703. } else if (materialExtensions[EXTENSIONS.KHR_MATERIALS_UNLIT]) {
  31704. var kmuExtension = extensions[EXTENSIONS.KHR_MATERIALS_UNLIT];
  31705. materialType = kmuExtension.getMaterialType();
  31706. pending.push(kmuExtension.extendParams(materialParams, materialDef, parser));
  31707. } else {
  31708. // Specification:
  31709. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  31710. materialType = _threeModule.MeshStandardMaterial;
  31711. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  31712. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  31713. materialParams.opacity = 1.0;
  31714. if (Array.isArray(metallicRoughness.baseColorFactor)) {
  31715. var array = metallicRoughness.baseColorFactor;
  31716. materialParams.color.fromArray(array);
  31717. materialParams.opacity = array[3];
  31718. }
  31719. if (metallicRoughness.baseColorTexture !== undefined) {
  31720. pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture));
  31721. }
  31722. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  31723. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  31724. if (metallicRoughness.metallicRoughnessTexture !== undefined) {
  31725. pending.push(parser.assignTexture(materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture));
  31726. pending.push(parser.assignTexture(materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture));
  31727. }
  31728. }
  31729. if (materialDef.doubleSided === true) {
  31730. materialParams.side = _threeModule.DoubleSide;
  31731. }
  31732. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  31733. if (alphaMode === ALPHA_MODES.BLEND) {
  31734. materialParams.transparent = true;
  31735. } else {
  31736. materialParams.transparent = false;
  31737. if (alphaMode === ALPHA_MODES.MASK) {
  31738. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  31739. }
  31740. }
  31741. if (materialDef.normalTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  31742. pending.push(parser.assignTexture(materialParams, 'normalMap', materialDef.normalTexture));
  31743. materialParams.normalScale = new _threeModule.Vector2(1, 1);
  31744. if (materialDef.normalTexture.scale !== undefined) {
  31745. materialParams.normalScale.set(materialDef.normalTexture.scale, materialDef.normalTexture.scale);
  31746. }
  31747. }
  31748. if (materialDef.occlusionTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  31749. pending.push(parser.assignTexture(materialParams, 'aoMap', materialDef.occlusionTexture));
  31750. if (materialDef.occlusionTexture.strength !== undefined) {
  31751. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  31752. }
  31753. }
  31754. if (materialDef.emissiveFactor !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  31755. materialParams.emissive = new _threeModule.Color().fromArray(materialDef.emissiveFactor);
  31756. }
  31757. if (materialDef.emissiveTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  31758. pending.push(parser.assignTexture(materialParams, 'emissiveMap', materialDef.emissiveTexture));
  31759. }
  31760. return Promise.all(pending).then(function () {
  31761. var material;
  31762. if (materialType === _threeModule.ShaderMaterial) {
  31763. material = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].createMaterial(materialParams);
  31764. } else {
  31765. material = new materialType(materialParams);
  31766. }
  31767. if (materialDef.name !== undefined) material.name = materialDef.name; // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  31768. if (material.map) material.map.encoding = _threeModule.sRGBEncoding;
  31769. if (material.emissiveMap) material.emissiveMap.encoding = _threeModule.sRGBEncoding;
  31770. if (material.specularMap) material.specularMap.encoding = _threeModule.sRGBEncoding;
  31771. assignExtrasToUserData(material, materialDef);
  31772. if (materialDef.extensions) addUnknownExtensionsToUserData(extensions, material, materialDef);
  31773. return material;
  31774. });
  31775. };
  31776. /**
  31777. * @param {BufferGeometry} geometry
  31778. * @param {GLTF.Primitive} primitiveDef
  31779. * @param {GLTFParser} parser
  31780. * @return {Promise<BufferGeometry>}
  31781. */
  31782. function addPrimitiveAttributes(geometry, primitiveDef, parser) {
  31783. var attributes = primitiveDef.attributes;
  31784. var pending = [];
  31785. function assignAttributeAccessor(accessorIndex, attributeName) {
  31786. return parser.getDependency('accessor', accessorIndex).then(function (accessor) {
  31787. geometry.addAttribute(attributeName, accessor);
  31788. });
  31789. }
  31790. for (var gltfAttributeName in attributes) {
  31791. var threeAttributeName = ATTRIBUTES[gltfAttributeName] || gltfAttributeName.toLowerCase(); // Skip attributes already provided by e.g. Draco extension.
  31792. if (threeAttributeName in geometry.attributes) continue;
  31793. pending.push(assignAttributeAccessor(attributes[gltfAttributeName], threeAttributeName));
  31794. }
  31795. if (primitiveDef.indices !== undefined && !geometry.index) {
  31796. var accessor = parser.getDependency('accessor', primitiveDef.indices).then(function (accessor) {
  31797. geometry.setIndex(accessor);
  31798. });
  31799. pending.push(accessor);
  31800. }
  31801. assignExtrasToUserData(geometry, primitiveDef);
  31802. return Promise.all(pending).then(function () {
  31803. return primitiveDef.targets !== undefined ? addMorphTargets(geometry, primitiveDef.targets, parser) : geometry;
  31804. });
  31805. }
  31806. /**
  31807. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  31808. *
  31809. * Creates BufferGeometries from primitives.
  31810. *
  31811. * @param {Array<GLTF.Primitive>} primitives
  31812. * @return {Promise<Array<BufferGeometry>>}
  31813. */
  31814. GLTFParser.prototype.loadGeometries = function (primitives) {
  31815. var parser = this;
  31816. var extensions = this.extensions;
  31817. var cache = this.primitiveCache;
  31818. function createDracoPrimitive(primitive) {
  31819. return extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(primitive, parser).then(function (geometry) {
  31820. return addPrimitiveAttributes(geometry, primitive, parser);
  31821. });
  31822. }
  31823. var pending = [];
  31824. for (var i = 0, il = primitives.length; i < il; i++) {
  31825. var primitive = primitives[i];
  31826. var cacheKey = createPrimitiveKey(primitive); // See if we've already created this geometry
  31827. var cached = cache[cacheKey];
  31828. if (cached) {
  31829. // Use the cached geometry if it exists
  31830. pending.push(cached.promise);
  31831. } else {
  31832. var geometryPromise;
  31833. if (primitive.extensions && primitive.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]) {
  31834. // Use DRACO geometry if available
  31835. geometryPromise = createDracoPrimitive(primitive);
  31836. } else {
  31837. // Otherwise create a new geometry
  31838. geometryPromise = addPrimitiveAttributes(new _threeModule.BufferGeometry(), primitive, parser);
  31839. } // Cache this geometry
  31840. cache[cacheKey] = {
  31841. primitive: primitive,
  31842. promise: geometryPromise
  31843. };
  31844. pending.push(geometryPromise);
  31845. }
  31846. }
  31847. return Promise.all(pending);
  31848. };
  31849. /**
  31850. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  31851. * @param {number} meshIndex
  31852. * @return {Promise<Group|Mesh|SkinnedMesh>}
  31853. */
  31854. GLTFParser.prototype.loadMesh = function (meshIndex) {
  31855. var parser = this;
  31856. var json = this.json;
  31857. var meshDef = json.meshes[meshIndex];
  31858. var primitives = meshDef.primitives;
  31859. var pending = [];
  31860. for (var i = 0, il = primitives.length; i < il; i++) {
  31861. var material = primitives[i].material === undefined ? createDefaultMaterial() : this.getDependency('material', primitives[i].material);
  31862. pending.push(material);
  31863. }
  31864. return Promise.all(pending).then(function (originalMaterials) {
  31865. return parser.loadGeometries(primitives).then(function (geometries) {
  31866. var meshes = [];
  31867. for (var i = 0, il = geometries.length; i < il; i++) {
  31868. var geometry = geometries[i];
  31869. var primitive = primitives[i]; // 1. create Mesh
  31870. var mesh;
  31871. var material = originalMaterials[i];
  31872. if (primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN || primitive.mode === undefined) {
  31873. // .isSkinnedMesh isn't in glTF spec. See .markDefs()
  31874. mesh = meshDef.isSkinnedMesh === true ? new _threeModule.SkinnedMesh(geometry, material) : new _threeModule.Mesh(geometry, material);
  31875. if (mesh.isSkinnedMesh === true && !mesh.geometry.attributes.skinWeight.normalized) {
  31876. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  31877. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  31878. mesh.normalizeSkinWeights();
  31879. }
  31880. if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP) {
  31881. mesh.drawMode = _threeModule.TriangleStripDrawMode;
  31882. } else if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN) {
  31883. mesh.drawMode = _threeModule.TriangleFanDrawMode;
  31884. }
  31885. } else if (primitive.mode === WEBGL_CONSTANTS.LINES) {
  31886. mesh = new _threeModule.LineSegments(geometry, material);
  31887. } else if (primitive.mode === WEBGL_CONSTANTS.LINE_STRIP) {
  31888. mesh = new _threeModule.Line(geometry, material);
  31889. } else if (primitive.mode === WEBGL_CONSTANTS.LINE_LOOP) {
  31890. mesh = new _threeModule.LineLoop(geometry, material);
  31891. } else if (primitive.mode === WEBGL_CONSTANTS.POINTS) {
  31892. mesh = new _threeModule.Points(geometry, material);
  31893. } else {
  31894. throw new Error('THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode);
  31895. }
  31896. if (Object.keys(mesh.geometry.morphAttributes).length > 0) {
  31897. updateMorphTargets(mesh, meshDef);
  31898. }
  31899. mesh.name = meshDef.name || 'mesh_' + meshIndex;
  31900. if (geometries.length > 1) mesh.name += '_' + i;
  31901. assignExtrasToUserData(mesh, meshDef);
  31902. parser.assignFinalMaterial(mesh);
  31903. meshes.push(mesh);
  31904. }
  31905. if (meshes.length === 1) {
  31906. return meshes[0];
  31907. }
  31908. var group = new _threeModule.Group();
  31909. for (var i = 0, il = meshes.length; i < il; i++) {
  31910. group.add(meshes[i]);
  31911. }
  31912. return group;
  31913. });
  31914. });
  31915. };
  31916. /**
  31917. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  31918. * @param {number} cameraIndex
  31919. * @return {Promise<THREE.Camera>}
  31920. */
  31921. GLTFParser.prototype.loadCamera = function (cameraIndex) {
  31922. var camera;
  31923. var cameraDef = this.json.cameras[cameraIndex];
  31924. var params = cameraDef[cameraDef.type];
  31925. if (!params) {
  31926. console.warn('THREE.GLTFLoader: Missing camera parameters.');
  31927. return;
  31928. }
  31929. if (cameraDef.type === 'perspective') {
  31930. camera = new _threeModule.PerspectiveCamera(_threeModule.Math.radToDeg(params.yfov), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6);
  31931. } else if (cameraDef.type === 'orthographic') {
  31932. camera = new _threeModule.OrthographicCamera(params.xmag / -2, params.xmag / 2, params.ymag / 2, params.ymag / -2, params.znear, params.zfar);
  31933. }
  31934. if (cameraDef.name !== undefined) camera.name = cameraDef.name;
  31935. assignExtrasToUserData(camera, cameraDef);
  31936. return Promise.resolve(camera);
  31937. };
  31938. /**
  31939. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  31940. * @param {number} skinIndex
  31941. * @return {Promise<Object>}
  31942. */
  31943. GLTFParser.prototype.loadSkin = function (skinIndex) {
  31944. var skinDef = this.json.skins[skinIndex];
  31945. var skinEntry = {
  31946. joints: skinDef.joints
  31947. };
  31948. if (skinDef.inverseBindMatrices === undefined) {
  31949. return Promise.resolve(skinEntry);
  31950. }
  31951. return this.getDependency('accessor', skinDef.inverseBindMatrices).then(function (accessor) {
  31952. skinEntry.inverseBindMatrices = accessor;
  31953. return skinEntry;
  31954. });
  31955. };
  31956. /**
  31957. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  31958. * @param {number} animationIndex
  31959. * @return {Promise<AnimationClip>}
  31960. */
  31961. GLTFParser.prototype.loadAnimation = function (animationIndex) {
  31962. var json = this.json;
  31963. var animationDef = json.animations[animationIndex];
  31964. var pendingNodes = [];
  31965. var pendingInputAccessors = [];
  31966. var pendingOutputAccessors = [];
  31967. var pendingSamplers = [];
  31968. var pendingTargets = [];
  31969. for (var i = 0, il = animationDef.channels.length; i < il; i++) {
  31970. var channel = animationDef.channels[i];
  31971. var sampler = animationDef.samplers[channel.sampler];
  31972. var target = channel.target;
  31973. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  31974. var input = animationDef.parameters !== undefined ? animationDef.parameters[sampler.input] : sampler.input;
  31975. var output = animationDef.parameters !== undefined ? animationDef.parameters[sampler.output] : sampler.output;
  31976. pendingNodes.push(this.getDependency('node', name));
  31977. pendingInputAccessors.push(this.getDependency('accessor', input));
  31978. pendingOutputAccessors.push(this.getDependency('accessor', output));
  31979. pendingSamplers.push(sampler);
  31980. pendingTargets.push(target);
  31981. }
  31982. return Promise.all([Promise.all(pendingNodes), Promise.all(pendingInputAccessors), Promise.all(pendingOutputAccessors), Promise.all(pendingSamplers), Promise.all(pendingTargets)]).then(function (dependencies) {
  31983. var nodes = dependencies[0];
  31984. var inputAccessors = dependencies[1];
  31985. var outputAccessors = dependencies[2];
  31986. var samplers = dependencies[3];
  31987. var targets = dependencies[4];
  31988. var tracks = [];
  31989. for (var i = 0, il = nodes.length; i < il; i++) {
  31990. var node = nodes[i];
  31991. var inputAccessor = inputAccessors[i];
  31992. var outputAccessor = outputAccessors[i];
  31993. var sampler = samplers[i];
  31994. var target = targets[i];
  31995. if (node === undefined) continue;
  31996. node.updateMatrix();
  31997. node.matrixAutoUpdate = true;
  31998. var TypedKeyframeTrack;
  31999. switch (PATH_PROPERTIES[target.path]) {
  32000. case PATH_PROPERTIES.weights:
  32001. TypedKeyframeTrack = _threeModule.NumberKeyframeTrack;
  32002. break;
  32003. case PATH_PROPERTIES.rotation:
  32004. TypedKeyframeTrack = _threeModule.QuaternionKeyframeTrack;
  32005. break;
  32006. case PATH_PROPERTIES.position:
  32007. case PATH_PROPERTIES.scale:
  32008. default:
  32009. TypedKeyframeTrack = _threeModule.VectorKeyframeTrack;
  32010. break;
  32011. }
  32012. var targetName = node.name ? node.name : node.uuid;
  32013. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[sampler.interpolation] : _threeModule.InterpolateLinear;
  32014. var targetNames = [];
  32015. if (PATH_PROPERTIES[target.path] === PATH_PROPERTIES.weights) {
  32016. // Node may be a Group (glTF mesh with several primitives) or a Mesh.
  32017. node.traverse(function (object) {
  32018. if (object.isMesh === true && object.morphTargetInfluences) {
  32019. targetNames.push(object.name ? object.name : object.uuid);
  32020. }
  32021. });
  32022. } else {
  32023. targetNames.push(targetName);
  32024. }
  32025. var outputArray = outputAccessor.array;
  32026. if (outputAccessor.normalized) {
  32027. var scale;
  32028. if (outputArray.constructor === Int8Array) {
  32029. scale = 1 / 127;
  32030. } else if (outputArray.constructor === Uint8Array) {
  32031. scale = 1 / 255;
  32032. } else if (outputArray.constructor == Int16Array) {
  32033. scale = 1 / 32767;
  32034. } else if (outputArray.constructor === Uint16Array) {
  32035. scale = 1 / 65535;
  32036. } else {
  32037. throw new Error('THREE.GLTFLoader: Unsupported output accessor component type.');
  32038. }
  32039. var scaled = new Float32Array(outputArray.length);
  32040. for (var j = 0, jl = outputArray.length; j < jl; j++) {
  32041. scaled[j] = outputArray[j] * scale;
  32042. }
  32043. outputArray = scaled;
  32044. }
  32045. for (var j = 0, jl = targetNames.length; j < jl; j++) {
  32046. var track = new TypedKeyframeTrack(targetNames[j] + '.' + PATH_PROPERTIES[target.path], inputAccessor.array, outputArray, interpolation); // Override interpolation with custom factory method.
  32047. if (sampler.interpolation === 'CUBICSPLINE') {
  32048. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline(result) {
  32049. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  32050. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  32051. // must be divided by three to get the interpolant's sampleSize argument.
  32052. return new GLTFCubicSplineInterpolant(this.times, this.values, this.getValueSize() / 3, result);
  32053. }; // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  32054. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  32055. }
  32056. tracks.push(track);
  32057. }
  32058. }
  32059. var name = animationDef.name !== undefined ? animationDef.name : 'animation_' + animationIndex;
  32060. return new _threeModule.AnimationClip(name, undefined, tracks);
  32061. });
  32062. };
  32063. /**
  32064. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  32065. * @param {number} nodeIndex
  32066. * @return {Promise<Object3D>}
  32067. */
  32068. GLTFParser.prototype.loadNode = function (nodeIndex) {
  32069. var json = this.json;
  32070. var extensions = this.extensions;
  32071. var parser = this;
  32072. var meshReferences = json.meshReferences;
  32073. var meshUses = json.meshUses;
  32074. var nodeDef = json.nodes[nodeIndex];
  32075. return function () {
  32076. var pending = [];
  32077. if (nodeDef.mesh !== undefined) {
  32078. pending.push(parser.getDependency('mesh', nodeDef.mesh).then(function (mesh) {
  32079. var node;
  32080. if (meshReferences[nodeDef.mesh] > 1) {
  32081. var instanceNum = meshUses[nodeDef.mesh]++;
  32082. node = mesh.clone();
  32083. node.name += '_instance_' + instanceNum; // onBeforeRender copy for Specular-Glossiness
  32084. node.onBeforeRender = mesh.onBeforeRender;
  32085. for (var i = 0, il = node.children.length; i < il; i++) {
  32086. node.children[i].name += '_instance_' + instanceNum;
  32087. node.children[i].onBeforeRender = mesh.children[i].onBeforeRender;
  32088. }
  32089. } else {
  32090. node = mesh;
  32091. } // if weights are provided on the node, override weights on the mesh.
  32092. if (nodeDef.weights !== undefined) {
  32093. node.traverse(function (o) {
  32094. if (!o.isMesh) return;
  32095. for (var i = 0, il = nodeDef.weights.length; i < il; i++) {
  32096. o.morphTargetInfluences[i] = nodeDef.weights[i];
  32097. }
  32098. });
  32099. }
  32100. return node;
  32101. }));
  32102. }
  32103. if (nodeDef.camera !== undefined) {
  32104. pending.push(parser.getDependency('camera', nodeDef.camera));
  32105. }
  32106. if (nodeDef.extensions && nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL] && nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].light !== undefined) {
  32107. pending.push(parser.getDependency('light', nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].light));
  32108. }
  32109. return Promise.all(pending);
  32110. }().then(function (objects) {
  32111. var node; // .isBone isn't in glTF spec. See .markDefs
  32112. if (nodeDef.isBone === true) {
  32113. node = new _threeModule.Bone();
  32114. } else if (objects.length > 1) {
  32115. node = new _threeModule.Group();
  32116. } else if (objects.length === 1) {
  32117. node = objects[0];
  32118. } else {
  32119. node = new _threeModule.Object3D();
  32120. }
  32121. if (node !== objects[0]) {
  32122. for (var i = 0, il = objects.length; i < il; i++) {
  32123. node.add(objects[i]);
  32124. }
  32125. }
  32126. if (nodeDef.name !== undefined) {
  32127. node.userData.name = nodeDef.name;
  32128. node.name = _threeModule.PropertyBinding.sanitizeNodeName(nodeDef.name);
  32129. }
  32130. assignExtrasToUserData(node, nodeDef);
  32131. if (nodeDef.extensions) addUnknownExtensionsToUserData(extensions, node, nodeDef);
  32132. if (nodeDef.matrix !== undefined) {
  32133. var matrix = new _threeModule.Matrix4();
  32134. matrix.fromArray(nodeDef.matrix);
  32135. node.applyMatrix(matrix);
  32136. } else {
  32137. if (nodeDef.translation !== undefined) {
  32138. node.position.fromArray(nodeDef.translation);
  32139. }
  32140. if (nodeDef.rotation !== undefined) {
  32141. node.quaternion.fromArray(nodeDef.rotation);
  32142. }
  32143. if (nodeDef.scale !== undefined) {
  32144. node.scale.fromArray(nodeDef.scale);
  32145. }
  32146. }
  32147. return node;
  32148. });
  32149. };
  32150. /**
  32151. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  32152. * @param {number} sceneIndex
  32153. * @return {Promise<Scene>}
  32154. */
  32155. GLTFParser.prototype.loadScene = function () {
  32156. // scene node hierachy builder
  32157. function buildNodeHierachy(nodeId, parentObject, json, parser) {
  32158. var nodeDef = json.nodes[nodeId];
  32159. return parser.getDependency('node', nodeId).then(function (node) {
  32160. if (nodeDef.skin === undefined) return node; // build skeleton here as well
  32161. var skinEntry;
  32162. return parser.getDependency('skin', nodeDef.skin).then(function (skin) {
  32163. skinEntry = skin;
  32164. var pendingJoints = [];
  32165. for (var i = 0, il = skinEntry.joints.length; i < il; i++) {
  32166. pendingJoints.push(parser.getDependency('node', skinEntry.joints[i]));
  32167. }
  32168. return Promise.all(pendingJoints);
  32169. }).then(function (jointNodes) {
  32170. node.traverse(function (mesh) {
  32171. if (!mesh.isMesh) return;
  32172. var bones = [];
  32173. var boneInverses = [];
  32174. for (var j = 0, jl = jointNodes.length; j < jl; j++) {
  32175. var jointNode = jointNodes[j];
  32176. if (jointNode) {
  32177. bones.push(jointNode);
  32178. var mat = new _threeModule.Matrix4();
  32179. if (skinEntry.inverseBindMatrices !== undefined) {
  32180. mat.fromArray(skinEntry.inverseBindMatrices.array, j * 16);
  32181. }
  32182. boneInverses.push(mat);
  32183. } else {
  32184. console.warn('THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[j]);
  32185. }
  32186. }
  32187. mesh.bind(new _threeModule.Skeleton(bones, boneInverses), mesh.matrixWorld);
  32188. });
  32189. return node;
  32190. });
  32191. }).then(function (node) {
  32192. // build node hierachy
  32193. parentObject.add(node);
  32194. var pending = [];
  32195. if (nodeDef.children) {
  32196. var children = nodeDef.children;
  32197. for (var i = 0, il = children.length; i < il; i++) {
  32198. var child = children[i];
  32199. pending.push(buildNodeHierachy(child, node, json, parser));
  32200. }
  32201. }
  32202. return Promise.all(pending);
  32203. });
  32204. }
  32205. return function loadScene(sceneIndex) {
  32206. var json = this.json;
  32207. var extensions = this.extensions;
  32208. var sceneDef = this.json.scenes[sceneIndex];
  32209. var parser = this;
  32210. var scene = new _threeModule.Scene();
  32211. if (sceneDef.name !== undefined) scene.name = sceneDef.name;
  32212. assignExtrasToUserData(scene, sceneDef);
  32213. if (sceneDef.extensions) addUnknownExtensionsToUserData(extensions, scene, sceneDef);
  32214. var nodeIds = sceneDef.nodes || [];
  32215. var pending = [];
  32216. for (var i = 0, il = nodeIds.length; i < il; i++) {
  32217. pending.push(buildNodeHierachy(nodeIds[i], scene, json, parser));
  32218. }
  32219. return Promise.all(pending).then(function () {
  32220. return scene;
  32221. });
  32222. };
  32223. }();
  32224. return GLTFLoader;
  32225. }();
  32226. exports.GLTFLoader = GLTFLoader;
  32227. },{"../../../build/three.module.js":"../node_modules/three/build/three.module.js"}],"../src/ThreeB3DMLoader.js":[function(require,module,exports) {
  32228. "use strict";
  32229. Object.defineProperty(exports, "__esModule", {
  32230. value: true
  32231. });
  32232. exports.ThreeB3DMLoader = void 0;
  32233. var _B3DMLoader = require("./B3DMLoader.js");
  32234. var _GLTFLoader = require("three/examples/jsm/loaders/GLTFLoader.js");
  32235. class ThreeB3DMLoader extends _B3DMLoader.B3DMLoader {
  32236. parse(buffer) {
  32237. const b3dm = super.parse(buffer);
  32238. const gltfBuffer = b3dm.glbBytes.slice().buffer;
  32239. return new Promise((resolve, reject) => {
  32240. new _GLTFLoader.GLTFLoader().parse(gltfBuffer, null, resolve, reject);
  32241. });
  32242. }
  32243. }
  32244. exports.ThreeB3DMLoader = ThreeB3DMLoader;
  32245. },{"./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) {
  32246. "use strict";
  32247. Object.defineProperty(exports, "__esModule", {
  32248. value: true
  32249. });
  32250. exports.ThreeTilesRenderer = void 0;
  32251. var _TilesRenderer = require("./TilesRenderer.js");
  32252. var _ThreeB3DMLoader = require("./ThreeB3DMLoader.js");
  32253. var _three = require("three");
  32254. const DEG2RAD = _three.Math.DEG2RAD;
  32255. const tempMat = new _three.Matrix4();
  32256. const tempQuaternion = new _three.Quaternion();
  32257. const tempVector = new _three.Vector3();
  32258. const resVector = new _three.Vector2();
  32259. const vecX = new _three.Vector3();
  32260. const vecY = new _three.Vector3();
  32261. const vecZ = new _three.Vector3();
  32262. const ray = new _three.Ray();
  32263. const _sphere = new _three.Sphere(); // Specialization of "Group" that only updates world matrices of children if
  32264. // the transform has changed since the last update and ignores the "force"
  32265. // parameter under the assumption that the children tiles will not move.
  32266. class TilesGroup extends _three.Group {
  32267. constructor(tilesRenderer) {
  32268. super();
  32269. this.tilesRenderer = tilesRenderer;
  32270. }
  32271. raycast(raycaster, intersects) {
  32272. // TODO: Figure out how to do traversal here -- submit issue to three.js?
  32273. const tilesRenderer = this.tilesRenderer;
  32274. const visibleSet = tilesRenderer.visibleSet;
  32275. const activeSet = tilesRenderer.activeSet;
  32276. activeSet.forEach(scene => {
  32277. if (!visibleSet.has(scene)) {
  32278. raycaster.intersectObject(scene, true, intersects);
  32279. }
  32280. });
  32281. }
  32282. updateMatrixWorld(force) {
  32283. if (this.matrixAutoUpdate) {
  32284. this.updateMatrix();
  32285. }
  32286. if (this.matrixWorldNeedsUpdate || force) {
  32287. if (this.parent === null) {
  32288. tempMat.copy(this.matrix);
  32289. } else {
  32290. tempMat.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  32291. }
  32292. this.matrixWorldNeedsUpdate = false;
  32293. const elA = tempMat.elements;
  32294. const elB = this.matrixWorld.elements;
  32295. let isDifferent = false;
  32296. for (let i = 0; i < 16; i++) {
  32297. const itemA = elA[i];
  32298. const itemB = elB[i];
  32299. const diff = Math.abs(itemA - itemB);
  32300. if (diff > Number.EPSILON) {
  32301. isDifferent = true;
  32302. break;
  32303. }
  32304. }
  32305. if (isDifferent) {
  32306. this.matrixWorld.copy(tempMat); // update children
  32307. // the children will not have to change unless the parent group has updated
  32308. const children = this.children;
  32309. for (let i = 0, l = children.length; i < l; i++) {
  32310. children[i].updateMatrixWorld();
  32311. }
  32312. }
  32313. }
  32314. }
  32315. }
  32316. class ThreeTilesRenderer extends _TilesRenderer.TilesRenderer {
  32317. get displayBounds() {
  32318. return this._displayBounds;
  32319. }
  32320. set displayBounds(val) {
  32321. if (val !== this.displayBounds) {
  32322. this._displayBounds = val;
  32323. this.traverse(t => {
  32324. const scene = t.cached.scene;
  32325. const boxHelper = t.cached.boxHelper;
  32326. if (scene) {
  32327. if (val) {
  32328. scene.add(boxHelper);
  32329. boxHelper.updateMatrixWorld(true);
  32330. } else {
  32331. scene.remove(boxHelper);
  32332. }
  32333. }
  32334. });
  32335. }
  32336. }
  32337. constructor(url, cameras, renderer) {
  32338. super(url);
  32339. this.group = new TilesGroup(this);
  32340. this.cameras = Array.isArray(cameras) ? cameras : [cameras];
  32341. this.frustums = [];
  32342. this.renderer = renderer;
  32343. this.activeSet = new Set();
  32344. this.visibleSet = new Set();
  32345. }
  32346. /* Public API */
  32347. getBounds(box) {
  32348. if (!this.root) {
  32349. return false;
  32350. }
  32351. const cached = this.root.cached;
  32352. const boundingBox = cached.box;
  32353. const obbMat = cached.boxTransform;
  32354. const transformMat = cached.transform;
  32355. box.copy(boundingBox);
  32356. tempMat.multiplyMatrices(transformMat, obbMat);
  32357. box.applyMatrix4(tempMat);
  32358. return true;
  32359. }
  32360. raycast(raycaster, intersects) {
  32361. const activeSet = this.activeSet;
  32362. const group = this.group;
  32363. this.traverse(tile => {
  32364. const cached = tile.tempMat.copy(transformMat);
  32365. group.matrixWorld;
  32366. tempMat.copy(transformMat);
  32367. ;
  32368. const sphere = cached.sphere;
  32369. if (sphere) {
  32370. _sphere.copy(sphere);
  32371. _sphere.applyMatrix4(tempMat);
  32372. if (!raycaster.ray.intersectsSphere(_sphere)) {
  32373. return true;
  32374. }
  32375. }
  32376. const boundingBox = cached.box;
  32377. const obbMat = cached.boxTransform;
  32378. if (boundingBox) {
  32379. tempMat.multiply(obbMat);
  32380. tempMat.getInverse(tempMat);
  32381. ray.copy(raycaster.ray).applyMatrix4(tempMat);
  32382. if (!ray.intersectsBox(boundingBox)) {
  32383. return true;
  32384. }
  32385. } // TODO: check region
  32386. // TODO: how do we prevent the child checks from happening?
  32387. const scene = cached.scene;
  32388. if (activeSet.has(scene)) {
  32389. raycaster.intersectObject(scene, true, intersects);
  32390. }
  32391. });
  32392. }
  32393. /* Overriden */
  32394. update() {
  32395. const group = this.group;
  32396. const renderer = this.renderer;
  32397. const cameras = this.cameras;
  32398. const frustums = this.frustums; // automatically scale the array of frustums to match the cameras
  32399. while (frustums.length > cameras.length) {
  32400. frustums.pop();
  32401. }
  32402. while (frustums.length < cameras.length) {
  32403. frustums.push(new _three.Frustum());
  32404. } // store the camera frustums in the 3d tiles root frame
  32405. for (let i = 0, l = frustums.length; i < l; i++) {
  32406. const camera = cameras[i];
  32407. const frustum = frustums[i];
  32408. tempMat.copy(group.matrixWorld);
  32409. tempMat.premultiply(camera.matrixWorldInverse);
  32410. tempMat.premultiply(camera.projectionMatrix);
  32411. frustum.setFromMatrix(tempMat);
  32412. } // store the resolution of the render
  32413. renderer.getSize(resVector);
  32414. resVector.multiplyScalar(renderer.getPixelRatio());
  32415. super.update();
  32416. }
  32417. preprocessNode(tile, parentTile, tileSetDir) {
  32418. super.preprocessNode(tile, parentTile, tileSetDir);
  32419. const transform = new _three.Matrix4();
  32420. if (tile.transform) {
  32421. const transformArr = tile.transform;
  32422. for (let i = 0; i < 16; i++) {
  32423. transform.elements[i] = transformArr[i];
  32424. }
  32425. } else {
  32426. transform.identity();
  32427. }
  32428. if (parentTile) {
  32429. transform.multiply(parentTile.cached.transform);
  32430. }
  32431. let box = null;
  32432. let boxTransform = null;
  32433. if ('box' in tile.boundingVolume) {
  32434. const data = tile.boundingVolume.box;
  32435. box = new _three.Box3();
  32436. boxTransform = new _three.Matrix4(); // get the extents of the bounds in each axis
  32437. vecX.set(data[3], data[4], data[5]);
  32438. vecY.set(data[6], data[7], data[8]);
  32439. vecZ.set(data[9], data[10], data[11]);
  32440. const scaleX = vecX.length();
  32441. const scaleY = vecY.length();
  32442. const scaleZ = vecZ.length();
  32443. vecX.normalize();
  32444. vecY.normalize();
  32445. vecZ.normalize(); // create the oriented frame that the box exists in
  32446. boxTransform.set(vecX.x, vecY.x, vecZ.x, data[0], vecX.y, vecY.y, vecZ.y, data[1], vecX.z, vecY.z, vecZ.z, data[2], 0, 0, 0, 1); // scale the box by the extents
  32447. box.min.set(-scaleX, -scaleY, -scaleZ);
  32448. box.max.set(scaleX, scaleY, scaleZ);
  32449. }
  32450. let sphere = null;
  32451. if ('sphere' in tile.boundingVolume) {
  32452. const data = tile.boundingVolume.sphere;
  32453. sphere = new _three.Sphere();
  32454. sphere.center.set(data[0], data[1], data[2]);
  32455. sphere.radius = data[3];
  32456. } else if ('box' in tile.boundingVolume) {
  32457. sphere = new _three.Sphere();
  32458. box.getBoundingSphere(sphere);
  32459. boxTransform.decompose(sphere.center, tempQuaternion, tempVector);
  32460. }
  32461. let region = null;
  32462. if ('region' in tile.boundingVolume) {
  32463. console.warn('ThreeTilesRenderer: region bounding volume not supported.');
  32464. }
  32465. tile.cached = {
  32466. loadIndex: 0,
  32467. transform,
  32468. active: false,
  32469. box,
  32470. boxTransform,
  32471. sphere,
  32472. region,
  32473. boxHelper: null,
  32474. scene: null
  32475. };
  32476. }
  32477. parseTile(buffer, tile) {
  32478. tile._loadIndex = tile._loadIndex || 0;
  32479. tile._loadIndex++; // TODO: 90 degree rotation must be applied to GLTF file to resolve "up"
  32480. const loadIndex = tile._loadIndex;
  32481. return new _ThreeB3DMLoader.ThreeB3DMLoader().parse(buffer).then(res => {
  32482. if (tile._loadIndex !== loadIndex) {
  32483. return;
  32484. }
  32485. const cached = tile.cached;
  32486. const cachedBox = cached.box;
  32487. const cachedBoxMat = cached.boxTransform; // add a helper group to represent the obb rotation matrix
  32488. const boxHelper = new _three.Box3Helper(cachedBox);
  32489. const boxHelperGroup = new _three.Group();
  32490. cachedBoxMat.decompose(boxHelperGroup.position, boxHelperGroup.quaternion, boxHelperGroup.scale);
  32491. boxHelperGroup.add(boxHelper);
  32492. boxHelperGroup.updateMatrixWorld(true);
  32493. const scene = res.scene;
  32494. cached.transform.decompose(scene.position, scene.quaternion, scene.scale);
  32495. scene.traverse(c => c.frustumCulled = false);
  32496. cached.boxHelper = boxHelperGroup;
  32497. cached.scene = res.scene;
  32498. if (this.displayBounds) {
  32499. cached.scene.add(cached.boxHelper);
  32500. }
  32501. });
  32502. }
  32503. disposeTile(tile) {
  32504. const cached = tile.cached;
  32505. if (cached.scene) {
  32506. const scene = cached.scene;
  32507. if (scene.parent) {
  32508. scene.parent.remove(scene);
  32509. }
  32510. scene.traverse(c => {
  32511. if (c.geometry) {
  32512. c.geometry.dispose();
  32513. }
  32514. if (c.material) {
  32515. c.material.dispose(); // TODO: dispose textures
  32516. }
  32517. });
  32518. cached.scene = null;
  32519. cached.boxHelper = null;
  32520. }
  32521. tile._loadIndex++;
  32522. }
  32523. setTileVisible(tile, visible) {
  32524. const scene = tile.cached.scene;
  32525. const visibleSet = this.visibleSet;
  32526. const group = this.group;
  32527. if (visible) {
  32528. if (scene && !scene.parent) {
  32529. group.add(scene);
  32530. visibleSet.add(scene);
  32531. scene.updateMatrixWorld(true);
  32532. }
  32533. } else {
  32534. group.remove(scene);
  32535. visibleSet.delete(scene);
  32536. }
  32537. }
  32538. setTileActive(tile, active) {
  32539. const cached = tile.cached;
  32540. const activeSet = this.activeSet;
  32541. if (active !== cached.active) {
  32542. cached.active = active;
  32543. if (active) {
  32544. activeSet.add(cached.scene);
  32545. } else {
  32546. activeSet.delete(cached.scene);
  32547. }
  32548. }
  32549. }
  32550. calculateError(tile) {
  32551. const cached = tile.cached;
  32552. const cameras = this.cameras; // TODO: Use the content bounding volume here?
  32553. const boundingVolume = tile.boundingVolume;
  32554. const transformMat = cached.transform;
  32555. if ('box' in boundingVolume) {
  32556. const group = this.group;
  32557. const boundingBox = cached.box;
  32558. const obbMat = cached.boxTransform; // TODO: these can likely be cached? Or the world transform mat can be used
  32559. // transformMat can be rolled into oobMat
  32560. tempMat.copy(transformMat);
  32561. tempMat.multiply(obbMat);
  32562. tempMat.getInverse(tempMat);
  32563. let minError = Infinity;
  32564. for (let i = 0, l = cameras.length; i < l; i++) {
  32565. // transform camera position into local frame of the tile bounding box
  32566. const cam = cameras[i];
  32567. tempVector.copy(cam.position);
  32568. tempVector.applyMatrix4(tempMat);
  32569. let error;
  32570. if (cam.isOrthographic) {
  32571. const w = cam.right - cam.left;
  32572. const h = cam.top - cam.bottom;
  32573. const pixelSize = Math.Max(h, w) / Math.Max(resVector.width, resVector.height);
  32574. error = tile.geometricError / pixelSize;
  32575. } else {
  32576. const distance = boundingBox.distanceToPoint(tempVector); // assume the scales on all axes are uniform.
  32577. let scale; // account for tile scale.
  32578. tempVector.setFromMatrixScale(tempMat);
  32579. scale = tempVector.x; // account for parent group scale. Divide because this matrix has not been inverted like the previous one.
  32580. tempVector.setFromMatrixScale(group.matrixWorld);
  32581. scale /= tempVector.x;
  32582. if (Math.abs(Math.max(scale.x - scale.y, scale.x - scale.z)) > 1e-6) {
  32583. console.warn('ThreeTilesRenderer : Non uniform scale used for tile which may cause issues when claculating screen space error.');
  32584. }
  32585. const scaledDistance = distance * scale;
  32586. const sseDenominator = 2 * Math.tan(0.5 * cam.fov * DEG2RAD);
  32587. error = tile.geometricError * resVector.height / (scaledDistance * sseDenominator);
  32588. }
  32589. minError = Math.min(minError, error);
  32590. }
  32591. return minError;
  32592. } else if ('sphere' in boundingVolume) {
  32593. const sphere = cached.sphere;
  32594. console.warn('ThreeTilesRenderer : Sphere bounds not supported.');
  32595. } else if ('region' in boundingVolume) {
  32596. // unsupported
  32597. console.warn('ThreeTilesRenderer : Region bounds not supported.');
  32598. }
  32599. return Infinity;
  32600. }
  32601. tileInView(tile) {
  32602. // TODO: we should use the more precise bounding volumes here if possible
  32603. // cache the root-space planes
  32604. const sphere = tile.cached.sphere;
  32605. if (sphere) {
  32606. _sphere.copy(sphere);
  32607. _sphere.applyMatrix4(tile.cached.transform);
  32608. const frustums = this.frustums;
  32609. for (let i = 0, l = frustums.length; i < l; i++) {
  32610. const frustum = frustums[i];
  32611. if (frustum.intersectsSphere(_sphere)) {
  32612. return true;
  32613. }
  32614. }
  32615. return false;
  32616. }
  32617. return true;
  32618. }
  32619. }
  32620. exports.ThreeTilesRenderer = ThreeTilesRenderer;
  32621. },{"./TilesRenderer.js":"../src/TilesRenderer.js","./ThreeB3DMLoader.js":"../src/ThreeB3DMLoader.js","three":"../node_modules/three/build/three.module.js"}],"../node_modules/three/examples/jsm/controls/OrbitControls.js":[function(require,module,exports) {
  32622. "use strict";
  32623. Object.defineProperty(exports, "__esModule", {
  32624. value: true
  32625. });
  32626. exports.MapControls = exports.OrbitControls = void 0;
  32627. var _threeModule = require("../../../build/three.module.js");
  32628. /**
  32629. * @author qiao / https://github.com/qiao
  32630. * @author mrdoob / http://mrdoob.com
  32631. * @author alteredq / http://alteredqualia.com/
  32632. * @author WestLangley / http://github.com/WestLangley
  32633. * @author erich666 / http://erichaines.com
  32634. * @author ScieCode / http://github.com/sciecode
  32635. */
  32636. // This set of controls performs orbiting, dollying (zooming), and panning.
  32637. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  32638. //
  32639. // Orbit - left mouse / touch: one-finger move
  32640. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  32641. // Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move
  32642. var OrbitControls = function (object, domElement) {
  32643. this.object = object;
  32644. this.domElement = domElement !== undefined ? domElement : document; // Set to false to disable this control
  32645. this.enabled = true; // "target" sets the location of focus, where the object orbits around
  32646. this.target = new _threeModule.Vector3(); // How far you can dolly in and out ( PerspectiveCamera only )
  32647. this.minDistance = 0;
  32648. this.maxDistance = Infinity; // How far you can zoom in and out ( OrthographicCamera only )
  32649. this.minZoom = 0;
  32650. this.maxZoom = Infinity; // How far you can orbit vertically, upper and lower limits.
  32651. // Range is 0 to Math.PI radians.
  32652. this.minPolarAngle = 0; // radians
  32653. this.maxPolarAngle = Math.PI; // radians
  32654. // How far you can orbit horizontally, upper and lower limits.
  32655. // If set, must be a sub-interval of the interval [ - Math.PI, Math.PI ].
  32656. this.minAzimuthAngle = -Infinity; // radians
  32657. this.maxAzimuthAngle = Infinity; // radians
  32658. // Set to true to enable damping (inertia)
  32659. // If damping is enabled, you must call controls.update() in your animation loop
  32660. this.enableDamping = false;
  32661. this.dampingFactor = 0.05; // This option actually enables dollying in and out; left as "zoom" for backwards compatibility.
  32662. // Set to false to disable zooming
  32663. this.enableZoom = true;
  32664. this.zoomSpeed = 1.0; // Set to false to disable rotating
  32665. this.enableRotate = true;
  32666. this.rotateSpeed = 1.0; // Set to false to disable panning
  32667. this.enablePan = true;
  32668. this.panSpeed = 1.0;
  32669. this.screenSpacePanning = false; // if true, pan in screen-space
  32670. this.keyPanSpeed = 7.0; // pixels moved per arrow key push
  32671. // Set to true to automatically rotate around the target
  32672. // If auto-rotate is enabled, you must call controls.update() in your animation loop
  32673. this.autoRotate = false;
  32674. this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60
  32675. // Set to false to disable use of the keys
  32676. this.enableKeys = true; // The four arrow keys
  32677. this.keys = {
  32678. LEFT: 37,
  32679. UP: 38,
  32680. RIGHT: 39,
  32681. BOTTOM: 40
  32682. }; // Mouse buttons
  32683. this.mouseButtons = {
  32684. LEFT: _threeModule.MOUSE.ROTATE,
  32685. MIDDLE: _threeModule.MOUSE.DOLLY,
  32686. RIGHT: _threeModule.MOUSE.PAN
  32687. }; // Touch fingers
  32688. this.touches = {
  32689. ONE: _threeModule.TOUCH.ROTATE,
  32690. TWO: _threeModule.TOUCH.DOLLY_PAN
  32691. }; // for reset
  32692. this.target0 = this.target.clone();
  32693. this.position0 = this.object.position.clone();
  32694. this.zoom0 = this.object.zoom; //
  32695. // public methods
  32696. //
  32697. this.getPolarAngle = function () {
  32698. return spherical.phi;
  32699. };
  32700. this.getAzimuthalAngle = function () {
  32701. return spherical.theta;
  32702. };
  32703. this.saveState = function () {
  32704. scope.target0.copy(scope.target);
  32705. scope.position0.copy(scope.object.position);
  32706. scope.zoom0 = scope.object.zoom;
  32707. };
  32708. this.reset = function () {
  32709. scope.target.copy(scope.target0);
  32710. scope.object.position.copy(scope.position0);
  32711. scope.object.zoom = scope.zoom0;
  32712. scope.object.updateProjectionMatrix();
  32713. scope.dispatchEvent(changeEvent);
  32714. scope.update();
  32715. state = STATE.NONE;
  32716. }; // this method is exposed, but perhaps it would be better if we can make it private...
  32717. this.update = function () {
  32718. var offset = new _threeModule.Vector3(); // so camera.up is the orbit axis
  32719. var quat = new _threeModule.Quaternion().setFromUnitVectors(object.up, new _threeModule.Vector3(0, 1, 0));
  32720. var quatInverse = quat.clone().inverse();
  32721. var lastPosition = new _threeModule.Vector3();
  32722. var lastQuaternion = new _threeModule.Quaternion();
  32723. return function update() {
  32724. var position = scope.object.position;
  32725. offset.copy(position).sub(scope.target); // rotate offset to "y-axis-is-up" space
  32726. offset.applyQuaternion(quat); // angle from z-axis around y-axis
  32727. spherical.setFromVector3(offset);
  32728. if (scope.autoRotate && state === STATE.NONE) {
  32729. rotateLeft(getAutoRotationAngle());
  32730. }
  32731. if (scope.enableDamping) {
  32732. spherical.theta += sphericalDelta.theta * scope.dampingFactor;
  32733. spherical.phi += sphericalDelta.phi * scope.dampingFactor;
  32734. } else {
  32735. spherical.theta += sphericalDelta.theta;
  32736. spherical.phi += sphericalDelta.phi;
  32737. } // restrict theta to be between desired limits
  32738. spherical.theta = Math.max(scope.minAzimuthAngle, Math.min(scope.maxAzimuthAngle, spherical.theta)); // restrict phi to be between desired limits
  32739. spherical.phi = Math.max(scope.minPolarAngle, Math.min(scope.maxPolarAngle, spherical.phi));
  32740. spherical.makeSafe();
  32741. spherical.radius *= scale; // restrict radius to be between desired limits
  32742. spherical.radius = Math.max(scope.minDistance, Math.min(scope.maxDistance, spherical.radius)); // move target to panned location
  32743. if (scope.enableDamping === true) {
  32744. scope.target.addScaledVector(panOffset, scope.dampingFactor);
  32745. } else {
  32746. scope.target.add(panOffset);
  32747. }
  32748. offset.setFromSpherical(spherical); // rotate offset back to "camera-up-vector-is-up" space
  32749. offset.applyQuaternion(quatInverse);
  32750. position.copy(scope.target).add(offset);
  32751. scope.object.lookAt(scope.target);
  32752. if (scope.enableDamping === true) {
  32753. sphericalDelta.theta *= 1 - scope.dampingFactor;
  32754. sphericalDelta.phi *= 1 - scope.dampingFactor;
  32755. panOffset.multiplyScalar(1 - scope.dampingFactor);
  32756. } else {
  32757. sphericalDelta.set(0, 0, 0);
  32758. panOffset.set(0, 0, 0);
  32759. }
  32760. scale = 1; // update condition is:
  32761. // min(camera displacement, camera rotation in radians)^2 > EPS
  32762. // using small-angle approximation cos(x/2) = 1 - x^2 / 8
  32763. if (zoomChanged || lastPosition.distanceToSquared(scope.object.position) > EPS || 8 * (1 - lastQuaternion.dot(scope.object.quaternion)) > EPS) {
  32764. scope.dispatchEvent(changeEvent);
  32765. lastPosition.copy(scope.object.position);
  32766. lastQuaternion.copy(scope.object.quaternion);
  32767. zoomChanged = false;
  32768. return true;
  32769. }
  32770. return false;
  32771. };
  32772. }();
  32773. this.dispose = function () {
  32774. scope.domElement.removeEventListener('contextmenu', onContextMenu, false);
  32775. scope.domElement.removeEventListener('mousedown', onMouseDown, false);
  32776. scope.domElement.removeEventListener('wheel', onMouseWheel, false);
  32777. scope.domElement.removeEventListener('touchstart', onTouchStart, false);
  32778. scope.domElement.removeEventListener('touchend', onTouchEnd, false);
  32779. scope.domElement.removeEventListener('touchmove', onTouchMove, false);
  32780. document.removeEventListener('mousemove', onMouseMove, false);
  32781. document.removeEventListener('mouseup', onMouseUp, false);
  32782. window.removeEventListener('keydown', onKeyDown, false); //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here?
  32783. }; //
  32784. // internals
  32785. //
  32786. var scope = this;
  32787. var changeEvent = {
  32788. type: 'change'
  32789. };
  32790. var startEvent = {
  32791. type: 'start'
  32792. };
  32793. var endEvent = {
  32794. type: 'end'
  32795. };
  32796. var STATE = {
  32797. NONE: -1,
  32798. ROTATE: 0,
  32799. DOLLY: 1,
  32800. PAN: 2,
  32801. TOUCH_ROTATE: 3,
  32802. TOUCH_PAN: 4,
  32803. TOUCH_DOLLY_PAN: 5,
  32804. TOUCH_DOLLY_ROTATE: 6
  32805. };
  32806. var state = STATE.NONE;
  32807. var EPS = 0.000001; // current position in spherical coordinates
  32808. var spherical = new _threeModule.Spherical();
  32809. var sphericalDelta = new _threeModule.Spherical();
  32810. var scale = 1;
  32811. var panOffset = new _threeModule.Vector3();
  32812. var zoomChanged = false;
  32813. var rotateStart = new _threeModule.Vector2();
  32814. var rotateEnd = new _threeModule.Vector2();
  32815. var rotateDelta = new _threeModule.Vector2();
  32816. var panStart = new _threeModule.Vector2();
  32817. var panEnd = new _threeModule.Vector2();
  32818. var panDelta = new _threeModule.Vector2();
  32819. var dollyStart = new _threeModule.Vector2();
  32820. var dollyEnd = new _threeModule.Vector2();
  32821. var dollyDelta = new _threeModule.Vector2();
  32822. function getAutoRotationAngle() {
  32823. return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
  32824. }
  32825. function getZoomScale() {
  32826. return Math.pow(0.95, scope.zoomSpeed);
  32827. }
  32828. function rotateLeft(angle) {
  32829. sphericalDelta.theta -= angle;
  32830. }
  32831. function rotateUp(angle) {
  32832. sphericalDelta.phi -= angle;
  32833. }
  32834. var panLeft = function () {
  32835. var v = new _threeModule.Vector3();
  32836. return function panLeft(distance, objectMatrix) {
  32837. v.setFromMatrixColumn(objectMatrix, 0); // get X column of objectMatrix
  32838. v.multiplyScalar(-distance);
  32839. panOffset.add(v);
  32840. };
  32841. }();
  32842. var panUp = function () {
  32843. var v = new _threeModule.Vector3();
  32844. return function panUp(distance, objectMatrix) {
  32845. if (scope.screenSpacePanning === true) {
  32846. v.setFromMatrixColumn(objectMatrix, 1);
  32847. } else {
  32848. v.setFromMatrixColumn(objectMatrix, 0);
  32849. v.crossVectors(scope.object.up, v);
  32850. }
  32851. v.multiplyScalar(distance);
  32852. panOffset.add(v);
  32853. };
  32854. }(); // deltaX and deltaY are in pixels; right and down are positive
  32855. var pan = function () {
  32856. var offset = new _threeModule.Vector3();
  32857. return function pan(deltaX, deltaY) {
  32858. var element = scope.domElement === document ? scope.domElement.body : scope.domElement;
  32859. if (scope.object.isPerspectiveCamera) {
  32860. // perspective
  32861. var position = scope.object.position;
  32862. offset.copy(position).sub(scope.target);
  32863. var targetDistance = offset.length(); // half of the fov is center to top of screen
  32864. targetDistance *= Math.tan(scope.object.fov / 2 * Math.PI / 180.0); // we use only clientHeight here so aspect ratio does not distort speed
  32865. panLeft(2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix);
  32866. panUp(2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix);
  32867. } else if (scope.object.isOrthographicCamera) {
  32868. // orthographic
  32869. panLeft(deltaX * (scope.object.right - scope.object.left) / scope.object.zoom / element.clientWidth, scope.object.matrix);
  32870. panUp(deltaY * (scope.object.top - scope.object.bottom) / scope.object.zoom / element.clientHeight, scope.object.matrix);
  32871. } else {
  32872. // camera neither orthographic nor perspective
  32873. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.');
  32874. scope.enablePan = false;
  32875. }
  32876. };
  32877. }();
  32878. function dollyIn(dollyScale) {
  32879. if (scope.object.isPerspectiveCamera) {
  32880. scale /= dollyScale;
  32881. } else if (scope.object.isOrthographicCamera) {
  32882. scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom * dollyScale));
  32883. scope.object.updateProjectionMatrix();
  32884. zoomChanged = true;
  32885. } else {
  32886. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.');
  32887. scope.enableZoom = false;
  32888. }
  32889. }
  32890. function dollyOut(dollyScale) {
  32891. if (scope.object.isPerspectiveCamera) {
  32892. scale *= dollyScale;
  32893. } else if (scope.object.isOrthographicCamera) {
  32894. scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom / dollyScale));
  32895. scope.object.updateProjectionMatrix();
  32896. zoomChanged = true;
  32897. } else {
  32898. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.');
  32899. scope.enableZoom = false;
  32900. }
  32901. } //
  32902. // event callbacks - update the object state
  32903. //
  32904. function handleMouseDownRotate(event) {
  32905. rotateStart.set(event.clientX, event.clientY);
  32906. }
  32907. function handleMouseDownDolly(event) {
  32908. dollyStart.set(event.clientX, event.clientY);
  32909. }
  32910. function handleMouseDownPan(event) {
  32911. panStart.set(event.clientX, event.clientY);
  32912. }
  32913. function handleMouseMoveRotate(event) {
  32914. rotateEnd.set(event.clientX, event.clientY);
  32915. rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);
  32916. var element = scope.domElement === document ? scope.domElement.body : scope.domElement;
  32917. rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height
  32918. rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight);
  32919. rotateStart.copy(rotateEnd);
  32920. scope.update();
  32921. }
  32922. function handleMouseMoveDolly(event) {
  32923. dollyEnd.set(event.clientX, event.clientY);
  32924. dollyDelta.subVectors(dollyEnd, dollyStart);
  32925. if (dollyDelta.y > 0) {
  32926. dollyIn(getZoomScale());
  32927. } else if (dollyDelta.y < 0) {
  32928. dollyOut(getZoomScale());
  32929. }
  32930. dollyStart.copy(dollyEnd);
  32931. scope.update();
  32932. }
  32933. function handleMouseMovePan(event) {
  32934. panEnd.set(event.clientX, event.clientY);
  32935. panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);
  32936. pan(panDelta.x, panDelta.y);
  32937. panStart.copy(panEnd);
  32938. scope.update();
  32939. }
  32940. function handleMouseUp()
  32941. /*event*/
  32942. {// no-op
  32943. }
  32944. function handleMouseWheel(event) {
  32945. if (event.deltaY < 0) {
  32946. dollyOut(getZoomScale());
  32947. } else if (event.deltaY > 0) {
  32948. dollyIn(getZoomScale());
  32949. }
  32950. scope.update();
  32951. }
  32952. function handleKeyDown(event) {
  32953. var needsUpdate = false;
  32954. switch (event.keyCode) {
  32955. case scope.keys.UP:
  32956. pan(0, scope.keyPanSpeed);
  32957. needsUpdate = true;
  32958. break;
  32959. case scope.keys.BOTTOM:
  32960. pan(0, -scope.keyPanSpeed);
  32961. needsUpdate = true;
  32962. break;
  32963. case scope.keys.LEFT:
  32964. pan(scope.keyPanSpeed, 0);
  32965. needsUpdate = true;
  32966. break;
  32967. case scope.keys.RIGHT:
  32968. pan(-scope.keyPanSpeed, 0);
  32969. needsUpdate = true;
  32970. break;
  32971. }
  32972. if (needsUpdate) {
  32973. // prevent the browser from scrolling on cursor keys
  32974. event.preventDefault();
  32975. scope.update();
  32976. }
  32977. }
  32978. function handleTouchStartRotate(event) {
  32979. if (event.touches.length == 1) {
  32980. rotateStart.set(event.touches[0].pageX, event.touches[0].pageY);
  32981. } else {
  32982. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  32983. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  32984. rotateStart.set(x, y);
  32985. }
  32986. }
  32987. function handleTouchStartPan(event) {
  32988. if (event.touches.length == 1) {
  32989. panStart.set(event.touches[0].pageX, event.touches[0].pageY);
  32990. } else {
  32991. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  32992. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  32993. panStart.set(x, y);
  32994. }
  32995. }
  32996. function handleTouchStartDolly(event) {
  32997. var dx = event.touches[0].pageX - event.touches[1].pageX;
  32998. var dy = event.touches[0].pageY - event.touches[1].pageY;
  32999. var distance = Math.sqrt(dx * dx + dy * dy);
  33000. dollyStart.set(0, distance);
  33001. }
  33002. function handleTouchStartDollyPan(event) {
  33003. if (scope.enableZoom) handleTouchStartDolly(event);
  33004. if (scope.enablePan) handleTouchStartPan(event);
  33005. }
  33006. function handleTouchStartDollyRotate(event) {
  33007. if (scope.enableZoom) handleTouchStartDolly(event);
  33008. if (scope.enableRotate) handleTouchStartRotate(event);
  33009. }
  33010. function handleTouchMoveRotate(event) {
  33011. if (event.touches.length == 1) {
  33012. rotateEnd.set(event.touches[0].pageX, event.touches[0].pageY);
  33013. } else {
  33014. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  33015. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  33016. rotateEnd.set(x, y);
  33017. }
  33018. rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);
  33019. var element = scope.domElement === document ? scope.domElement.body : scope.domElement;
  33020. rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height
  33021. rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight);
  33022. rotateStart.copy(rotateEnd);
  33023. }
  33024. function handleTouchMovePan(event) {
  33025. if (event.touches.length == 1) {
  33026. panEnd.set(event.touches[0].pageX, event.touches[0].pageY);
  33027. } else {
  33028. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  33029. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  33030. panEnd.set(x, y);
  33031. }
  33032. panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);
  33033. pan(panDelta.x, panDelta.y);
  33034. panStart.copy(panEnd);
  33035. }
  33036. function handleTouchMoveDolly(event) {
  33037. var dx = event.touches[0].pageX - event.touches[1].pageX;
  33038. var dy = event.touches[0].pageY - event.touches[1].pageY;
  33039. var distance = Math.sqrt(dx * dx + dy * dy);
  33040. dollyEnd.set(0, distance);
  33041. dollyDelta.set(0, Math.pow(dollyEnd.y / dollyStart.y, scope.zoomSpeed));
  33042. dollyIn(dollyDelta.y);
  33043. dollyStart.copy(dollyEnd);
  33044. }
  33045. function handleTouchMoveDollyPan(event) {
  33046. if (scope.enableZoom) handleTouchMoveDolly(event);
  33047. if (scope.enablePan) handleTouchMovePan(event);
  33048. }
  33049. function handleTouchMoveDollyRotate(event) {
  33050. if (scope.enableZoom) handleTouchMoveDolly(event);
  33051. if (scope.enableRotate) handleTouchMoveRotate(event);
  33052. }
  33053. function handleTouchEnd()
  33054. /*event*/
  33055. {} // no-op
  33056. //
  33057. // event handlers - FSM: listen for events and reset state
  33058. //
  33059. function onMouseDown(event) {
  33060. if (scope.enabled === false) return; // Prevent the browser from scrolling.
  33061. event.preventDefault(); // Manually set the focus since calling preventDefault above
  33062. // prevents the browser from setting it automatically.
  33063. scope.domElement.focus ? scope.domElement.focus() : window.focus();
  33064. switch (event.button) {
  33065. case 0:
  33066. switch (scope.mouseButtons.LEFT) {
  33067. case _threeModule.MOUSE.ROTATE:
  33068. if (event.ctrlKey || event.metaKey || event.shiftKey) {
  33069. if (scope.enablePan === false) return;
  33070. handleMouseDownPan(event);
  33071. state = STATE.PAN;
  33072. } else {
  33073. if (scope.enableRotate === false) return;
  33074. handleMouseDownRotate(event);
  33075. state = STATE.ROTATE;
  33076. }
  33077. break;
  33078. case _threeModule.MOUSE.PAN:
  33079. if (event.ctrlKey || event.metaKey || event.shiftKey) {
  33080. if (scope.enableRotate === false) return;
  33081. handleMouseDownRotate(event);
  33082. state = STATE.ROTATE;
  33083. } else {
  33084. if (scope.enablePan === false) return;
  33085. handleMouseDownPan(event);
  33086. state = STATE.PAN;
  33087. }
  33088. break;
  33089. default:
  33090. state = STATE.NONE;
  33091. }
  33092. break;
  33093. case 1:
  33094. switch (scope.mouseButtons.MIDDLE) {
  33095. case _threeModule.MOUSE.DOLLY:
  33096. if (scope.enableZoom === false) return;
  33097. handleMouseDownDolly(event);
  33098. state = STATE.DOLLY;
  33099. break;
  33100. default:
  33101. state = STATE.NONE;
  33102. }
  33103. break;
  33104. case 2:
  33105. switch (scope.mouseButtons.RIGHT) {
  33106. case _threeModule.MOUSE.ROTATE:
  33107. if (scope.enableRotate === false) return;
  33108. handleMouseDownRotate(event);
  33109. state = STATE.ROTATE;
  33110. break;
  33111. case _threeModule.MOUSE.PAN:
  33112. if (scope.enablePan === false) return;
  33113. handleMouseDownPan(event);
  33114. state = STATE.PAN;
  33115. break;
  33116. default:
  33117. state = STATE.NONE;
  33118. }
  33119. break;
  33120. }
  33121. if (state !== STATE.NONE) {
  33122. document.addEventListener('mousemove', onMouseMove, false);
  33123. document.addEventListener('mouseup', onMouseUp, false);
  33124. scope.dispatchEvent(startEvent);
  33125. }
  33126. }
  33127. function onMouseMove(event) {
  33128. if (scope.enabled === false) return;
  33129. event.preventDefault();
  33130. switch (state) {
  33131. case STATE.ROTATE:
  33132. if (scope.enableRotate === false) return;
  33133. handleMouseMoveRotate(event);
  33134. break;
  33135. case STATE.DOLLY:
  33136. if (scope.enableZoom === false) return;
  33137. handleMouseMoveDolly(event);
  33138. break;
  33139. case STATE.PAN:
  33140. if (scope.enablePan === false) return;
  33141. handleMouseMovePan(event);
  33142. break;
  33143. }
  33144. }
  33145. function onMouseUp(event) {
  33146. if (scope.enabled === false) return;
  33147. handleMouseUp(event);
  33148. document.removeEventListener('mousemove', onMouseMove, false);
  33149. document.removeEventListener('mouseup', onMouseUp, false);
  33150. scope.dispatchEvent(endEvent);
  33151. state = STATE.NONE;
  33152. }
  33153. function onMouseWheel(event) {
  33154. if (scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE && state !== STATE.ROTATE) return;
  33155. event.preventDefault();
  33156. event.stopPropagation();
  33157. scope.dispatchEvent(startEvent);
  33158. handleMouseWheel(event);
  33159. scope.dispatchEvent(endEvent);
  33160. }
  33161. function onKeyDown(event) {
  33162. if (scope.enabled === false || scope.enableKeys === false || scope.enablePan === false) return;
  33163. handleKeyDown(event);
  33164. }
  33165. function onTouchStart(event) {
  33166. if (scope.enabled === false) return;
  33167. event.preventDefault();
  33168. switch (event.touches.length) {
  33169. case 1:
  33170. switch (scope.touches.ONE) {
  33171. case _threeModule.TOUCH.ROTATE:
  33172. if (scope.enableRotate === false) return;
  33173. handleTouchStartRotate(event);
  33174. state = STATE.TOUCH_ROTATE;
  33175. break;
  33176. case _threeModule.TOUCH.PAN:
  33177. if (scope.enablePan === false) return;
  33178. handleTouchStartPan(event);
  33179. state = STATE.TOUCH_PAN;
  33180. break;
  33181. default:
  33182. state = STATE.NONE;
  33183. }
  33184. break;
  33185. case 2:
  33186. switch (scope.touches.TWO) {
  33187. case _threeModule.TOUCH.DOLLY_PAN:
  33188. if (scope.enableZoom === false && scope.enablePan === false) return;
  33189. handleTouchStartDollyPan(event);
  33190. state = STATE.TOUCH_DOLLY_PAN;
  33191. break;
  33192. case _threeModule.TOUCH.DOLLY_ROTATE:
  33193. if (scope.enableZoom === false && scope.enableRotate === false) return;
  33194. handleTouchStartDollyRotate(event);
  33195. state = STATE.TOUCH_DOLLY_ROTATE;
  33196. break;
  33197. default:
  33198. state = STATE.NONE;
  33199. }
  33200. break;
  33201. default:
  33202. state = STATE.NONE;
  33203. }
  33204. if (state !== STATE.NONE) {
  33205. scope.dispatchEvent(startEvent);
  33206. }
  33207. }
  33208. function onTouchMove(event) {
  33209. if (scope.enabled === false) return;
  33210. event.preventDefault();
  33211. event.stopPropagation();
  33212. switch (state) {
  33213. case STATE.TOUCH_ROTATE:
  33214. if (scope.enableRotate === false) return;
  33215. handleTouchMoveRotate(event);
  33216. scope.update();
  33217. break;
  33218. case STATE.TOUCH_PAN:
  33219. if (scope.enablePan === false) return;
  33220. handleTouchMovePan(event);
  33221. scope.update();
  33222. break;
  33223. case STATE.TOUCH_DOLLY_PAN:
  33224. if (scope.enableZoom === false && scope.enablePan === false) return;
  33225. handleTouchMoveDollyPan(event);
  33226. scope.update();
  33227. break;
  33228. case STATE.TOUCH_DOLLY_ROTATE:
  33229. if (scope.enableZoom === false && scope.enableRotate === false) return;
  33230. handleTouchMoveDollyRotate(event);
  33231. scope.update();
  33232. break;
  33233. default:
  33234. state = STATE.NONE;
  33235. }
  33236. }
  33237. function onTouchEnd(event) {
  33238. if (scope.enabled === false) return;
  33239. handleTouchEnd(event);
  33240. scope.dispatchEvent(endEvent);
  33241. state = STATE.NONE;
  33242. }
  33243. function onContextMenu(event) {
  33244. if (scope.enabled === false) return;
  33245. event.preventDefault();
  33246. } //
  33247. scope.domElement.addEventListener('contextmenu', onContextMenu, false);
  33248. scope.domElement.addEventListener('mousedown', onMouseDown, false);
  33249. scope.domElement.addEventListener('wheel', onMouseWheel, false);
  33250. scope.domElement.addEventListener('touchstart', onTouchStart, false);
  33251. scope.domElement.addEventListener('touchend', onTouchEnd, false);
  33252. scope.domElement.addEventListener('touchmove', onTouchMove, false);
  33253. window.addEventListener('keydown', onKeyDown, false); // force an update at start
  33254. this.update();
  33255. };
  33256. exports.OrbitControls = OrbitControls;
  33257. OrbitControls.prototype = Object.create(_threeModule.EventDispatcher.prototype);
  33258. OrbitControls.prototype.constructor = OrbitControls; // This set of controls performs orbiting, dollying (zooming), and panning.
  33259. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  33260. // This is very similar to OrbitControls, another set of touch behavior
  33261. //
  33262. // Orbit - right mouse, or left mouse + ctrl/meta/shiftKey / touch: two-finger rotate
  33263. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  33264. // Pan - left mouse, or arrow keys / touch: one-finger move
  33265. var MapControls = function (object, domElement) {
  33266. OrbitControls.call(this, object, domElement);
  33267. this.mouseButtons.LEFT = _threeModule.MOUSE.PAN;
  33268. this.mouseButtons.RIGHT = _threeModule.MOUSE.ROTATE;
  33269. this.touches.ONE = _threeModule.TOUCH.PAN;
  33270. this.touches.TWO = _threeModule.TOUCH.DOLLY_ROTATE;
  33271. };
  33272. exports.MapControls = MapControls;
  33273. MapControls.prototype = Object.create(_threeModule.EventDispatcher.prototype);
  33274. MapControls.prototype.constructor = MapControls;
  33275. },{"../../../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) {
  33276. "use strict";
  33277. Object.defineProperty(exports, "__esModule", {
  33278. value: true
  33279. });
  33280. exports.default = exports.GUI = exports.gui = exports.dom = exports.controllers = exports.color = void 0;
  33281. /**
  33282. * dat-gui JavaScript Controller Library
  33283. * http://code.google.com/p/dat-gui
  33284. *
  33285. * Copyright 2011 Data Arts Team, Google Creative Lab
  33286. *
  33287. * Licensed under the Apache License, Version 2.0 (the "License");
  33288. * you may not use this file except in compliance with the License.
  33289. * You may obtain a copy of the License at
  33290. *
  33291. * http://www.apache.org/licenses/LICENSE-2.0
  33292. */
  33293. function ___$insertStyle(css) {
  33294. if (!css) {
  33295. return;
  33296. }
  33297. if (typeof window === 'undefined') {
  33298. return;
  33299. }
  33300. var style = document.createElement('style');
  33301. style.setAttribute('type', 'text/css');
  33302. style.innerHTML = css;
  33303. document.head.appendChild(style);
  33304. return css;
  33305. }
  33306. function colorToString(color, forceCSSHex) {
  33307. var colorFormat = color.__state.conversionName.toString();
  33308. var r = Math.round(color.r);
  33309. var g = Math.round(color.g);
  33310. var b = Math.round(color.b);
  33311. var a = color.a;
  33312. var h = Math.round(color.h);
  33313. var s = color.s.toFixed(1);
  33314. var v = color.v.toFixed(1);
  33315. if (forceCSSHex || colorFormat === 'THREE_CHAR_HEX' || colorFormat === 'SIX_CHAR_HEX') {
  33316. var str = color.hex.toString(16);
  33317. while (str.length < 6) {
  33318. str = '0' + str;
  33319. }
  33320. return '#' + str;
  33321. } else if (colorFormat === 'CSS_RGB') {
  33322. return 'rgb(' + r + ',' + g + ',' + b + ')';
  33323. } else if (colorFormat === 'CSS_RGBA') {
  33324. return 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
  33325. } else if (colorFormat === 'HEX') {
  33326. return '0x' + color.hex.toString(16);
  33327. } else if (colorFormat === 'RGB_ARRAY') {
  33328. return '[' + r + ',' + g + ',' + b + ']';
  33329. } else if (colorFormat === 'RGBA_ARRAY') {
  33330. return '[' + r + ',' + g + ',' + b + ',' + a + ']';
  33331. } else if (colorFormat === 'RGB_OBJ') {
  33332. return '{r:' + r + ',g:' + g + ',b:' + b + '}';
  33333. } else if (colorFormat === 'RGBA_OBJ') {
  33334. return '{r:' + r + ',g:' + g + ',b:' + b + ',a:' + a + '}';
  33335. } else if (colorFormat === 'HSV_OBJ') {
  33336. return '{h:' + h + ',s:' + s + ',v:' + v + '}';
  33337. } else if (colorFormat === 'HSVA_OBJ') {
  33338. return '{h:' + h + ',s:' + s + ',v:' + v + ',a:' + a + '}';
  33339. }
  33340. return 'unknown format';
  33341. }
  33342. var ARR_EACH = Array.prototype.forEach;
  33343. var ARR_SLICE = Array.prototype.slice;
  33344. var Common = {
  33345. BREAK: {},
  33346. extend: function extend(target) {
  33347. this.each(ARR_SLICE.call(arguments, 1), function (obj) {
  33348. var keys = this.isObject(obj) ? Object.keys(obj) : [];
  33349. keys.forEach(function (key) {
  33350. if (!this.isUndefined(obj[key])) {
  33351. target[key] = obj[key];
  33352. }
  33353. }.bind(this));
  33354. }, this);
  33355. return target;
  33356. },
  33357. defaults: function defaults(target) {
  33358. this.each(ARR_SLICE.call(arguments, 1), function (obj) {
  33359. var keys = this.isObject(obj) ? Object.keys(obj) : [];
  33360. keys.forEach(function (key) {
  33361. if (this.isUndefined(target[key])) {
  33362. target[key] = obj[key];
  33363. }
  33364. }.bind(this));
  33365. }, this);
  33366. return target;
  33367. },
  33368. compose: function compose() {
  33369. var toCall = ARR_SLICE.call(arguments);
  33370. return function () {
  33371. var args = ARR_SLICE.call(arguments);
  33372. for (var i = toCall.length - 1; i >= 0; i--) {
  33373. args = [toCall[i].apply(this, args)];
  33374. }
  33375. return args[0];
  33376. };
  33377. },
  33378. each: function each(obj, itr, scope) {
  33379. if (!obj) {
  33380. return;
  33381. }
  33382. if (ARR_EACH && obj.forEach && obj.forEach === ARR_EACH) {
  33383. obj.forEach(itr, scope);
  33384. } else if (obj.length === obj.length + 0) {
  33385. var key = void 0;
  33386. var l = void 0;
  33387. for (key = 0, l = obj.length; key < l; key++) {
  33388. if (key in obj && itr.call(scope, obj[key], key) === this.BREAK) {
  33389. return;
  33390. }
  33391. }
  33392. } else {
  33393. for (var _key in obj) {
  33394. if (itr.call(scope, obj[_key], _key) === this.BREAK) {
  33395. return;
  33396. }
  33397. }
  33398. }
  33399. },
  33400. defer: function defer(fnc) {
  33401. setTimeout(fnc, 0);
  33402. },
  33403. debounce: function debounce(func, threshold, callImmediately) {
  33404. var timeout = void 0;
  33405. return function () {
  33406. var obj = this;
  33407. var args = arguments;
  33408. function delayed() {
  33409. timeout = null;
  33410. if (!callImmediately) func.apply(obj, args);
  33411. }
  33412. var callNow = callImmediately || !timeout;
  33413. clearTimeout(timeout);
  33414. timeout = setTimeout(delayed, threshold);
  33415. if (callNow) {
  33416. func.apply(obj, args);
  33417. }
  33418. };
  33419. },
  33420. toArray: function toArray(obj) {
  33421. if (obj.toArray) return obj.toArray();
  33422. return ARR_SLICE.call(obj);
  33423. },
  33424. isUndefined: function isUndefined(obj) {
  33425. return obj === undefined;
  33426. },
  33427. isNull: function isNull(obj) {
  33428. return obj === null;
  33429. },
  33430. isNaN: function (_isNaN) {
  33431. function isNaN() {
  33432. return _isNaN.apply(this, arguments);
  33433. }
  33434. isNaN.toString = function () {
  33435. return _isNaN.toString();
  33436. };
  33437. return isNaN;
  33438. }(function (obj) {
  33439. return isNaN(obj);
  33440. }),
  33441. isArray: Array.isArray || function (obj) {
  33442. return obj.constructor === Array;
  33443. },
  33444. isObject: function isObject(obj) {
  33445. return obj === Object(obj);
  33446. },
  33447. isNumber: function isNumber(obj) {
  33448. return obj === obj + 0;
  33449. },
  33450. isString: function isString(obj) {
  33451. return obj === obj + '';
  33452. },
  33453. isBoolean: function isBoolean(obj) {
  33454. return obj === false || obj === true;
  33455. },
  33456. isFunction: function isFunction(obj) {
  33457. return Object.prototype.toString.call(obj) === '[object Function]';
  33458. }
  33459. };
  33460. var INTERPRETATIONS = [{
  33461. litmus: Common.isString,
  33462. conversions: {
  33463. THREE_CHAR_HEX: {
  33464. read: function read(original) {
  33465. var test = original.match(/^#([A-F0-9])([A-F0-9])([A-F0-9])$/i);
  33466. if (test === null) {
  33467. return false;
  33468. }
  33469. return {
  33470. space: 'HEX',
  33471. hex: parseInt('0x' + test[1].toString() + test[1].toString() + test[2].toString() + test[2].toString() + test[3].toString() + test[3].toString(), 0)
  33472. };
  33473. },
  33474. write: colorToString
  33475. },
  33476. SIX_CHAR_HEX: {
  33477. read: function read(original) {
  33478. var test = original.match(/^#([A-F0-9]{6})$/i);
  33479. if (test === null) {
  33480. return false;
  33481. }
  33482. return {
  33483. space: 'HEX',
  33484. hex: parseInt('0x' + test[1].toString(), 0)
  33485. };
  33486. },
  33487. write: colorToString
  33488. },
  33489. CSS_RGB: {
  33490. read: function read(original) {
  33491. var test = original.match(/^rgb\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);
  33492. if (test === null) {
  33493. return false;
  33494. }
  33495. return {
  33496. space: 'RGB',
  33497. r: parseFloat(test[1]),
  33498. g: parseFloat(test[2]),
  33499. b: parseFloat(test[3])
  33500. };
  33501. },
  33502. write: colorToString
  33503. },
  33504. CSS_RGBA: {
  33505. read: function read(original) {
  33506. var test = original.match(/^rgba\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);
  33507. if (test === null) {
  33508. return false;
  33509. }
  33510. return {
  33511. space: 'RGB',
  33512. r: parseFloat(test[1]),
  33513. g: parseFloat(test[2]),
  33514. b: parseFloat(test[3]),
  33515. a: parseFloat(test[4])
  33516. };
  33517. },
  33518. write: colorToString
  33519. }
  33520. }
  33521. }, {
  33522. litmus: Common.isNumber,
  33523. conversions: {
  33524. HEX: {
  33525. read: function read(original) {
  33526. return {
  33527. space: 'HEX',
  33528. hex: original,
  33529. conversionName: 'HEX'
  33530. };
  33531. },
  33532. write: function write(color) {
  33533. return color.hex;
  33534. }
  33535. }
  33536. }
  33537. }, {
  33538. litmus: Common.isArray,
  33539. conversions: {
  33540. RGB_ARRAY: {
  33541. read: function read(original) {
  33542. if (original.length !== 3) {
  33543. return false;
  33544. }
  33545. return {
  33546. space: 'RGB',
  33547. r: original[0],
  33548. g: original[1],
  33549. b: original[2]
  33550. };
  33551. },
  33552. write: function write(color) {
  33553. return [color.r, color.g, color.b];
  33554. }
  33555. },
  33556. RGBA_ARRAY: {
  33557. read: function read(original) {
  33558. if (original.length !== 4) return false;
  33559. return {
  33560. space: 'RGB',
  33561. r: original[0],
  33562. g: original[1],
  33563. b: original[2],
  33564. a: original[3]
  33565. };
  33566. },
  33567. write: function write(color) {
  33568. return [color.r, color.g, color.b, color.a];
  33569. }
  33570. }
  33571. }
  33572. }, {
  33573. litmus: Common.isObject,
  33574. conversions: {
  33575. RGBA_OBJ: {
  33576. read: function read(original) {
  33577. if (Common.isNumber(original.r) && Common.isNumber(original.g) && Common.isNumber(original.b) && Common.isNumber(original.a)) {
  33578. return {
  33579. space: 'RGB',
  33580. r: original.r,
  33581. g: original.g,
  33582. b: original.b,
  33583. a: original.a
  33584. };
  33585. }
  33586. return false;
  33587. },
  33588. write: function write(color) {
  33589. return {
  33590. r: color.r,
  33591. g: color.g,
  33592. b: color.b,
  33593. a: color.a
  33594. };
  33595. }
  33596. },
  33597. RGB_OBJ: {
  33598. read: function read(original) {
  33599. if (Common.isNumber(original.r) && Common.isNumber(original.g) && Common.isNumber(original.b)) {
  33600. return {
  33601. space: 'RGB',
  33602. r: original.r,
  33603. g: original.g,
  33604. b: original.b
  33605. };
  33606. }
  33607. return false;
  33608. },
  33609. write: function write(color) {
  33610. return {
  33611. r: color.r,
  33612. g: color.g,
  33613. b: color.b
  33614. };
  33615. }
  33616. },
  33617. HSVA_OBJ: {
  33618. read: function read(original) {
  33619. if (Common.isNumber(original.h) && Common.isNumber(original.s) && Common.isNumber(original.v) && Common.isNumber(original.a)) {
  33620. return {
  33621. space: 'HSV',
  33622. h: original.h,
  33623. s: original.s,
  33624. v: original.v,
  33625. a: original.a
  33626. };
  33627. }
  33628. return false;
  33629. },
  33630. write: function write(color) {
  33631. return {
  33632. h: color.h,
  33633. s: color.s,
  33634. v: color.v,
  33635. a: color.a
  33636. };
  33637. }
  33638. },
  33639. HSV_OBJ: {
  33640. read: function read(original) {
  33641. if (Common.isNumber(original.h) && Common.isNumber(original.s) && Common.isNumber(original.v)) {
  33642. return {
  33643. space: 'HSV',
  33644. h: original.h,
  33645. s: original.s,
  33646. v: original.v
  33647. };
  33648. }
  33649. return false;
  33650. },
  33651. write: function write(color) {
  33652. return {
  33653. h: color.h,
  33654. s: color.s,
  33655. v: color.v
  33656. };
  33657. }
  33658. }
  33659. }
  33660. }];
  33661. var result = void 0;
  33662. var toReturn = void 0;
  33663. var interpret = function interpret() {
  33664. toReturn = false;
  33665. var original = arguments.length > 1 ? Common.toArray(arguments) : arguments[0];
  33666. Common.each(INTERPRETATIONS, function (family) {
  33667. if (family.litmus(original)) {
  33668. Common.each(family.conversions, function (conversion, conversionName) {
  33669. result = conversion.read(original);
  33670. if (toReturn === false && result !== false) {
  33671. toReturn = result;
  33672. result.conversionName = conversionName;
  33673. result.conversion = conversion;
  33674. return Common.BREAK;
  33675. }
  33676. });
  33677. return Common.BREAK;
  33678. }
  33679. });
  33680. return toReturn;
  33681. };
  33682. var tmpComponent = void 0;
  33683. var ColorMath = {
  33684. hsv_to_rgb: function hsv_to_rgb(h, s, v) {
  33685. var hi = Math.floor(h / 60) % 6;
  33686. var f = h / 60 - Math.floor(h / 60);
  33687. var p = v * (1.0 - s);
  33688. var q = v * (1.0 - f * s);
  33689. var t = v * (1.0 - (1.0 - f) * s);
  33690. var c = [[v, t, p], [q, v, p], [p, v, t], [p, q, v], [t, p, v], [v, p, q]][hi];
  33691. return {
  33692. r: c[0] * 255,
  33693. g: c[1] * 255,
  33694. b: c[2] * 255
  33695. };
  33696. },
  33697. rgb_to_hsv: function rgb_to_hsv(r, g, b) {
  33698. var min = Math.min(r, g, b);
  33699. var max = Math.max(r, g, b);
  33700. var delta = max - min;
  33701. var h = void 0;
  33702. var s = void 0;
  33703. if (max !== 0) {
  33704. s = delta / max;
  33705. } else {
  33706. return {
  33707. h: NaN,
  33708. s: 0,
  33709. v: 0
  33710. };
  33711. }
  33712. if (r === max) {
  33713. h = (g - b) / delta;
  33714. } else if (g === max) {
  33715. h = 2 + (b - r) / delta;
  33716. } else {
  33717. h = 4 + (r - g) / delta;
  33718. }
  33719. h /= 6;
  33720. if (h < 0) {
  33721. h += 1;
  33722. }
  33723. return {
  33724. h: h * 360,
  33725. s: s,
  33726. v: max / 255
  33727. };
  33728. },
  33729. rgb_to_hex: function rgb_to_hex(r, g, b) {
  33730. var hex = this.hex_with_component(0, 2, r);
  33731. hex = this.hex_with_component(hex, 1, g);
  33732. hex = this.hex_with_component(hex, 0, b);
  33733. return hex;
  33734. },
  33735. component_from_hex: function component_from_hex(hex, componentIndex) {
  33736. return hex >> componentIndex * 8 & 0xFF;
  33737. },
  33738. hex_with_component: function hex_with_component(hex, componentIndex, value) {
  33739. return value << (tmpComponent = componentIndex * 8) | hex & ~(0xFF << tmpComponent);
  33740. }
  33741. };
  33742. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  33743. return typeof obj;
  33744. } : function (obj) {
  33745. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  33746. };
  33747. var classCallCheck = function (instance, Constructor) {
  33748. if (!(instance instanceof Constructor)) {
  33749. throw new TypeError("Cannot call a class as a function");
  33750. }
  33751. };
  33752. var createClass = function () {
  33753. function defineProperties(target, props) {
  33754. for (var i = 0; i < props.length; i++) {
  33755. var descriptor = props[i];
  33756. descriptor.enumerable = descriptor.enumerable || false;
  33757. descriptor.configurable = true;
  33758. if ("value" in descriptor) descriptor.writable = true;
  33759. Object.defineProperty(target, descriptor.key, descriptor);
  33760. }
  33761. }
  33762. return function (Constructor, protoProps, staticProps) {
  33763. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  33764. if (staticProps) defineProperties(Constructor, staticProps);
  33765. return Constructor;
  33766. };
  33767. }();
  33768. var get = function get(object, property, receiver) {
  33769. if (object === null) object = Function.prototype;
  33770. var desc = Object.getOwnPropertyDescriptor(object, property);
  33771. if (desc === undefined) {
  33772. var parent = Object.getPrototypeOf(object);
  33773. if (parent === null) {
  33774. return undefined;
  33775. } else {
  33776. return get(parent, property, receiver);
  33777. }
  33778. } else if ("value" in desc) {
  33779. return desc.value;
  33780. } else {
  33781. var getter = desc.get;
  33782. if (getter === undefined) {
  33783. return undefined;
  33784. }
  33785. return getter.call(receiver);
  33786. }
  33787. };
  33788. var inherits = function (subClass, superClass) {
  33789. if (typeof superClass !== "function" && superClass !== null) {
  33790. throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
  33791. }
  33792. subClass.prototype = Object.create(superClass && superClass.prototype, {
  33793. constructor: {
  33794. value: subClass,
  33795. enumerable: false,
  33796. writable: true,
  33797. configurable: true
  33798. }
  33799. });
  33800. if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
  33801. };
  33802. var possibleConstructorReturn = function (self, call) {
  33803. if (!self) {
  33804. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  33805. }
  33806. return call && (typeof call === "object" || typeof call === "function") ? call : self;
  33807. };
  33808. var Color = function () {
  33809. function Color() {
  33810. classCallCheck(this, Color);
  33811. this.__state = interpret.apply(this, arguments);
  33812. if (this.__state === false) {
  33813. throw new Error('Failed to interpret color arguments');
  33814. }
  33815. this.__state.a = this.__state.a || 1;
  33816. }
  33817. createClass(Color, [{
  33818. key: 'toString',
  33819. value: function toString() {
  33820. return colorToString(this);
  33821. }
  33822. }, {
  33823. key: 'toHexString',
  33824. value: function toHexString() {
  33825. return colorToString(this, true);
  33826. }
  33827. }, {
  33828. key: 'toOriginal',
  33829. value: function toOriginal() {
  33830. return this.__state.conversion.write(this);
  33831. }
  33832. }]);
  33833. return Color;
  33834. }();
  33835. function defineRGBComponent(target, component, componentHexIndex) {
  33836. Object.defineProperty(target, component, {
  33837. get: function get$$1() {
  33838. if (this.__state.space === 'RGB') {
  33839. return this.__state[component];
  33840. }
  33841. Color.recalculateRGB(this, component, componentHexIndex);
  33842. return this.__state[component];
  33843. },
  33844. set: function set$$1(v) {
  33845. if (this.__state.space !== 'RGB') {
  33846. Color.recalculateRGB(this, component, componentHexIndex);
  33847. this.__state.space = 'RGB';
  33848. }
  33849. this.__state[component] = v;
  33850. }
  33851. });
  33852. }
  33853. function defineHSVComponent(target, component) {
  33854. Object.defineProperty(target, component, {
  33855. get: function get$$1() {
  33856. if (this.__state.space === 'HSV') {
  33857. return this.__state[component];
  33858. }
  33859. Color.recalculateHSV(this);
  33860. return this.__state[component];
  33861. },
  33862. set: function set$$1(v) {
  33863. if (this.__state.space !== 'HSV') {
  33864. Color.recalculateHSV(this);
  33865. this.__state.space = 'HSV';
  33866. }
  33867. this.__state[component] = v;
  33868. }
  33869. });
  33870. }
  33871. Color.recalculateRGB = function (color, component, componentHexIndex) {
  33872. if (color.__state.space === 'HEX') {
  33873. color.__state[component] = ColorMath.component_from_hex(color.__state.hex, componentHexIndex);
  33874. } else if (color.__state.space === 'HSV') {
  33875. Common.extend(color.__state, ColorMath.hsv_to_rgb(color.__state.h, color.__state.s, color.__state.v));
  33876. } else {
  33877. throw new Error('Corrupted color state');
  33878. }
  33879. };
  33880. Color.recalculateHSV = function (color) {
  33881. var result = ColorMath.rgb_to_hsv(color.r, color.g, color.b);
  33882. Common.extend(color.__state, {
  33883. s: result.s,
  33884. v: result.v
  33885. });
  33886. if (!Common.isNaN(result.h)) {
  33887. color.__state.h = result.h;
  33888. } else if (Common.isUndefined(color.__state.h)) {
  33889. color.__state.h = 0;
  33890. }
  33891. };
  33892. Color.COMPONENTS = ['r', 'g', 'b', 'h', 's', 'v', 'hex', 'a'];
  33893. defineRGBComponent(Color.prototype, 'r', 2);
  33894. defineRGBComponent(Color.prototype, 'g', 1);
  33895. defineRGBComponent(Color.prototype, 'b', 0);
  33896. defineHSVComponent(Color.prototype, 'h');
  33897. defineHSVComponent(Color.prototype, 's');
  33898. defineHSVComponent(Color.prototype, 'v');
  33899. Object.defineProperty(Color.prototype, 'a', {
  33900. get: function get$$1() {
  33901. return this.__state.a;
  33902. },
  33903. set: function set$$1(v) {
  33904. this.__state.a = v;
  33905. }
  33906. });
  33907. Object.defineProperty(Color.prototype, 'hex', {
  33908. get: function get$$1() {
  33909. if (!this.__state.space !== 'HEX') {
  33910. this.__state.hex = ColorMath.rgb_to_hex(this.r, this.g, this.b);
  33911. }
  33912. return this.__state.hex;
  33913. },
  33914. set: function set$$1(v) {
  33915. this.__state.space = 'HEX';
  33916. this.__state.hex = v;
  33917. }
  33918. });
  33919. var Controller = function () {
  33920. function Controller(object, property) {
  33921. classCallCheck(this, Controller);
  33922. this.initialValue = object[property];
  33923. this.domElement = document.createElement('div');
  33924. this.object = object;
  33925. this.property = property;
  33926. this.__onChange = undefined;
  33927. this.__onFinishChange = undefined;
  33928. }
  33929. createClass(Controller, [{
  33930. key: 'onChange',
  33931. value: function onChange(fnc) {
  33932. this.__onChange = fnc;
  33933. return this;
  33934. }
  33935. }, {
  33936. key: 'onFinishChange',
  33937. value: function onFinishChange(fnc) {
  33938. this.__onFinishChange = fnc;
  33939. return this;
  33940. }
  33941. }, {
  33942. key: 'setValue',
  33943. value: function setValue(newValue) {
  33944. this.object[this.property] = newValue;
  33945. if (this.__onChange) {
  33946. this.__onChange.call(this, newValue);
  33947. }
  33948. this.updateDisplay();
  33949. return this;
  33950. }
  33951. }, {
  33952. key: 'getValue',
  33953. value: function getValue() {
  33954. return this.object[this.property];
  33955. }
  33956. }, {
  33957. key: 'updateDisplay',
  33958. value: function updateDisplay() {
  33959. return this;
  33960. }
  33961. }, {
  33962. key: 'isModified',
  33963. value: function isModified() {
  33964. return this.initialValue !== this.getValue();
  33965. }
  33966. }]);
  33967. return Controller;
  33968. }();
  33969. var EVENT_MAP = {
  33970. HTMLEvents: ['change'],
  33971. MouseEvents: ['click', 'mousemove', 'mousedown', 'mouseup', 'mouseover'],
  33972. KeyboardEvents: ['keydown']
  33973. };
  33974. var EVENT_MAP_INV = {};
  33975. Common.each(EVENT_MAP, function (v, k) {
  33976. Common.each(v, function (e) {
  33977. EVENT_MAP_INV[e] = k;
  33978. });
  33979. });
  33980. var CSS_VALUE_PIXELS = /(\d+(\.\d+)?)px/;
  33981. function cssValueToPixels(val) {
  33982. if (val === '0' || Common.isUndefined(val)) {
  33983. return 0;
  33984. }
  33985. var match = val.match(CSS_VALUE_PIXELS);
  33986. if (!Common.isNull(match)) {
  33987. return parseFloat(match[1]);
  33988. }
  33989. return 0;
  33990. }
  33991. var dom = {
  33992. makeSelectable: function makeSelectable(elem, selectable) {
  33993. if (elem === undefined || elem.style === undefined) return;
  33994. elem.onselectstart = selectable ? function () {
  33995. return false;
  33996. } : function () {};
  33997. elem.style.MozUserSelect = selectable ? 'auto' : 'none';
  33998. elem.style.KhtmlUserSelect = selectable ? 'auto' : 'none';
  33999. elem.unselectable = selectable ? 'on' : 'off';
  34000. },
  34001. makeFullscreen: function makeFullscreen(elem, hor, vert) {
  34002. var vertical = vert;
  34003. var horizontal = hor;
  34004. if (Common.isUndefined(horizontal)) {
  34005. horizontal = true;
  34006. }
  34007. if (Common.isUndefined(vertical)) {
  34008. vertical = true;
  34009. }
  34010. elem.style.position = 'absolute';
  34011. if (horizontal) {
  34012. elem.style.left = 0;
  34013. elem.style.right = 0;
  34014. }
  34015. if (vertical) {
  34016. elem.style.top = 0;
  34017. elem.style.bottom = 0;
  34018. }
  34019. },
  34020. fakeEvent: function fakeEvent(elem, eventType, pars, aux) {
  34021. var params = pars || {};
  34022. var className = EVENT_MAP_INV[eventType];
  34023. if (!className) {
  34024. throw new Error('Event type ' + eventType + ' not supported.');
  34025. }
  34026. var evt = document.createEvent(className);
  34027. switch (className) {
  34028. case 'MouseEvents':
  34029. {
  34030. var clientX = params.x || params.clientX || 0;
  34031. var clientY = params.y || params.clientY || 0;
  34032. evt.initMouseEvent(eventType, params.bubbles || false, params.cancelable || true, window, params.clickCount || 1, 0, 0, clientX, clientY, false, false, false, false, 0, null);
  34033. break;
  34034. }
  34035. case 'KeyboardEvents':
  34036. {
  34037. var init = evt.initKeyboardEvent || evt.initKeyEvent;
  34038. Common.defaults(params, {
  34039. cancelable: true,
  34040. ctrlKey: false,
  34041. altKey: false,
  34042. shiftKey: false,
  34043. metaKey: false,
  34044. keyCode: undefined,
  34045. charCode: undefined
  34046. });
  34047. init(eventType, params.bubbles || false, params.cancelable, window, params.ctrlKey, params.altKey, params.shiftKey, params.metaKey, params.keyCode, params.charCode);
  34048. break;
  34049. }
  34050. default:
  34051. {
  34052. evt.initEvent(eventType, params.bubbles || false, params.cancelable || true);
  34053. break;
  34054. }
  34055. }
  34056. Common.defaults(evt, aux);
  34057. elem.dispatchEvent(evt);
  34058. },
  34059. bind: function bind(elem, event, func, newBool) {
  34060. var bool = newBool || false;
  34061. if (elem.addEventListener) {
  34062. elem.addEventListener(event, func, bool);
  34063. } else if (elem.attachEvent) {
  34064. elem.attachEvent('on' + event, func);
  34065. }
  34066. return dom;
  34067. },
  34068. unbind: function unbind(elem, event, func, newBool) {
  34069. var bool = newBool || false;
  34070. if (elem.removeEventListener) {
  34071. elem.removeEventListener(event, func, bool);
  34072. } else if (elem.detachEvent) {
  34073. elem.detachEvent('on' + event, func);
  34074. }
  34075. return dom;
  34076. },
  34077. addClass: function addClass(elem, className) {
  34078. if (elem.className === undefined) {
  34079. elem.className = className;
  34080. } else if (elem.className !== className) {
  34081. var classes = elem.className.split(/ +/);
  34082. if (classes.indexOf(className) === -1) {
  34083. classes.push(className);
  34084. elem.className = classes.join(' ').replace(/^\s+/, '').replace(/\s+$/, '');
  34085. }
  34086. }
  34087. return dom;
  34088. },
  34089. removeClass: function removeClass(elem, className) {
  34090. if (className) {
  34091. if (elem.className === className) {
  34092. elem.removeAttribute('class');
  34093. } else {
  34094. var classes = elem.className.split(/ +/);
  34095. var index = classes.indexOf(className);
  34096. if (index !== -1) {
  34097. classes.splice(index, 1);
  34098. elem.className = classes.join(' ');
  34099. }
  34100. }
  34101. } else {
  34102. elem.className = undefined;
  34103. }
  34104. return dom;
  34105. },
  34106. hasClass: function hasClass(elem, className) {
  34107. return new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)').test(elem.className) || false;
  34108. },
  34109. getWidth: function getWidth(elem) {
  34110. var style = getComputedStyle(elem);
  34111. return cssValueToPixels(style['border-left-width']) + cssValueToPixels(style['border-right-width']) + cssValueToPixels(style['padding-left']) + cssValueToPixels(style['padding-right']) + cssValueToPixels(style.width);
  34112. },
  34113. getHeight: function getHeight(elem) {
  34114. var style = getComputedStyle(elem);
  34115. return cssValueToPixels(style['border-top-width']) + cssValueToPixels(style['border-bottom-width']) + cssValueToPixels(style['padding-top']) + cssValueToPixels(style['padding-bottom']) + cssValueToPixels(style.height);
  34116. },
  34117. getOffset: function getOffset(el) {
  34118. var elem = el;
  34119. var offset = {
  34120. left: 0,
  34121. top: 0
  34122. };
  34123. if (elem.offsetParent) {
  34124. do {
  34125. offset.left += elem.offsetLeft;
  34126. offset.top += elem.offsetTop;
  34127. elem = elem.offsetParent;
  34128. } while (elem);
  34129. }
  34130. return offset;
  34131. },
  34132. isActive: function isActive(elem) {
  34133. return elem === document.activeElement && (elem.type || elem.href);
  34134. }
  34135. };
  34136. var BooleanController = function (_Controller) {
  34137. inherits(BooleanController, _Controller);
  34138. function BooleanController(object, property) {
  34139. classCallCheck(this, BooleanController);
  34140. var _this2 = possibleConstructorReturn(this, (BooleanController.__proto__ || Object.getPrototypeOf(BooleanController)).call(this, object, property));
  34141. var _this = _this2;
  34142. _this2.__prev = _this2.getValue();
  34143. _this2.__checkbox = document.createElement('input');
  34144. _this2.__checkbox.setAttribute('type', 'checkbox');
  34145. function onChange() {
  34146. _this.setValue(!_this.__prev);
  34147. }
  34148. dom.bind(_this2.__checkbox, 'change', onChange, false);
  34149. _this2.domElement.appendChild(_this2.__checkbox);
  34150. _this2.updateDisplay();
  34151. return _this2;
  34152. }
  34153. createClass(BooleanController, [{
  34154. key: 'setValue',
  34155. value: function setValue(v) {
  34156. var toReturn = get(BooleanController.prototype.__proto__ || Object.getPrototypeOf(BooleanController.prototype), 'setValue', this).call(this, v);
  34157. if (this.__onFinishChange) {
  34158. this.__onFinishChange.call(this, this.getValue());
  34159. }
  34160. this.__prev = this.getValue();
  34161. return toReturn;
  34162. }
  34163. }, {
  34164. key: 'updateDisplay',
  34165. value: function updateDisplay() {
  34166. if (this.getValue() === true) {
  34167. this.__checkbox.setAttribute('checked', 'checked');
  34168. this.__checkbox.checked = true;
  34169. this.__prev = true;
  34170. } else {
  34171. this.__checkbox.checked = false;
  34172. this.__prev = false;
  34173. }
  34174. return get(BooleanController.prototype.__proto__ || Object.getPrototypeOf(BooleanController.prototype), 'updateDisplay', this).call(this);
  34175. }
  34176. }]);
  34177. return BooleanController;
  34178. }(Controller);
  34179. var OptionController = function (_Controller) {
  34180. inherits(OptionController, _Controller);
  34181. function OptionController(object, property, opts) {
  34182. classCallCheck(this, OptionController);
  34183. var _this2 = possibleConstructorReturn(this, (OptionController.__proto__ || Object.getPrototypeOf(OptionController)).call(this, object, property));
  34184. var options = opts;
  34185. var _this = _this2;
  34186. _this2.__select = document.createElement('select');
  34187. if (Common.isArray(options)) {
  34188. var map = {};
  34189. Common.each(options, function (element) {
  34190. map[element] = element;
  34191. });
  34192. options = map;
  34193. }
  34194. Common.each(options, function (value, key) {
  34195. var opt = document.createElement('option');
  34196. opt.innerHTML = key;
  34197. opt.setAttribute('value', value);
  34198. _this.__select.appendChild(opt);
  34199. });
  34200. _this2.updateDisplay();
  34201. dom.bind(_this2.__select, 'change', function () {
  34202. var desiredValue = this.options[this.selectedIndex].value;
  34203. _this.setValue(desiredValue);
  34204. });
  34205. _this2.domElement.appendChild(_this2.__select);
  34206. return _this2;
  34207. }
  34208. createClass(OptionController, [{
  34209. key: 'setValue',
  34210. value: function setValue(v) {
  34211. var toReturn = get(OptionController.prototype.__proto__ || Object.getPrototypeOf(OptionController.prototype), 'setValue', this).call(this, v);
  34212. if (this.__onFinishChange) {
  34213. this.__onFinishChange.call(this, this.getValue());
  34214. }
  34215. return toReturn;
  34216. }
  34217. }, {
  34218. key: 'updateDisplay',
  34219. value: function updateDisplay() {
  34220. if (dom.isActive(this.__select)) return this;
  34221. this.__select.value = this.getValue();
  34222. return get(OptionController.prototype.__proto__ || Object.getPrototypeOf(OptionController.prototype), 'updateDisplay', this).call(this);
  34223. }
  34224. }]);
  34225. return OptionController;
  34226. }(Controller);
  34227. var StringController = function (_Controller) {
  34228. inherits(StringController, _Controller);
  34229. function StringController(object, property) {
  34230. classCallCheck(this, StringController);
  34231. var _this2 = possibleConstructorReturn(this, (StringController.__proto__ || Object.getPrototypeOf(StringController)).call(this, object, property));
  34232. var _this = _this2;
  34233. function onChange() {
  34234. _this.setValue(_this.__input.value);
  34235. }
  34236. function onBlur() {
  34237. if (_this.__onFinishChange) {
  34238. _this.__onFinishChange.call(_this, _this.getValue());
  34239. }
  34240. }
  34241. _this2.__input = document.createElement('input');
  34242. _this2.__input.setAttribute('type', 'text');
  34243. dom.bind(_this2.__input, 'keyup', onChange);
  34244. dom.bind(_this2.__input, 'change', onChange);
  34245. dom.bind(_this2.__input, 'blur', onBlur);
  34246. dom.bind(_this2.__input, 'keydown', function (e) {
  34247. if (e.keyCode === 13) {
  34248. this.blur();
  34249. }
  34250. });
  34251. _this2.updateDisplay();
  34252. _this2.domElement.appendChild(_this2.__input);
  34253. return _this2;
  34254. }
  34255. createClass(StringController, [{
  34256. key: 'updateDisplay',
  34257. value: function updateDisplay() {
  34258. if (!dom.isActive(this.__input)) {
  34259. this.__input.value = this.getValue();
  34260. }
  34261. return get(StringController.prototype.__proto__ || Object.getPrototypeOf(StringController.prototype), 'updateDisplay', this).call(this);
  34262. }
  34263. }]);
  34264. return StringController;
  34265. }(Controller);
  34266. function numDecimals(x) {
  34267. var _x = x.toString();
  34268. if (_x.indexOf('.') > -1) {
  34269. return _x.length - _x.indexOf('.') - 1;
  34270. }
  34271. return 0;
  34272. }
  34273. var NumberController = function (_Controller) {
  34274. inherits(NumberController, _Controller);
  34275. function NumberController(object, property, params) {
  34276. classCallCheck(this, NumberController);
  34277. var _this = possibleConstructorReturn(this, (NumberController.__proto__ || Object.getPrototypeOf(NumberController)).call(this, object, property));
  34278. var _params = params || {};
  34279. _this.__min = _params.min;
  34280. _this.__max = _params.max;
  34281. _this.__step = _params.step;
  34282. if (Common.isUndefined(_this.__step)) {
  34283. if (_this.initialValue === 0) {
  34284. _this.__impliedStep = 1;
  34285. } else {
  34286. _this.__impliedStep = Math.pow(10, Math.floor(Math.log(Math.abs(_this.initialValue)) / Math.LN10)) / 10;
  34287. }
  34288. } else {
  34289. _this.__impliedStep = _this.__step;
  34290. }
  34291. _this.__precision = numDecimals(_this.__impliedStep);
  34292. return _this;
  34293. }
  34294. createClass(NumberController, [{
  34295. key: 'setValue',
  34296. value: function setValue(v) {
  34297. var _v = v;
  34298. if (this.__min !== undefined && _v < this.__min) {
  34299. _v = this.__min;
  34300. } else if (this.__max !== undefined && _v > this.__max) {
  34301. _v = this.__max;
  34302. }
  34303. if (this.__step !== undefined && _v % this.__step !== 0) {
  34304. _v = Math.round(_v / this.__step) * this.__step;
  34305. }
  34306. return get(NumberController.prototype.__proto__ || Object.getPrototypeOf(NumberController.prototype), 'setValue', this).call(this, _v);
  34307. }
  34308. }, {
  34309. key: 'min',
  34310. value: function min(minValue) {
  34311. this.__min = minValue;
  34312. return this;
  34313. }
  34314. }, {
  34315. key: 'max',
  34316. value: function max(maxValue) {
  34317. this.__max = maxValue;
  34318. return this;
  34319. }
  34320. }, {
  34321. key: 'step',
  34322. value: function step(stepValue) {
  34323. this.__step = stepValue;
  34324. this.__impliedStep = stepValue;
  34325. this.__precision = numDecimals(stepValue);
  34326. return this;
  34327. }
  34328. }]);
  34329. return NumberController;
  34330. }(Controller);
  34331. function roundToDecimal(value, decimals) {
  34332. var tenTo = Math.pow(10, decimals);
  34333. return Math.round(value * tenTo) / tenTo;
  34334. }
  34335. var NumberControllerBox = function (_NumberController) {
  34336. inherits(NumberControllerBox, _NumberController);
  34337. function NumberControllerBox(object, property, params) {
  34338. classCallCheck(this, NumberControllerBox);
  34339. var _this2 = possibleConstructorReturn(this, (NumberControllerBox.__proto__ || Object.getPrototypeOf(NumberControllerBox)).call(this, object, property, params));
  34340. _this2.__truncationSuspended = false;
  34341. var _this = _this2;
  34342. var prevY = void 0;
  34343. function onChange() {
  34344. var attempted = parseFloat(_this.__input.value);
  34345. if (!Common.isNaN(attempted)) {
  34346. _this.setValue(attempted);
  34347. }
  34348. }
  34349. function onFinish() {
  34350. if (_this.__onFinishChange) {
  34351. _this.__onFinishChange.call(_this, _this.getValue());
  34352. }
  34353. }
  34354. function onBlur() {
  34355. onFinish();
  34356. }
  34357. function onMouseDrag(e) {
  34358. var diff = prevY - e.clientY;
  34359. _this.setValue(_this.getValue() + diff * _this.__impliedStep);
  34360. prevY = e.clientY;
  34361. }
  34362. function onMouseUp() {
  34363. dom.unbind(window, 'mousemove', onMouseDrag);
  34364. dom.unbind(window, 'mouseup', onMouseUp);
  34365. onFinish();
  34366. }
  34367. function onMouseDown(e) {
  34368. dom.bind(window, 'mousemove', onMouseDrag);
  34369. dom.bind(window, 'mouseup', onMouseUp);
  34370. prevY = e.clientY;
  34371. }
  34372. _this2.__input = document.createElement('input');
  34373. _this2.__input.setAttribute('type', 'text');
  34374. dom.bind(_this2.__input, 'change', onChange);
  34375. dom.bind(_this2.__input, 'blur', onBlur);
  34376. dom.bind(_this2.__input, 'mousedown', onMouseDown);
  34377. dom.bind(_this2.__input, 'keydown', function (e) {
  34378. if (e.keyCode === 13) {
  34379. _this.__truncationSuspended = true;
  34380. this.blur();
  34381. _this.__truncationSuspended = false;
  34382. onFinish();
  34383. }
  34384. });
  34385. _this2.updateDisplay();
  34386. _this2.domElement.appendChild(_this2.__input);
  34387. return _this2;
  34388. }
  34389. createClass(NumberControllerBox, [{
  34390. key: 'updateDisplay',
  34391. value: function updateDisplay() {
  34392. this.__input.value = this.__truncationSuspended ? this.getValue() : roundToDecimal(this.getValue(), this.__precision);
  34393. return get(NumberControllerBox.prototype.__proto__ || Object.getPrototypeOf(NumberControllerBox.prototype), 'updateDisplay', this).call(this);
  34394. }
  34395. }]);
  34396. return NumberControllerBox;
  34397. }(NumberController);
  34398. function map(v, i1, i2, o1, o2) {
  34399. return o1 + (o2 - o1) * ((v - i1) / (i2 - i1));
  34400. }
  34401. var NumberControllerSlider = function (_NumberController) {
  34402. inherits(NumberControllerSlider, _NumberController);
  34403. function NumberControllerSlider(object, property, min, max, step) {
  34404. classCallCheck(this, NumberControllerSlider);
  34405. var _this2 = possibleConstructorReturn(this, (NumberControllerSlider.__proto__ || Object.getPrototypeOf(NumberControllerSlider)).call(this, object, property, {
  34406. min: min,
  34407. max: max,
  34408. step: step
  34409. }));
  34410. var _this = _this2;
  34411. _this2.__background = document.createElement('div');
  34412. _this2.__foreground = document.createElement('div');
  34413. dom.bind(_this2.__background, 'mousedown', onMouseDown);
  34414. dom.bind(_this2.__background, 'touchstart', onTouchStart);
  34415. dom.addClass(_this2.__background, 'slider');
  34416. dom.addClass(_this2.__foreground, 'slider-fg');
  34417. function onMouseDown(e) {
  34418. document.activeElement.blur();
  34419. dom.bind(window, 'mousemove', onMouseDrag);
  34420. dom.bind(window, 'mouseup', onMouseUp);
  34421. onMouseDrag(e);
  34422. }
  34423. function onMouseDrag(e) {
  34424. e.preventDefault();
  34425. var bgRect = _this.__background.getBoundingClientRect();
  34426. _this.setValue(map(e.clientX, bgRect.left, bgRect.right, _this.__min, _this.__max));
  34427. return false;
  34428. }
  34429. function onMouseUp() {
  34430. dom.unbind(window, 'mousemove', onMouseDrag);
  34431. dom.unbind(window, 'mouseup', onMouseUp);
  34432. if (_this.__onFinishChange) {
  34433. _this.__onFinishChange.call(_this, _this.getValue());
  34434. }
  34435. }
  34436. function onTouchStart(e) {
  34437. if (e.touches.length !== 1) {
  34438. return;
  34439. }
  34440. dom.bind(window, 'touchmove', onTouchMove);
  34441. dom.bind(window, 'touchend', onTouchEnd);
  34442. onTouchMove(e);
  34443. }
  34444. function onTouchMove(e) {
  34445. var clientX = e.touches[0].clientX;
  34446. var bgRect = _this.__background.getBoundingClientRect();
  34447. _this.setValue(map(clientX, bgRect.left, bgRect.right, _this.__min, _this.__max));
  34448. }
  34449. function onTouchEnd() {
  34450. dom.unbind(window, 'touchmove', onTouchMove);
  34451. dom.unbind(window, 'touchend', onTouchEnd);
  34452. if (_this.__onFinishChange) {
  34453. _this.__onFinishChange.call(_this, _this.getValue());
  34454. }
  34455. }
  34456. _this2.updateDisplay();
  34457. _this2.__background.appendChild(_this2.__foreground);
  34458. _this2.domElement.appendChild(_this2.__background);
  34459. return _this2;
  34460. }
  34461. createClass(NumberControllerSlider, [{
  34462. key: 'updateDisplay',
  34463. value: function updateDisplay() {
  34464. var pct = (this.getValue() - this.__min) / (this.__max - this.__min);
  34465. this.__foreground.style.width = pct * 100 + '%';
  34466. return get(NumberControllerSlider.prototype.__proto__ || Object.getPrototypeOf(NumberControllerSlider.prototype), 'updateDisplay', this).call(this);
  34467. }
  34468. }]);
  34469. return NumberControllerSlider;
  34470. }(NumberController);
  34471. var FunctionController = function (_Controller) {
  34472. inherits(FunctionController, _Controller);
  34473. function FunctionController(object, property, text) {
  34474. classCallCheck(this, FunctionController);
  34475. var _this2 = possibleConstructorReturn(this, (FunctionController.__proto__ || Object.getPrototypeOf(FunctionController)).call(this, object, property));
  34476. var _this = _this2;
  34477. _this2.__button = document.createElement('div');
  34478. _this2.__button.innerHTML = text === undefined ? 'Fire' : text;
  34479. dom.bind(_this2.__button, 'click', function (e) {
  34480. e.preventDefault();
  34481. _this.fire();
  34482. return false;
  34483. });
  34484. dom.addClass(_this2.__button, 'button');
  34485. _this2.domElement.appendChild(_this2.__button);
  34486. return _this2;
  34487. }
  34488. createClass(FunctionController, [{
  34489. key: 'fire',
  34490. value: function fire() {
  34491. if (this.__onChange) {
  34492. this.__onChange.call(this);
  34493. }
  34494. this.getValue().call(this.object);
  34495. if (this.__onFinishChange) {
  34496. this.__onFinishChange.call(this, this.getValue());
  34497. }
  34498. }
  34499. }]);
  34500. return FunctionController;
  34501. }(Controller);
  34502. var ColorController = function (_Controller) {
  34503. inherits(ColorController, _Controller);
  34504. function ColorController(object, property) {
  34505. classCallCheck(this, ColorController);
  34506. var _this2 = possibleConstructorReturn(this, (ColorController.__proto__ || Object.getPrototypeOf(ColorController)).call(this, object, property));
  34507. _this2.__color = new Color(_this2.getValue());
  34508. _this2.__temp = new Color(0);
  34509. var _this = _this2;
  34510. _this2.domElement = document.createElement('div');
  34511. dom.makeSelectable(_this2.domElement, false);
  34512. _this2.__selector = document.createElement('div');
  34513. _this2.__selector.className = 'selector';
  34514. _this2.__saturation_field = document.createElement('div');
  34515. _this2.__saturation_field.className = 'saturation-field';
  34516. _this2.__field_knob = document.createElement('div');
  34517. _this2.__field_knob.className = 'field-knob';
  34518. _this2.__field_knob_border = '2px solid ';
  34519. _this2.__hue_knob = document.createElement('div');
  34520. _this2.__hue_knob.className = 'hue-knob';
  34521. _this2.__hue_field = document.createElement('div');
  34522. _this2.__hue_field.className = 'hue-field';
  34523. _this2.__input = document.createElement('input');
  34524. _this2.__input.type = 'text';
  34525. _this2.__input_textShadow = '0 1px 1px ';
  34526. dom.bind(_this2.__input, 'keydown', function (e) {
  34527. if (e.keyCode === 13) {
  34528. onBlur.call(this);
  34529. }
  34530. });
  34531. dom.bind(_this2.__input, 'blur', onBlur);
  34532. dom.bind(_this2.__selector, 'mousedown', function () {
  34533. dom.addClass(this, 'drag').bind(window, 'mouseup', function () {
  34534. dom.removeClass(_this.__selector, 'drag');
  34535. });
  34536. });
  34537. dom.bind(_this2.__selector, 'touchstart', function () {
  34538. dom.addClass(this, 'drag').bind(window, 'touchend', function () {
  34539. dom.removeClass(_this.__selector, 'drag');
  34540. });
  34541. });
  34542. var valueField = document.createElement('div');
  34543. Common.extend(_this2.__selector.style, {
  34544. width: '122px',
  34545. height: '102px',
  34546. padding: '3px',
  34547. backgroundColor: '#222',
  34548. boxShadow: '0px 1px 3px rgba(0,0,0,0.3)'
  34549. });
  34550. Common.extend(_this2.__field_knob.style, {
  34551. position: 'absolute',
  34552. width: '12px',
  34553. height: '12px',
  34554. border: _this2.__field_knob_border + (_this2.__color.v < 0.5 ? '#fff' : '#000'),
  34555. boxShadow: '0px 1px 3px rgba(0,0,0,0.5)',
  34556. borderRadius: '12px',
  34557. zIndex: 1
  34558. });
  34559. Common.extend(_this2.__hue_knob.style, {
  34560. position: 'absolute',
  34561. width: '15px',
  34562. height: '2px',
  34563. borderRight: '4px solid #fff',
  34564. zIndex: 1
  34565. });
  34566. Common.extend(_this2.__saturation_field.style, {
  34567. width: '100px',
  34568. height: '100px',
  34569. border: '1px solid #555',
  34570. marginRight: '3px',
  34571. display: 'inline-block',
  34572. cursor: 'pointer'
  34573. });
  34574. Common.extend(valueField.style, {
  34575. width: '100%',
  34576. height: '100%',
  34577. background: 'none'
  34578. });
  34579. linearGradient(valueField, 'top', 'rgba(0,0,0,0)', '#000');
  34580. Common.extend(_this2.__hue_field.style, {
  34581. width: '15px',
  34582. height: '100px',
  34583. border: '1px solid #555',
  34584. cursor: 'ns-resize',
  34585. position: 'absolute',
  34586. top: '3px',
  34587. right: '3px'
  34588. });
  34589. hueGradient(_this2.__hue_field);
  34590. Common.extend(_this2.__input.style, {
  34591. outline: 'none',
  34592. textAlign: 'center',
  34593. color: '#fff',
  34594. border: 0,
  34595. fontWeight: 'bold',
  34596. textShadow: _this2.__input_textShadow + 'rgba(0,0,0,0.7)'
  34597. });
  34598. dom.bind(_this2.__saturation_field, 'mousedown', fieldDown);
  34599. dom.bind(_this2.__saturation_field, 'touchstart', fieldDown);
  34600. dom.bind(_this2.__field_knob, 'mousedown', fieldDown);
  34601. dom.bind(_this2.__field_knob, 'touchstart', fieldDown);
  34602. dom.bind(_this2.__hue_field, 'mousedown', fieldDownH);
  34603. dom.bind(_this2.__hue_field, 'touchstart', fieldDownH);
  34604. function fieldDown(e) {
  34605. setSV(e);
  34606. dom.bind(window, 'mousemove', setSV);
  34607. dom.bind(window, 'touchmove', setSV);
  34608. dom.bind(window, 'mouseup', fieldUpSV);
  34609. dom.bind(window, 'touchend', fieldUpSV);
  34610. }
  34611. function fieldDownH(e) {
  34612. setH(e);
  34613. dom.bind(window, 'mousemove', setH);
  34614. dom.bind(window, 'touchmove', setH);
  34615. dom.bind(window, 'mouseup', fieldUpH);
  34616. dom.bind(window, 'touchend', fieldUpH);
  34617. }
  34618. function fieldUpSV() {
  34619. dom.unbind(window, 'mousemove', setSV);
  34620. dom.unbind(window, 'touchmove', setSV);
  34621. dom.unbind(window, 'mouseup', fieldUpSV);
  34622. dom.unbind(window, 'touchend', fieldUpSV);
  34623. onFinish();
  34624. }
  34625. function fieldUpH() {
  34626. dom.unbind(window, 'mousemove', setH);
  34627. dom.unbind(window, 'touchmove', setH);
  34628. dom.unbind(window, 'mouseup', fieldUpH);
  34629. dom.unbind(window, 'touchend', fieldUpH);
  34630. onFinish();
  34631. }
  34632. function onBlur() {
  34633. var i = interpret(this.value);
  34634. if (i !== false) {
  34635. _this.__color.__state = i;
  34636. _this.setValue(_this.__color.toOriginal());
  34637. } else {
  34638. this.value = _this.__color.toString();
  34639. }
  34640. }
  34641. function onFinish() {
  34642. if (_this.__onFinishChange) {
  34643. _this.__onFinishChange.call(_this, _this.__color.toOriginal());
  34644. }
  34645. }
  34646. _this2.__saturation_field.appendChild(valueField);
  34647. _this2.__selector.appendChild(_this2.__field_knob);
  34648. _this2.__selector.appendChild(_this2.__saturation_field);
  34649. _this2.__selector.appendChild(_this2.__hue_field);
  34650. _this2.__hue_field.appendChild(_this2.__hue_knob);
  34651. _this2.domElement.appendChild(_this2.__input);
  34652. _this2.domElement.appendChild(_this2.__selector);
  34653. _this2.updateDisplay();
  34654. function setSV(e) {
  34655. if (e.type.indexOf('touch') === -1) {
  34656. e.preventDefault();
  34657. }
  34658. var fieldRect = _this.__saturation_field.getBoundingClientRect();
  34659. var _ref = e.touches && e.touches[0] || e,
  34660. clientX = _ref.clientX,
  34661. clientY = _ref.clientY;
  34662. var s = (clientX - fieldRect.left) / (fieldRect.right - fieldRect.left);
  34663. var v = 1 - (clientY - fieldRect.top) / (fieldRect.bottom - fieldRect.top);
  34664. if (v > 1) {
  34665. v = 1;
  34666. } else if (v < 0) {
  34667. v = 0;
  34668. }
  34669. if (s > 1) {
  34670. s = 1;
  34671. } else if (s < 0) {
  34672. s = 0;
  34673. }
  34674. _this.__color.v = v;
  34675. _this.__color.s = s;
  34676. _this.setValue(_this.__color.toOriginal());
  34677. return false;
  34678. }
  34679. function setH(e) {
  34680. if (e.type.indexOf('touch') === -1) {
  34681. e.preventDefault();
  34682. }
  34683. var fieldRect = _this.__hue_field.getBoundingClientRect();
  34684. var _ref2 = e.touches && e.touches[0] || e,
  34685. clientY = _ref2.clientY;
  34686. var h = 1 - (clientY - fieldRect.top) / (fieldRect.bottom - fieldRect.top);
  34687. if (h > 1) {
  34688. h = 1;
  34689. } else if (h < 0) {
  34690. h = 0;
  34691. }
  34692. _this.__color.h = h * 360;
  34693. _this.setValue(_this.__color.toOriginal());
  34694. return false;
  34695. }
  34696. return _this2;
  34697. }
  34698. createClass(ColorController, [{
  34699. key: 'updateDisplay',
  34700. value: function updateDisplay() {
  34701. var i = interpret(this.getValue());
  34702. if (i !== false) {
  34703. var mismatch = false;
  34704. Common.each(Color.COMPONENTS, function (component) {
  34705. if (!Common.isUndefined(i[component]) && !Common.isUndefined(this.__color.__state[component]) && i[component] !== this.__color.__state[component]) {
  34706. mismatch = true;
  34707. return {};
  34708. }
  34709. }, this);
  34710. if (mismatch) {
  34711. Common.extend(this.__color.__state, i);
  34712. }
  34713. }
  34714. Common.extend(this.__temp.__state, this.__color.__state);
  34715. this.__temp.a = 1;
  34716. var flip = this.__color.v < 0.5 || this.__color.s > 0.5 ? 255 : 0;
  34717. var _flip = 255 - flip;
  34718. Common.extend(this.__field_knob.style, {
  34719. marginLeft: 100 * this.__color.s - 7 + 'px',
  34720. marginTop: 100 * (1 - this.__color.v) - 7 + 'px',
  34721. backgroundColor: this.__temp.toHexString(),
  34722. border: this.__field_knob_border + 'rgb(' + flip + ',' + flip + ',' + flip + ')'
  34723. });
  34724. this.__hue_knob.style.marginTop = (1 - this.__color.h / 360) * 100 + 'px';
  34725. this.__temp.s = 1;
  34726. this.__temp.v = 1;
  34727. linearGradient(this.__saturation_field, 'left', '#fff', this.__temp.toHexString());
  34728. this.__input.value = this.__color.toString();
  34729. Common.extend(this.__input.style, {
  34730. backgroundColor: this.__color.toHexString(),
  34731. color: 'rgb(' + flip + ',' + flip + ',' + flip + ')',
  34732. textShadow: this.__input_textShadow + 'rgba(' + _flip + ',' + _flip + ',' + _flip + ',.7)'
  34733. });
  34734. }
  34735. }]);
  34736. return ColorController;
  34737. }(Controller);
  34738. var vendors = ['-moz-', '-o-', '-webkit-', '-ms-', ''];
  34739. function linearGradient(elem, x, a, b) {
  34740. elem.style.background = '';
  34741. Common.each(vendors, function (vendor) {
  34742. elem.style.cssText += 'background: ' + vendor + 'linear-gradient(' + x + ', ' + a + ' 0%, ' + b + ' 100%); ';
  34743. });
  34744. }
  34745. function hueGradient(elem) {
  34746. elem.style.background = '';
  34747. elem.style.cssText += 'background: -moz-linear-gradient(top, #ff0000 0%, #ff00ff 17%, #0000ff 34%, #00ffff 50%, #00ff00 67%, #ffff00 84%, #ff0000 100%);';
  34748. elem.style.cssText += 'background: -webkit-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  34749. elem.style.cssText += 'background: -o-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  34750. elem.style.cssText += 'background: -ms-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  34751. elem.style.cssText += 'background: linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  34752. }
  34753. var css = {
  34754. load: function load(url, indoc) {
  34755. var doc = indoc || document;
  34756. var link = doc.createElement('link');
  34757. link.type = 'text/css';
  34758. link.rel = 'stylesheet';
  34759. link.href = url;
  34760. doc.getElementsByTagName('head')[0].appendChild(link);
  34761. },
  34762. inject: function inject(cssContent, indoc) {
  34763. var doc = indoc || document;
  34764. var injected = document.createElement('style');
  34765. injected.type = 'text/css';
  34766. injected.innerHTML = cssContent;
  34767. var head = doc.getElementsByTagName('head')[0];
  34768. try {
  34769. head.appendChild(injected);
  34770. } catch (e) {}
  34771. }
  34772. };
  34773. 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>";
  34774. var ControllerFactory = function ControllerFactory(object, property) {
  34775. var initialValue = object[property];
  34776. if (Common.isArray(arguments[2]) || Common.isObject(arguments[2])) {
  34777. return new OptionController(object, property, arguments[2]);
  34778. }
  34779. if (Common.isNumber(initialValue)) {
  34780. if (Common.isNumber(arguments[2]) && Common.isNumber(arguments[3])) {
  34781. if (Common.isNumber(arguments[4])) {
  34782. return new NumberControllerSlider(object, property, arguments[2], arguments[3], arguments[4]);
  34783. }
  34784. return new NumberControllerSlider(object, property, arguments[2], arguments[3]);
  34785. }
  34786. if (Common.isNumber(arguments[4])) {
  34787. return new NumberControllerBox(object, property, {
  34788. min: arguments[2],
  34789. max: arguments[3],
  34790. step: arguments[4]
  34791. });
  34792. }
  34793. return new NumberControllerBox(object, property, {
  34794. min: arguments[2],
  34795. max: arguments[3]
  34796. });
  34797. }
  34798. if (Common.isString(initialValue)) {
  34799. return new StringController(object, property);
  34800. }
  34801. if (Common.isFunction(initialValue)) {
  34802. return new FunctionController(object, property, '');
  34803. }
  34804. if (Common.isBoolean(initialValue)) {
  34805. return new BooleanController(object, property);
  34806. }
  34807. return null;
  34808. };
  34809. function requestAnimationFrame(callback) {
  34810. setTimeout(callback, 1000 / 60);
  34811. }
  34812. var requestAnimationFrame$1 = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || requestAnimationFrame;
  34813. var CenteredDiv = function () {
  34814. function CenteredDiv() {
  34815. classCallCheck(this, CenteredDiv);
  34816. this.backgroundElement = document.createElement('div');
  34817. Common.extend(this.backgroundElement.style, {
  34818. backgroundColor: 'rgba(0,0,0,0.8)',
  34819. top: 0,
  34820. left: 0,
  34821. display: 'none',
  34822. zIndex: '1000',
  34823. opacity: 0,
  34824. WebkitTransition: 'opacity 0.2s linear',
  34825. transition: 'opacity 0.2s linear'
  34826. });
  34827. dom.makeFullscreen(this.backgroundElement);
  34828. this.backgroundElement.style.position = 'fixed';
  34829. this.domElement = document.createElement('div');
  34830. Common.extend(this.domElement.style, {
  34831. position: 'fixed',
  34832. display: 'none',
  34833. zIndex: '1001',
  34834. opacity: 0,
  34835. WebkitTransition: '-webkit-transform 0.2s ease-out, opacity 0.2s linear',
  34836. transition: 'transform 0.2s ease-out, opacity 0.2s linear'
  34837. });
  34838. document.body.appendChild(this.backgroundElement);
  34839. document.body.appendChild(this.domElement);
  34840. var _this = this;
  34841. dom.bind(this.backgroundElement, 'click', function () {
  34842. _this.hide();
  34843. });
  34844. }
  34845. createClass(CenteredDiv, [{
  34846. key: 'show',
  34847. value: function show() {
  34848. var _this = this;
  34849. this.backgroundElement.style.display = 'block';
  34850. this.domElement.style.display = 'block';
  34851. this.domElement.style.opacity = 0;
  34852. this.domElement.style.webkitTransform = 'scale(1.1)';
  34853. this.layout();
  34854. Common.defer(function () {
  34855. _this.backgroundElement.style.opacity = 1;
  34856. _this.domElement.style.opacity = 1;
  34857. _this.domElement.style.webkitTransform = 'scale(1)';
  34858. });
  34859. }
  34860. }, {
  34861. key: 'hide',
  34862. value: function hide() {
  34863. var _this = this;
  34864. var hide = function hide() {
  34865. _this.domElement.style.display = 'none';
  34866. _this.backgroundElement.style.display = 'none';
  34867. dom.unbind(_this.domElement, 'webkitTransitionEnd', hide);
  34868. dom.unbind(_this.domElement, 'transitionend', hide);
  34869. dom.unbind(_this.domElement, 'oTransitionEnd', hide);
  34870. };
  34871. dom.bind(this.domElement, 'webkitTransitionEnd', hide);
  34872. dom.bind(this.domElement, 'transitionend', hide);
  34873. dom.bind(this.domElement, 'oTransitionEnd', hide);
  34874. this.backgroundElement.style.opacity = 0;
  34875. this.domElement.style.opacity = 0;
  34876. this.domElement.style.webkitTransform = 'scale(1.1)';
  34877. }
  34878. }, {
  34879. key: 'layout',
  34880. value: function layout() {
  34881. this.domElement.style.left = window.innerWidth / 2 - dom.getWidth(this.domElement) / 2 + 'px';
  34882. this.domElement.style.top = window.innerHeight / 2 - dom.getHeight(this.domElement) / 2 + 'px';
  34883. }
  34884. }]);
  34885. return CenteredDiv;
  34886. }();
  34887. 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");
  34888. css.inject(styleSheet);
  34889. var CSS_NAMESPACE = 'dg';
  34890. var HIDE_KEY_CODE = 72;
  34891. var CLOSE_BUTTON_HEIGHT = 20;
  34892. var DEFAULT_DEFAULT_PRESET_NAME = 'Default';
  34893. var SUPPORTS_LOCAL_STORAGE = function () {
  34894. try {
  34895. return !!window.localStorage;
  34896. } catch (e) {
  34897. return false;
  34898. }
  34899. }();
  34900. var SAVE_DIALOGUE = void 0;
  34901. var autoPlaceVirgin = true;
  34902. var autoPlaceContainer = void 0;
  34903. var hide = false;
  34904. var hideableGuis = [];
  34905. var GUI = function GUI(pars) {
  34906. var _this = this;
  34907. var params = pars || {};
  34908. this.domElement = document.createElement('div');
  34909. this.__ul = document.createElement('ul');
  34910. this.domElement.appendChild(this.__ul);
  34911. dom.addClass(this.domElement, CSS_NAMESPACE);
  34912. this.__folders = {};
  34913. this.__controllers = [];
  34914. this.__rememberedObjects = [];
  34915. this.__rememberedObjectIndecesToControllers = [];
  34916. this.__listening = [];
  34917. params = Common.defaults(params, {
  34918. closeOnTop: false,
  34919. autoPlace: true,
  34920. width: GUI.DEFAULT_WIDTH
  34921. });
  34922. params = Common.defaults(params, {
  34923. resizable: params.autoPlace,
  34924. hideable: params.autoPlace
  34925. });
  34926. if (!Common.isUndefined(params.load)) {
  34927. if (params.preset) {
  34928. params.load.preset = params.preset;
  34929. }
  34930. } else {
  34931. params.load = {
  34932. preset: DEFAULT_DEFAULT_PRESET_NAME
  34933. };
  34934. }
  34935. if (Common.isUndefined(params.parent) && params.hideable) {
  34936. hideableGuis.push(this);
  34937. }
  34938. params.resizable = Common.isUndefined(params.parent) && params.resizable;
  34939. if (params.autoPlace && Common.isUndefined(params.scrollable)) {
  34940. params.scrollable = true;
  34941. }
  34942. var useLocalStorage = SUPPORTS_LOCAL_STORAGE && localStorage.getItem(getLocalStorageHash(this, 'isLocal')) === 'true';
  34943. var saveToLocalStorage = void 0;
  34944. var titleRow = void 0;
  34945. Object.defineProperties(this, {
  34946. parent: {
  34947. get: function get$$1() {
  34948. return params.parent;
  34949. }
  34950. },
  34951. scrollable: {
  34952. get: function get$$1() {
  34953. return params.scrollable;
  34954. }
  34955. },
  34956. autoPlace: {
  34957. get: function get$$1() {
  34958. return params.autoPlace;
  34959. }
  34960. },
  34961. closeOnTop: {
  34962. get: function get$$1() {
  34963. return params.closeOnTop;
  34964. }
  34965. },
  34966. preset: {
  34967. get: function get$$1() {
  34968. if (_this.parent) {
  34969. return _this.getRoot().preset;
  34970. }
  34971. return params.load.preset;
  34972. },
  34973. set: function set$$1(v) {
  34974. if (_this.parent) {
  34975. _this.getRoot().preset = v;
  34976. } else {
  34977. params.load.preset = v;
  34978. }
  34979. setPresetSelectIndex(this);
  34980. _this.revert();
  34981. }
  34982. },
  34983. width: {
  34984. get: function get$$1() {
  34985. return params.width;
  34986. },
  34987. set: function set$$1(v) {
  34988. params.width = v;
  34989. setWidth(_this, v);
  34990. }
  34991. },
  34992. name: {
  34993. get: function get$$1() {
  34994. return params.name;
  34995. },
  34996. set: function set$$1(v) {
  34997. params.name = v;
  34998. if (titleRow) {
  34999. titleRow.innerHTML = params.name;
  35000. }
  35001. }
  35002. },
  35003. closed: {
  35004. get: function get$$1() {
  35005. return params.closed;
  35006. },
  35007. set: function set$$1(v) {
  35008. params.closed = v;
  35009. if (params.closed) {
  35010. dom.addClass(_this.__ul, GUI.CLASS_CLOSED);
  35011. } else {
  35012. dom.removeClass(_this.__ul, GUI.CLASS_CLOSED);
  35013. }
  35014. this.onResize();
  35015. if (_this.__closeButton) {
  35016. _this.__closeButton.innerHTML = v ? GUI.TEXT_OPEN : GUI.TEXT_CLOSED;
  35017. }
  35018. }
  35019. },
  35020. load: {
  35021. get: function get$$1() {
  35022. return params.load;
  35023. }
  35024. },
  35025. useLocalStorage: {
  35026. get: function get$$1() {
  35027. return useLocalStorage;
  35028. },
  35029. set: function set$$1(bool) {
  35030. if (SUPPORTS_LOCAL_STORAGE) {
  35031. useLocalStorage = bool;
  35032. if (bool) {
  35033. dom.bind(window, 'unload', saveToLocalStorage);
  35034. } else {
  35035. dom.unbind(window, 'unload', saveToLocalStorage);
  35036. }
  35037. localStorage.setItem(getLocalStorageHash(_this, 'isLocal'), bool);
  35038. }
  35039. }
  35040. }
  35041. });
  35042. if (Common.isUndefined(params.parent)) {
  35043. this.closed = params.closed || false;
  35044. dom.addClass(this.domElement, GUI.CLASS_MAIN);
  35045. dom.makeSelectable(this.domElement, false);
  35046. if (SUPPORTS_LOCAL_STORAGE) {
  35047. if (useLocalStorage) {
  35048. _this.useLocalStorage = true;
  35049. var savedGui = localStorage.getItem(getLocalStorageHash(this, 'gui'));
  35050. if (savedGui) {
  35051. params.load = JSON.parse(savedGui);
  35052. }
  35053. }
  35054. }
  35055. this.__closeButton = document.createElement('div');
  35056. this.__closeButton.innerHTML = GUI.TEXT_CLOSED;
  35057. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BUTTON);
  35058. if (params.closeOnTop) {
  35059. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_TOP);
  35060. this.domElement.insertBefore(this.__closeButton, this.domElement.childNodes[0]);
  35061. } else {
  35062. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BOTTOM);
  35063. this.domElement.appendChild(this.__closeButton);
  35064. }
  35065. dom.bind(this.__closeButton, 'click', function () {
  35066. _this.closed = !_this.closed;
  35067. });
  35068. } else {
  35069. if (params.closed === undefined) {
  35070. params.closed = true;
  35071. }
  35072. var titleRowName = document.createTextNode(params.name);
  35073. dom.addClass(titleRowName, 'controller-name');
  35074. titleRow = addRow(_this, titleRowName);
  35075. var onClickTitle = function onClickTitle(e) {
  35076. e.preventDefault();
  35077. _this.closed = !_this.closed;
  35078. return false;
  35079. };
  35080. dom.addClass(this.__ul, GUI.CLASS_CLOSED);
  35081. dom.addClass(titleRow, 'title');
  35082. dom.bind(titleRow, 'click', onClickTitle);
  35083. if (!params.closed) {
  35084. this.closed = false;
  35085. }
  35086. }
  35087. if (params.autoPlace) {
  35088. if (Common.isUndefined(params.parent)) {
  35089. if (autoPlaceVirgin) {
  35090. autoPlaceContainer = document.createElement('div');
  35091. dom.addClass(autoPlaceContainer, CSS_NAMESPACE);
  35092. dom.addClass(autoPlaceContainer, GUI.CLASS_AUTO_PLACE_CONTAINER);
  35093. document.body.appendChild(autoPlaceContainer);
  35094. autoPlaceVirgin = false;
  35095. }
  35096. autoPlaceContainer.appendChild(this.domElement);
  35097. dom.addClass(this.domElement, GUI.CLASS_AUTO_PLACE);
  35098. }
  35099. if (!this.parent) {
  35100. setWidth(_this, params.width);
  35101. }
  35102. }
  35103. this.__resizeHandler = function () {
  35104. _this.onResizeDebounced();
  35105. };
  35106. dom.bind(window, 'resize', this.__resizeHandler);
  35107. dom.bind(this.__ul, 'webkitTransitionEnd', this.__resizeHandler);
  35108. dom.bind(this.__ul, 'transitionend', this.__resizeHandler);
  35109. dom.bind(this.__ul, 'oTransitionEnd', this.__resizeHandler);
  35110. this.onResize();
  35111. if (params.resizable) {
  35112. addResizeHandle(this);
  35113. }
  35114. saveToLocalStorage = function saveToLocalStorage() {
  35115. if (SUPPORTS_LOCAL_STORAGE && localStorage.getItem(getLocalStorageHash(_this, 'isLocal')) === 'true') {
  35116. localStorage.setItem(getLocalStorageHash(_this, 'gui'), JSON.stringify(_this.getSaveObject()));
  35117. }
  35118. };
  35119. this.saveToLocalStorageIfPossible = saveToLocalStorage;
  35120. function resetWidth() {
  35121. var root = _this.getRoot();
  35122. root.width += 1;
  35123. Common.defer(function () {
  35124. root.width -= 1;
  35125. });
  35126. }
  35127. if (!params.parent) {
  35128. resetWidth();
  35129. }
  35130. };
  35131. GUI.toggleHide = function () {
  35132. hide = !hide;
  35133. Common.each(hideableGuis, function (gui) {
  35134. gui.domElement.style.display = hide ? 'none' : '';
  35135. });
  35136. };
  35137. GUI.CLASS_AUTO_PLACE = 'a';
  35138. GUI.CLASS_AUTO_PLACE_CONTAINER = 'ac';
  35139. GUI.CLASS_MAIN = 'main';
  35140. GUI.CLASS_CONTROLLER_ROW = 'cr';
  35141. GUI.CLASS_TOO_TALL = 'taller-than-window';
  35142. GUI.CLASS_CLOSED = 'closed';
  35143. GUI.CLASS_CLOSE_BUTTON = 'close-button';
  35144. GUI.CLASS_CLOSE_TOP = 'close-top';
  35145. GUI.CLASS_CLOSE_BOTTOM = 'close-bottom';
  35146. GUI.CLASS_DRAG = 'drag';
  35147. GUI.DEFAULT_WIDTH = 245;
  35148. GUI.TEXT_CLOSED = 'Close Controls';
  35149. GUI.TEXT_OPEN = 'Open Controls';
  35150. GUI._keydownHandler = function (e) {
  35151. if (document.activeElement.type !== 'text' && (e.which === HIDE_KEY_CODE || e.keyCode === HIDE_KEY_CODE)) {
  35152. GUI.toggleHide();
  35153. }
  35154. };
  35155. dom.bind(window, 'keydown', GUI._keydownHandler, false);
  35156. Common.extend(GUI.prototype, {
  35157. add: function add(object, property) {
  35158. return _add(this, object, property, {
  35159. factoryArgs: Array.prototype.slice.call(arguments, 2)
  35160. });
  35161. },
  35162. addColor: function addColor(object, property) {
  35163. return _add(this, object, property, {
  35164. color: true
  35165. });
  35166. },
  35167. remove: function remove(controller) {
  35168. this.__ul.removeChild(controller.__li);
  35169. this.__controllers.splice(this.__controllers.indexOf(controller), 1);
  35170. var _this = this;
  35171. Common.defer(function () {
  35172. _this.onResize();
  35173. });
  35174. },
  35175. destroy: function destroy() {
  35176. if (this.parent) {
  35177. throw new Error('Only the root GUI should be removed with .destroy(). ' + 'For subfolders, use gui.removeFolder(folder) instead.');
  35178. }
  35179. if (this.autoPlace) {
  35180. autoPlaceContainer.removeChild(this.domElement);
  35181. }
  35182. var _this = this;
  35183. Common.each(this.__folders, function (subfolder) {
  35184. _this.removeFolder(subfolder);
  35185. });
  35186. dom.unbind(window, 'keydown', GUI._keydownHandler, false);
  35187. removeListeners(this);
  35188. },
  35189. addFolder: function addFolder(name) {
  35190. if (this.__folders[name] !== undefined) {
  35191. throw new Error('You already have a folder in this GUI by the' + ' name "' + name + '"');
  35192. }
  35193. var newGuiParams = {
  35194. name: name,
  35195. parent: this
  35196. };
  35197. newGuiParams.autoPlace = this.autoPlace;
  35198. if (this.load && this.load.folders && this.load.folders[name]) {
  35199. newGuiParams.closed = this.load.folders[name].closed;
  35200. newGuiParams.load = this.load.folders[name];
  35201. }
  35202. var gui = new GUI(newGuiParams);
  35203. this.__folders[name] = gui;
  35204. var li = addRow(this, gui.domElement);
  35205. dom.addClass(li, 'folder');
  35206. return gui;
  35207. },
  35208. removeFolder: function removeFolder(folder) {
  35209. this.__ul.removeChild(folder.domElement.parentElement);
  35210. delete this.__folders[folder.name];
  35211. if (this.load && this.load.folders && this.load.folders[folder.name]) {
  35212. delete this.load.folders[folder.name];
  35213. }
  35214. removeListeners(folder);
  35215. var _this = this;
  35216. Common.each(folder.__folders, function (subfolder) {
  35217. folder.removeFolder(subfolder);
  35218. });
  35219. Common.defer(function () {
  35220. _this.onResize();
  35221. });
  35222. },
  35223. open: function open() {
  35224. this.closed = false;
  35225. },
  35226. close: function close() {
  35227. this.closed = true;
  35228. },
  35229. hide: function hide() {
  35230. this.domElement.style.display = 'none';
  35231. },
  35232. show: function show() {
  35233. this.domElement.style.display = '';
  35234. },
  35235. onResize: function onResize() {
  35236. var root = this.getRoot();
  35237. if (root.scrollable) {
  35238. var top = dom.getOffset(root.__ul).top;
  35239. var h = 0;
  35240. Common.each(root.__ul.childNodes, function (node) {
  35241. if (!(root.autoPlace && node === root.__save_row)) {
  35242. h += dom.getHeight(node);
  35243. }
  35244. });
  35245. if (window.innerHeight - top - CLOSE_BUTTON_HEIGHT < h) {
  35246. dom.addClass(root.domElement, GUI.CLASS_TOO_TALL);
  35247. root.__ul.style.height = window.innerHeight - top - CLOSE_BUTTON_HEIGHT + 'px';
  35248. } else {
  35249. dom.removeClass(root.domElement, GUI.CLASS_TOO_TALL);
  35250. root.__ul.style.height = 'auto';
  35251. }
  35252. }
  35253. if (root.__resize_handle) {
  35254. Common.defer(function () {
  35255. root.__resize_handle.style.height = root.__ul.offsetHeight + 'px';
  35256. });
  35257. }
  35258. if (root.__closeButton) {
  35259. root.__closeButton.style.width = root.width + 'px';
  35260. }
  35261. },
  35262. onResizeDebounced: Common.debounce(function () {
  35263. this.onResize();
  35264. }, 50),
  35265. remember: function remember() {
  35266. if (Common.isUndefined(SAVE_DIALOGUE)) {
  35267. SAVE_DIALOGUE = new CenteredDiv();
  35268. SAVE_DIALOGUE.domElement.innerHTML = saveDialogContents;
  35269. }
  35270. if (this.parent) {
  35271. throw new Error('You can only call remember on a top level GUI.');
  35272. }
  35273. var _this = this;
  35274. Common.each(Array.prototype.slice.call(arguments), function (object) {
  35275. if (_this.__rememberedObjects.length === 0) {
  35276. addSaveMenu(_this);
  35277. }
  35278. if (_this.__rememberedObjects.indexOf(object) === -1) {
  35279. _this.__rememberedObjects.push(object);
  35280. }
  35281. });
  35282. if (this.autoPlace) {
  35283. setWidth(this, this.width);
  35284. }
  35285. },
  35286. getRoot: function getRoot() {
  35287. var gui = this;
  35288. while (gui.parent) {
  35289. gui = gui.parent;
  35290. }
  35291. return gui;
  35292. },
  35293. getSaveObject: function getSaveObject() {
  35294. var toReturn = this.load;
  35295. toReturn.closed = this.closed;
  35296. if (this.__rememberedObjects.length > 0) {
  35297. toReturn.preset = this.preset;
  35298. if (!toReturn.remembered) {
  35299. toReturn.remembered = {};
  35300. }
  35301. toReturn.remembered[this.preset] = getCurrentPreset(this);
  35302. }
  35303. toReturn.folders = {};
  35304. Common.each(this.__folders, function (element, key) {
  35305. toReturn.folders[key] = element.getSaveObject();
  35306. });
  35307. return toReturn;
  35308. },
  35309. save: function save() {
  35310. if (!this.load.remembered) {
  35311. this.load.remembered = {};
  35312. }
  35313. this.load.remembered[this.preset] = getCurrentPreset(this);
  35314. markPresetModified(this, false);
  35315. this.saveToLocalStorageIfPossible();
  35316. },
  35317. saveAs: function saveAs(presetName) {
  35318. if (!this.load.remembered) {
  35319. this.load.remembered = {};
  35320. this.load.remembered[DEFAULT_DEFAULT_PRESET_NAME] = getCurrentPreset(this, true);
  35321. }
  35322. this.load.remembered[presetName] = getCurrentPreset(this);
  35323. this.preset = presetName;
  35324. addPresetOption(this, presetName, true);
  35325. this.saveToLocalStorageIfPossible();
  35326. },
  35327. revert: function revert(gui) {
  35328. Common.each(this.__controllers, function (controller) {
  35329. if (!this.getRoot().load.remembered) {
  35330. controller.setValue(controller.initialValue);
  35331. } else {
  35332. recallSavedValue(gui || this.getRoot(), controller);
  35333. }
  35334. if (controller.__onFinishChange) {
  35335. controller.__onFinishChange.call(controller, controller.getValue());
  35336. }
  35337. }, this);
  35338. Common.each(this.__folders, function (folder) {
  35339. folder.revert(folder);
  35340. });
  35341. if (!gui) {
  35342. markPresetModified(this.getRoot(), false);
  35343. }
  35344. },
  35345. listen: function listen(controller) {
  35346. var init = this.__listening.length === 0;
  35347. this.__listening.push(controller);
  35348. if (init) {
  35349. updateDisplays(this.__listening);
  35350. }
  35351. },
  35352. updateDisplay: function updateDisplay() {
  35353. Common.each(this.__controllers, function (controller) {
  35354. controller.updateDisplay();
  35355. });
  35356. Common.each(this.__folders, function (folder) {
  35357. folder.updateDisplay();
  35358. });
  35359. }
  35360. });
  35361. function addRow(gui, newDom, liBefore) {
  35362. var li = document.createElement('li');
  35363. if (newDom) {
  35364. li.appendChild(newDom);
  35365. }
  35366. if (liBefore) {
  35367. gui.__ul.insertBefore(li, liBefore);
  35368. } else {
  35369. gui.__ul.appendChild(li);
  35370. }
  35371. gui.onResize();
  35372. return li;
  35373. }
  35374. function removeListeners(gui) {
  35375. dom.unbind(window, 'resize', gui.__resizeHandler);
  35376. if (gui.saveToLocalStorageIfPossible) {
  35377. dom.unbind(window, 'unload', gui.saveToLocalStorageIfPossible);
  35378. }
  35379. }
  35380. function markPresetModified(gui, modified) {
  35381. var opt = gui.__preset_select[gui.__preset_select.selectedIndex];
  35382. if (modified) {
  35383. opt.innerHTML = opt.value + '*';
  35384. } else {
  35385. opt.innerHTML = opt.value;
  35386. }
  35387. }
  35388. function augmentController(gui, li, controller) {
  35389. controller.__li = li;
  35390. controller.__gui = gui;
  35391. Common.extend(controller, {
  35392. options: function options(_options) {
  35393. if (arguments.length > 1) {
  35394. var nextSibling = controller.__li.nextElementSibling;
  35395. controller.remove();
  35396. return _add(gui, controller.object, controller.property, {
  35397. before: nextSibling,
  35398. factoryArgs: [Common.toArray(arguments)]
  35399. });
  35400. }
  35401. if (Common.isArray(_options) || Common.isObject(_options)) {
  35402. var _nextSibling = controller.__li.nextElementSibling;
  35403. controller.remove();
  35404. return _add(gui, controller.object, controller.property, {
  35405. before: _nextSibling,
  35406. factoryArgs: [_options]
  35407. });
  35408. }
  35409. },
  35410. name: function name(_name) {
  35411. controller.__li.firstElementChild.firstElementChild.innerHTML = _name;
  35412. return controller;
  35413. },
  35414. listen: function listen() {
  35415. controller.__gui.listen(controller);
  35416. return controller;
  35417. },
  35418. remove: function remove() {
  35419. controller.__gui.remove(controller);
  35420. return controller;
  35421. }
  35422. });
  35423. if (controller instanceof NumberControllerSlider) {
  35424. var box = new NumberControllerBox(controller.object, controller.property, {
  35425. min: controller.__min,
  35426. max: controller.__max,
  35427. step: controller.__step
  35428. });
  35429. Common.each(['updateDisplay', 'onChange', 'onFinishChange', 'step', 'min', 'max'], function (method) {
  35430. var pc = controller[method];
  35431. var pb = box[method];
  35432. controller[method] = box[method] = function () {
  35433. var args = Array.prototype.slice.call(arguments);
  35434. pb.apply(box, args);
  35435. return pc.apply(controller, args);
  35436. };
  35437. });
  35438. dom.addClass(li, 'has-slider');
  35439. controller.domElement.insertBefore(box.domElement, controller.domElement.firstElementChild);
  35440. } else if (controller instanceof NumberControllerBox) {
  35441. var r = function r(returned) {
  35442. if (Common.isNumber(controller.__min) && Common.isNumber(controller.__max)) {
  35443. var oldName = controller.__li.firstElementChild.firstElementChild.innerHTML;
  35444. var wasListening = controller.__gui.__listening.indexOf(controller) > -1;
  35445. controller.remove();
  35446. var newController = _add(gui, controller.object, controller.property, {
  35447. before: controller.__li.nextElementSibling,
  35448. factoryArgs: [controller.__min, controller.__max, controller.__step]
  35449. });
  35450. newController.name(oldName);
  35451. if (wasListening) newController.listen();
  35452. return newController;
  35453. }
  35454. return returned;
  35455. };
  35456. controller.min = Common.compose(r, controller.min);
  35457. controller.max = Common.compose(r, controller.max);
  35458. } else if (controller instanceof BooleanController) {
  35459. dom.bind(li, 'click', function () {
  35460. dom.fakeEvent(controller.__checkbox, 'click');
  35461. });
  35462. dom.bind(controller.__checkbox, 'click', function (e) {
  35463. e.stopPropagation();
  35464. });
  35465. } else if (controller instanceof FunctionController) {
  35466. dom.bind(li, 'click', function () {
  35467. dom.fakeEvent(controller.__button, 'click');
  35468. });
  35469. dom.bind(li, 'mouseover', function () {
  35470. dom.addClass(controller.__button, 'hover');
  35471. });
  35472. dom.bind(li, 'mouseout', function () {
  35473. dom.removeClass(controller.__button, 'hover');
  35474. });
  35475. } else if (controller instanceof ColorController) {
  35476. dom.addClass(li, 'color');
  35477. controller.updateDisplay = Common.compose(function (val) {
  35478. li.style.borderLeftColor = controller.__color.toString();
  35479. return val;
  35480. }, controller.updateDisplay);
  35481. controller.updateDisplay();
  35482. }
  35483. controller.setValue = Common.compose(function (val) {
  35484. if (gui.getRoot().__preset_select && controller.isModified()) {
  35485. markPresetModified(gui.getRoot(), true);
  35486. }
  35487. return val;
  35488. }, controller.setValue);
  35489. }
  35490. function recallSavedValue(gui, controller) {
  35491. var root = gui.getRoot();
  35492. var matchedIndex = root.__rememberedObjects.indexOf(controller.object);
  35493. if (matchedIndex !== -1) {
  35494. var controllerMap = root.__rememberedObjectIndecesToControllers[matchedIndex];
  35495. if (controllerMap === undefined) {
  35496. controllerMap = {};
  35497. root.__rememberedObjectIndecesToControllers[matchedIndex] = controllerMap;
  35498. }
  35499. controllerMap[controller.property] = controller;
  35500. if (root.load && root.load.remembered) {
  35501. var presetMap = root.load.remembered;
  35502. var preset = void 0;
  35503. if (presetMap[gui.preset]) {
  35504. preset = presetMap[gui.preset];
  35505. } else if (presetMap[DEFAULT_DEFAULT_PRESET_NAME]) {
  35506. preset = presetMap[DEFAULT_DEFAULT_PRESET_NAME];
  35507. } else {
  35508. return;
  35509. }
  35510. if (preset[matchedIndex] && preset[matchedIndex][controller.property] !== undefined) {
  35511. var value = preset[matchedIndex][controller.property];
  35512. controller.initialValue = value;
  35513. controller.setValue(value);
  35514. }
  35515. }
  35516. }
  35517. }
  35518. function _add(gui, object, property, params) {
  35519. if (object[property] === undefined) {
  35520. throw new Error('Object "' + object + '" has no property "' + property + '"');
  35521. }
  35522. var controller = void 0;
  35523. if (params.color) {
  35524. controller = new ColorController(object, property);
  35525. } else {
  35526. var factoryArgs = [object, property].concat(params.factoryArgs);
  35527. controller = ControllerFactory.apply(gui, factoryArgs);
  35528. }
  35529. if (params.before instanceof Controller) {
  35530. params.before = params.before.__li;
  35531. }
  35532. recallSavedValue(gui, controller);
  35533. dom.addClass(controller.domElement, 'c');
  35534. var name = document.createElement('span');
  35535. dom.addClass(name, 'property-name');
  35536. name.innerHTML = controller.property;
  35537. var container = document.createElement('div');
  35538. container.appendChild(name);
  35539. container.appendChild(controller.domElement);
  35540. var li = addRow(gui, container, params.before);
  35541. dom.addClass(li, GUI.CLASS_CONTROLLER_ROW);
  35542. if (controller instanceof ColorController) {
  35543. dom.addClass(li, 'color');
  35544. } else {
  35545. dom.addClass(li, _typeof(controller.getValue()));
  35546. }
  35547. augmentController(gui, li, controller);
  35548. gui.__controllers.push(controller);
  35549. return controller;
  35550. }
  35551. function getLocalStorageHash(gui, key) {
  35552. return document.location.href + '.' + key;
  35553. }
  35554. function addPresetOption(gui, name, setSelected) {
  35555. var opt = document.createElement('option');
  35556. opt.innerHTML = name;
  35557. opt.value = name;
  35558. gui.__preset_select.appendChild(opt);
  35559. if (setSelected) {
  35560. gui.__preset_select.selectedIndex = gui.__preset_select.length - 1;
  35561. }
  35562. }
  35563. function showHideExplain(gui, explain) {
  35564. explain.style.display = gui.useLocalStorage ? 'block' : 'none';
  35565. }
  35566. function addSaveMenu(gui) {
  35567. var div = gui.__save_row = document.createElement('li');
  35568. dom.addClass(gui.domElement, 'has-save');
  35569. gui.__ul.insertBefore(div, gui.__ul.firstChild);
  35570. dom.addClass(div, 'save-row');
  35571. var gears = document.createElement('span');
  35572. gears.innerHTML = '&nbsp;';
  35573. dom.addClass(gears, 'button gears');
  35574. var button = document.createElement('span');
  35575. button.innerHTML = 'Save';
  35576. dom.addClass(button, 'button');
  35577. dom.addClass(button, 'save');
  35578. var button2 = document.createElement('span');
  35579. button2.innerHTML = 'New';
  35580. dom.addClass(button2, 'button');
  35581. dom.addClass(button2, 'save-as');
  35582. var button3 = document.createElement('span');
  35583. button3.innerHTML = 'Revert';
  35584. dom.addClass(button3, 'button');
  35585. dom.addClass(button3, 'revert');
  35586. var select = gui.__preset_select = document.createElement('select');
  35587. if (gui.load && gui.load.remembered) {
  35588. Common.each(gui.load.remembered, function (value, key) {
  35589. addPresetOption(gui, key, key === gui.preset);
  35590. });
  35591. } else {
  35592. addPresetOption(gui, DEFAULT_DEFAULT_PRESET_NAME, false);
  35593. }
  35594. dom.bind(select, 'change', function () {
  35595. for (var index = 0; index < gui.__preset_select.length; index++) {
  35596. gui.__preset_select[index].innerHTML = gui.__preset_select[index].value;
  35597. }
  35598. gui.preset = this.value;
  35599. });
  35600. div.appendChild(select);
  35601. div.appendChild(gears);
  35602. div.appendChild(button);
  35603. div.appendChild(button2);
  35604. div.appendChild(button3);
  35605. if (SUPPORTS_LOCAL_STORAGE) {
  35606. var explain = document.getElementById('dg-local-explain');
  35607. var localStorageCheckBox = document.getElementById('dg-local-storage');
  35608. var saveLocally = document.getElementById('dg-save-locally');
  35609. saveLocally.style.display = 'block';
  35610. if (localStorage.getItem(getLocalStorageHash(gui, 'isLocal')) === 'true') {
  35611. localStorageCheckBox.setAttribute('checked', 'checked');
  35612. }
  35613. showHideExplain(gui, explain);
  35614. dom.bind(localStorageCheckBox, 'change', function () {
  35615. gui.useLocalStorage = !gui.useLocalStorage;
  35616. showHideExplain(gui, explain);
  35617. });
  35618. }
  35619. var newConstructorTextArea = document.getElementById('dg-new-constructor');
  35620. dom.bind(newConstructorTextArea, 'keydown', function (e) {
  35621. if (e.metaKey && (e.which === 67 || e.keyCode === 67)) {
  35622. SAVE_DIALOGUE.hide();
  35623. }
  35624. });
  35625. dom.bind(gears, 'click', function () {
  35626. newConstructorTextArea.innerHTML = JSON.stringify(gui.getSaveObject(), undefined, 2);
  35627. SAVE_DIALOGUE.show();
  35628. newConstructorTextArea.focus();
  35629. newConstructorTextArea.select();
  35630. });
  35631. dom.bind(button, 'click', function () {
  35632. gui.save();
  35633. });
  35634. dom.bind(button2, 'click', function () {
  35635. var presetName = prompt('Enter a new preset name.');
  35636. if (presetName) {
  35637. gui.saveAs(presetName);
  35638. }
  35639. });
  35640. dom.bind(button3, 'click', function () {
  35641. gui.revert();
  35642. });
  35643. }
  35644. function addResizeHandle(gui) {
  35645. var pmouseX = void 0;
  35646. gui.__resize_handle = document.createElement('div');
  35647. Common.extend(gui.__resize_handle.style, {
  35648. width: '6px',
  35649. marginLeft: '-3px',
  35650. height: '200px',
  35651. cursor: 'ew-resize',
  35652. position: 'absolute'
  35653. });
  35654. function drag(e) {
  35655. e.preventDefault();
  35656. gui.width += pmouseX - e.clientX;
  35657. gui.onResize();
  35658. pmouseX = e.clientX;
  35659. return false;
  35660. }
  35661. function dragStop() {
  35662. dom.removeClass(gui.__closeButton, GUI.CLASS_DRAG);
  35663. dom.unbind(window, 'mousemove', drag);
  35664. dom.unbind(window, 'mouseup', dragStop);
  35665. }
  35666. function dragStart(e) {
  35667. e.preventDefault();
  35668. pmouseX = e.clientX;
  35669. dom.addClass(gui.__closeButton, GUI.CLASS_DRAG);
  35670. dom.bind(window, 'mousemove', drag);
  35671. dom.bind(window, 'mouseup', dragStop);
  35672. return false;
  35673. }
  35674. dom.bind(gui.__resize_handle, 'mousedown', dragStart);
  35675. dom.bind(gui.__closeButton, 'mousedown', dragStart);
  35676. gui.domElement.insertBefore(gui.__resize_handle, gui.domElement.firstElementChild);
  35677. }
  35678. function setWidth(gui, w) {
  35679. gui.domElement.style.width = w + 'px';
  35680. if (gui.__save_row && gui.autoPlace) {
  35681. gui.__save_row.style.width = w + 'px';
  35682. }
  35683. if (gui.__closeButton) {
  35684. gui.__closeButton.style.width = w + 'px';
  35685. }
  35686. }
  35687. function getCurrentPreset(gui, useInitialValues) {
  35688. var toReturn = {};
  35689. Common.each(gui.__rememberedObjects, function (val, index) {
  35690. var savedValues = {};
  35691. var controllerMap = gui.__rememberedObjectIndecesToControllers[index];
  35692. Common.each(controllerMap, function (controller, property) {
  35693. savedValues[property] = useInitialValues ? controller.initialValue : controller.getValue();
  35694. });
  35695. toReturn[index] = savedValues;
  35696. });
  35697. return toReturn;
  35698. }
  35699. function setPresetSelectIndex(gui) {
  35700. for (var index = 0; index < gui.__preset_select.length; index++) {
  35701. if (gui.__preset_select[index].value === gui.preset) {
  35702. gui.__preset_select.selectedIndex = index;
  35703. }
  35704. }
  35705. }
  35706. function updateDisplays(controllerArray) {
  35707. if (controllerArray.length !== 0) {
  35708. requestAnimationFrame$1.call(window, function () {
  35709. updateDisplays(controllerArray);
  35710. });
  35711. }
  35712. Common.each(controllerArray, function (c) {
  35713. c.updateDisplay();
  35714. });
  35715. }
  35716. var color = {
  35717. Color: Color,
  35718. math: ColorMath,
  35719. interpret: interpret
  35720. };
  35721. exports.color = color;
  35722. var controllers = {
  35723. Controller: Controller,
  35724. BooleanController: BooleanController,
  35725. OptionController: OptionController,
  35726. StringController: StringController,
  35727. NumberController: NumberController,
  35728. NumberControllerBox: NumberControllerBox,
  35729. NumberControllerSlider: NumberControllerSlider,
  35730. FunctionController: FunctionController,
  35731. ColorController: ColorController
  35732. };
  35733. exports.controllers = controllers;
  35734. var dom$1 = {
  35735. dom: dom
  35736. };
  35737. exports.dom = dom$1;
  35738. var gui = {
  35739. GUI: GUI
  35740. };
  35741. exports.gui = gui;
  35742. var GUI$1 = GUI;
  35743. exports.GUI = GUI$1;
  35744. var index = {
  35745. color: color,
  35746. controllers: controllers,
  35747. dom: dom$1,
  35748. gui: gui,
  35749. GUI: GUI$1
  35750. };
  35751. var _default = index;
  35752. exports.default = _default;
  35753. },{}],"../node_modules/three/examples/jsm/libs/stats.module.js":[function(require,module,exports) {
  35754. "use strict";
  35755. Object.defineProperty(exports, "__esModule", {
  35756. value: true
  35757. });
  35758. exports.default = void 0;
  35759. /**
  35760. * @author mrdoob / http://mrdoob.com/
  35761. */
  35762. var Stats = function () {
  35763. var mode = 0;
  35764. var container = document.createElement('div');
  35765. container.style.cssText = 'position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000';
  35766. container.addEventListener('click', function (event) {
  35767. event.preventDefault();
  35768. showPanel(++mode % container.children.length);
  35769. }, false); //
  35770. function addPanel(panel) {
  35771. container.appendChild(panel.dom);
  35772. return panel;
  35773. }
  35774. function showPanel(id) {
  35775. for (var i = 0; i < container.children.length; i++) {
  35776. container.children[i].style.display = i === id ? 'block' : 'none';
  35777. }
  35778. mode = id;
  35779. } //
  35780. var beginTime = (performance || Date).now(),
  35781. prevTime = beginTime,
  35782. frames = 0;
  35783. var fpsPanel = addPanel(new Stats.Panel('FPS', '#0ff', '#002'));
  35784. var msPanel = addPanel(new Stats.Panel('MS', '#0f0', '#020'));
  35785. if (self.performance && self.performance.memory) {
  35786. var memPanel = addPanel(new Stats.Panel('MB', '#f08', '#201'));
  35787. }
  35788. showPanel(0);
  35789. return {
  35790. REVISION: 16,
  35791. dom: container,
  35792. addPanel: addPanel,
  35793. showPanel: showPanel,
  35794. begin: function () {
  35795. beginTime = (performance || Date).now();
  35796. },
  35797. end: function () {
  35798. frames++;
  35799. var time = (performance || Date).now();
  35800. msPanel.update(time - beginTime, 200);
  35801. if (time >= prevTime + 1000) {
  35802. fpsPanel.update(frames * 1000 / (time - prevTime), 100);
  35803. prevTime = time;
  35804. frames = 0;
  35805. if (memPanel) {
  35806. var memory = performance.memory;
  35807. memPanel.update(memory.usedJSHeapSize / 1048576, memory.jsHeapSizeLimit / 1048576);
  35808. }
  35809. }
  35810. return time;
  35811. },
  35812. update: function () {
  35813. beginTime = this.end();
  35814. },
  35815. // Backwards Compatibility
  35816. domElement: container,
  35817. setMode: showPanel
  35818. };
  35819. };
  35820. Stats.Panel = function (name, fg, bg) {
  35821. var min = Infinity,
  35822. max = 0,
  35823. round = Math.round;
  35824. var PR = round(window.devicePixelRatio || 1);
  35825. var WIDTH = 80 * PR,
  35826. HEIGHT = 48 * PR,
  35827. TEXT_X = 3 * PR,
  35828. TEXT_Y = 2 * PR,
  35829. GRAPH_X = 3 * PR,
  35830. GRAPH_Y = 15 * PR,
  35831. GRAPH_WIDTH = 74 * PR,
  35832. GRAPH_HEIGHT = 30 * PR;
  35833. var canvas = document.createElement('canvas');
  35834. canvas.width = WIDTH;
  35835. canvas.height = HEIGHT;
  35836. canvas.style.cssText = 'width:80px;height:48px';
  35837. var context = canvas.getContext('2d');
  35838. context.font = 'bold ' + 9 * PR + 'px Helvetica,Arial,sans-serif';
  35839. context.textBaseline = 'top';
  35840. context.fillStyle = bg;
  35841. context.fillRect(0, 0, WIDTH, HEIGHT);
  35842. context.fillStyle = fg;
  35843. context.fillText(name, TEXT_X, TEXT_Y);
  35844. context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
  35845. context.fillStyle = bg;
  35846. context.globalAlpha = 0.9;
  35847. context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
  35848. return {
  35849. dom: canvas,
  35850. update: function (value, maxValue) {
  35851. min = Math.min(min, value);
  35852. max = Math.max(max, value);
  35853. context.fillStyle = bg;
  35854. context.globalAlpha = 1;
  35855. context.fillRect(0, 0, WIDTH, GRAPH_Y);
  35856. context.fillStyle = fg;
  35857. context.fillText(round(value) + ' ' + name + ' (' + round(min) + '-' + round(max) + ')', TEXT_X, TEXT_Y);
  35858. context.drawImage(canvas, GRAPH_X + PR, GRAPH_Y, GRAPH_WIDTH - PR, GRAPH_HEIGHT, GRAPH_X, GRAPH_Y, GRAPH_WIDTH - PR, GRAPH_HEIGHT);
  35859. context.fillRect(GRAPH_X + GRAPH_WIDTH - PR, GRAPH_Y, PR, GRAPH_HEIGHT);
  35860. context.fillStyle = bg;
  35861. context.globalAlpha = 0.9;
  35862. context.fillRect(GRAPH_X + GRAPH_WIDTH - PR, GRAPH_Y, PR, round((1 - value / maxValue) * GRAPH_HEIGHT));
  35863. }
  35864. };
  35865. };
  35866. var _default = Stats;
  35867. exports.default = _default;
  35868. },{}],"index.js":[function(require,module,exports) {
  35869. "use strict";
  35870. var _ThreeTilesRenderer = require("../src/ThreeTilesRenderer.js");
  35871. var _three = require("three");
  35872. var _OrbitControls = require("three/examples/jsm/controls/OrbitControls.js");
  35873. var dat = _interopRequireWildcard(require("three/examples/jsm/libs/dat.gui.module.js"));
  35874. var _statsModule = _interopRequireDefault(require("three/examples/jsm/libs/stats.module.js"));
  35875. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  35876. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
  35877. 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; }
  35878. let camera, controls, scene, renderer, tiles, cameraHelper;
  35879. let thirdPersonCamera, thirdPersonRenderer, thirdPersonControls;
  35880. let box;
  35881. let raycaster, mouse, rayIntersect;
  35882. let offsetParent;
  35883. let statsContainer, stats;
  35884. let params = {
  35885. 'errorTarget': 6,
  35886. 'errorThreshold': 60,
  35887. 'maxDepth': 15,
  35888. 'loadSiblings': true,
  35889. 'up': '+Y',
  35890. 'displayBounds': false,
  35891. 'showThirdPerson': true,
  35892. 'reload': reinstantiateTiles
  35893. };
  35894. init();
  35895. animate();
  35896. function reinstantiateTiles() {
  35897. const url = window.location.hash.replace(/^#/, '') || './SampleTileset/tileset.json';
  35898. if (tiles) {
  35899. offsetParent.remove(tiles.group);
  35900. }
  35901. tiles = new _ThreeTilesRenderer.ThreeTilesRenderer(url, camera, renderer);
  35902. offsetParent.add(tiles.group);
  35903. }
  35904. function init() {
  35905. // Third person camera view
  35906. thirdPersonCamera = new _three.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 3000);
  35907. thirdPersonCamera.position.set(50, 40, 40);
  35908. thirdPersonCamera.lookAt(0, 0, 0);
  35909. thirdPersonRenderer = new _three.WebGLRenderer({
  35910. antialias: true
  35911. });
  35912. thirdPersonRenderer.setPixelRatio(window.devicePixelRatio);
  35913. thirdPersonRenderer.setSize(window.innerWidth, window.innerHeight);
  35914. thirdPersonRenderer.setClearColor(0x0f1416);
  35915. document.body.appendChild(thirdPersonRenderer.domElement);
  35916. thirdPersonRenderer.domElement.style.position = 'fixed';
  35917. thirdPersonRenderer.domElement.style.left = '5px';
  35918. thirdPersonRenderer.domElement.style.bottom = '5px';
  35919. thirdPersonControls = new _OrbitControls.OrbitControls(thirdPersonCamera, thirdPersonRenderer.domElement);
  35920. thirdPersonControls.screenSpacePanning = false;
  35921. thirdPersonControls.minDistance = 1;
  35922. thirdPersonControls.maxDistance = 2000; // primary camera view
  35923. scene = new _three.Scene();
  35924. renderer = new _three.WebGLRenderer({
  35925. antialias: true
  35926. });
  35927. renderer.setPixelRatio(window.devicePixelRatio);
  35928. renderer.setSize(window.innerWidth, window.innerHeight);
  35929. renderer.setClearColor(0x151c1f);
  35930. renderer.gammaInput = true;
  35931. renderer.gameOutput = true;
  35932. document.body.appendChild(renderer.domElement);
  35933. camera = new _three.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 2000);
  35934. camera.position.set(100, 100, 100);
  35935. cameraHelper = new _three.CameraHelper(camera);
  35936. scene.add(cameraHelper); // controls
  35937. controls = new _OrbitControls.OrbitControls(camera, renderer.domElement);
  35938. controls.screenSpacePanning = false;
  35939. controls.minDistance = 1;
  35940. controls.maxDistance = 2000; // lights
  35941. var dirLight = new _three.DirectionalLight(0xffffff);
  35942. dirLight.position.set(1, 1, 1);
  35943. scene.add(dirLight);
  35944. var ambLight = new _three.AmbientLight(0x222222);
  35945. scene.add(ambLight);
  35946. box = new _three.Box3();
  35947. raycaster = new _three.Raycaster();
  35948. mouse = new _three.Vector2();
  35949. rayIntersect = new _three.Group();
  35950. const rayMesh = new _three.Mesh(new _three.CylinderBufferGeometry(0.25, 0.25, 10), new _three.MeshBasicMaterial({
  35951. color: 0xe91e63
  35952. }));
  35953. rayMesh.rotation.x = Math.PI / 2;
  35954. rayMesh.position.z += 5;
  35955. rayIntersect.add(rayMesh);
  35956. const rayRing = new _three.Mesh(new _three.TorusBufferGeometry(1.5, 0.2, 16, 100), new _three.MeshBasicMaterial({
  35957. color: 0xe91e63
  35958. }));
  35959. rayIntersect.add(rayRing);
  35960. scene.add(rayIntersect);
  35961. offsetParent = new _three.Group();
  35962. scene.add(offsetParent);
  35963. reinstantiateTiles();
  35964. onWindowResize();
  35965. window.addEventListener('resize', onWindowResize, false);
  35966. window.addEventListener('mousemove', onMouseMove, false); // GUI
  35967. const gui = new dat.GUI();
  35968. const tiles = gui.addFolder('Tiles Options');
  35969. tiles.add(params, 'loadSiblings');
  35970. tiles.add(params, 'errorTarget').min(0).max(50);
  35971. tiles.add(params, 'errorThreshold').min(0).max(1000);
  35972. tiles.add(params, 'maxDepth').min(1).max(100);
  35973. tiles.add(params, 'up', ['+Y', '-Z']);
  35974. tiles.open();
  35975. gui.add(params, 'displayBounds');
  35976. gui.add(params, 'showThirdPerson');
  35977. gui.add(params, 'reload');
  35978. gui.open();
  35979. statsContainer = document.createElement('div');
  35980. statsContainer.style.position = 'absolute';
  35981. statsContainer.style.top = 0;
  35982. statsContainer.style.left = 0;
  35983. statsContainer.style.color = 'white';
  35984. statsContainer.style.width = '100%';
  35985. statsContainer.style.textAlign = 'center';
  35986. statsContainer.style.padding = '10px';
  35987. document.body.appendChild(statsContainer); // Stats
  35988. stats = new _statsModule.default();
  35989. stats.showPanel(0);
  35990. document.body.appendChild(stats.dom);
  35991. }
  35992. function onWindowResize() {
  35993. thirdPersonCamera.aspect = window.innerWidth / window.innerHeight;
  35994. thirdPersonCamera.updateProjectionMatrix();
  35995. thirdPersonRenderer.setSize(Math.floor(window.innerWidth / 3), Math.floor(window.innerHeight / 3));
  35996. camera.aspect = window.innerWidth / window.innerHeight;
  35997. camera.updateProjectionMatrix();
  35998. renderer.setSize(window.innerWidth, window.innerHeight);
  35999. }
  36000. function onMouseMove(e) {
  36001. mouse.x = e.clientX / window.innerWidth * 2 - 1;
  36002. mouse.y = -(e.clientY / window.innerHeight) * 2 + 1;
  36003. raycaster.setFromCamera(mouse, camera);
  36004. const results = raycaster.intersectObject(tiles.group, true);
  36005. if (results.length) {
  36006. const closestHit = results[0];
  36007. rayIntersect.position.copy(closestHit.point);
  36008. closestHit.face.normal.add(closestHit.point);
  36009. rayIntersect.lookAt(closestHit.face.normal);
  36010. }
  36011. }
  36012. function animate() {
  36013. // update options
  36014. tiles.errorTarget = params.errorTarget;
  36015. tiles.errorThreshold = params.errorThreshold;
  36016. tiles.loadSiblings = params.loadSiblings;
  36017. tiles.maxDepth = params.maxDepth;
  36018. tiles.displayBounds = params.displayBounds; // update tiles
  36019. tiles.update();
  36020. window.tiles = tiles;
  36021. offsetParent.rotation.set(0, 0, 0);
  36022. if (params.up === '-Z') {
  36023. offsetParent.rotation.x = Math.PI / 2;
  36024. } // update tiles center
  36025. if (tiles.getBounds(box)) {
  36026. box.getCenter(tiles.group.position);
  36027. tiles.group.position.multiplyScalar(-1);
  36028. }
  36029. stats.begin();
  36030. render();
  36031. stats.end();
  36032. requestAnimationFrame(animate);
  36033. }
  36034. function render() {
  36035. // render primary view
  36036. cameraHelper.visible = false;
  36037. renderer.render(scene, camera); // render third person view
  36038. thirdPersonRenderer.domElement.style.visibility = params.showThirdPerson ? 'visible' : 'hidden';
  36039. if (params.showThirdPerson) {
  36040. cameraHelper.visible = true;
  36041. thirdPersonRenderer.render(scene, thirdPersonCamera);
  36042. }
  36043. statsContainer.innerText = `Downloading: ${tiles.stats.downloading} Parsing: ${tiles.stats.parsing} Visible: ${tiles.group.children.length}`;
  36044. }
  36045. },{"../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) {
  36046. var global = arguments[3];
  36047. var OVERLAY_ID = '__parcel__error__overlay__';
  36048. var OldModule = module.bundle.Module;
  36049. function Module(moduleName) {
  36050. OldModule.call(this, moduleName);
  36051. this.hot = {
  36052. data: module.bundle.hotData,
  36053. _acceptCallbacks: [],
  36054. _disposeCallbacks: [],
  36055. accept: function (fn) {
  36056. this._acceptCallbacks.push(fn || function () {});
  36057. },
  36058. dispose: function (fn) {
  36059. this._disposeCallbacks.push(fn);
  36060. }
  36061. };
  36062. module.bundle.hotData = null;
  36063. }
  36064. module.bundle.Module = Module;
  36065. var checkedAssets, assetsToAccept;
  36066. var parent = module.bundle.parent;
  36067. if ((!parent || !parent.isParcelRequire) && typeof WebSocket !== 'undefined') {
  36068. var hostname = "" || location.hostname;
  36069. var protocol = location.protocol === 'https:' ? 'wss' : 'ws';
  36070. var ws = new WebSocket(protocol + '://' + hostname + ':' + "61189" + '/');
  36071. ws.onmessage = function (event) {
  36072. checkedAssets = {};
  36073. assetsToAccept = [];
  36074. var data = JSON.parse(event.data);
  36075. if (data.type === 'update') {
  36076. var handled = false;
  36077. data.assets.forEach(function (asset) {
  36078. if (!asset.isNew) {
  36079. var didAccept = hmrAcceptCheck(global.parcelRequire, asset.id);
  36080. if (didAccept) {
  36081. handled = true;
  36082. }
  36083. }
  36084. }); // Enable HMR for CSS by default.
  36085. handled = handled || data.assets.every(function (asset) {
  36086. return asset.type === 'css' && asset.generated.js;
  36087. });
  36088. if (handled) {
  36089. console.clear();
  36090. data.assets.forEach(function (asset) {
  36091. hmrApply(global.parcelRequire, asset);
  36092. });
  36093. assetsToAccept.forEach(function (v) {
  36094. hmrAcceptRun(v[0], v[1]);
  36095. });
  36096. } else if (location.reload) {
  36097. // `location` global exists in a web worker context but lacks `.reload()` function.
  36098. location.reload();
  36099. }
  36100. }
  36101. if (data.type === 'reload') {
  36102. ws.close();
  36103. ws.onclose = function () {
  36104. location.reload();
  36105. };
  36106. }
  36107. if (data.type === 'error-resolved') {
  36108. console.log('[parcel] ✨ Error resolved');
  36109. removeErrorOverlay();
  36110. }
  36111. if (data.type === 'error') {
  36112. console.error('[parcel] 🚨 ' + data.error.message + '\n' + data.error.stack);
  36113. removeErrorOverlay();
  36114. var overlay = createErrorOverlay(data);
  36115. document.body.appendChild(overlay);
  36116. }
  36117. };
  36118. }
  36119. function removeErrorOverlay() {
  36120. var overlay = document.getElementById(OVERLAY_ID);
  36121. if (overlay) {
  36122. overlay.remove();
  36123. }
  36124. }
  36125. function createErrorOverlay(data) {
  36126. var overlay = document.createElement('div');
  36127. overlay.id = OVERLAY_ID; // html encode message and stack trace
  36128. var message = document.createElement('div');
  36129. var stackTrace = document.createElement('pre');
  36130. message.innerText = data.error.message;
  36131. stackTrace.innerText = data.error.stack;
  36132. 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>';
  36133. return overlay;
  36134. }
  36135. function getParents(bundle, id) {
  36136. var modules = bundle.modules;
  36137. if (!modules) {
  36138. return [];
  36139. }
  36140. var parents = [];
  36141. var k, d, dep;
  36142. for (k in modules) {
  36143. for (d in modules[k][1]) {
  36144. dep = modules[k][1][d];
  36145. if (dep === id || Array.isArray(dep) && dep[dep.length - 1] === id) {
  36146. parents.push(k);
  36147. }
  36148. }
  36149. }
  36150. if (bundle.parent) {
  36151. parents = parents.concat(getParents(bundle.parent, id));
  36152. }
  36153. return parents;
  36154. }
  36155. function hmrApply(bundle, asset) {
  36156. var modules = bundle.modules;
  36157. if (!modules) {
  36158. return;
  36159. }
  36160. if (modules[asset.id] || !bundle.parent) {
  36161. var fn = new Function('require', 'module', 'exports', asset.generated.js);
  36162. asset.isNew = !modules[asset.id];
  36163. modules[asset.id] = [fn, asset.deps];
  36164. } else if (bundle.parent) {
  36165. hmrApply(bundle.parent, asset);
  36166. }
  36167. }
  36168. function hmrAcceptCheck(bundle, id) {
  36169. var modules = bundle.modules;
  36170. if (!modules) {
  36171. return;
  36172. }
  36173. if (!modules[id] && bundle.parent) {
  36174. return hmrAcceptCheck(bundle.parent, id);
  36175. }
  36176. if (checkedAssets[id]) {
  36177. return;
  36178. }
  36179. checkedAssets[id] = true;
  36180. var cached = bundle.cache[id];
  36181. assetsToAccept.push([bundle, id]);
  36182. if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
  36183. return true;
  36184. }
  36185. return getParents(global.parcelRequire, id).some(function (id) {
  36186. return hmrAcceptCheck(global.parcelRequire, id);
  36187. });
  36188. }
  36189. function hmrAcceptRun(bundle, id) {
  36190. var cached = bundle.cache[id];
  36191. bundle.hotData = {};
  36192. if (cached) {
  36193. cached.hot.data = bundle.hotData;
  36194. }
  36195. if (cached && cached.hot && cached.hot._disposeCallbacks.length) {
  36196. cached.hot._disposeCallbacks.forEach(function (cb) {
  36197. cb(bundle.hotData);
  36198. });
  36199. }
  36200. delete bundle.cache[id];
  36201. bundle(id);
  36202. cached = bundle.cache[id];
  36203. if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
  36204. cached.hot._acceptCallbacks.forEach(function (cb) {
  36205. cb();
  36206. });
  36207. return true;
  36208. }
  36209. }
  36210. },{}]},{},["../node_modules/parcel-bundler/src/builtins/hmr-runtime.js","index.js"], null)
  36211. //# sourceMappingURL=example.e31bb0bc.js.map