example.e31bb0bc.js 1.4 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078
  1. // modules are defined as an array
  2. // [ module function, map of requires ]
  3. //
  4. // map of requires is short require name -> numeric require
  5. //
  6. // anything defined in a previous bundle is accessed via the
  7. // orig method which is the require for previous bundles
  8. parcelRequire = (function (modules, cache, entry, globalName) {
  9. // Save the require from previous bundle to this closure if any
  10. var previousRequire = typeof parcelRequire === 'function' && parcelRequire;
  11. var nodeRequire = typeof require === 'function' && require;
  12. function newRequire(name, jumped) {
  13. if (!cache[name]) {
  14. if (!modules[name]) {
  15. // if we cannot find the module within our internal map or
  16. // cache jump to the current global require ie. the last bundle
  17. // that was added to the page.
  18. var currentRequire = typeof parcelRequire === 'function' && parcelRequire;
  19. if (!jumped && currentRequire) {
  20. return currentRequire(name, true);
  21. }
  22. // If there are other bundles on this page the require from the
  23. // previous one is saved to 'previousRequire'. Repeat this as
  24. // many times as there are bundles until the module is found or
  25. // we exhaust the require chain.
  26. if (previousRequire) {
  27. return previousRequire(name, true);
  28. }
  29. // Try the node require function if it exists.
  30. if (nodeRequire && typeof name === 'string') {
  31. return nodeRequire(name);
  32. }
  33. var err = new Error('Cannot find module \'' + name + '\'');
  34. err.code = 'MODULE_NOT_FOUND';
  35. throw err;
  36. }
  37. localRequire.resolve = resolve;
  38. localRequire.cache = {};
  39. var module = cache[name] = new newRequire.Module(name);
  40. modules[name][0].call(module.exports, localRequire, module, module.exports, this);
  41. }
  42. return cache[name].exports;
  43. function localRequire(x){
  44. return newRequire(localRequire.resolve(x));
  45. }
  46. function resolve(x){
  47. return modules[name][1][x] || x;
  48. }
  49. }
  50. function Module(moduleName) {
  51. this.id = moduleName;
  52. this.bundle = newRequire;
  53. this.exports = {};
  54. }
  55. newRequire.isParcelRequire = true;
  56. newRequire.Module = Module;
  57. newRequire.modules = modules;
  58. newRequire.cache = cache;
  59. newRequire.parent = previousRequire;
  60. newRequire.register = function (id, exports) {
  61. modules[id] = [function (require, module) {
  62. module.exports = exports;
  63. }, {}];
  64. };
  65. var error;
  66. for (var i = 0; i < entry.length; i++) {
  67. try {
  68. newRequire(entry[i]);
  69. } catch (e) {
  70. // Save first error but execute all entries
  71. if (!error) {
  72. error = e;
  73. }
  74. }
  75. }
  76. if (entry.length) {
  77. // Expose entry point to Node, AMD or browser globals
  78. // Based on https://github.com/ForbesLindesay/umd/blob/master/template.js
  79. var mainExports = newRequire(entry[entry.length - 1]);
  80. // CommonJS
  81. if (typeof exports === "object" && typeof module !== "undefined") {
  82. module.exports = mainExports;
  83. // RequireJS
  84. } else if (typeof define === "function" && define.amd) {
  85. define(function () {
  86. return mainExports;
  87. });
  88. // <script>
  89. } else if (globalName) {
  90. this[globalName] = mainExports;
  91. }
  92. }
  93. // Override the current require with this new one
  94. parcelRequire = newRequire;
  95. if (error) {
  96. // throw error from earlier, _after updating parcelRequire_
  97. throw error;
  98. }
  99. return newRequire;
  100. })({"../node_modules/three/build/three.module.js":[function(require,module,exports) {
  101. "use strict";
  102. Object.defineProperty(exports, "__esModule", {
  103. value: true
  104. });
  105. exports.AmbientLight = AmbientLight;
  106. exports.AmbientLightProbe = AmbientLightProbe;
  107. exports.AnimationClip = AnimationClip;
  108. exports.AnimationLoader = AnimationLoader;
  109. exports.AnimationMixer = AnimationMixer;
  110. exports.AnimationObjectGroup = AnimationObjectGroup;
  111. exports.ArcCurve = ArcCurve;
  112. exports.ArrayCamera = ArrayCamera;
  113. exports.ArrowHelper = ArrowHelper;
  114. exports.Audio = Audio;
  115. exports.AudioAnalyser = AudioAnalyser;
  116. exports.AudioListener = AudioListener;
  117. exports.AudioLoader = AudioLoader;
  118. exports.AxesHelper = AxesHelper;
  119. exports.AxisHelper = AxisHelper;
  120. exports.BinaryTextureLoader = BinaryTextureLoader;
  121. exports.Bone = Bone;
  122. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  123. exports.BoundingBoxHelper = BoundingBoxHelper;
  124. exports.Box2 = Box2;
  125. exports.Box3 = Box3;
  126. exports.Box3Helper = Box3Helper;
  127. exports.BoxHelper = BoxHelper;
  128. exports.BufferAttribute = BufferAttribute;
  129. exports.BufferGeometry = BufferGeometry;
  130. exports.BufferGeometryLoader = BufferGeometryLoader;
  131. exports.Camera = Camera;
  132. exports.CameraHelper = CameraHelper;
  133. exports.CanvasRenderer = CanvasRenderer;
  134. exports.CanvasTexture = CanvasTexture;
  135. exports.CatmullRomCurve3 = CatmullRomCurve3;
  136. exports.CircleBufferGeometry = CircleBufferGeometry;
  137. exports.CircleGeometry = CircleGeometry;
  138. exports.Clock = Clock;
  139. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  140. exports.Color = Color;
  141. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  142. exports.CompressedTexture = CompressedTexture;
  143. exports.CompressedTextureLoader = CompressedTextureLoader;
  144. exports.ConeBufferGeometry = ConeBufferGeometry;
  145. exports.ConeGeometry = ConeGeometry;
  146. exports.CubeCamera = CubeCamera;
  147. exports.CubeTexture = CubeTexture;
  148. exports.CubeTextureLoader = CubeTextureLoader;
  149. exports.CubicBezierCurve = CubicBezierCurve;
  150. exports.CubicBezierCurve3 = CubicBezierCurve3;
  151. exports.CubicInterpolant = CubicInterpolant;
  152. exports.Curve = Curve;
  153. exports.CurvePath = CurvePath;
  154. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  155. exports.CylinderGeometry = CylinderGeometry;
  156. exports.Cylindrical = Cylindrical;
  157. exports.DataTexture = DataTexture;
  158. exports.DataTexture2DArray = DataTexture2DArray;
  159. exports.DataTexture3D = DataTexture3D;
  160. exports.DataTextureLoader = DataTextureLoader;
  161. exports.DepthTexture = DepthTexture;
  162. exports.DirectionalLight = DirectionalLight;
  163. exports.DirectionalLightHelper = DirectionalLightHelper;
  164. exports.DirectionalLightShadow = DirectionalLightShadow;
  165. exports.DiscreteInterpolant = DiscreteInterpolant;
  166. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  167. exports.DodecahedronGeometry = DodecahedronGeometry;
  168. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  169. exports.EdgesGeometry = EdgesGeometry;
  170. exports.EdgesHelper = EdgesHelper;
  171. exports.EllipseCurve = EllipseCurve;
  172. exports.Euler = Euler;
  173. exports.EventDispatcher = EventDispatcher;
  174. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  175. exports.ExtrudeGeometry = ExtrudeGeometry;
  176. exports.Face3 = Face3;
  177. exports.Face4 = Face4;
  178. exports.FaceNormalsHelper = FaceNormalsHelper;
  179. exports.FileLoader = FileLoader;
  180. exports.Float32Attribute = Float32Attribute;
  181. exports.Float32BufferAttribute = Float32BufferAttribute;
  182. exports.Float64Attribute = Float64Attribute;
  183. exports.Float64BufferAttribute = Float64BufferAttribute;
  184. exports.Fog = Fog;
  185. exports.FogExp2 = FogExp2;
  186. exports.Font = Font;
  187. exports.FontLoader = FontLoader;
  188. exports.Frustum = Frustum;
  189. exports.Geometry = Geometry;
  190. exports.GridHelper = GridHelper;
  191. exports.Group = Group;
  192. exports.HemisphereLight = HemisphereLight;
  193. exports.HemisphereLightHelper = HemisphereLightHelper;
  194. exports.HemisphereLightProbe = HemisphereLightProbe;
  195. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  196. exports.IcosahedronGeometry = IcosahedronGeometry;
  197. exports.ImageBitmapLoader = ImageBitmapLoader;
  198. exports.ImageLoader = ImageLoader;
  199. exports.ImmediateRenderObject = ImmediateRenderObject;
  200. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  201. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  202. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  203. exports.InstancedMesh = InstancedMesh;
  204. exports.Int16Attribute = Int16Attribute;
  205. exports.Int16BufferAttribute = Int16BufferAttribute;
  206. exports.Int32Attribute = Int32Attribute;
  207. exports.Int32BufferAttribute = Int32BufferAttribute;
  208. exports.Int8Attribute = Int8Attribute;
  209. exports.Int8BufferAttribute = Int8BufferAttribute;
  210. exports.InterleavedBuffer = InterleavedBuffer;
  211. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  212. exports.Interpolant = Interpolant;
  213. exports.JSONLoader = JSONLoader;
  214. exports.KeyframeTrack = KeyframeTrack;
  215. exports.LOD = LOD;
  216. exports.LatheBufferGeometry = LatheBufferGeometry;
  217. exports.LatheGeometry = LatheGeometry;
  218. exports.Layers = Layers;
  219. exports.LensFlare = LensFlare;
  220. exports.Light = Light;
  221. exports.LightProbe = LightProbe;
  222. exports.LightProbeHelper = LightProbeHelper;
  223. exports.LightShadow = LightShadow;
  224. exports.Line = Line;
  225. exports.Line3 = Line3;
  226. exports.LineBasicMaterial = LineBasicMaterial;
  227. exports.LineCurve = LineCurve;
  228. exports.LineCurve3 = LineCurve3;
  229. exports.LineDashedMaterial = LineDashedMaterial;
  230. exports.LineLoop = LineLoop;
  231. exports.LineSegments = LineSegments;
  232. exports.LinearInterpolant = LinearInterpolant;
  233. exports.Loader = Loader;
  234. exports.LoadingManager = LoadingManager;
  235. exports.Material = Material;
  236. exports.MaterialLoader = MaterialLoader;
  237. exports.Matrix3 = Matrix3;
  238. exports.Matrix4 = Matrix4;
  239. exports.Mesh = Mesh;
  240. exports.MeshBasicMaterial = MeshBasicMaterial;
  241. exports.MeshDepthMaterial = MeshDepthMaterial;
  242. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  243. exports.MeshFaceMaterial = MeshFaceMaterial;
  244. exports.MeshLambertMaterial = MeshLambertMaterial;
  245. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  246. exports.MeshNormalMaterial = MeshNormalMaterial;
  247. exports.MeshPhongMaterial = MeshPhongMaterial;
  248. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  249. exports.MeshStandardMaterial = MeshStandardMaterial;
  250. exports.MeshToonMaterial = MeshToonMaterial;
  251. exports.MultiMaterial = MultiMaterial;
  252. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  253. exports.Object3D = Object3D;
  254. exports.ObjectLoader = ObjectLoader;
  255. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  256. exports.OctahedronGeometry = OctahedronGeometry;
  257. exports.OrthographicCamera = OrthographicCamera;
  258. exports.ParametricBufferGeometry = ParametricBufferGeometry;
  259. exports.ParametricGeometry = ParametricGeometry;
  260. exports.Particle = Particle;
  261. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  262. exports.ParticleSystem = ParticleSystem;
  263. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  264. exports.Path = Path;
  265. exports.PerspectiveCamera = PerspectiveCamera;
  266. exports.Plane = Plane;
  267. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  268. exports.PlaneGeometry = PlaneGeometry;
  269. exports.PlaneHelper = PlaneHelper;
  270. exports.PointCloud = PointCloud;
  271. exports.PointCloudMaterial = PointCloudMaterial;
  272. exports.PointLight = PointLight;
  273. exports.PointLightHelper = PointLightHelper;
  274. exports.Points = Points;
  275. exports.PointsMaterial = PointsMaterial;
  276. exports.PolarGridHelper = PolarGridHelper;
  277. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  278. exports.PolyhedronGeometry = PolyhedronGeometry;
  279. exports.PositionalAudio = PositionalAudio;
  280. exports.PositionalAudioHelper = PositionalAudioHelper;
  281. exports.PropertyBinding = PropertyBinding;
  282. exports.PropertyMixer = PropertyMixer;
  283. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  284. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  285. exports.Quaternion = Quaternion;
  286. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  287. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  288. exports.RawShaderMaterial = RawShaderMaterial;
  289. exports.Ray = Ray;
  290. exports.Raycaster = Raycaster;
  291. exports.RectAreaLight = RectAreaLight;
  292. exports.RectAreaLightHelper = RectAreaLightHelper;
  293. exports.RingBufferGeometry = RingBufferGeometry;
  294. exports.RingGeometry = RingGeometry;
  295. exports.Scene = Scene;
  296. exports.ShaderMaterial = ShaderMaterial;
  297. exports.ShadowMaterial = ShadowMaterial;
  298. exports.Shape = Shape;
  299. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  300. exports.ShapeGeometry = ShapeGeometry;
  301. exports.ShapePath = ShapePath;
  302. exports.Skeleton = Skeleton;
  303. exports.SkeletonHelper = SkeletonHelper;
  304. exports.SkinnedMesh = SkinnedMesh;
  305. exports.Sphere = Sphere;
  306. exports.SphereBufferGeometry = SphereBufferGeometry;
  307. exports.SphereGeometry = SphereGeometry;
  308. exports.Spherical = Spherical;
  309. exports.SphericalHarmonics3 = SphericalHarmonics3;
  310. exports.Spline = Spline;
  311. exports.SplineCurve = SplineCurve;
  312. exports.SplineCurve3 = SplineCurve3;
  313. exports.SpotLight = SpotLight;
  314. exports.SpotLightHelper = SpotLightHelper;
  315. exports.SpotLightShadow = SpotLightShadow;
  316. exports.Sprite = Sprite;
  317. exports.SpriteMaterial = SpriteMaterial;
  318. exports.StereoCamera = StereoCamera;
  319. exports.StringKeyframeTrack = StringKeyframeTrack;
  320. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  321. exports.TetrahedronGeometry = TetrahedronGeometry;
  322. exports.TextBufferGeometry = TextBufferGeometry;
  323. exports.TextGeometry = TextGeometry;
  324. exports.Texture = Texture;
  325. exports.TextureLoader = TextureLoader;
  326. exports.TorusBufferGeometry = TorusBufferGeometry;
  327. exports.TorusGeometry = TorusGeometry;
  328. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  329. exports.TorusKnotGeometry = TorusKnotGeometry;
  330. exports.Triangle = Triangle;
  331. exports.TubeBufferGeometry = TubeBufferGeometry;
  332. exports.TubeGeometry = TubeGeometry;
  333. exports.Uint16Attribute = Uint16Attribute;
  334. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  335. exports.Uint32Attribute = Uint32Attribute;
  336. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  337. exports.Uint8Attribute = Uint8Attribute;
  338. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  339. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  340. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  341. exports.Uniform = Uniform;
  342. exports.Vector2 = Vector2;
  343. exports.Vector3 = Vector3;
  344. exports.Vector4 = Vector4;
  345. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  346. exports.Vertex = Vertex;
  347. exports.VertexNormalsHelper = VertexNormalsHelper;
  348. exports.VideoTexture = VideoTexture;
  349. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  350. exports.WebGLRenderTarget = WebGLRenderTarget;
  351. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  352. exports.WebGLRenderer = WebGLRenderer;
  353. exports.WebGLUtils = WebGLUtils;
  354. exports.WireframeGeometry = WireframeGeometry;
  355. exports.WireframeHelper = WireframeHelper;
  356. exports.XHRLoader = XHRLoader;
  357. 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;
  358. 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;
  359. // Polyfills
  360. if (Number.EPSILON === undefined) {
  361. Number.EPSILON = Math.pow(2, -52);
  362. }
  363. if (Number.isInteger === undefined) {
  364. // Missing in IE
  365. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
  366. Number.isInteger = function (value) {
  367. return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
  368. };
  369. } //
  370. if (Math.sign === undefined) {
  371. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  372. Math.sign = function (x) {
  373. return x < 0 ? -1 : x > 0 ? 1 : +x;
  374. };
  375. }
  376. if ('name' in Function.prototype === false) {
  377. // Missing in IE
  378. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  379. Object.defineProperty(Function.prototype, 'name', {
  380. get: function () {
  381. return this.toString().match(/^\s*function\s*([^\(\s]*)/)[1];
  382. }
  383. });
  384. }
  385. if (Object.assign === undefined) {
  386. // Missing in IE
  387. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  388. Object.assign = function (target) {
  389. if (target === undefined || target === null) {
  390. throw new TypeError('Cannot convert undefined or null to object');
  391. }
  392. var output = Object(target);
  393. for (var index = 1; index < arguments.length; index++) {
  394. var source = arguments[index];
  395. if (source !== undefined && source !== null) {
  396. for (var nextKey in source) {
  397. if (Object.prototype.hasOwnProperty.call(source, nextKey)) {
  398. output[nextKey] = source[nextKey];
  399. }
  400. }
  401. }
  402. }
  403. return output;
  404. };
  405. }
  406. var REVISION = '109';
  407. exports.REVISION = REVISION;
  408. var MOUSE = {
  409. LEFT: 0,
  410. MIDDLE: 1,
  411. RIGHT: 2,
  412. ROTATE: 0,
  413. DOLLY: 1,
  414. PAN: 2
  415. };
  416. exports.MOUSE = MOUSE;
  417. var TOUCH = {
  418. ROTATE: 0,
  419. PAN: 1,
  420. DOLLY_PAN: 2,
  421. DOLLY_ROTATE: 3
  422. };
  423. exports.TOUCH = TOUCH;
  424. var CullFaceNone = 0;
  425. exports.CullFaceNone = CullFaceNone;
  426. var CullFaceBack = 1;
  427. exports.CullFaceBack = CullFaceBack;
  428. var CullFaceFront = 2;
  429. exports.CullFaceFront = CullFaceFront;
  430. var CullFaceFrontBack = 3;
  431. exports.CullFaceFrontBack = CullFaceFrontBack;
  432. var FrontFaceDirectionCW = 0;
  433. exports.FrontFaceDirectionCW = FrontFaceDirectionCW;
  434. var FrontFaceDirectionCCW = 1;
  435. exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW;
  436. var BasicShadowMap = 0;
  437. exports.BasicShadowMap = BasicShadowMap;
  438. var PCFShadowMap = 1;
  439. exports.PCFShadowMap = PCFShadowMap;
  440. var PCFSoftShadowMap = 2;
  441. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  442. var VSMShadowMap = 3;
  443. exports.VSMShadowMap = VSMShadowMap;
  444. var FrontSide = 0;
  445. exports.FrontSide = FrontSide;
  446. var BackSide = 1;
  447. exports.BackSide = BackSide;
  448. var DoubleSide = 2;
  449. exports.DoubleSide = DoubleSide;
  450. var FlatShading = 1;
  451. exports.FlatShading = FlatShading;
  452. var SmoothShading = 2;
  453. exports.SmoothShading = SmoothShading;
  454. var NoColors = 0;
  455. exports.NoColors = NoColors;
  456. var FaceColors = 1;
  457. exports.FaceColors = FaceColors;
  458. var VertexColors = 2;
  459. exports.VertexColors = VertexColors;
  460. var NoBlending = 0;
  461. exports.NoBlending = NoBlending;
  462. var NormalBlending = 1;
  463. exports.NormalBlending = NormalBlending;
  464. var AdditiveBlending = 2;
  465. exports.AdditiveBlending = AdditiveBlending;
  466. var SubtractiveBlending = 3;
  467. exports.SubtractiveBlending = SubtractiveBlending;
  468. var MultiplyBlending = 4;
  469. exports.MultiplyBlending = MultiplyBlending;
  470. var CustomBlending = 5;
  471. exports.CustomBlending = CustomBlending;
  472. var AddEquation = 100;
  473. exports.AddEquation = AddEquation;
  474. var SubtractEquation = 101;
  475. exports.SubtractEquation = SubtractEquation;
  476. var ReverseSubtractEquation = 102;
  477. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  478. var MinEquation = 103;
  479. exports.MinEquation = MinEquation;
  480. var MaxEquation = 104;
  481. exports.MaxEquation = MaxEquation;
  482. var ZeroFactor = 200;
  483. exports.ZeroFactor = ZeroFactor;
  484. var OneFactor = 201;
  485. exports.OneFactor = OneFactor;
  486. var SrcColorFactor = 202;
  487. exports.SrcColorFactor = SrcColorFactor;
  488. var OneMinusSrcColorFactor = 203;
  489. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  490. var SrcAlphaFactor = 204;
  491. exports.SrcAlphaFactor = SrcAlphaFactor;
  492. var OneMinusSrcAlphaFactor = 205;
  493. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  494. var DstAlphaFactor = 206;
  495. exports.DstAlphaFactor = DstAlphaFactor;
  496. var OneMinusDstAlphaFactor = 207;
  497. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  498. var DstColorFactor = 208;
  499. exports.DstColorFactor = DstColorFactor;
  500. var OneMinusDstColorFactor = 209;
  501. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  502. var SrcAlphaSaturateFactor = 210;
  503. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  504. var NeverDepth = 0;
  505. exports.NeverDepth = NeverDepth;
  506. var AlwaysDepth = 1;
  507. exports.AlwaysDepth = AlwaysDepth;
  508. var LessDepth = 2;
  509. exports.LessDepth = LessDepth;
  510. var LessEqualDepth = 3;
  511. exports.LessEqualDepth = LessEqualDepth;
  512. var EqualDepth = 4;
  513. exports.EqualDepth = EqualDepth;
  514. var GreaterEqualDepth = 5;
  515. exports.GreaterEqualDepth = GreaterEqualDepth;
  516. var GreaterDepth = 6;
  517. exports.GreaterDepth = GreaterDepth;
  518. var NotEqualDepth = 7;
  519. exports.NotEqualDepth = NotEqualDepth;
  520. var MultiplyOperation = 0;
  521. exports.MultiplyOperation = MultiplyOperation;
  522. var MixOperation = 1;
  523. exports.MixOperation = MixOperation;
  524. var AddOperation = 2;
  525. exports.AddOperation = AddOperation;
  526. var NoToneMapping = 0;
  527. exports.NoToneMapping = NoToneMapping;
  528. var LinearToneMapping = 1;
  529. exports.LinearToneMapping = LinearToneMapping;
  530. var ReinhardToneMapping = 2;
  531. exports.ReinhardToneMapping = ReinhardToneMapping;
  532. var Uncharted2ToneMapping = 3;
  533. exports.Uncharted2ToneMapping = Uncharted2ToneMapping;
  534. var CineonToneMapping = 4;
  535. exports.CineonToneMapping = CineonToneMapping;
  536. var ACESFilmicToneMapping = 5;
  537. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  538. var UVMapping = 300;
  539. exports.UVMapping = UVMapping;
  540. var CubeReflectionMapping = 301;
  541. exports.CubeReflectionMapping = CubeReflectionMapping;
  542. var CubeRefractionMapping = 302;
  543. exports.CubeRefractionMapping = CubeRefractionMapping;
  544. var EquirectangularReflectionMapping = 303;
  545. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  546. var EquirectangularRefractionMapping = 304;
  547. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  548. var SphericalReflectionMapping = 305;
  549. exports.SphericalReflectionMapping = SphericalReflectionMapping;
  550. var CubeUVReflectionMapping = 306;
  551. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  552. var CubeUVRefractionMapping = 307;
  553. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  554. var RepeatWrapping = 1000;
  555. exports.RepeatWrapping = RepeatWrapping;
  556. var ClampToEdgeWrapping = 1001;
  557. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  558. var MirroredRepeatWrapping = 1002;
  559. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  560. var NearestFilter = 1003;
  561. exports.NearestFilter = NearestFilter;
  562. var NearestMipmapNearestFilter = 1004;
  563. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  564. var NearestMipMapNearestFilter = 1004;
  565. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  566. var NearestMipmapLinearFilter = 1005;
  567. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  568. var NearestMipMapLinearFilter = 1005;
  569. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  570. var LinearFilter = 1006;
  571. exports.LinearFilter = LinearFilter;
  572. var LinearMipmapNearestFilter = 1007;
  573. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  574. var LinearMipMapNearestFilter = 1007;
  575. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  576. var LinearMipmapLinearFilter = 1008;
  577. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  578. var LinearMipMapLinearFilter = 1008;
  579. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  580. var UnsignedByteType = 1009;
  581. exports.UnsignedByteType = UnsignedByteType;
  582. var ByteType = 1010;
  583. exports.ByteType = ByteType;
  584. var ShortType = 1011;
  585. exports.ShortType = ShortType;
  586. var UnsignedShortType = 1012;
  587. exports.UnsignedShortType = UnsignedShortType;
  588. var IntType = 1013;
  589. exports.IntType = IntType;
  590. var UnsignedIntType = 1014;
  591. exports.UnsignedIntType = UnsignedIntType;
  592. var FloatType = 1015;
  593. exports.FloatType = FloatType;
  594. var HalfFloatType = 1016;
  595. exports.HalfFloatType = HalfFloatType;
  596. var UnsignedShort4444Type = 1017;
  597. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  598. var UnsignedShort5551Type = 1018;
  599. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  600. var UnsignedShort565Type = 1019;
  601. exports.UnsignedShort565Type = UnsignedShort565Type;
  602. var UnsignedInt248Type = 1020;
  603. exports.UnsignedInt248Type = UnsignedInt248Type;
  604. var AlphaFormat = 1021;
  605. exports.AlphaFormat = AlphaFormat;
  606. var RGBFormat = 1022;
  607. exports.RGBFormat = RGBFormat;
  608. var RGBAFormat = 1023;
  609. exports.RGBAFormat = RGBAFormat;
  610. var LuminanceFormat = 1024;
  611. exports.LuminanceFormat = LuminanceFormat;
  612. var LuminanceAlphaFormat = 1025;
  613. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  614. var RGBEFormat = RGBAFormat;
  615. exports.RGBEFormat = RGBEFormat;
  616. var DepthFormat = 1026;
  617. exports.DepthFormat = DepthFormat;
  618. var DepthStencilFormat = 1027;
  619. exports.DepthStencilFormat = DepthStencilFormat;
  620. var RedFormat = 1028;
  621. exports.RedFormat = RedFormat;
  622. var RGB_S3TC_DXT1_Format = 33776;
  623. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  624. var RGBA_S3TC_DXT1_Format = 33777;
  625. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  626. var RGBA_S3TC_DXT3_Format = 33778;
  627. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  628. var RGBA_S3TC_DXT5_Format = 33779;
  629. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  630. var RGB_PVRTC_4BPPV1_Format = 35840;
  631. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  632. var RGB_PVRTC_2BPPV1_Format = 35841;
  633. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  634. var RGBA_PVRTC_4BPPV1_Format = 35842;
  635. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  636. var RGBA_PVRTC_2BPPV1_Format = 35843;
  637. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  638. var RGB_ETC1_Format = 36196;
  639. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  640. var RGBA_ASTC_4x4_Format = 37808;
  641. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  642. var RGBA_ASTC_5x4_Format = 37809;
  643. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  644. var RGBA_ASTC_5x5_Format = 37810;
  645. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  646. var RGBA_ASTC_6x5_Format = 37811;
  647. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  648. var RGBA_ASTC_6x6_Format = 37812;
  649. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  650. var RGBA_ASTC_8x5_Format = 37813;
  651. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  652. var RGBA_ASTC_8x6_Format = 37814;
  653. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  654. var RGBA_ASTC_8x8_Format = 37815;
  655. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  656. var RGBA_ASTC_10x5_Format = 37816;
  657. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  658. var RGBA_ASTC_10x6_Format = 37817;
  659. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  660. var RGBA_ASTC_10x8_Format = 37818;
  661. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  662. var RGBA_ASTC_10x10_Format = 37819;
  663. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  664. var RGBA_ASTC_12x10_Format = 37820;
  665. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  666. var RGBA_ASTC_12x12_Format = 37821;
  667. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  668. var LoopOnce = 2200;
  669. exports.LoopOnce = LoopOnce;
  670. var LoopRepeat = 2201;
  671. exports.LoopRepeat = LoopRepeat;
  672. var LoopPingPong = 2202;
  673. exports.LoopPingPong = LoopPingPong;
  674. var InterpolateDiscrete = 2300;
  675. exports.InterpolateDiscrete = InterpolateDiscrete;
  676. var InterpolateLinear = 2301;
  677. exports.InterpolateLinear = InterpolateLinear;
  678. var InterpolateSmooth = 2302;
  679. exports.InterpolateSmooth = InterpolateSmooth;
  680. var ZeroCurvatureEnding = 2400;
  681. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  682. var ZeroSlopeEnding = 2401;
  683. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  684. var WrapAroundEnding = 2402;
  685. exports.WrapAroundEnding = WrapAroundEnding;
  686. var TrianglesDrawMode = 0;
  687. exports.TrianglesDrawMode = TrianglesDrawMode;
  688. var TriangleStripDrawMode = 1;
  689. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  690. var TriangleFanDrawMode = 2;
  691. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  692. var LinearEncoding = 3000;
  693. exports.LinearEncoding = LinearEncoding;
  694. var sRGBEncoding = 3001;
  695. exports.sRGBEncoding = sRGBEncoding;
  696. var GammaEncoding = 3007;
  697. exports.GammaEncoding = GammaEncoding;
  698. var RGBEEncoding = 3002;
  699. exports.RGBEEncoding = RGBEEncoding;
  700. var LogLuvEncoding = 3003;
  701. exports.LogLuvEncoding = LogLuvEncoding;
  702. var RGBM7Encoding = 3004;
  703. exports.RGBM7Encoding = RGBM7Encoding;
  704. var RGBM16Encoding = 3005;
  705. exports.RGBM16Encoding = RGBM16Encoding;
  706. var RGBDEncoding = 3006;
  707. exports.RGBDEncoding = RGBDEncoding;
  708. var BasicDepthPacking = 3200;
  709. exports.BasicDepthPacking = BasicDepthPacking;
  710. var RGBADepthPacking = 3201;
  711. exports.RGBADepthPacking = RGBADepthPacking;
  712. var TangentSpaceNormalMap = 0;
  713. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  714. var ObjectSpaceNormalMap = 1;
  715. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  716. var ZeroStencilOp = 0;
  717. exports.ZeroStencilOp = ZeroStencilOp;
  718. var KeepStencilOp = 7680;
  719. exports.KeepStencilOp = KeepStencilOp;
  720. var ReplaceStencilOp = 7681;
  721. exports.ReplaceStencilOp = ReplaceStencilOp;
  722. var IncrementStencilOp = 7682;
  723. exports.IncrementStencilOp = IncrementStencilOp;
  724. var DecrementStencilOp = 7683;
  725. exports.DecrementStencilOp = DecrementStencilOp;
  726. var IncrementWrapStencilOp = 34055;
  727. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  728. var DecrementWrapStencilOp = 34056;
  729. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  730. var InvertStencilOp = 5386;
  731. exports.InvertStencilOp = InvertStencilOp;
  732. var NeverStencilFunc = 512;
  733. exports.NeverStencilFunc = NeverStencilFunc;
  734. var LessStencilFunc = 513;
  735. exports.LessStencilFunc = LessStencilFunc;
  736. var EqualStencilFunc = 514;
  737. exports.EqualStencilFunc = EqualStencilFunc;
  738. var LessEqualStencilFunc = 515;
  739. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  740. var GreaterStencilFunc = 516;
  741. exports.GreaterStencilFunc = GreaterStencilFunc;
  742. var NotEqualStencilFunc = 517;
  743. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  744. var GreaterEqualStencilFunc = 518;
  745. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  746. var AlwaysStencilFunc = 519;
  747. /**
  748. * https://github.com/mrdoob/eventdispatcher.js/
  749. */
  750. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  751. function EventDispatcher() {}
  752. Object.assign(EventDispatcher.prototype, {
  753. addEventListener: function (type, listener) {
  754. if (this._listeners === undefined) this._listeners = {};
  755. var listeners = this._listeners;
  756. if (listeners[type] === undefined) {
  757. listeners[type] = [];
  758. }
  759. if (listeners[type].indexOf(listener) === -1) {
  760. listeners[type].push(listener);
  761. }
  762. },
  763. hasEventListener: function (type, listener) {
  764. if (this._listeners === undefined) return false;
  765. var listeners = this._listeners;
  766. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  767. },
  768. removeEventListener: function (type, listener) {
  769. if (this._listeners === undefined) return;
  770. var listeners = this._listeners;
  771. var listenerArray = listeners[type];
  772. if (listenerArray !== undefined) {
  773. var index = listenerArray.indexOf(listener);
  774. if (index !== -1) {
  775. listenerArray.splice(index, 1);
  776. }
  777. }
  778. },
  779. dispatchEvent: function (event) {
  780. if (this._listeners === undefined) return;
  781. var listeners = this._listeners;
  782. var listenerArray = listeners[event.type];
  783. if (listenerArray !== undefined) {
  784. event.target = this;
  785. var array = listenerArray.slice(0);
  786. for (var i = 0, l = array.length; i < l; i++) {
  787. array[i].call(this, event);
  788. }
  789. }
  790. }
  791. });
  792. /**
  793. * @author alteredq / http://alteredqualia.com/
  794. * @author mrdoob / http://mrdoob.com/
  795. */
  796. var _lut = [];
  797. for (var i = 0; i < 256; i++) {
  798. _lut[i] = (i < 16 ? '0' : '') + i.toString(16);
  799. }
  800. var _Math = {
  801. DEG2RAD: Math.PI / 180,
  802. RAD2DEG: 180 / Math.PI,
  803. generateUUID: function () {
  804. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  805. var d0 = Math.random() * 0xffffffff | 0;
  806. var d1 = Math.random() * 0xffffffff | 0;
  807. var d2 = Math.random() * 0xffffffff | 0;
  808. var d3 = Math.random() * 0xffffffff | 0;
  809. 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.
  810. return uuid.toUpperCase();
  811. },
  812. clamp: function (value, min, max) {
  813. return Math.max(min, Math.min(max, value));
  814. },
  815. // compute euclidian modulo of m % n
  816. // https://en.wikipedia.org/wiki/Modulo_operation
  817. euclideanModulo: function (n, m) {
  818. return (n % m + m) % m;
  819. },
  820. // Linear mapping from range <a1, a2> to range <b1, b2>
  821. mapLinear: function (x, a1, a2, b1, b2) {
  822. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  823. },
  824. // https://en.wikipedia.org/wiki/Linear_interpolation
  825. lerp: function (x, y, t) {
  826. return (1 - t) * x + t * y;
  827. },
  828. // http://en.wikipedia.org/wiki/Smoothstep
  829. smoothstep: function (x, min, max) {
  830. if (x <= min) return 0;
  831. if (x >= max) return 1;
  832. x = (x - min) / (max - min);
  833. return x * x * (3 - 2 * x);
  834. },
  835. smootherstep: function (x, min, max) {
  836. if (x <= min) return 0;
  837. if (x >= max) return 1;
  838. x = (x - min) / (max - min);
  839. return x * x * x * (x * (x * 6 - 15) + 10);
  840. },
  841. // Random integer from <low, high> interval
  842. randInt: function (low, high) {
  843. return low + Math.floor(Math.random() * (high - low + 1));
  844. },
  845. // Random float from <low, high> interval
  846. randFloat: function (low, high) {
  847. return low + Math.random() * (high - low);
  848. },
  849. // Random float from <-range/2, range/2> interval
  850. randFloatSpread: function (range) {
  851. return range * (0.5 - Math.random());
  852. },
  853. degToRad: function (degrees) {
  854. return degrees * _Math.DEG2RAD;
  855. },
  856. radToDeg: function (radians) {
  857. return radians * _Math.RAD2DEG;
  858. },
  859. isPowerOfTwo: function (value) {
  860. return (value & value - 1) === 0 && value !== 0;
  861. },
  862. ceilPowerOfTwo: function (value) {
  863. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  864. },
  865. floorPowerOfTwo: function (value) {
  866. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  867. }
  868. };
  869. /**
  870. * @author mrdoob / http://mrdoob.com/
  871. * @author philogb / http://blog.thejit.org/
  872. * @author egraether / http://egraether.com/
  873. * @author zz85 / http://www.lab4games.net/zz85/blog
  874. */
  875. exports.Math = _Math;
  876. function Vector2(x, y) {
  877. this.x = x || 0;
  878. this.y = y || 0;
  879. }
  880. Object.defineProperties(Vector2.prototype, {
  881. "width": {
  882. get: function () {
  883. return this.x;
  884. },
  885. set: function (value) {
  886. this.x = value;
  887. }
  888. },
  889. "height": {
  890. get: function () {
  891. return this.y;
  892. },
  893. set: function (value) {
  894. this.y = value;
  895. }
  896. }
  897. });
  898. Object.assign(Vector2.prototype, {
  899. isVector2: true,
  900. set: function (x, y) {
  901. this.x = x;
  902. this.y = y;
  903. return this;
  904. },
  905. setScalar: function (scalar) {
  906. this.x = scalar;
  907. this.y = scalar;
  908. return this;
  909. },
  910. setX: function (x) {
  911. this.x = x;
  912. return this;
  913. },
  914. setY: function (y) {
  915. this.y = y;
  916. return this;
  917. },
  918. setComponent: function (index, value) {
  919. switch (index) {
  920. case 0:
  921. this.x = value;
  922. break;
  923. case 1:
  924. this.y = value;
  925. break;
  926. default:
  927. throw new Error('index is out of range: ' + index);
  928. }
  929. return this;
  930. },
  931. getComponent: function (index) {
  932. switch (index) {
  933. case 0:
  934. return this.x;
  935. case 1:
  936. return this.y;
  937. default:
  938. throw new Error('index is out of range: ' + index);
  939. }
  940. },
  941. clone: function () {
  942. return new this.constructor(this.x, this.y);
  943. },
  944. copy: function (v) {
  945. this.x = v.x;
  946. this.y = v.y;
  947. return this;
  948. },
  949. add: function (v, w) {
  950. if (w !== undefined) {
  951. console.warn('THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  952. return this.addVectors(v, w);
  953. }
  954. this.x += v.x;
  955. this.y += v.y;
  956. return this;
  957. },
  958. addScalar: function (s) {
  959. this.x += s;
  960. this.y += s;
  961. return this;
  962. },
  963. addVectors: function (a, b) {
  964. this.x = a.x + b.x;
  965. this.y = a.y + b.y;
  966. return this;
  967. },
  968. addScaledVector: function (v, s) {
  969. this.x += v.x * s;
  970. this.y += v.y * s;
  971. return this;
  972. },
  973. sub: function (v, w) {
  974. if (w !== undefined) {
  975. console.warn('THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  976. return this.subVectors(v, w);
  977. }
  978. this.x -= v.x;
  979. this.y -= v.y;
  980. return this;
  981. },
  982. subScalar: function (s) {
  983. this.x -= s;
  984. this.y -= s;
  985. return this;
  986. },
  987. subVectors: function (a, b) {
  988. this.x = a.x - b.x;
  989. this.y = a.y - b.y;
  990. return this;
  991. },
  992. multiply: function (v) {
  993. this.x *= v.x;
  994. this.y *= v.y;
  995. return this;
  996. },
  997. multiplyScalar: function (scalar) {
  998. this.x *= scalar;
  999. this.y *= scalar;
  1000. return this;
  1001. },
  1002. divide: function (v) {
  1003. this.x /= v.x;
  1004. this.y /= v.y;
  1005. return this;
  1006. },
  1007. divideScalar: function (scalar) {
  1008. return this.multiplyScalar(1 / scalar);
  1009. },
  1010. applyMatrix3: function (m) {
  1011. var x = this.x,
  1012. y = this.y;
  1013. var e = m.elements;
  1014. this.x = e[0] * x + e[3] * y + e[6];
  1015. this.y = e[1] * x + e[4] * y + e[7];
  1016. return this;
  1017. },
  1018. min: function (v) {
  1019. this.x = Math.min(this.x, v.x);
  1020. this.y = Math.min(this.y, v.y);
  1021. return this;
  1022. },
  1023. max: function (v) {
  1024. this.x = Math.max(this.x, v.x);
  1025. this.y = Math.max(this.y, v.y);
  1026. return this;
  1027. },
  1028. clamp: function (min, max) {
  1029. // assumes min < max, componentwise
  1030. this.x = Math.max(min.x, Math.min(max.x, this.x));
  1031. this.y = Math.max(min.y, Math.min(max.y, this.y));
  1032. return this;
  1033. },
  1034. clampScalar: function (minVal, maxVal) {
  1035. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  1036. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  1037. return this;
  1038. },
  1039. clampLength: function (min, max) {
  1040. var length = this.length();
  1041. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  1042. },
  1043. floor: function () {
  1044. this.x = Math.floor(this.x);
  1045. this.y = Math.floor(this.y);
  1046. return this;
  1047. },
  1048. ceil: function () {
  1049. this.x = Math.ceil(this.x);
  1050. this.y = Math.ceil(this.y);
  1051. return this;
  1052. },
  1053. round: function () {
  1054. this.x = Math.round(this.x);
  1055. this.y = Math.round(this.y);
  1056. return this;
  1057. },
  1058. roundToZero: function () {
  1059. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  1060. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  1061. return this;
  1062. },
  1063. negate: function () {
  1064. this.x = -this.x;
  1065. this.y = -this.y;
  1066. return this;
  1067. },
  1068. dot: function (v) {
  1069. return this.x * v.x + this.y * v.y;
  1070. },
  1071. cross: function (v) {
  1072. return this.x * v.y - this.y * v.x;
  1073. },
  1074. lengthSq: function () {
  1075. return this.x * this.x + this.y * this.y;
  1076. },
  1077. length: function () {
  1078. return Math.sqrt(this.x * this.x + this.y * this.y);
  1079. },
  1080. manhattanLength: function () {
  1081. return Math.abs(this.x) + Math.abs(this.y);
  1082. },
  1083. normalize: function () {
  1084. return this.divideScalar(this.length() || 1);
  1085. },
  1086. angle: function () {
  1087. // computes the angle in radians with respect to the positive x-axis
  1088. var angle = Math.atan2(this.y, this.x);
  1089. if (angle < 0) angle += 2 * Math.PI;
  1090. return angle;
  1091. },
  1092. distanceTo: function (v) {
  1093. return Math.sqrt(this.distanceToSquared(v));
  1094. },
  1095. distanceToSquared: function (v) {
  1096. var dx = this.x - v.x,
  1097. dy = this.y - v.y;
  1098. return dx * dx + dy * dy;
  1099. },
  1100. manhattanDistanceTo: function (v) {
  1101. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  1102. },
  1103. setLength: function (length) {
  1104. return this.normalize().multiplyScalar(length);
  1105. },
  1106. lerp: function (v, alpha) {
  1107. this.x += (v.x - this.x) * alpha;
  1108. this.y += (v.y - this.y) * alpha;
  1109. return this;
  1110. },
  1111. lerpVectors: function (v1, v2, alpha) {
  1112. return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
  1113. },
  1114. equals: function (v) {
  1115. return v.x === this.x && v.y === this.y;
  1116. },
  1117. fromArray: function (array, offset) {
  1118. if (offset === undefined) offset = 0;
  1119. this.x = array[offset];
  1120. this.y = array[offset + 1];
  1121. return this;
  1122. },
  1123. toArray: function (array, offset) {
  1124. if (array === undefined) array = [];
  1125. if (offset === undefined) offset = 0;
  1126. array[offset] = this.x;
  1127. array[offset + 1] = this.y;
  1128. return array;
  1129. },
  1130. fromBufferAttribute: function (attribute, index, offset) {
  1131. if (offset !== undefined) {
  1132. console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');
  1133. }
  1134. this.x = attribute.getX(index);
  1135. this.y = attribute.getY(index);
  1136. return this;
  1137. },
  1138. rotateAround: function (center, angle) {
  1139. var c = Math.cos(angle),
  1140. s = Math.sin(angle);
  1141. var x = this.x - center.x;
  1142. var y = this.y - center.y;
  1143. this.x = x * c - y * s + center.x;
  1144. this.y = x * s + y * c + center.y;
  1145. return this;
  1146. }
  1147. });
  1148. /**
  1149. * @author mikael emtinger / http://gomo.se/
  1150. * @author alteredq / http://alteredqualia.com/
  1151. * @author WestLangley / http://github.com/WestLangley
  1152. * @author bhouston / http://clara.io
  1153. */
  1154. function Quaternion(x, y, z, w) {
  1155. this._x = x || 0;
  1156. this._y = y || 0;
  1157. this._z = z || 0;
  1158. this._w = w !== undefined ? w : 1;
  1159. }
  1160. Object.assign(Quaternion, {
  1161. slerp: function (qa, qb, qm, t) {
  1162. return qm.copy(qa).slerp(qb, t);
  1163. },
  1164. slerpFlat: function (dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  1165. // fuzz-free, array-based Quaternion SLERP operation
  1166. var x0 = src0[srcOffset0 + 0],
  1167. y0 = src0[srcOffset0 + 1],
  1168. z0 = src0[srcOffset0 + 2],
  1169. w0 = src0[srcOffset0 + 3],
  1170. x1 = src1[srcOffset1 + 0],
  1171. y1 = src1[srcOffset1 + 1],
  1172. z1 = src1[srcOffset1 + 2],
  1173. w1 = src1[srcOffset1 + 3];
  1174. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  1175. var s = 1 - t,
  1176. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1177. dir = cos >= 0 ? 1 : -1,
  1178. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  1179. if (sqrSin > Number.EPSILON) {
  1180. var sin = Math.sqrt(sqrSin),
  1181. len = Math.atan2(sin, cos * dir);
  1182. s = Math.sin(s * len) / sin;
  1183. t = Math.sin(t * len) / sin;
  1184. }
  1185. var tDir = t * dir;
  1186. x0 = x0 * s + x1 * tDir;
  1187. y0 = y0 * s + y1 * tDir;
  1188. z0 = z0 * s + z1 * tDir;
  1189. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  1190. if (s === 1 - t) {
  1191. var f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  1192. x0 *= f;
  1193. y0 *= f;
  1194. z0 *= f;
  1195. w0 *= f;
  1196. }
  1197. }
  1198. dst[dstOffset] = x0;
  1199. dst[dstOffset + 1] = y0;
  1200. dst[dstOffset + 2] = z0;
  1201. dst[dstOffset + 3] = w0;
  1202. }
  1203. });
  1204. Object.defineProperties(Quaternion.prototype, {
  1205. x: {
  1206. get: function () {
  1207. return this._x;
  1208. },
  1209. set: function (value) {
  1210. this._x = value;
  1211. this._onChangeCallback();
  1212. }
  1213. },
  1214. y: {
  1215. get: function () {
  1216. return this._y;
  1217. },
  1218. set: function (value) {
  1219. this._y = value;
  1220. this._onChangeCallback();
  1221. }
  1222. },
  1223. z: {
  1224. get: function () {
  1225. return this._z;
  1226. },
  1227. set: function (value) {
  1228. this._z = value;
  1229. this._onChangeCallback();
  1230. }
  1231. },
  1232. w: {
  1233. get: function () {
  1234. return this._w;
  1235. },
  1236. set: function (value) {
  1237. this._w = value;
  1238. this._onChangeCallback();
  1239. }
  1240. }
  1241. });
  1242. Object.assign(Quaternion.prototype, {
  1243. isQuaternion: true,
  1244. set: function (x, y, z, w) {
  1245. this._x = x;
  1246. this._y = y;
  1247. this._z = z;
  1248. this._w = w;
  1249. this._onChangeCallback();
  1250. return this;
  1251. },
  1252. clone: function () {
  1253. return new this.constructor(this._x, this._y, this._z, this._w);
  1254. },
  1255. copy: function (quaternion) {
  1256. this._x = quaternion.x;
  1257. this._y = quaternion.y;
  1258. this._z = quaternion.z;
  1259. this._w = quaternion.w;
  1260. this._onChangeCallback();
  1261. return this;
  1262. },
  1263. setFromEuler: function (euler, update) {
  1264. if (!(euler && euler.isEuler)) {
  1265. throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
  1266. }
  1267. var x = euler._x,
  1268. y = euler._y,
  1269. z = euler._z,
  1270. order = euler.order; // http://www.mathworks.com/matlabcentral/fileexchange/
  1271. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1272. // content/SpinCalc.m
  1273. var cos = Math.cos;
  1274. var sin = Math.sin;
  1275. var c1 = cos(x / 2);
  1276. var c2 = cos(y / 2);
  1277. var c3 = cos(z / 2);
  1278. var s1 = sin(x / 2);
  1279. var s2 = sin(y / 2);
  1280. var s3 = sin(z / 2);
  1281. if (order === 'XYZ') {
  1282. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1283. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1284. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1285. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1286. } else if (order === 'YXZ') {
  1287. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1288. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1289. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1290. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1291. } else if (order === 'ZXY') {
  1292. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1293. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1294. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1295. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1296. } else if (order === 'ZYX') {
  1297. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1298. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1299. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1300. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1301. } else if (order === 'YZX') {
  1302. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1303. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1304. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1305. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1306. } else if (order === 'XZY') {
  1307. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1308. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1309. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1310. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1311. }
  1312. if (update !== false) this._onChangeCallback();
  1313. return this;
  1314. },
  1315. setFromAxisAngle: function (axis, angle) {
  1316. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1317. // assumes axis is normalized
  1318. var halfAngle = angle / 2,
  1319. s = Math.sin(halfAngle);
  1320. this._x = axis.x * s;
  1321. this._y = axis.y * s;
  1322. this._z = axis.z * s;
  1323. this._w = Math.cos(halfAngle);
  1324. this._onChangeCallback();
  1325. return this;
  1326. },
  1327. setFromRotationMatrix: function (m) {
  1328. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1329. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1330. var te = m.elements,
  1331. m11 = te[0],
  1332. m12 = te[4],
  1333. m13 = te[8],
  1334. m21 = te[1],
  1335. m22 = te[5],
  1336. m23 = te[9],
  1337. m31 = te[2],
  1338. m32 = te[6],
  1339. m33 = te[10],
  1340. trace = m11 + m22 + m33,
  1341. s;
  1342. if (trace > 0) {
  1343. s = 0.5 / Math.sqrt(trace + 1.0);
  1344. this._w = 0.25 / s;
  1345. this._x = (m32 - m23) * s;
  1346. this._y = (m13 - m31) * s;
  1347. this._z = (m21 - m12) * s;
  1348. } else if (m11 > m22 && m11 > m33) {
  1349. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1350. this._w = (m32 - m23) / s;
  1351. this._x = 0.25 * s;
  1352. this._y = (m12 + m21) / s;
  1353. this._z = (m13 + m31) / s;
  1354. } else if (m22 > m33) {
  1355. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1356. this._w = (m13 - m31) / s;
  1357. this._x = (m12 + m21) / s;
  1358. this._y = 0.25 * s;
  1359. this._z = (m23 + m32) / s;
  1360. } else {
  1361. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1362. this._w = (m21 - m12) / s;
  1363. this._x = (m13 + m31) / s;
  1364. this._y = (m23 + m32) / s;
  1365. this._z = 0.25 * s;
  1366. }
  1367. this._onChangeCallback();
  1368. return this;
  1369. },
  1370. setFromUnitVectors: function (vFrom, vTo) {
  1371. // assumes direction vectors vFrom and vTo are normalized
  1372. var EPS = 0.000001;
  1373. var r = vFrom.dot(vTo) + 1;
  1374. if (r < EPS) {
  1375. r = 0;
  1376. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  1377. this._x = -vFrom.y;
  1378. this._y = vFrom.x;
  1379. this._z = 0;
  1380. this._w = r;
  1381. } else {
  1382. this._x = 0;
  1383. this._y = -vFrom.z;
  1384. this._z = vFrom.y;
  1385. this._w = r;
  1386. }
  1387. } else {
  1388. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  1389. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  1390. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  1391. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  1392. this._w = r;
  1393. }
  1394. return this.normalize();
  1395. },
  1396. angleTo: function (q) {
  1397. return 2 * Math.acos(Math.abs(_Math.clamp(this.dot(q), -1, 1)));
  1398. },
  1399. rotateTowards: function (q, step) {
  1400. var angle = this.angleTo(q);
  1401. if (angle === 0) return this;
  1402. var t = Math.min(1, step / angle);
  1403. this.slerp(q, t);
  1404. return this;
  1405. },
  1406. inverse: function () {
  1407. // quaternion is assumed to have unit length
  1408. return this.conjugate();
  1409. },
  1410. conjugate: function () {
  1411. this._x *= -1;
  1412. this._y *= -1;
  1413. this._z *= -1;
  1414. this._onChangeCallback();
  1415. return this;
  1416. },
  1417. dot: function (v) {
  1418. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1419. },
  1420. lengthSq: function () {
  1421. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1422. },
  1423. length: function () {
  1424. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  1425. },
  1426. normalize: function () {
  1427. var l = this.length();
  1428. if (l === 0) {
  1429. this._x = 0;
  1430. this._y = 0;
  1431. this._z = 0;
  1432. this._w = 1;
  1433. } else {
  1434. l = 1 / l;
  1435. this._x = this._x * l;
  1436. this._y = this._y * l;
  1437. this._z = this._z * l;
  1438. this._w = this._w * l;
  1439. }
  1440. this._onChangeCallback();
  1441. return this;
  1442. },
  1443. multiply: function (q, p) {
  1444. if (p !== undefined) {
  1445. console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
  1446. return this.multiplyQuaternions(q, p);
  1447. }
  1448. return this.multiplyQuaternions(this, q);
  1449. },
  1450. premultiply: function (q) {
  1451. return this.multiplyQuaternions(q, this);
  1452. },
  1453. multiplyQuaternions: function (a, b) {
  1454. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  1455. var qax = a._x,
  1456. qay = a._y,
  1457. qaz = a._z,
  1458. qaw = a._w;
  1459. var qbx = b._x,
  1460. qby = b._y,
  1461. qbz = b._z,
  1462. qbw = b._w;
  1463. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  1464. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  1465. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  1466. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  1467. this._onChangeCallback();
  1468. return this;
  1469. },
  1470. slerp: function (qb, t) {
  1471. if (t === 0) return this;
  1472. if (t === 1) return this.copy(qb);
  1473. var x = this._x,
  1474. y = this._y,
  1475. z = this._z,
  1476. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  1477. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  1478. if (cosHalfTheta < 0) {
  1479. this._w = -qb._w;
  1480. this._x = -qb._x;
  1481. this._y = -qb._y;
  1482. this._z = -qb._z;
  1483. cosHalfTheta = -cosHalfTheta;
  1484. } else {
  1485. this.copy(qb);
  1486. }
  1487. if (cosHalfTheta >= 1.0) {
  1488. this._w = w;
  1489. this._x = x;
  1490. this._y = y;
  1491. this._z = z;
  1492. return this;
  1493. }
  1494. var sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  1495. if (sqrSinHalfTheta <= Number.EPSILON) {
  1496. var s = 1 - t;
  1497. this._w = s * w + t * this._w;
  1498. this._x = s * x + t * this._x;
  1499. this._y = s * y + t * this._y;
  1500. this._z = s * z + t * this._z;
  1501. this.normalize();
  1502. this._onChangeCallback();
  1503. return this;
  1504. }
  1505. var sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  1506. var halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  1507. var ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  1508. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  1509. this._w = w * ratioA + this._w * ratioB;
  1510. this._x = x * ratioA + this._x * ratioB;
  1511. this._y = y * ratioA + this._y * ratioB;
  1512. this._z = z * ratioA + this._z * ratioB;
  1513. this._onChangeCallback();
  1514. return this;
  1515. },
  1516. equals: function (quaternion) {
  1517. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  1518. },
  1519. fromArray: function (array, offset) {
  1520. if (offset === undefined) offset = 0;
  1521. this._x = array[offset];
  1522. this._y = array[offset + 1];
  1523. this._z = array[offset + 2];
  1524. this._w = array[offset + 3];
  1525. this._onChangeCallback();
  1526. return this;
  1527. },
  1528. toArray: function (array, offset) {
  1529. if (array === undefined) array = [];
  1530. if (offset === undefined) offset = 0;
  1531. array[offset] = this._x;
  1532. array[offset + 1] = this._y;
  1533. array[offset + 2] = this._z;
  1534. array[offset + 3] = this._w;
  1535. return array;
  1536. },
  1537. _onChange: function (callback) {
  1538. this._onChangeCallback = callback;
  1539. return this;
  1540. },
  1541. _onChangeCallback: function () {}
  1542. });
  1543. /**
  1544. * @author mrdoob / http://mrdoob.com/
  1545. * @author kile / http://kile.stravaganza.org/
  1546. * @author philogb / http://blog.thejit.org/
  1547. * @author mikael emtinger / http://gomo.se/
  1548. * @author egraether / http://egraether.com/
  1549. * @author WestLangley / http://github.com/WestLangley
  1550. */
  1551. var _vector = new Vector3();
  1552. var _quaternion = new Quaternion();
  1553. function Vector3(x, y, z) {
  1554. this.x = x || 0;
  1555. this.y = y || 0;
  1556. this.z = z || 0;
  1557. }
  1558. Object.assign(Vector3.prototype, {
  1559. isVector3: true,
  1560. set: function (x, y, z) {
  1561. this.x = x;
  1562. this.y = y;
  1563. this.z = z;
  1564. return this;
  1565. },
  1566. setScalar: function (scalar) {
  1567. this.x = scalar;
  1568. this.y = scalar;
  1569. this.z = scalar;
  1570. return this;
  1571. },
  1572. setX: function (x) {
  1573. this.x = x;
  1574. return this;
  1575. },
  1576. setY: function (y) {
  1577. this.y = y;
  1578. return this;
  1579. },
  1580. setZ: function (z) {
  1581. this.z = z;
  1582. return this;
  1583. },
  1584. setComponent: function (index, value) {
  1585. switch (index) {
  1586. case 0:
  1587. this.x = value;
  1588. break;
  1589. case 1:
  1590. this.y = value;
  1591. break;
  1592. case 2:
  1593. this.z = value;
  1594. break;
  1595. default:
  1596. throw new Error('index is out of range: ' + index);
  1597. }
  1598. return this;
  1599. },
  1600. getComponent: function (index) {
  1601. switch (index) {
  1602. case 0:
  1603. return this.x;
  1604. case 1:
  1605. return this.y;
  1606. case 2:
  1607. return this.z;
  1608. default:
  1609. throw new Error('index is out of range: ' + index);
  1610. }
  1611. },
  1612. clone: function () {
  1613. return new this.constructor(this.x, this.y, this.z);
  1614. },
  1615. copy: function (v) {
  1616. this.x = v.x;
  1617. this.y = v.y;
  1618. this.z = v.z;
  1619. return this;
  1620. },
  1621. add: function (v, w) {
  1622. if (w !== undefined) {
  1623. console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  1624. return this.addVectors(v, w);
  1625. }
  1626. this.x += v.x;
  1627. this.y += v.y;
  1628. this.z += v.z;
  1629. return this;
  1630. },
  1631. addScalar: function (s) {
  1632. this.x += s;
  1633. this.y += s;
  1634. this.z += s;
  1635. return this;
  1636. },
  1637. addVectors: function (a, b) {
  1638. this.x = a.x + b.x;
  1639. this.y = a.y + b.y;
  1640. this.z = a.z + b.z;
  1641. return this;
  1642. },
  1643. addScaledVector: function (v, s) {
  1644. this.x += v.x * s;
  1645. this.y += v.y * s;
  1646. this.z += v.z * s;
  1647. return this;
  1648. },
  1649. sub: function (v, w) {
  1650. if (w !== undefined) {
  1651. console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  1652. return this.subVectors(v, w);
  1653. }
  1654. this.x -= v.x;
  1655. this.y -= v.y;
  1656. this.z -= v.z;
  1657. return this;
  1658. },
  1659. subScalar: function (s) {
  1660. this.x -= s;
  1661. this.y -= s;
  1662. this.z -= s;
  1663. return this;
  1664. },
  1665. subVectors: function (a, b) {
  1666. this.x = a.x - b.x;
  1667. this.y = a.y - b.y;
  1668. this.z = a.z - b.z;
  1669. return this;
  1670. },
  1671. multiply: function (v, w) {
  1672. if (w !== undefined) {
  1673. console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');
  1674. return this.multiplyVectors(v, w);
  1675. }
  1676. this.x *= v.x;
  1677. this.y *= v.y;
  1678. this.z *= v.z;
  1679. return this;
  1680. },
  1681. multiplyScalar: function (scalar) {
  1682. this.x *= scalar;
  1683. this.y *= scalar;
  1684. this.z *= scalar;
  1685. return this;
  1686. },
  1687. multiplyVectors: function (a, b) {
  1688. this.x = a.x * b.x;
  1689. this.y = a.y * b.y;
  1690. this.z = a.z * b.z;
  1691. return this;
  1692. },
  1693. applyEuler: function (euler) {
  1694. if (!(euler && euler.isEuler)) {
  1695. console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
  1696. }
  1697. return this.applyQuaternion(_quaternion.setFromEuler(euler));
  1698. },
  1699. applyAxisAngle: function (axis, angle) {
  1700. return this.applyQuaternion(_quaternion.setFromAxisAngle(axis, angle));
  1701. },
  1702. applyMatrix3: function (m) {
  1703. var x = this.x,
  1704. y = this.y,
  1705. z = this.z;
  1706. var e = m.elements;
  1707. this.x = e[0] * x + e[3] * y + e[6] * z;
  1708. this.y = e[1] * x + e[4] * y + e[7] * z;
  1709. this.z = e[2] * x + e[5] * y + e[8] * z;
  1710. return this;
  1711. },
  1712. applyMatrix4: function (m) {
  1713. var x = this.x,
  1714. y = this.y,
  1715. z = this.z;
  1716. var e = m.elements;
  1717. var w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  1718. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  1719. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  1720. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  1721. return this;
  1722. },
  1723. applyQuaternion: function (q) {
  1724. var x = this.x,
  1725. y = this.y,
  1726. z = this.z;
  1727. var qx = q.x,
  1728. qy = q.y,
  1729. qz = q.z,
  1730. qw = q.w; // calculate quat * vector
  1731. var ix = qw * x + qy * z - qz * y;
  1732. var iy = qw * y + qz * x - qx * z;
  1733. var iz = qw * z + qx * y - qy * x;
  1734. var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  1735. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  1736. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  1737. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  1738. return this;
  1739. },
  1740. project: function (camera) {
  1741. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  1742. },
  1743. unproject: function (camera) {
  1744. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  1745. },
  1746. transformDirection: function (m) {
  1747. // input: THREE.Matrix4 affine matrix
  1748. // vector interpreted as a direction
  1749. var x = this.x,
  1750. y = this.y,
  1751. z = this.z;
  1752. var e = m.elements;
  1753. this.x = e[0] * x + e[4] * y + e[8] * z;
  1754. this.y = e[1] * x + e[5] * y + e[9] * z;
  1755. this.z = e[2] * x + e[6] * y + e[10] * z;
  1756. return this.normalize();
  1757. },
  1758. divide: function (v) {
  1759. this.x /= v.x;
  1760. this.y /= v.y;
  1761. this.z /= v.z;
  1762. return this;
  1763. },
  1764. divideScalar: function (scalar) {
  1765. return this.multiplyScalar(1 / scalar);
  1766. },
  1767. min: function (v) {
  1768. this.x = Math.min(this.x, v.x);
  1769. this.y = Math.min(this.y, v.y);
  1770. this.z = Math.min(this.z, v.z);
  1771. return this;
  1772. },
  1773. max: function (v) {
  1774. this.x = Math.max(this.x, v.x);
  1775. this.y = Math.max(this.y, v.y);
  1776. this.z = Math.max(this.z, v.z);
  1777. return this;
  1778. },
  1779. clamp: function (min, max) {
  1780. // assumes min < max, componentwise
  1781. this.x = Math.max(min.x, Math.min(max.x, this.x));
  1782. this.y = Math.max(min.y, Math.min(max.y, this.y));
  1783. this.z = Math.max(min.z, Math.min(max.z, this.z));
  1784. return this;
  1785. },
  1786. clampScalar: function (minVal, maxVal) {
  1787. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  1788. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  1789. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  1790. return this;
  1791. },
  1792. clampLength: function (min, max) {
  1793. var length = this.length();
  1794. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  1795. },
  1796. floor: function () {
  1797. this.x = Math.floor(this.x);
  1798. this.y = Math.floor(this.y);
  1799. this.z = Math.floor(this.z);
  1800. return this;
  1801. },
  1802. ceil: function () {
  1803. this.x = Math.ceil(this.x);
  1804. this.y = Math.ceil(this.y);
  1805. this.z = Math.ceil(this.z);
  1806. return this;
  1807. },
  1808. round: function () {
  1809. this.x = Math.round(this.x);
  1810. this.y = Math.round(this.y);
  1811. this.z = Math.round(this.z);
  1812. return this;
  1813. },
  1814. roundToZero: function () {
  1815. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  1816. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  1817. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  1818. return this;
  1819. },
  1820. negate: function () {
  1821. this.x = -this.x;
  1822. this.y = -this.y;
  1823. this.z = -this.z;
  1824. return this;
  1825. },
  1826. dot: function (v) {
  1827. return this.x * v.x + this.y * v.y + this.z * v.z;
  1828. },
  1829. // TODO lengthSquared?
  1830. lengthSq: function () {
  1831. return this.x * this.x + this.y * this.y + this.z * this.z;
  1832. },
  1833. length: function () {
  1834. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1835. },
  1836. manhattanLength: function () {
  1837. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  1838. },
  1839. normalize: function () {
  1840. return this.divideScalar(this.length() || 1);
  1841. },
  1842. setLength: function (length) {
  1843. return this.normalize().multiplyScalar(length);
  1844. },
  1845. lerp: function (v, alpha) {
  1846. this.x += (v.x - this.x) * alpha;
  1847. this.y += (v.y - this.y) * alpha;
  1848. this.z += (v.z - this.z) * alpha;
  1849. return this;
  1850. },
  1851. lerpVectors: function (v1, v2, alpha) {
  1852. return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
  1853. },
  1854. cross: function (v, w) {
  1855. if (w !== undefined) {
  1856. console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
  1857. return this.crossVectors(v, w);
  1858. }
  1859. return this.crossVectors(this, v);
  1860. },
  1861. crossVectors: function (a, b) {
  1862. var ax = a.x,
  1863. ay = a.y,
  1864. az = a.z;
  1865. var bx = b.x,
  1866. by = b.y,
  1867. bz = b.z;
  1868. this.x = ay * bz - az * by;
  1869. this.y = az * bx - ax * bz;
  1870. this.z = ax * by - ay * bx;
  1871. return this;
  1872. },
  1873. projectOnVector: function (v) {
  1874. // v cannot be the zero v
  1875. var scalar = v.dot(this) / v.lengthSq();
  1876. return this.copy(v).multiplyScalar(scalar);
  1877. },
  1878. projectOnPlane: function (planeNormal) {
  1879. _vector.copy(this).projectOnVector(planeNormal);
  1880. return this.sub(_vector);
  1881. },
  1882. reflect: function (normal) {
  1883. // reflect incident vector off plane orthogonal to normal
  1884. // normal is assumed to have unit length
  1885. return this.sub(_vector.copy(normal).multiplyScalar(2 * this.dot(normal)));
  1886. },
  1887. angleTo: function (v) {
  1888. var denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  1889. if (denominator === 0) console.error('THREE.Vector3: angleTo() can\'t handle zero length vectors.');
  1890. var theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  1891. return Math.acos(_Math.clamp(theta, -1, 1));
  1892. },
  1893. distanceTo: function (v) {
  1894. return Math.sqrt(this.distanceToSquared(v));
  1895. },
  1896. distanceToSquared: function (v) {
  1897. var dx = this.x - v.x,
  1898. dy = this.y - v.y,
  1899. dz = this.z - v.z;
  1900. return dx * dx + dy * dy + dz * dz;
  1901. },
  1902. manhattanDistanceTo: function (v) {
  1903. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  1904. },
  1905. setFromSpherical: function (s) {
  1906. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  1907. },
  1908. setFromSphericalCoords: function (radius, phi, theta) {
  1909. var sinPhiRadius = Math.sin(phi) * radius;
  1910. this.x = sinPhiRadius * Math.sin(theta);
  1911. this.y = Math.cos(phi) * radius;
  1912. this.z = sinPhiRadius * Math.cos(theta);
  1913. return this;
  1914. },
  1915. setFromCylindrical: function (c) {
  1916. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  1917. },
  1918. setFromCylindricalCoords: function (radius, theta, y) {
  1919. this.x = radius * Math.sin(theta);
  1920. this.y = y;
  1921. this.z = radius * Math.cos(theta);
  1922. return this;
  1923. },
  1924. setFromMatrixPosition: function (m) {
  1925. var e = m.elements;
  1926. this.x = e[12];
  1927. this.y = e[13];
  1928. this.z = e[14];
  1929. return this;
  1930. },
  1931. setFromMatrixScale: function (m) {
  1932. var sx = this.setFromMatrixColumn(m, 0).length();
  1933. var sy = this.setFromMatrixColumn(m, 1).length();
  1934. var sz = this.setFromMatrixColumn(m, 2).length();
  1935. this.x = sx;
  1936. this.y = sy;
  1937. this.z = sz;
  1938. return this;
  1939. },
  1940. setFromMatrixColumn: function (m, index) {
  1941. return this.fromArray(m.elements, index * 4);
  1942. },
  1943. equals: function (v) {
  1944. return v.x === this.x && v.y === this.y && v.z === this.z;
  1945. },
  1946. fromArray: function (array, offset) {
  1947. if (offset === undefined) offset = 0;
  1948. this.x = array[offset];
  1949. this.y = array[offset + 1];
  1950. this.z = array[offset + 2];
  1951. return this;
  1952. },
  1953. toArray: function (array, offset) {
  1954. if (array === undefined) array = [];
  1955. if (offset === undefined) offset = 0;
  1956. array[offset] = this.x;
  1957. array[offset + 1] = this.y;
  1958. array[offset + 2] = this.z;
  1959. return array;
  1960. },
  1961. fromBufferAttribute: function (attribute, index, offset) {
  1962. if (offset !== undefined) {
  1963. console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
  1964. }
  1965. this.x = attribute.getX(index);
  1966. this.y = attribute.getY(index);
  1967. this.z = attribute.getZ(index);
  1968. return this;
  1969. }
  1970. });
  1971. /**
  1972. * @author alteredq / http://alteredqualia.com/
  1973. * @author WestLangley / http://github.com/WestLangley
  1974. * @author bhouston / http://clara.io
  1975. * @author tschw
  1976. */
  1977. var _vector$1 = new Vector3();
  1978. function Matrix3() {
  1979. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  1980. if (arguments.length > 0) {
  1981. console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');
  1982. }
  1983. }
  1984. Object.assign(Matrix3.prototype, {
  1985. isMatrix3: true,
  1986. set: function (n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  1987. var te = this.elements;
  1988. te[0] = n11;
  1989. te[1] = n21;
  1990. te[2] = n31;
  1991. te[3] = n12;
  1992. te[4] = n22;
  1993. te[5] = n32;
  1994. te[6] = n13;
  1995. te[7] = n23;
  1996. te[8] = n33;
  1997. return this;
  1998. },
  1999. identity: function () {
  2000. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  2001. return this;
  2002. },
  2003. clone: function () {
  2004. return new this.constructor().fromArray(this.elements);
  2005. },
  2006. copy: function (m) {
  2007. var te = this.elements;
  2008. var me = m.elements;
  2009. te[0] = me[0];
  2010. te[1] = me[1];
  2011. te[2] = me[2];
  2012. te[3] = me[3];
  2013. te[4] = me[4];
  2014. te[5] = me[5];
  2015. te[6] = me[6];
  2016. te[7] = me[7];
  2017. te[8] = me[8];
  2018. return this;
  2019. },
  2020. setFromMatrix4: function (m) {
  2021. var me = m.elements;
  2022. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  2023. return this;
  2024. },
  2025. applyToBufferAttribute: function (attribute) {
  2026. for (var i = 0, l = attribute.count; i < l; i++) {
  2027. _vector$1.x = attribute.getX(i);
  2028. _vector$1.y = attribute.getY(i);
  2029. _vector$1.z = attribute.getZ(i);
  2030. _vector$1.applyMatrix3(this);
  2031. attribute.setXYZ(i, _vector$1.x, _vector$1.y, _vector$1.z);
  2032. }
  2033. return attribute;
  2034. },
  2035. multiply: function (m) {
  2036. return this.multiplyMatrices(this, m);
  2037. },
  2038. premultiply: function (m) {
  2039. return this.multiplyMatrices(m, this);
  2040. },
  2041. multiplyMatrices: function (a, b) {
  2042. var ae = a.elements;
  2043. var be = b.elements;
  2044. var te = this.elements;
  2045. var a11 = ae[0],
  2046. a12 = ae[3],
  2047. a13 = ae[6];
  2048. var a21 = ae[1],
  2049. a22 = ae[4],
  2050. a23 = ae[7];
  2051. var a31 = ae[2],
  2052. a32 = ae[5],
  2053. a33 = ae[8];
  2054. var b11 = be[0],
  2055. b12 = be[3],
  2056. b13 = be[6];
  2057. var b21 = be[1],
  2058. b22 = be[4],
  2059. b23 = be[7];
  2060. var b31 = be[2],
  2061. b32 = be[5],
  2062. b33 = be[8];
  2063. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  2064. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  2065. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  2066. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  2067. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  2068. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  2069. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  2070. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  2071. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  2072. return this;
  2073. },
  2074. multiplyScalar: function (s) {
  2075. var te = this.elements;
  2076. te[0] *= s;
  2077. te[3] *= s;
  2078. te[6] *= s;
  2079. te[1] *= s;
  2080. te[4] *= s;
  2081. te[7] *= s;
  2082. te[2] *= s;
  2083. te[5] *= s;
  2084. te[8] *= s;
  2085. return this;
  2086. },
  2087. determinant: function () {
  2088. var te = this.elements;
  2089. var a = te[0],
  2090. b = te[1],
  2091. c = te[2],
  2092. d = te[3],
  2093. e = te[4],
  2094. f = te[5],
  2095. g = te[6],
  2096. h = te[7],
  2097. i = te[8];
  2098. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  2099. },
  2100. getInverse: function (matrix, throwOnDegenerate) {
  2101. if (matrix && matrix.isMatrix4) {
  2102. console.error("THREE.Matrix3: .getInverse() no longer takes a Matrix4 argument.");
  2103. }
  2104. var me = matrix.elements,
  2105. te = this.elements,
  2106. n11 = me[0],
  2107. n21 = me[1],
  2108. n31 = me[2],
  2109. n12 = me[3],
  2110. n22 = me[4],
  2111. n32 = me[5],
  2112. n13 = me[6],
  2113. n23 = me[7],
  2114. n33 = me[8],
  2115. t11 = n33 * n22 - n32 * n23,
  2116. t12 = n32 * n13 - n33 * n12,
  2117. t13 = n23 * n12 - n22 * n13,
  2118. det = n11 * t11 + n21 * t12 + n31 * t13;
  2119. if (det === 0) {
  2120. var msg = "THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0";
  2121. if (throwOnDegenerate === true) {
  2122. throw new Error(msg);
  2123. } else {
  2124. console.warn(msg);
  2125. }
  2126. return this.identity();
  2127. }
  2128. var detInv = 1 / det;
  2129. te[0] = t11 * detInv;
  2130. te[1] = (n31 * n23 - n33 * n21) * detInv;
  2131. te[2] = (n32 * n21 - n31 * n22) * detInv;
  2132. te[3] = t12 * detInv;
  2133. te[4] = (n33 * n11 - n31 * n13) * detInv;
  2134. te[5] = (n31 * n12 - n32 * n11) * detInv;
  2135. te[6] = t13 * detInv;
  2136. te[7] = (n21 * n13 - n23 * n11) * detInv;
  2137. te[8] = (n22 * n11 - n21 * n12) * detInv;
  2138. return this;
  2139. },
  2140. transpose: function () {
  2141. var tmp,
  2142. m = this.elements;
  2143. tmp = m[1];
  2144. m[1] = m[3];
  2145. m[3] = tmp;
  2146. tmp = m[2];
  2147. m[2] = m[6];
  2148. m[6] = tmp;
  2149. tmp = m[5];
  2150. m[5] = m[7];
  2151. m[7] = tmp;
  2152. return this;
  2153. },
  2154. getNormalMatrix: function (matrix4) {
  2155. return this.setFromMatrix4(matrix4).getInverse(this).transpose();
  2156. },
  2157. transposeIntoArray: function (r) {
  2158. var m = this.elements;
  2159. r[0] = m[0];
  2160. r[1] = m[3];
  2161. r[2] = m[6];
  2162. r[3] = m[1];
  2163. r[4] = m[4];
  2164. r[5] = m[7];
  2165. r[6] = m[2];
  2166. r[7] = m[5];
  2167. r[8] = m[8];
  2168. return this;
  2169. },
  2170. setUvTransform: function (tx, ty, sx, sy, rotation, cx, cy) {
  2171. var c = Math.cos(rotation);
  2172. var s = Math.sin(rotation);
  2173. 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);
  2174. },
  2175. scale: function (sx, sy) {
  2176. var te = this.elements;
  2177. te[0] *= sx;
  2178. te[3] *= sx;
  2179. te[6] *= sx;
  2180. te[1] *= sy;
  2181. te[4] *= sy;
  2182. te[7] *= sy;
  2183. return this;
  2184. },
  2185. rotate: function (theta) {
  2186. var c = Math.cos(theta);
  2187. var s = Math.sin(theta);
  2188. var te = this.elements;
  2189. var a11 = te[0],
  2190. a12 = te[3],
  2191. a13 = te[6];
  2192. var a21 = te[1],
  2193. a22 = te[4],
  2194. a23 = te[7];
  2195. te[0] = c * a11 + s * a21;
  2196. te[3] = c * a12 + s * a22;
  2197. te[6] = c * a13 + s * a23;
  2198. te[1] = -s * a11 + c * a21;
  2199. te[4] = -s * a12 + c * a22;
  2200. te[7] = -s * a13 + c * a23;
  2201. return this;
  2202. },
  2203. translate: function (tx, ty) {
  2204. var te = this.elements;
  2205. te[0] += tx * te[2];
  2206. te[3] += tx * te[5];
  2207. te[6] += tx * te[8];
  2208. te[1] += ty * te[2];
  2209. te[4] += ty * te[5];
  2210. te[7] += ty * te[8];
  2211. return this;
  2212. },
  2213. equals: function (matrix) {
  2214. var te = this.elements;
  2215. var me = matrix.elements;
  2216. for (var i = 0; i < 9; i++) {
  2217. if (te[i] !== me[i]) return false;
  2218. }
  2219. return true;
  2220. },
  2221. fromArray: function (array, offset) {
  2222. if (offset === undefined) offset = 0;
  2223. for (var i = 0; i < 9; i++) {
  2224. this.elements[i] = array[i + offset];
  2225. }
  2226. return this;
  2227. },
  2228. toArray: function (array, offset) {
  2229. if (array === undefined) array = [];
  2230. if (offset === undefined) offset = 0;
  2231. var te = this.elements;
  2232. array[offset] = te[0];
  2233. array[offset + 1] = te[1];
  2234. array[offset + 2] = te[2];
  2235. array[offset + 3] = te[3];
  2236. array[offset + 4] = te[4];
  2237. array[offset + 5] = te[5];
  2238. array[offset + 6] = te[6];
  2239. array[offset + 7] = te[7];
  2240. array[offset + 8] = te[8];
  2241. return array;
  2242. }
  2243. });
  2244. /**
  2245. * @author mrdoob / http://mrdoob.com/
  2246. * @author alteredq / http://alteredqualia.com/
  2247. * @author szimek / https://github.com/szimek/
  2248. */
  2249. var _canvas;
  2250. var ImageUtils = {
  2251. getDataURL: function (image) {
  2252. var canvas;
  2253. if (typeof HTMLCanvasElement == 'undefined') {
  2254. return image.src;
  2255. } else if (image instanceof HTMLCanvasElement) {
  2256. canvas = image;
  2257. } else {
  2258. if (_canvas === undefined) _canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  2259. _canvas.width = image.width;
  2260. _canvas.height = image.height;
  2261. var context = _canvas.getContext('2d');
  2262. if (image instanceof ImageData) {
  2263. context.putImageData(image, 0, 0);
  2264. } else {
  2265. context.drawImage(image, 0, 0, image.width, image.height);
  2266. }
  2267. canvas = _canvas;
  2268. }
  2269. if (canvas.width > 2048 || canvas.height > 2048) {
  2270. return canvas.toDataURL('image/jpeg', 0.6);
  2271. } else {
  2272. return canvas.toDataURL('image/png');
  2273. }
  2274. }
  2275. };
  2276. /**
  2277. * @author mrdoob / http://mrdoob.com/
  2278. * @author alteredq / http://alteredqualia.com/
  2279. * @author szimek / https://github.com/szimek/
  2280. */
  2281. exports.ImageUtils = ImageUtils;
  2282. var textureId = 0;
  2283. function Texture(image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  2284. Object.defineProperty(this, 'id', {
  2285. value: textureId++
  2286. });
  2287. this.uuid = _Math.generateUUID();
  2288. this.name = '';
  2289. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  2290. this.mipmaps = [];
  2291. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  2292. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  2293. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  2294. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  2295. this.minFilter = minFilter !== undefined ? minFilter : LinearMipmapLinearFilter;
  2296. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  2297. this.format = format !== undefined ? format : RGBAFormat;
  2298. this.type = type !== undefined ? type : UnsignedByteType;
  2299. this.offset = new Vector2(0, 0);
  2300. this.repeat = new Vector2(1, 1);
  2301. this.center = new Vector2(0, 0);
  2302. this.rotation = 0;
  2303. this.matrixAutoUpdate = true;
  2304. this.matrix = new Matrix3();
  2305. this.generateMipmaps = true;
  2306. this.premultiplyAlpha = false;
  2307. this.flipY = true;
  2308. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  2309. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  2310. //
  2311. // Also changing the encoding after already used by a Material will not automatically make the Material
  2312. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  2313. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  2314. this.version = 0;
  2315. this.onUpdate = null;
  2316. }
  2317. Texture.DEFAULT_IMAGE = undefined;
  2318. Texture.DEFAULT_MAPPING = UVMapping;
  2319. Texture.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  2320. constructor: Texture,
  2321. isTexture: true,
  2322. updateMatrix: function () {
  2323. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  2324. },
  2325. clone: function () {
  2326. return new this.constructor().copy(this);
  2327. },
  2328. copy: function (source) {
  2329. this.name = source.name;
  2330. this.image = source.image;
  2331. this.mipmaps = source.mipmaps.slice(0);
  2332. this.mapping = source.mapping;
  2333. this.wrapS = source.wrapS;
  2334. this.wrapT = source.wrapT;
  2335. this.magFilter = source.magFilter;
  2336. this.minFilter = source.minFilter;
  2337. this.anisotropy = source.anisotropy;
  2338. this.format = source.format;
  2339. this.type = source.type;
  2340. this.offset.copy(source.offset);
  2341. this.repeat.copy(source.repeat);
  2342. this.center.copy(source.center);
  2343. this.rotation = source.rotation;
  2344. this.matrixAutoUpdate = source.matrixAutoUpdate;
  2345. this.matrix.copy(source.matrix);
  2346. this.generateMipmaps = source.generateMipmaps;
  2347. this.premultiplyAlpha = source.premultiplyAlpha;
  2348. this.flipY = source.flipY;
  2349. this.unpackAlignment = source.unpackAlignment;
  2350. this.encoding = source.encoding;
  2351. return this;
  2352. },
  2353. toJSON: function (meta) {
  2354. var isRootObject = meta === undefined || typeof meta === 'string';
  2355. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  2356. return meta.textures[this.uuid];
  2357. }
  2358. var output = {
  2359. metadata: {
  2360. version: 4.5,
  2361. type: 'Texture',
  2362. generator: 'Texture.toJSON'
  2363. },
  2364. uuid: this.uuid,
  2365. name: this.name,
  2366. mapping: this.mapping,
  2367. repeat: [this.repeat.x, this.repeat.y],
  2368. offset: [this.offset.x, this.offset.y],
  2369. center: [this.center.x, this.center.y],
  2370. rotation: this.rotation,
  2371. wrap: [this.wrapS, this.wrapT],
  2372. format: this.format,
  2373. type: this.type,
  2374. encoding: this.encoding,
  2375. minFilter: this.minFilter,
  2376. magFilter: this.magFilter,
  2377. anisotropy: this.anisotropy,
  2378. flipY: this.flipY,
  2379. premultiplyAlpha: this.premultiplyAlpha,
  2380. unpackAlignment: this.unpackAlignment
  2381. };
  2382. if (this.image !== undefined) {
  2383. // TODO: Move to THREE.Image
  2384. var image = this.image;
  2385. if (image.uuid === undefined) {
  2386. image.uuid = _Math.generateUUID(); // UGH
  2387. }
  2388. if (!isRootObject && meta.images[image.uuid] === undefined) {
  2389. var url;
  2390. if (Array.isArray(image)) {
  2391. // process array of images e.g. CubeTexture
  2392. url = [];
  2393. for (var i = 0, l = image.length; i < l; i++) {
  2394. url.push(ImageUtils.getDataURL(image[i]));
  2395. }
  2396. } else {
  2397. // process single image
  2398. url = ImageUtils.getDataURL(image);
  2399. }
  2400. meta.images[image.uuid] = {
  2401. uuid: image.uuid,
  2402. url: url
  2403. };
  2404. }
  2405. output.image = image.uuid;
  2406. }
  2407. if (!isRootObject) {
  2408. meta.textures[this.uuid] = output;
  2409. }
  2410. return output;
  2411. },
  2412. dispose: function () {
  2413. this.dispatchEvent({
  2414. type: 'dispose'
  2415. });
  2416. },
  2417. transformUv: function (uv) {
  2418. if (this.mapping !== UVMapping) return uv;
  2419. uv.applyMatrix3(this.matrix);
  2420. if (uv.x < 0 || uv.x > 1) {
  2421. switch (this.wrapS) {
  2422. case RepeatWrapping:
  2423. uv.x = uv.x - Math.floor(uv.x);
  2424. break;
  2425. case ClampToEdgeWrapping:
  2426. uv.x = uv.x < 0 ? 0 : 1;
  2427. break;
  2428. case MirroredRepeatWrapping:
  2429. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  2430. uv.x = Math.ceil(uv.x) - uv.x;
  2431. } else {
  2432. uv.x = uv.x - Math.floor(uv.x);
  2433. }
  2434. break;
  2435. }
  2436. }
  2437. if (uv.y < 0 || uv.y > 1) {
  2438. switch (this.wrapT) {
  2439. case RepeatWrapping:
  2440. uv.y = uv.y - Math.floor(uv.y);
  2441. break;
  2442. case ClampToEdgeWrapping:
  2443. uv.y = uv.y < 0 ? 0 : 1;
  2444. break;
  2445. case MirroredRepeatWrapping:
  2446. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  2447. uv.y = Math.ceil(uv.y) - uv.y;
  2448. } else {
  2449. uv.y = uv.y - Math.floor(uv.y);
  2450. }
  2451. break;
  2452. }
  2453. }
  2454. if (this.flipY) {
  2455. uv.y = 1 - uv.y;
  2456. }
  2457. return uv;
  2458. }
  2459. });
  2460. Object.defineProperty(Texture.prototype, "needsUpdate", {
  2461. set: function (value) {
  2462. if (value === true) this.version++;
  2463. }
  2464. });
  2465. /**
  2466. * @author supereggbert / http://www.paulbrunt.co.uk/
  2467. * @author philogb / http://blog.thejit.org/
  2468. * @author mikael emtinger / http://gomo.se/
  2469. * @author egraether / http://egraether.com/
  2470. * @author WestLangley / http://github.com/WestLangley
  2471. */
  2472. function Vector4(x, y, z, w) {
  2473. this.x = x || 0;
  2474. this.y = y || 0;
  2475. this.z = z || 0;
  2476. this.w = w !== undefined ? w : 1;
  2477. }
  2478. Object.defineProperties(Vector4.prototype, {
  2479. "width": {
  2480. get: function () {
  2481. return this.z;
  2482. },
  2483. set: function (value) {
  2484. this.z = value;
  2485. }
  2486. },
  2487. "height": {
  2488. get: function () {
  2489. return this.w;
  2490. },
  2491. set: function (value) {
  2492. this.w = value;
  2493. }
  2494. }
  2495. });
  2496. Object.assign(Vector4.prototype, {
  2497. isVector4: true,
  2498. set: function (x, y, z, w) {
  2499. this.x = x;
  2500. this.y = y;
  2501. this.z = z;
  2502. this.w = w;
  2503. return this;
  2504. },
  2505. setScalar: function (scalar) {
  2506. this.x = scalar;
  2507. this.y = scalar;
  2508. this.z = scalar;
  2509. this.w = scalar;
  2510. return this;
  2511. },
  2512. setX: function (x) {
  2513. this.x = x;
  2514. return this;
  2515. },
  2516. setY: function (y) {
  2517. this.y = y;
  2518. return this;
  2519. },
  2520. setZ: function (z) {
  2521. this.z = z;
  2522. return this;
  2523. },
  2524. setW: function (w) {
  2525. this.w = w;
  2526. return this;
  2527. },
  2528. setComponent: function (index, value) {
  2529. switch (index) {
  2530. case 0:
  2531. this.x = value;
  2532. break;
  2533. case 1:
  2534. this.y = value;
  2535. break;
  2536. case 2:
  2537. this.z = value;
  2538. break;
  2539. case 3:
  2540. this.w = value;
  2541. break;
  2542. default:
  2543. throw new Error('index is out of range: ' + index);
  2544. }
  2545. return this;
  2546. },
  2547. getComponent: function (index) {
  2548. switch (index) {
  2549. case 0:
  2550. return this.x;
  2551. case 1:
  2552. return this.y;
  2553. case 2:
  2554. return this.z;
  2555. case 3:
  2556. return this.w;
  2557. default:
  2558. throw new Error('index is out of range: ' + index);
  2559. }
  2560. },
  2561. clone: function () {
  2562. return new this.constructor(this.x, this.y, this.z, this.w);
  2563. },
  2564. copy: function (v) {
  2565. this.x = v.x;
  2566. this.y = v.y;
  2567. this.z = v.z;
  2568. this.w = v.w !== undefined ? v.w : 1;
  2569. return this;
  2570. },
  2571. add: function (v, w) {
  2572. if (w !== undefined) {
  2573. console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  2574. return this.addVectors(v, w);
  2575. }
  2576. this.x += v.x;
  2577. this.y += v.y;
  2578. this.z += v.z;
  2579. this.w += v.w;
  2580. return this;
  2581. },
  2582. addScalar: function (s) {
  2583. this.x += s;
  2584. this.y += s;
  2585. this.z += s;
  2586. this.w += s;
  2587. return this;
  2588. },
  2589. addVectors: function (a, b) {
  2590. this.x = a.x + b.x;
  2591. this.y = a.y + b.y;
  2592. this.z = a.z + b.z;
  2593. this.w = a.w + b.w;
  2594. return this;
  2595. },
  2596. addScaledVector: function (v, s) {
  2597. this.x += v.x * s;
  2598. this.y += v.y * s;
  2599. this.z += v.z * s;
  2600. this.w += v.w * s;
  2601. return this;
  2602. },
  2603. sub: function (v, w) {
  2604. if (w !== undefined) {
  2605. console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  2606. return this.subVectors(v, w);
  2607. }
  2608. this.x -= v.x;
  2609. this.y -= v.y;
  2610. this.z -= v.z;
  2611. this.w -= v.w;
  2612. return this;
  2613. },
  2614. subScalar: function (s) {
  2615. this.x -= s;
  2616. this.y -= s;
  2617. this.z -= s;
  2618. this.w -= s;
  2619. return this;
  2620. },
  2621. subVectors: function (a, b) {
  2622. this.x = a.x - b.x;
  2623. this.y = a.y - b.y;
  2624. this.z = a.z - b.z;
  2625. this.w = a.w - b.w;
  2626. return this;
  2627. },
  2628. multiplyScalar: function (scalar) {
  2629. this.x *= scalar;
  2630. this.y *= scalar;
  2631. this.z *= scalar;
  2632. this.w *= scalar;
  2633. return this;
  2634. },
  2635. applyMatrix4: function (m) {
  2636. var x = this.x,
  2637. y = this.y,
  2638. z = this.z,
  2639. w = this.w;
  2640. var e = m.elements;
  2641. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  2642. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  2643. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  2644. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  2645. return this;
  2646. },
  2647. divideScalar: function (scalar) {
  2648. return this.multiplyScalar(1 / scalar);
  2649. },
  2650. setAxisAngleFromQuaternion: function (q) {
  2651. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  2652. // q is assumed to be normalized
  2653. this.w = 2 * Math.acos(q.w);
  2654. var s = Math.sqrt(1 - q.w * q.w);
  2655. if (s < 0.0001) {
  2656. this.x = 1;
  2657. this.y = 0;
  2658. this.z = 0;
  2659. } else {
  2660. this.x = q.x / s;
  2661. this.y = q.y / s;
  2662. this.z = q.z / s;
  2663. }
  2664. return this;
  2665. },
  2666. setAxisAngleFromRotationMatrix: function (m) {
  2667. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  2668. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2669. var angle,
  2670. x,
  2671. y,
  2672. z,
  2673. // variables for result
  2674. epsilon = 0.01,
  2675. // margin to allow for rounding errors
  2676. epsilon2 = 0.1,
  2677. // margin to distinguish between 0 and 180 degrees
  2678. te = m.elements,
  2679. m11 = te[0],
  2680. m12 = te[4],
  2681. m13 = te[8],
  2682. m21 = te[1],
  2683. m22 = te[5],
  2684. m23 = te[9],
  2685. m31 = te[2],
  2686. m32 = te[6],
  2687. m33 = te[10];
  2688. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  2689. // singularity found
  2690. // first check for identity matrix which must have +1 for all terms
  2691. // in leading diagonal and zero in other terms
  2692. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  2693. // this singularity is identity matrix so angle = 0
  2694. this.set(1, 0, 0, 0);
  2695. return this; // zero angle, arbitrary axis
  2696. } // otherwise this singularity is angle = 180
  2697. angle = Math.PI;
  2698. var xx = (m11 + 1) / 2;
  2699. var yy = (m22 + 1) / 2;
  2700. var zz = (m33 + 1) / 2;
  2701. var xy = (m12 + m21) / 4;
  2702. var xz = (m13 + m31) / 4;
  2703. var yz = (m23 + m32) / 4;
  2704. if (xx > yy && xx > zz) {
  2705. // m11 is the largest diagonal term
  2706. if (xx < epsilon) {
  2707. x = 0;
  2708. y = 0.707106781;
  2709. z = 0.707106781;
  2710. } else {
  2711. x = Math.sqrt(xx);
  2712. y = xy / x;
  2713. z = xz / x;
  2714. }
  2715. } else if (yy > zz) {
  2716. // m22 is the largest diagonal term
  2717. if (yy < epsilon) {
  2718. x = 0.707106781;
  2719. y = 0;
  2720. z = 0.707106781;
  2721. } else {
  2722. y = Math.sqrt(yy);
  2723. x = xy / y;
  2724. z = yz / y;
  2725. }
  2726. } else {
  2727. // m33 is the largest diagonal term so base result on this
  2728. if (zz < epsilon) {
  2729. x = 0.707106781;
  2730. y = 0.707106781;
  2731. z = 0;
  2732. } else {
  2733. z = Math.sqrt(zz);
  2734. x = xz / z;
  2735. y = yz / z;
  2736. }
  2737. }
  2738. this.set(x, y, z, angle);
  2739. return this; // return 180 deg rotation
  2740. } // as we have reached here there are no singularities so we can handle normally
  2741. var s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  2742. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  2743. // caught by singularity test above, but I've left it in just in case
  2744. this.x = (m32 - m23) / s;
  2745. this.y = (m13 - m31) / s;
  2746. this.z = (m21 - m12) / s;
  2747. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  2748. return this;
  2749. },
  2750. min: function (v) {
  2751. this.x = Math.min(this.x, v.x);
  2752. this.y = Math.min(this.y, v.y);
  2753. this.z = Math.min(this.z, v.z);
  2754. this.w = Math.min(this.w, v.w);
  2755. return this;
  2756. },
  2757. max: function (v) {
  2758. this.x = Math.max(this.x, v.x);
  2759. this.y = Math.max(this.y, v.y);
  2760. this.z = Math.max(this.z, v.z);
  2761. this.w = Math.max(this.w, v.w);
  2762. return this;
  2763. },
  2764. clamp: function (min, max) {
  2765. // assumes min < max, componentwise
  2766. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2767. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2768. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2769. this.w = Math.max(min.w, Math.min(max.w, this.w));
  2770. return this;
  2771. },
  2772. clampScalar: function (minVal, maxVal) {
  2773. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2774. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2775. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2776. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  2777. return this;
  2778. },
  2779. clampLength: function (min, max) {
  2780. var length = this.length();
  2781. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2782. },
  2783. floor: function () {
  2784. this.x = Math.floor(this.x);
  2785. this.y = Math.floor(this.y);
  2786. this.z = Math.floor(this.z);
  2787. this.w = Math.floor(this.w);
  2788. return this;
  2789. },
  2790. ceil: function () {
  2791. this.x = Math.ceil(this.x);
  2792. this.y = Math.ceil(this.y);
  2793. this.z = Math.ceil(this.z);
  2794. this.w = Math.ceil(this.w);
  2795. return this;
  2796. },
  2797. round: function () {
  2798. this.x = Math.round(this.x);
  2799. this.y = Math.round(this.y);
  2800. this.z = Math.round(this.z);
  2801. this.w = Math.round(this.w);
  2802. return this;
  2803. },
  2804. roundToZero: function () {
  2805. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2806. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2807. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2808. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  2809. return this;
  2810. },
  2811. negate: function () {
  2812. this.x = -this.x;
  2813. this.y = -this.y;
  2814. this.z = -this.z;
  2815. this.w = -this.w;
  2816. return this;
  2817. },
  2818. dot: function (v) {
  2819. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  2820. },
  2821. lengthSq: function () {
  2822. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  2823. },
  2824. length: function () {
  2825. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2826. },
  2827. manhattanLength: function () {
  2828. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  2829. },
  2830. normalize: function () {
  2831. return this.divideScalar(this.length() || 1);
  2832. },
  2833. setLength: function (length) {
  2834. return this.normalize().multiplyScalar(length);
  2835. },
  2836. lerp: function (v, alpha) {
  2837. this.x += (v.x - this.x) * alpha;
  2838. this.y += (v.y - this.y) * alpha;
  2839. this.z += (v.z - this.z) * alpha;
  2840. this.w += (v.w - this.w) * alpha;
  2841. return this;
  2842. },
  2843. lerpVectors: function (v1, v2, alpha) {
  2844. return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
  2845. },
  2846. equals: function (v) {
  2847. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  2848. },
  2849. fromArray: function (array, offset) {
  2850. if (offset === undefined) offset = 0;
  2851. this.x = array[offset];
  2852. this.y = array[offset + 1];
  2853. this.z = array[offset + 2];
  2854. this.w = array[offset + 3];
  2855. return this;
  2856. },
  2857. toArray: function (array, offset) {
  2858. if (array === undefined) array = [];
  2859. if (offset === undefined) offset = 0;
  2860. array[offset] = this.x;
  2861. array[offset + 1] = this.y;
  2862. array[offset + 2] = this.z;
  2863. array[offset + 3] = this.w;
  2864. return array;
  2865. },
  2866. fromBufferAttribute: function (attribute, index, offset) {
  2867. if (offset !== undefined) {
  2868. console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');
  2869. }
  2870. this.x = attribute.getX(index);
  2871. this.y = attribute.getY(index);
  2872. this.z = attribute.getZ(index);
  2873. this.w = attribute.getW(index);
  2874. return this;
  2875. }
  2876. });
  2877. /**
  2878. * @author szimek / https://github.com/szimek/
  2879. * @author alteredq / http://alteredqualia.com/
  2880. * @author Marius Kintel / https://github.com/kintel
  2881. */
  2882. /*
  2883. In options, we can specify:
  2884. * Texture parameters for an auto-generated target texture
  2885. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  2886. */
  2887. function WebGLRenderTarget(width, height, options) {
  2888. this.width = width;
  2889. this.height = height;
  2890. this.scissor = new Vector4(0, 0, width, height);
  2891. this.scissorTest = false;
  2892. this.viewport = new Vector4(0, 0, width, height);
  2893. options = options || {};
  2894. this.texture = new Texture(undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  2895. this.texture.image = {};
  2896. this.texture.image.width = width;
  2897. this.texture.image.height = height;
  2898. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  2899. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  2900. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  2901. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  2902. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  2903. }
  2904. WebGLRenderTarget.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  2905. constructor: WebGLRenderTarget,
  2906. isWebGLRenderTarget: true,
  2907. setSize: function (width, height) {
  2908. if (this.width !== width || this.height !== height) {
  2909. this.width = width;
  2910. this.height = height;
  2911. this.texture.image.width = width;
  2912. this.texture.image.height = height;
  2913. this.dispose();
  2914. }
  2915. this.viewport.set(0, 0, width, height);
  2916. this.scissor.set(0, 0, width, height);
  2917. },
  2918. clone: function () {
  2919. return new this.constructor().copy(this);
  2920. },
  2921. copy: function (source) {
  2922. this.width = source.width;
  2923. this.height = source.height;
  2924. this.viewport.copy(source.viewport);
  2925. this.texture = source.texture.clone();
  2926. this.depthBuffer = source.depthBuffer;
  2927. this.stencilBuffer = source.stencilBuffer;
  2928. this.depthTexture = source.depthTexture;
  2929. return this;
  2930. },
  2931. dispose: function () {
  2932. this.dispatchEvent({
  2933. type: 'dispose'
  2934. });
  2935. }
  2936. });
  2937. /**
  2938. * @author Mugen87 / https://github.com/Mugen87
  2939. * @author Matt DesLauriers / @mattdesl
  2940. */
  2941. function WebGLMultisampleRenderTarget(width, height, options) {
  2942. WebGLRenderTarget.call(this, width, height, options);
  2943. this.samples = 4;
  2944. }
  2945. WebGLMultisampleRenderTarget.prototype = Object.assign(Object.create(WebGLRenderTarget.prototype), {
  2946. constructor: WebGLMultisampleRenderTarget,
  2947. isWebGLMultisampleRenderTarget: true,
  2948. copy: function (source) {
  2949. WebGLRenderTarget.prototype.copy.call(this, source);
  2950. this.samples = source.samples;
  2951. return this;
  2952. }
  2953. });
  2954. var _v1 = new Vector3();
  2955. var _m1 = new Matrix4();
  2956. var _zero = new Vector3(0, 0, 0);
  2957. var _one = new Vector3(1, 1, 1);
  2958. var _x = new Vector3();
  2959. var _y = new Vector3();
  2960. var _z = new Vector3();
  2961. /**
  2962. * @author mrdoob / http://mrdoob.com/
  2963. * @author supereggbert / http://www.paulbrunt.co.uk/
  2964. * @author philogb / http://blog.thejit.org/
  2965. * @author jordi_ros / http://plattsoft.com
  2966. * @author D1plo1d / http://github.com/D1plo1d
  2967. * @author alteredq / http://alteredqualia.com/
  2968. * @author mikael emtinger / http://gomo.se/
  2969. * @author timknip / http://www.floorplanner.com/
  2970. * @author bhouston / http://clara.io
  2971. * @author WestLangley / http://github.com/WestLangley
  2972. */
  2973. function Matrix4() {
  2974. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  2975. if (arguments.length > 0) {
  2976. console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
  2977. }
  2978. }
  2979. Object.assign(Matrix4.prototype, {
  2980. isMatrix4: true,
  2981. set: function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  2982. var te = this.elements;
  2983. te[0] = n11;
  2984. te[4] = n12;
  2985. te[8] = n13;
  2986. te[12] = n14;
  2987. te[1] = n21;
  2988. te[5] = n22;
  2989. te[9] = n23;
  2990. te[13] = n24;
  2991. te[2] = n31;
  2992. te[6] = n32;
  2993. te[10] = n33;
  2994. te[14] = n34;
  2995. te[3] = n41;
  2996. te[7] = n42;
  2997. te[11] = n43;
  2998. te[15] = n44;
  2999. return this;
  3000. },
  3001. identity: function () {
  3002. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3003. return this;
  3004. },
  3005. clone: function () {
  3006. return new Matrix4().fromArray(this.elements);
  3007. },
  3008. copy: function (m) {
  3009. var te = this.elements;
  3010. var me = m.elements;
  3011. te[0] = me[0];
  3012. te[1] = me[1];
  3013. te[2] = me[2];
  3014. te[3] = me[3];
  3015. te[4] = me[4];
  3016. te[5] = me[5];
  3017. te[6] = me[6];
  3018. te[7] = me[7];
  3019. te[8] = me[8];
  3020. te[9] = me[9];
  3021. te[10] = me[10];
  3022. te[11] = me[11];
  3023. te[12] = me[12];
  3024. te[13] = me[13];
  3025. te[14] = me[14];
  3026. te[15] = me[15];
  3027. return this;
  3028. },
  3029. copyPosition: function (m) {
  3030. var te = this.elements,
  3031. me = m.elements;
  3032. te[12] = me[12];
  3033. te[13] = me[13];
  3034. te[14] = me[14];
  3035. return this;
  3036. },
  3037. extractBasis: function (xAxis, yAxis, zAxis) {
  3038. xAxis.setFromMatrixColumn(this, 0);
  3039. yAxis.setFromMatrixColumn(this, 1);
  3040. zAxis.setFromMatrixColumn(this, 2);
  3041. return this;
  3042. },
  3043. makeBasis: function (xAxis, yAxis, zAxis) {
  3044. 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);
  3045. return this;
  3046. },
  3047. extractRotation: function (m) {
  3048. // this method does not support reflection matrices
  3049. var te = this.elements;
  3050. var me = m.elements;
  3051. var scaleX = 1 / _v1.setFromMatrixColumn(m, 0).length();
  3052. var scaleY = 1 / _v1.setFromMatrixColumn(m, 1).length();
  3053. var scaleZ = 1 / _v1.setFromMatrixColumn(m, 2).length();
  3054. te[0] = me[0] * scaleX;
  3055. te[1] = me[1] * scaleX;
  3056. te[2] = me[2] * scaleX;
  3057. te[3] = 0;
  3058. te[4] = me[4] * scaleY;
  3059. te[5] = me[5] * scaleY;
  3060. te[6] = me[6] * scaleY;
  3061. te[7] = 0;
  3062. te[8] = me[8] * scaleZ;
  3063. te[9] = me[9] * scaleZ;
  3064. te[10] = me[10] * scaleZ;
  3065. te[11] = 0;
  3066. te[12] = 0;
  3067. te[13] = 0;
  3068. te[14] = 0;
  3069. te[15] = 1;
  3070. return this;
  3071. },
  3072. makeRotationFromEuler: function (euler) {
  3073. if (!(euler && euler.isEuler)) {
  3074. console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
  3075. }
  3076. var te = this.elements;
  3077. var x = euler.x,
  3078. y = euler.y,
  3079. z = euler.z;
  3080. var a = Math.cos(x),
  3081. b = Math.sin(x);
  3082. var c = Math.cos(y),
  3083. d = Math.sin(y);
  3084. var e = Math.cos(z),
  3085. f = Math.sin(z);
  3086. if (euler.order === 'XYZ') {
  3087. var ae = a * e,
  3088. af = a * f,
  3089. be = b * e,
  3090. bf = b * f;
  3091. te[0] = c * e;
  3092. te[4] = -c * f;
  3093. te[8] = d;
  3094. te[1] = af + be * d;
  3095. te[5] = ae - bf * d;
  3096. te[9] = -b * c;
  3097. te[2] = bf - ae * d;
  3098. te[6] = be + af * d;
  3099. te[10] = a * c;
  3100. } else if (euler.order === 'YXZ') {
  3101. var ce = c * e,
  3102. cf = c * f,
  3103. de = d * e,
  3104. df = d * f;
  3105. te[0] = ce + df * b;
  3106. te[4] = de * b - cf;
  3107. te[8] = a * d;
  3108. te[1] = a * f;
  3109. te[5] = a * e;
  3110. te[9] = -b;
  3111. te[2] = cf * b - de;
  3112. te[6] = df + ce * b;
  3113. te[10] = a * c;
  3114. } else if (euler.order === 'ZXY') {
  3115. var ce = c * e,
  3116. cf = c * f,
  3117. de = d * e,
  3118. df = d * f;
  3119. te[0] = ce - df * b;
  3120. te[4] = -a * f;
  3121. te[8] = de + cf * b;
  3122. te[1] = cf + de * b;
  3123. te[5] = a * e;
  3124. te[9] = df - ce * b;
  3125. te[2] = -a * d;
  3126. te[6] = b;
  3127. te[10] = a * c;
  3128. } else if (euler.order === 'ZYX') {
  3129. var ae = a * e,
  3130. af = a * f,
  3131. be = b * e,
  3132. bf = b * f;
  3133. te[0] = c * e;
  3134. te[4] = be * d - af;
  3135. te[8] = ae * d + bf;
  3136. te[1] = c * f;
  3137. te[5] = bf * d + ae;
  3138. te[9] = af * d - be;
  3139. te[2] = -d;
  3140. te[6] = b * c;
  3141. te[10] = a * c;
  3142. } else if (euler.order === 'YZX') {
  3143. var ac = a * c,
  3144. ad = a * d,
  3145. bc = b * c,
  3146. bd = b * d;
  3147. te[0] = c * e;
  3148. te[4] = bd - ac * f;
  3149. te[8] = bc * f + ad;
  3150. te[1] = f;
  3151. te[5] = a * e;
  3152. te[9] = -b * e;
  3153. te[2] = -d * e;
  3154. te[6] = ad * f + bc;
  3155. te[10] = ac - bd * f;
  3156. } else if (euler.order === 'XZY') {
  3157. var ac = a * c,
  3158. ad = a * d,
  3159. bc = b * c,
  3160. bd = b * d;
  3161. te[0] = c * e;
  3162. te[4] = -f;
  3163. te[8] = d * e;
  3164. te[1] = ac * f + bd;
  3165. te[5] = a * e;
  3166. te[9] = ad * f - bc;
  3167. te[2] = bc * f - ad;
  3168. te[6] = b * e;
  3169. te[10] = bd * f + ac;
  3170. } // bottom row
  3171. te[3] = 0;
  3172. te[7] = 0;
  3173. te[11] = 0; // last column
  3174. te[12] = 0;
  3175. te[13] = 0;
  3176. te[14] = 0;
  3177. te[15] = 1;
  3178. return this;
  3179. },
  3180. makeRotationFromQuaternion: function (q) {
  3181. return this.compose(_zero, q, _one);
  3182. },
  3183. lookAt: function (eye, target, up) {
  3184. var te = this.elements;
  3185. _z.subVectors(eye, target);
  3186. if (_z.lengthSq() === 0) {
  3187. // eye and target are in the same position
  3188. _z.z = 1;
  3189. }
  3190. _z.normalize();
  3191. _x.crossVectors(up, _z);
  3192. if (_x.lengthSq() === 0) {
  3193. // up and z are parallel
  3194. if (Math.abs(up.z) === 1) {
  3195. _z.x += 0.0001;
  3196. } else {
  3197. _z.z += 0.0001;
  3198. }
  3199. _z.normalize();
  3200. _x.crossVectors(up, _z);
  3201. }
  3202. _x.normalize();
  3203. _y.crossVectors(_z, _x);
  3204. te[0] = _x.x;
  3205. te[4] = _y.x;
  3206. te[8] = _z.x;
  3207. te[1] = _x.y;
  3208. te[5] = _y.y;
  3209. te[9] = _z.y;
  3210. te[2] = _x.z;
  3211. te[6] = _y.z;
  3212. te[10] = _z.z;
  3213. return this;
  3214. },
  3215. multiply: function (m, n) {
  3216. if (n !== undefined) {
  3217. console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
  3218. return this.multiplyMatrices(m, n);
  3219. }
  3220. return this.multiplyMatrices(this, m);
  3221. },
  3222. premultiply: function (m) {
  3223. return this.multiplyMatrices(m, this);
  3224. },
  3225. multiplyMatrices: function (a, b) {
  3226. var ae = a.elements;
  3227. var be = b.elements;
  3228. var te = this.elements;
  3229. var a11 = ae[0],
  3230. a12 = ae[4],
  3231. a13 = ae[8],
  3232. a14 = ae[12];
  3233. var a21 = ae[1],
  3234. a22 = ae[5],
  3235. a23 = ae[9],
  3236. a24 = ae[13];
  3237. var a31 = ae[2],
  3238. a32 = ae[6],
  3239. a33 = ae[10],
  3240. a34 = ae[14];
  3241. var a41 = ae[3],
  3242. a42 = ae[7],
  3243. a43 = ae[11],
  3244. a44 = ae[15];
  3245. var b11 = be[0],
  3246. b12 = be[4],
  3247. b13 = be[8],
  3248. b14 = be[12];
  3249. var b21 = be[1],
  3250. b22 = be[5],
  3251. b23 = be[9],
  3252. b24 = be[13];
  3253. var b31 = be[2],
  3254. b32 = be[6],
  3255. b33 = be[10],
  3256. b34 = be[14];
  3257. var b41 = be[3],
  3258. b42 = be[7],
  3259. b43 = be[11],
  3260. b44 = be[15];
  3261. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3262. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3263. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3264. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3265. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3266. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3267. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3268. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3269. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3270. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3271. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3272. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3273. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3274. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3275. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3276. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3277. return this;
  3278. },
  3279. multiplyScalar: function (s) {
  3280. var te = this.elements;
  3281. te[0] *= s;
  3282. te[4] *= s;
  3283. te[8] *= s;
  3284. te[12] *= s;
  3285. te[1] *= s;
  3286. te[5] *= s;
  3287. te[9] *= s;
  3288. te[13] *= s;
  3289. te[2] *= s;
  3290. te[6] *= s;
  3291. te[10] *= s;
  3292. te[14] *= s;
  3293. te[3] *= s;
  3294. te[7] *= s;
  3295. te[11] *= s;
  3296. te[15] *= s;
  3297. return this;
  3298. },
  3299. applyToBufferAttribute: function (attribute) {
  3300. for (var i = 0, l = attribute.count; i < l; i++) {
  3301. _v1.x = attribute.getX(i);
  3302. _v1.y = attribute.getY(i);
  3303. _v1.z = attribute.getZ(i);
  3304. _v1.applyMatrix4(this);
  3305. attribute.setXYZ(i, _v1.x, _v1.y, _v1.z);
  3306. }
  3307. return attribute;
  3308. },
  3309. determinant: function () {
  3310. var te = this.elements;
  3311. var n11 = te[0],
  3312. n12 = te[4],
  3313. n13 = te[8],
  3314. n14 = te[12];
  3315. var n21 = te[1],
  3316. n22 = te[5],
  3317. n23 = te[9],
  3318. n24 = te[13];
  3319. var n31 = te[2],
  3320. n32 = te[6],
  3321. n33 = te[10],
  3322. n34 = te[14];
  3323. var n41 = te[3],
  3324. n42 = te[7],
  3325. n43 = te[11],
  3326. n44 = te[15]; //TODO: make this more efficient
  3327. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3328. 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);
  3329. },
  3330. transpose: function () {
  3331. var te = this.elements;
  3332. var tmp;
  3333. tmp = te[1];
  3334. te[1] = te[4];
  3335. te[4] = tmp;
  3336. tmp = te[2];
  3337. te[2] = te[8];
  3338. te[8] = tmp;
  3339. tmp = te[6];
  3340. te[6] = te[9];
  3341. te[9] = tmp;
  3342. tmp = te[3];
  3343. te[3] = te[12];
  3344. te[12] = tmp;
  3345. tmp = te[7];
  3346. te[7] = te[13];
  3347. te[13] = tmp;
  3348. tmp = te[11];
  3349. te[11] = te[14];
  3350. te[14] = tmp;
  3351. return this;
  3352. },
  3353. setPosition: function (x, y, z) {
  3354. var te = this.elements;
  3355. if (x.isVector3) {
  3356. te[12] = x.x;
  3357. te[13] = x.y;
  3358. te[14] = x.z;
  3359. } else {
  3360. te[12] = x;
  3361. te[13] = y;
  3362. te[14] = z;
  3363. }
  3364. return this;
  3365. },
  3366. getInverse: function (m, throwOnDegenerate) {
  3367. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3368. var te = this.elements,
  3369. me = m.elements,
  3370. n11 = me[0],
  3371. n21 = me[1],
  3372. n31 = me[2],
  3373. n41 = me[3],
  3374. n12 = me[4],
  3375. n22 = me[5],
  3376. n32 = me[6],
  3377. n42 = me[7],
  3378. n13 = me[8],
  3379. n23 = me[9],
  3380. n33 = me[10],
  3381. n43 = me[11],
  3382. n14 = me[12],
  3383. n24 = me[13],
  3384. n34 = me[14],
  3385. n44 = me[15],
  3386. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3387. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3388. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3389. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3390. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3391. if (det === 0) {
  3392. var msg = "THREE.Matrix4: .getInverse() can't invert matrix, determinant is 0";
  3393. if (throwOnDegenerate === true) {
  3394. throw new Error(msg);
  3395. } else {
  3396. console.warn(msg);
  3397. }
  3398. return this.identity();
  3399. }
  3400. var detInv = 1 / det;
  3401. te[0] = t11 * detInv;
  3402. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  3403. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  3404. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  3405. te[4] = t12 * detInv;
  3406. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  3407. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  3408. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  3409. te[8] = t13 * detInv;
  3410. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  3411. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  3412. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  3413. te[12] = t14 * detInv;
  3414. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  3415. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  3416. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  3417. return this;
  3418. },
  3419. scale: function (v) {
  3420. var te = this.elements;
  3421. var x = v.x,
  3422. y = v.y,
  3423. z = v.z;
  3424. te[0] *= x;
  3425. te[4] *= y;
  3426. te[8] *= z;
  3427. te[1] *= x;
  3428. te[5] *= y;
  3429. te[9] *= z;
  3430. te[2] *= x;
  3431. te[6] *= y;
  3432. te[10] *= z;
  3433. te[3] *= x;
  3434. te[7] *= y;
  3435. te[11] *= z;
  3436. return this;
  3437. },
  3438. getMaxScaleOnAxis: function () {
  3439. var te = this.elements;
  3440. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  3441. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  3442. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  3443. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  3444. },
  3445. makeTranslation: function (x, y, z) {
  3446. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  3447. return this;
  3448. },
  3449. makeRotationX: function (theta) {
  3450. var c = Math.cos(theta),
  3451. s = Math.sin(theta);
  3452. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  3453. return this;
  3454. },
  3455. makeRotationY: function (theta) {
  3456. var c = Math.cos(theta),
  3457. s = Math.sin(theta);
  3458. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  3459. return this;
  3460. },
  3461. makeRotationZ: function (theta) {
  3462. var c = Math.cos(theta),
  3463. s = Math.sin(theta);
  3464. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3465. return this;
  3466. },
  3467. makeRotationAxis: function (axis, angle) {
  3468. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3469. var c = Math.cos(angle);
  3470. var s = Math.sin(angle);
  3471. var t = 1 - c;
  3472. var x = axis.x,
  3473. y = axis.y,
  3474. z = axis.z;
  3475. var tx = t * x,
  3476. ty = t * y;
  3477. 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);
  3478. return this;
  3479. },
  3480. makeScale: function (x, y, z) {
  3481. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  3482. return this;
  3483. },
  3484. makeShear: function (x, y, z) {
  3485. this.set(1, y, z, 0, x, 1, z, 0, x, y, 1, 0, 0, 0, 0, 1);
  3486. return this;
  3487. },
  3488. compose: function (position, quaternion, scale) {
  3489. var te = this.elements;
  3490. var x = quaternion._x,
  3491. y = quaternion._y,
  3492. z = quaternion._z,
  3493. w = quaternion._w;
  3494. var x2 = x + x,
  3495. y2 = y + y,
  3496. z2 = z + z;
  3497. var xx = x * x2,
  3498. xy = x * y2,
  3499. xz = x * z2;
  3500. var yy = y * y2,
  3501. yz = y * z2,
  3502. zz = z * z2;
  3503. var wx = w * x2,
  3504. wy = w * y2,
  3505. wz = w * z2;
  3506. var sx = scale.x,
  3507. sy = scale.y,
  3508. sz = scale.z;
  3509. te[0] = (1 - (yy + zz)) * sx;
  3510. te[1] = (xy + wz) * sx;
  3511. te[2] = (xz - wy) * sx;
  3512. te[3] = 0;
  3513. te[4] = (xy - wz) * sy;
  3514. te[5] = (1 - (xx + zz)) * sy;
  3515. te[6] = (yz + wx) * sy;
  3516. te[7] = 0;
  3517. te[8] = (xz + wy) * sz;
  3518. te[9] = (yz - wx) * sz;
  3519. te[10] = (1 - (xx + yy)) * sz;
  3520. te[11] = 0;
  3521. te[12] = position.x;
  3522. te[13] = position.y;
  3523. te[14] = position.z;
  3524. te[15] = 1;
  3525. return this;
  3526. },
  3527. decompose: function (position, quaternion, scale) {
  3528. var te = this.elements;
  3529. var sx = _v1.set(te[0], te[1], te[2]).length();
  3530. var sy = _v1.set(te[4], te[5], te[6]).length();
  3531. var sz = _v1.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  3532. var det = this.determinant();
  3533. if (det < 0) sx = -sx;
  3534. position.x = te[12];
  3535. position.y = te[13];
  3536. position.z = te[14]; // scale the rotation part
  3537. _m1.copy(this);
  3538. var invSX = 1 / sx;
  3539. var invSY = 1 / sy;
  3540. var invSZ = 1 / sz;
  3541. _m1.elements[0] *= invSX;
  3542. _m1.elements[1] *= invSX;
  3543. _m1.elements[2] *= invSX;
  3544. _m1.elements[4] *= invSY;
  3545. _m1.elements[5] *= invSY;
  3546. _m1.elements[6] *= invSY;
  3547. _m1.elements[8] *= invSZ;
  3548. _m1.elements[9] *= invSZ;
  3549. _m1.elements[10] *= invSZ;
  3550. quaternion.setFromRotationMatrix(_m1);
  3551. scale.x = sx;
  3552. scale.y = sy;
  3553. scale.z = sz;
  3554. return this;
  3555. },
  3556. makePerspective: function (left, right, top, bottom, near, far) {
  3557. if (far === undefined) {
  3558. console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
  3559. }
  3560. var te = this.elements;
  3561. var x = 2 * near / (right - left);
  3562. var y = 2 * near / (top - bottom);
  3563. var a = (right + left) / (right - left);
  3564. var b = (top + bottom) / (top - bottom);
  3565. var c = -(far + near) / (far - near);
  3566. var d = -2 * far * near / (far - near);
  3567. te[0] = x;
  3568. te[4] = 0;
  3569. te[8] = a;
  3570. te[12] = 0;
  3571. te[1] = 0;
  3572. te[5] = y;
  3573. te[9] = b;
  3574. te[13] = 0;
  3575. te[2] = 0;
  3576. te[6] = 0;
  3577. te[10] = c;
  3578. te[14] = d;
  3579. te[3] = 0;
  3580. te[7] = 0;
  3581. te[11] = -1;
  3582. te[15] = 0;
  3583. return this;
  3584. },
  3585. makeOrthographic: function (left, right, top, bottom, near, far) {
  3586. var te = this.elements;
  3587. var w = 1.0 / (right - left);
  3588. var h = 1.0 / (top - bottom);
  3589. var p = 1.0 / (far - near);
  3590. var x = (right + left) * w;
  3591. var y = (top + bottom) * h;
  3592. var z = (far + near) * p;
  3593. te[0] = 2 * w;
  3594. te[4] = 0;
  3595. te[8] = 0;
  3596. te[12] = -x;
  3597. te[1] = 0;
  3598. te[5] = 2 * h;
  3599. te[9] = 0;
  3600. te[13] = -y;
  3601. te[2] = 0;
  3602. te[6] = 0;
  3603. te[10] = -2 * p;
  3604. te[14] = -z;
  3605. te[3] = 0;
  3606. te[7] = 0;
  3607. te[11] = 0;
  3608. te[15] = 1;
  3609. return this;
  3610. },
  3611. equals: function (matrix) {
  3612. var te = this.elements;
  3613. var me = matrix.elements;
  3614. for (var i = 0; i < 16; i++) {
  3615. if (te[i] !== me[i]) return false;
  3616. }
  3617. return true;
  3618. },
  3619. fromArray: function (array, offset) {
  3620. if (offset === undefined) offset = 0;
  3621. for (var i = 0; i < 16; i++) {
  3622. this.elements[i] = array[i + offset];
  3623. }
  3624. return this;
  3625. },
  3626. toArray: function (array, offset) {
  3627. if (array === undefined) array = [];
  3628. if (offset === undefined) offset = 0;
  3629. var te = this.elements;
  3630. array[offset] = te[0];
  3631. array[offset + 1] = te[1];
  3632. array[offset + 2] = te[2];
  3633. array[offset + 3] = te[3];
  3634. array[offset + 4] = te[4];
  3635. array[offset + 5] = te[5];
  3636. array[offset + 6] = te[6];
  3637. array[offset + 7] = te[7];
  3638. array[offset + 8] = te[8];
  3639. array[offset + 9] = te[9];
  3640. array[offset + 10] = te[10];
  3641. array[offset + 11] = te[11];
  3642. array[offset + 12] = te[12];
  3643. array[offset + 13] = te[13];
  3644. array[offset + 14] = te[14];
  3645. array[offset + 15] = te[15];
  3646. return array;
  3647. }
  3648. });
  3649. /**
  3650. * @author mrdoob / http://mrdoob.com/
  3651. * @author WestLangley / http://github.com/WestLangley
  3652. * @author bhouston / http://clara.io
  3653. */
  3654. var _matrix = new Matrix4();
  3655. var _quaternion$1 = new Quaternion();
  3656. function Euler(x, y, z, order) {
  3657. this._x = x || 0;
  3658. this._y = y || 0;
  3659. this._z = z || 0;
  3660. this._order = order || Euler.DefaultOrder;
  3661. }
  3662. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  3663. Euler.DefaultOrder = 'XYZ';
  3664. Object.defineProperties(Euler.prototype, {
  3665. x: {
  3666. get: function () {
  3667. return this._x;
  3668. },
  3669. set: function (value) {
  3670. this._x = value;
  3671. this._onChangeCallback();
  3672. }
  3673. },
  3674. y: {
  3675. get: function () {
  3676. return this._y;
  3677. },
  3678. set: function (value) {
  3679. this._y = value;
  3680. this._onChangeCallback();
  3681. }
  3682. },
  3683. z: {
  3684. get: function () {
  3685. return this._z;
  3686. },
  3687. set: function (value) {
  3688. this._z = value;
  3689. this._onChangeCallback();
  3690. }
  3691. },
  3692. order: {
  3693. get: function () {
  3694. return this._order;
  3695. },
  3696. set: function (value) {
  3697. this._order = value;
  3698. this._onChangeCallback();
  3699. }
  3700. }
  3701. });
  3702. Object.assign(Euler.prototype, {
  3703. isEuler: true,
  3704. set: function (x, y, z, order) {
  3705. this._x = x;
  3706. this._y = y;
  3707. this._z = z;
  3708. this._order = order || this._order;
  3709. this._onChangeCallback();
  3710. return this;
  3711. },
  3712. clone: function () {
  3713. return new this.constructor(this._x, this._y, this._z, this._order);
  3714. },
  3715. copy: function (euler) {
  3716. this._x = euler._x;
  3717. this._y = euler._y;
  3718. this._z = euler._z;
  3719. this._order = euler._order;
  3720. this._onChangeCallback();
  3721. return this;
  3722. },
  3723. setFromRotationMatrix: function (m, order, update) {
  3724. var clamp = _Math.clamp; // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3725. var te = m.elements;
  3726. var m11 = te[0],
  3727. m12 = te[4],
  3728. m13 = te[8];
  3729. var m21 = te[1],
  3730. m22 = te[5],
  3731. m23 = te[9];
  3732. var m31 = te[2],
  3733. m32 = te[6],
  3734. m33 = te[10];
  3735. order = order || this._order;
  3736. if (order === 'XYZ') {
  3737. this._y = Math.asin(clamp(m13, -1, 1));
  3738. if (Math.abs(m13) < 0.9999999) {
  3739. this._x = Math.atan2(-m23, m33);
  3740. this._z = Math.atan2(-m12, m11);
  3741. } else {
  3742. this._x = Math.atan2(m32, m22);
  3743. this._z = 0;
  3744. }
  3745. } else if (order === 'YXZ') {
  3746. this._x = Math.asin(-clamp(m23, -1, 1));
  3747. if (Math.abs(m23) < 0.9999999) {
  3748. this._y = Math.atan2(m13, m33);
  3749. this._z = Math.atan2(m21, m22);
  3750. } else {
  3751. this._y = Math.atan2(-m31, m11);
  3752. this._z = 0;
  3753. }
  3754. } else if (order === 'ZXY') {
  3755. this._x = Math.asin(clamp(m32, -1, 1));
  3756. if (Math.abs(m32) < 0.9999999) {
  3757. this._y = Math.atan2(-m31, m33);
  3758. this._z = Math.atan2(-m12, m22);
  3759. } else {
  3760. this._y = 0;
  3761. this._z = Math.atan2(m21, m11);
  3762. }
  3763. } else if (order === 'ZYX') {
  3764. this._y = Math.asin(-clamp(m31, -1, 1));
  3765. if (Math.abs(m31) < 0.9999999) {
  3766. this._x = Math.atan2(m32, m33);
  3767. this._z = Math.atan2(m21, m11);
  3768. } else {
  3769. this._x = 0;
  3770. this._z = Math.atan2(-m12, m22);
  3771. }
  3772. } else if (order === 'YZX') {
  3773. this._z = Math.asin(clamp(m21, -1, 1));
  3774. if (Math.abs(m21) < 0.9999999) {
  3775. this._x = Math.atan2(-m23, m22);
  3776. this._y = Math.atan2(-m31, m11);
  3777. } else {
  3778. this._x = 0;
  3779. this._y = Math.atan2(m13, m33);
  3780. }
  3781. } else if (order === 'XZY') {
  3782. this._z = Math.asin(-clamp(m12, -1, 1));
  3783. if (Math.abs(m12) < 0.9999999) {
  3784. this._x = Math.atan2(m32, m22);
  3785. this._y = Math.atan2(m13, m11);
  3786. } else {
  3787. this._x = Math.atan2(-m23, m33);
  3788. this._y = 0;
  3789. }
  3790. } else {
  3791. console.warn('THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order);
  3792. }
  3793. this._order = order;
  3794. if (update !== false) this._onChangeCallback();
  3795. return this;
  3796. },
  3797. setFromQuaternion: function (q, order, update) {
  3798. _matrix.makeRotationFromQuaternion(q);
  3799. return this.setFromRotationMatrix(_matrix, order, update);
  3800. },
  3801. setFromVector3: function (v, order) {
  3802. return this.set(v.x, v.y, v.z, order || this._order);
  3803. },
  3804. reorder: function (newOrder) {
  3805. // WARNING: this discards revolution information -bhouston
  3806. _quaternion$1.setFromEuler(this);
  3807. return this.setFromQuaternion(_quaternion$1, newOrder);
  3808. },
  3809. equals: function (euler) {
  3810. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  3811. },
  3812. fromArray: function (array) {
  3813. this._x = array[0];
  3814. this._y = array[1];
  3815. this._z = array[2];
  3816. if (array[3] !== undefined) this._order = array[3];
  3817. this._onChangeCallback();
  3818. return this;
  3819. },
  3820. toArray: function (array, offset) {
  3821. if (array === undefined) array = [];
  3822. if (offset === undefined) offset = 0;
  3823. array[offset] = this._x;
  3824. array[offset + 1] = this._y;
  3825. array[offset + 2] = this._z;
  3826. array[offset + 3] = this._order;
  3827. return array;
  3828. },
  3829. toVector3: function (optionalResult) {
  3830. if (optionalResult) {
  3831. return optionalResult.set(this._x, this._y, this._z);
  3832. } else {
  3833. return new Vector3(this._x, this._y, this._z);
  3834. }
  3835. },
  3836. _onChange: function (callback) {
  3837. this._onChangeCallback = callback;
  3838. return this;
  3839. },
  3840. _onChangeCallback: function () {}
  3841. });
  3842. /**
  3843. * @author mrdoob / http://mrdoob.com/
  3844. */
  3845. function Layers() {
  3846. this.mask = 1 | 0;
  3847. }
  3848. Object.assign(Layers.prototype, {
  3849. set: function (channel) {
  3850. this.mask = 1 << channel | 0;
  3851. },
  3852. enable: function (channel) {
  3853. this.mask |= 1 << channel | 0;
  3854. },
  3855. enableAll: function () {
  3856. this.mask = 0xffffffff | 0;
  3857. },
  3858. toggle: function (channel) {
  3859. this.mask ^= 1 << channel | 0;
  3860. },
  3861. disable: function (channel) {
  3862. this.mask &= ~(1 << channel | 0);
  3863. },
  3864. disableAll: function () {
  3865. this.mask = 0;
  3866. },
  3867. test: function (layers) {
  3868. return (this.mask & layers.mask) !== 0;
  3869. }
  3870. });
  3871. var _object3DId = 0;
  3872. var _v1$1 = new Vector3();
  3873. var _q1 = new Quaternion();
  3874. var _m1$1 = new Matrix4();
  3875. var _target = new Vector3();
  3876. var _position = new Vector3();
  3877. var _scale = new Vector3();
  3878. var _quaternion$2 = new Quaternion();
  3879. var _xAxis = new Vector3(1, 0, 0);
  3880. var _yAxis = new Vector3(0, 1, 0);
  3881. var _zAxis = new Vector3(0, 0, 1);
  3882. var _addedEvent = {
  3883. type: 'added'
  3884. };
  3885. var _removedEvent = {
  3886. type: 'removed'
  3887. };
  3888. /**
  3889. * @author mrdoob / http://mrdoob.com/
  3890. * @author mikael emtinger / http://gomo.se/
  3891. * @author alteredq / http://alteredqualia.com/
  3892. * @author WestLangley / http://github.com/WestLangley
  3893. * @author elephantatwork / www.elephantatwork.ch
  3894. */
  3895. function Object3D() {
  3896. Object.defineProperty(this, 'id', {
  3897. value: _object3DId++
  3898. });
  3899. this.uuid = _Math.generateUUID();
  3900. this.name = '';
  3901. this.type = 'Object3D';
  3902. this.parent = null;
  3903. this.children = [];
  3904. this.up = Object3D.DefaultUp.clone();
  3905. var position = new Vector3();
  3906. var rotation = new Euler();
  3907. var quaternion = new Quaternion();
  3908. var scale = new Vector3(1, 1, 1);
  3909. function onRotationChange() {
  3910. quaternion.setFromEuler(rotation, false);
  3911. }
  3912. function onQuaternionChange() {
  3913. rotation.setFromQuaternion(quaternion, undefined, false);
  3914. }
  3915. rotation._onChange(onRotationChange);
  3916. quaternion._onChange(onQuaternionChange);
  3917. Object.defineProperties(this, {
  3918. position: {
  3919. configurable: true,
  3920. enumerable: true,
  3921. value: position
  3922. },
  3923. rotation: {
  3924. configurable: true,
  3925. enumerable: true,
  3926. value: rotation
  3927. },
  3928. quaternion: {
  3929. configurable: true,
  3930. enumerable: true,
  3931. value: quaternion
  3932. },
  3933. scale: {
  3934. configurable: true,
  3935. enumerable: true,
  3936. value: scale
  3937. },
  3938. modelViewMatrix: {
  3939. value: new Matrix4()
  3940. },
  3941. normalMatrix: {
  3942. value: new Matrix3()
  3943. }
  3944. });
  3945. this.matrix = new Matrix4();
  3946. this.matrixWorld = new Matrix4();
  3947. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  3948. this.matrixWorldNeedsUpdate = false;
  3949. this.layers = new Layers();
  3950. this.visible = true;
  3951. this.castShadow = false;
  3952. this.receiveShadow = false;
  3953. this.frustumCulled = true;
  3954. this.renderOrder = 0;
  3955. this.userData = {};
  3956. }
  3957. Object3D.DefaultUp = new Vector3(0, 1, 0);
  3958. Object3D.DefaultMatrixAutoUpdate = true;
  3959. Object3D.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  3960. constructor: Object3D,
  3961. isObject3D: true,
  3962. onBeforeRender: function () {},
  3963. onAfterRender: function () {},
  3964. applyMatrix: function (matrix) {
  3965. if (this.matrixAutoUpdate) this.updateMatrix();
  3966. this.matrix.premultiply(matrix);
  3967. this.matrix.decompose(this.position, this.quaternion, this.scale);
  3968. },
  3969. applyQuaternion: function (q) {
  3970. this.quaternion.premultiply(q);
  3971. return this;
  3972. },
  3973. setRotationFromAxisAngle: function (axis, angle) {
  3974. // assumes axis is normalized
  3975. this.quaternion.setFromAxisAngle(axis, angle);
  3976. },
  3977. setRotationFromEuler: function (euler) {
  3978. this.quaternion.setFromEuler(euler, true);
  3979. },
  3980. setRotationFromMatrix: function (m) {
  3981. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3982. this.quaternion.setFromRotationMatrix(m);
  3983. },
  3984. setRotationFromQuaternion: function (q) {
  3985. // assumes q is normalized
  3986. this.quaternion.copy(q);
  3987. },
  3988. rotateOnAxis: function (axis, angle) {
  3989. // rotate object on axis in object space
  3990. // axis is assumed to be normalized
  3991. _q1.setFromAxisAngle(axis, angle);
  3992. this.quaternion.multiply(_q1);
  3993. return this;
  3994. },
  3995. rotateOnWorldAxis: function (axis, angle) {
  3996. // rotate object on axis in world space
  3997. // axis is assumed to be normalized
  3998. // method assumes no rotated parent
  3999. _q1.setFromAxisAngle(axis, angle);
  4000. this.quaternion.premultiply(_q1);
  4001. return this;
  4002. },
  4003. rotateX: function (angle) {
  4004. return this.rotateOnAxis(_xAxis, angle);
  4005. },
  4006. rotateY: function (angle) {
  4007. return this.rotateOnAxis(_yAxis, angle);
  4008. },
  4009. rotateZ: function (angle) {
  4010. return this.rotateOnAxis(_zAxis, angle);
  4011. },
  4012. translateOnAxis: function (axis, distance) {
  4013. // translate object by distance along axis in object space
  4014. // axis is assumed to be normalized
  4015. _v1$1.copy(axis).applyQuaternion(this.quaternion);
  4016. this.position.add(_v1$1.multiplyScalar(distance));
  4017. return this;
  4018. },
  4019. translateX: function (distance) {
  4020. return this.translateOnAxis(_xAxis, distance);
  4021. },
  4022. translateY: function (distance) {
  4023. return this.translateOnAxis(_yAxis, distance);
  4024. },
  4025. translateZ: function (distance) {
  4026. return this.translateOnAxis(_zAxis, distance);
  4027. },
  4028. localToWorld: function (vector) {
  4029. return vector.applyMatrix4(this.matrixWorld);
  4030. },
  4031. worldToLocal: function (vector) {
  4032. return vector.applyMatrix4(_m1$1.getInverse(this.matrixWorld));
  4033. },
  4034. lookAt: function (x, y, z) {
  4035. // This method does not support objects having non-uniformly-scaled parent(s)
  4036. if (x.isVector3) {
  4037. _target.copy(x);
  4038. } else {
  4039. _target.set(x, y, z);
  4040. }
  4041. var parent = this.parent;
  4042. this.updateWorldMatrix(true, false);
  4043. _position.setFromMatrixPosition(this.matrixWorld);
  4044. if (this.isCamera || this.isLight) {
  4045. _m1$1.lookAt(_position, _target, this.up);
  4046. } else {
  4047. _m1$1.lookAt(_target, _position, this.up);
  4048. }
  4049. this.quaternion.setFromRotationMatrix(_m1$1);
  4050. if (parent) {
  4051. _m1$1.extractRotation(parent.matrixWorld);
  4052. _q1.setFromRotationMatrix(_m1$1);
  4053. this.quaternion.premultiply(_q1.inverse());
  4054. }
  4055. },
  4056. add: function (object) {
  4057. if (arguments.length > 1) {
  4058. for (var i = 0; i < arguments.length; i++) {
  4059. this.add(arguments[i]);
  4060. }
  4061. return this;
  4062. }
  4063. if (object === this) {
  4064. console.error("THREE.Object3D.add: object can't be added as a child of itself.", object);
  4065. return this;
  4066. }
  4067. if (object && object.isObject3D) {
  4068. if (object.parent !== null) {
  4069. object.parent.remove(object);
  4070. }
  4071. object.parent = this;
  4072. this.children.push(object);
  4073. object.dispatchEvent(_addedEvent);
  4074. } else {
  4075. console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.", object);
  4076. }
  4077. return this;
  4078. },
  4079. remove: function (object) {
  4080. if (arguments.length > 1) {
  4081. for (var i = 0; i < arguments.length; i++) {
  4082. this.remove(arguments[i]);
  4083. }
  4084. return this;
  4085. }
  4086. var index = this.children.indexOf(object);
  4087. if (index !== -1) {
  4088. object.parent = null;
  4089. this.children.splice(index, 1);
  4090. object.dispatchEvent(_removedEvent);
  4091. }
  4092. return this;
  4093. },
  4094. attach: function (object) {
  4095. // adds object as a child of this, while maintaining the object's world transform
  4096. this.updateWorldMatrix(true, false);
  4097. _m1$1.getInverse(this.matrixWorld);
  4098. if (object.parent !== null) {
  4099. object.parent.updateWorldMatrix(true, false);
  4100. _m1$1.multiply(object.parent.matrixWorld);
  4101. }
  4102. object.applyMatrix(_m1$1);
  4103. object.updateWorldMatrix(false, false);
  4104. this.add(object);
  4105. return this;
  4106. },
  4107. getObjectById: function (id) {
  4108. return this.getObjectByProperty('id', id);
  4109. },
  4110. getObjectByName: function (name) {
  4111. return this.getObjectByProperty('name', name);
  4112. },
  4113. getObjectByProperty: function (name, value) {
  4114. if (this[name] === value) return this;
  4115. for (var i = 0, l = this.children.length; i < l; i++) {
  4116. var child = this.children[i];
  4117. var object = child.getObjectByProperty(name, value);
  4118. if (object !== undefined) {
  4119. return object;
  4120. }
  4121. }
  4122. return undefined;
  4123. },
  4124. getWorldPosition: function (target) {
  4125. if (target === undefined) {
  4126. console.warn('THREE.Object3D: .getWorldPosition() target is now required');
  4127. target = new Vector3();
  4128. }
  4129. this.updateMatrixWorld(true);
  4130. return target.setFromMatrixPosition(this.matrixWorld);
  4131. },
  4132. getWorldQuaternion: function (target) {
  4133. if (target === undefined) {
  4134. console.warn('THREE.Object3D: .getWorldQuaternion() target is now required');
  4135. target = new Quaternion();
  4136. }
  4137. this.updateMatrixWorld(true);
  4138. this.matrixWorld.decompose(_position, target, _scale);
  4139. return target;
  4140. },
  4141. getWorldScale: function (target) {
  4142. if (target === undefined) {
  4143. console.warn('THREE.Object3D: .getWorldScale() target is now required');
  4144. target = new Vector3();
  4145. }
  4146. this.updateMatrixWorld(true);
  4147. this.matrixWorld.decompose(_position, _quaternion$2, target);
  4148. return target;
  4149. },
  4150. getWorldDirection: function (target) {
  4151. if (target === undefined) {
  4152. console.warn('THREE.Object3D: .getWorldDirection() target is now required');
  4153. target = new Vector3();
  4154. }
  4155. this.updateMatrixWorld(true);
  4156. var e = this.matrixWorld.elements;
  4157. return target.set(e[8], e[9], e[10]).normalize();
  4158. },
  4159. raycast: function () {},
  4160. traverse: function (callback) {
  4161. callback(this);
  4162. var children = this.children;
  4163. for (var i = 0, l = children.length; i < l; i++) {
  4164. children[i].traverse(callback);
  4165. }
  4166. },
  4167. traverseVisible: function (callback) {
  4168. if (this.visible === false) return;
  4169. callback(this);
  4170. var children = this.children;
  4171. for (var i = 0, l = children.length; i < l; i++) {
  4172. children[i].traverseVisible(callback);
  4173. }
  4174. },
  4175. traverseAncestors: function (callback) {
  4176. var parent = this.parent;
  4177. if (parent !== null) {
  4178. callback(parent);
  4179. parent.traverseAncestors(callback);
  4180. }
  4181. },
  4182. updateMatrix: function () {
  4183. this.matrix.compose(this.position, this.quaternion, this.scale);
  4184. this.matrixWorldNeedsUpdate = true;
  4185. },
  4186. updateMatrixWorld: function (force) {
  4187. if (this.matrixAutoUpdate) this.updateMatrix();
  4188. if (this.matrixWorldNeedsUpdate || force) {
  4189. if (this.parent === null) {
  4190. this.matrixWorld.copy(this.matrix);
  4191. } else {
  4192. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4193. }
  4194. this.matrixWorldNeedsUpdate = false;
  4195. force = true;
  4196. } // update children
  4197. var children = this.children;
  4198. for (var i = 0, l = children.length; i < l; i++) {
  4199. children[i].updateMatrixWorld(force);
  4200. }
  4201. },
  4202. updateWorldMatrix: function (updateParents, updateChildren) {
  4203. var parent = this.parent;
  4204. if (updateParents === true && parent !== null) {
  4205. parent.updateWorldMatrix(true, false);
  4206. }
  4207. if (this.matrixAutoUpdate) this.updateMatrix();
  4208. if (this.parent === null) {
  4209. this.matrixWorld.copy(this.matrix);
  4210. } else {
  4211. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4212. } // update children
  4213. if (updateChildren === true) {
  4214. var children = this.children;
  4215. for (var i = 0, l = children.length; i < l; i++) {
  4216. children[i].updateWorldMatrix(false, true);
  4217. }
  4218. }
  4219. },
  4220. toJSON: function (meta) {
  4221. // meta is a string when called from JSON.stringify
  4222. var isRootObject = meta === undefined || typeof meta === 'string';
  4223. var output = {}; // meta is a hash used to collect geometries, materials.
  4224. // not providing it implies that this is the root object
  4225. // being serialized.
  4226. if (isRootObject) {
  4227. // initialize meta obj
  4228. meta = {
  4229. geometries: {},
  4230. materials: {},
  4231. textures: {},
  4232. images: {},
  4233. shapes: {}
  4234. };
  4235. output.metadata = {
  4236. version: 4.5,
  4237. type: 'Object',
  4238. generator: 'Object3D.toJSON'
  4239. };
  4240. } // standard Object3D serialization
  4241. var object = {};
  4242. object.uuid = this.uuid;
  4243. object.type = this.type;
  4244. if (this.name !== '') object.name = this.name;
  4245. if (this.castShadow === true) object.castShadow = true;
  4246. if (this.receiveShadow === true) object.receiveShadow = true;
  4247. if (this.visible === false) object.visible = false;
  4248. if (this.frustumCulled === false) object.frustumCulled = false;
  4249. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  4250. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  4251. object.layers = this.layers.mask;
  4252. object.matrix = this.matrix.toArray();
  4253. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  4254. if (this.isMesh && this.drawMode !== TrianglesDrawMode) object.drawMode = this.drawMode; //
  4255. function serialize(library, element) {
  4256. if (library[element.uuid] === undefined) {
  4257. library[element.uuid] = element.toJSON(meta);
  4258. }
  4259. return element.uuid;
  4260. }
  4261. if (this.isMesh || this.isLine || this.isPoints) {
  4262. object.geometry = serialize(meta.geometries, this.geometry);
  4263. var parameters = this.geometry.parameters;
  4264. if (parameters !== undefined && parameters.shapes !== undefined) {
  4265. var shapes = parameters.shapes;
  4266. if (Array.isArray(shapes)) {
  4267. for (var i = 0, l = shapes.length; i < l; i++) {
  4268. var shape = shapes[i];
  4269. serialize(meta.shapes, shape);
  4270. }
  4271. } else {
  4272. serialize(meta.shapes, shapes);
  4273. }
  4274. }
  4275. }
  4276. if (this.material !== undefined) {
  4277. if (Array.isArray(this.material)) {
  4278. var uuids = [];
  4279. for (var i = 0, l = this.material.length; i < l; i++) {
  4280. uuids.push(serialize(meta.materials, this.material[i]));
  4281. }
  4282. object.material = uuids;
  4283. } else {
  4284. object.material = serialize(meta.materials, this.material);
  4285. }
  4286. } //
  4287. if (this.children.length > 0) {
  4288. object.children = [];
  4289. for (var i = 0; i < this.children.length; i++) {
  4290. object.children.push(this.children[i].toJSON(meta).object);
  4291. }
  4292. }
  4293. if (isRootObject) {
  4294. var geometries = extractFromCache(meta.geometries);
  4295. var materials = extractFromCache(meta.materials);
  4296. var textures = extractFromCache(meta.textures);
  4297. var images = extractFromCache(meta.images);
  4298. var shapes = extractFromCache(meta.shapes);
  4299. if (geometries.length > 0) output.geometries = geometries;
  4300. if (materials.length > 0) output.materials = materials;
  4301. if (textures.length > 0) output.textures = textures;
  4302. if (images.length > 0) output.images = images;
  4303. if (shapes.length > 0) output.shapes = shapes;
  4304. }
  4305. output.object = object;
  4306. return output; // extract data from the cache hash
  4307. // remove metadata on each item
  4308. // and return as array
  4309. function extractFromCache(cache) {
  4310. var values = [];
  4311. for (var key in cache) {
  4312. var data = cache[key];
  4313. delete data.metadata;
  4314. values.push(data);
  4315. }
  4316. return values;
  4317. }
  4318. },
  4319. clone: function (recursive) {
  4320. return new this.constructor().copy(this, recursive);
  4321. },
  4322. copy: function (source, recursive) {
  4323. if (recursive === undefined) recursive = true;
  4324. this.name = source.name;
  4325. this.up.copy(source.up);
  4326. this.position.copy(source.position);
  4327. this.quaternion.copy(source.quaternion);
  4328. this.scale.copy(source.scale);
  4329. this.matrix.copy(source.matrix);
  4330. this.matrixWorld.copy(source.matrixWorld);
  4331. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4332. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4333. this.layers.mask = source.layers.mask;
  4334. this.visible = source.visible;
  4335. this.castShadow = source.castShadow;
  4336. this.receiveShadow = source.receiveShadow;
  4337. this.frustumCulled = source.frustumCulled;
  4338. this.renderOrder = source.renderOrder;
  4339. this.userData = JSON.parse(JSON.stringify(source.userData));
  4340. if (recursive === true) {
  4341. for (var i = 0; i < source.children.length; i++) {
  4342. var child = source.children[i];
  4343. this.add(child.clone());
  4344. }
  4345. }
  4346. return this;
  4347. }
  4348. });
  4349. /**
  4350. * @author mrdoob / http://mrdoob.com/
  4351. */
  4352. function Scene() {
  4353. Object3D.call(this);
  4354. this.type = 'Scene';
  4355. this.background = null;
  4356. this.fog = null;
  4357. this.overrideMaterial = null;
  4358. this.autoUpdate = true; // checked by the renderer
  4359. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  4360. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  4361. detail: this
  4362. })); // eslint-disable-line no-undef
  4363. }
  4364. }
  4365. Scene.prototype = Object.assign(Object.create(Object3D.prototype), {
  4366. constructor: Scene,
  4367. isScene: true,
  4368. copy: function (source, recursive) {
  4369. Object3D.prototype.copy.call(this, source, recursive);
  4370. if (source.background !== null) this.background = source.background.clone();
  4371. if (source.fog !== null) this.fog = source.fog.clone();
  4372. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  4373. this.autoUpdate = source.autoUpdate;
  4374. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4375. return this;
  4376. },
  4377. toJSON: function (meta) {
  4378. var data = Object3D.prototype.toJSON.call(this, meta);
  4379. if (this.background !== null) data.object.background = this.background.toJSON(meta);
  4380. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  4381. return data;
  4382. },
  4383. dispose: function () {
  4384. this.dispatchEvent({
  4385. type: 'dispose'
  4386. });
  4387. }
  4388. });
  4389. var _points = [new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3()];
  4390. var _vector$2 = new Vector3(); // triangle centered vertices
  4391. var _v0 = new Vector3();
  4392. var _v1$2 = new Vector3();
  4393. var _v2 = new Vector3(); // triangle edge vectors
  4394. var _f0 = new Vector3();
  4395. var _f1 = new Vector3();
  4396. var _f2 = new Vector3();
  4397. var _center = new Vector3();
  4398. var _extents = new Vector3();
  4399. var _triangleNormal = new Vector3();
  4400. var _testAxis = new Vector3();
  4401. /**
  4402. * @author bhouston / http://clara.io
  4403. * @author WestLangley / http://github.com/WestLangley
  4404. */
  4405. function Box3(min, max) {
  4406. this.min = min !== undefined ? min : new Vector3(+Infinity, +Infinity, +Infinity);
  4407. this.max = max !== undefined ? max : new Vector3(-Infinity, -Infinity, -Infinity);
  4408. }
  4409. Object.assign(Box3.prototype, {
  4410. isBox3: true,
  4411. set: function (min, max) {
  4412. this.min.copy(min);
  4413. this.max.copy(max);
  4414. return this;
  4415. },
  4416. setFromArray: function (array) {
  4417. var minX = +Infinity;
  4418. var minY = +Infinity;
  4419. var minZ = +Infinity;
  4420. var maxX = -Infinity;
  4421. var maxY = -Infinity;
  4422. var maxZ = -Infinity;
  4423. for (var i = 0, l = array.length; i < l; i += 3) {
  4424. var x = array[i];
  4425. var y = array[i + 1];
  4426. var z = array[i + 2];
  4427. if (x < minX) minX = x;
  4428. if (y < minY) minY = y;
  4429. if (z < minZ) minZ = z;
  4430. if (x > maxX) maxX = x;
  4431. if (y > maxY) maxY = y;
  4432. if (z > maxZ) maxZ = z;
  4433. }
  4434. this.min.set(minX, minY, minZ);
  4435. this.max.set(maxX, maxY, maxZ);
  4436. return this;
  4437. },
  4438. setFromBufferAttribute: function (attribute) {
  4439. var minX = +Infinity;
  4440. var minY = +Infinity;
  4441. var minZ = +Infinity;
  4442. var maxX = -Infinity;
  4443. var maxY = -Infinity;
  4444. var maxZ = -Infinity;
  4445. for (var i = 0, l = attribute.count; i < l; i++) {
  4446. var x = attribute.getX(i);
  4447. var y = attribute.getY(i);
  4448. var z = attribute.getZ(i);
  4449. if (x < minX) minX = x;
  4450. if (y < minY) minY = y;
  4451. if (z < minZ) minZ = z;
  4452. if (x > maxX) maxX = x;
  4453. if (y > maxY) maxY = y;
  4454. if (z > maxZ) maxZ = z;
  4455. }
  4456. this.min.set(minX, minY, minZ);
  4457. this.max.set(maxX, maxY, maxZ);
  4458. return this;
  4459. },
  4460. setFromPoints: function (points) {
  4461. this.makeEmpty();
  4462. for (var i = 0, il = points.length; i < il; i++) {
  4463. this.expandByPoint(points[i]);
  4464. }
  4465. return this;
  4466. },
  4467. setFromCenterAndSize: function (center, size) {
  4468. var halfSize = _vector$2.copy(size).multiplyScalar(0.5);
  4469. this.min.copy(center).sub(halfSize);
  4470. this.max.copy(center).add(halfSize);
  4471. return this;
  4472. },
  4473. setFromObject: function (object) {
  4474. this.makeEmpty();
  4475. return this.expandByObject(object);
  4476. },
  4477. clone: function () {
  4478. return new this.constructor().copy(this);
  4479. },
  4480. copy: function (box) {
  4481. this.min.copy(box.min);
  4482. this.max.copy(box.max);
  4483. return this;
  4484. },
  4485. makeEmpty: function () {
  4486. this.min.x = this.min.y = this.min.z = +Infinity;
  4487. this.max.x = this.max.y = this.max.z = -Infinity;
  4488. return this;
  4489. },
  4490. isEmpty: function () {
  4491. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  4492. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  4493. },
  4494. getCenter: function (target) {
  4495. if (target === undefined) {
  4496. console.warn('THREE.Box3: .getCenter() target is now required');
  4497. target = new Vector3();
  4498. }
  4499. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  4500. },
  4501. getSize: function (target) {
  4502. if (target === undefined) {
  4503. console.warn('THREE.Box3: .getSize() target is now required');
  4504. target = new Vector3();
  4505. }
  4506. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  4507. },
  4508. expandByPoint: function (point) {
  4509. this.min.min(point);
  4510. this.max.max(point);
  4511. return this;
  4512. },
  4513. expandByVector: function (vector) {
  4514. this.min.sub(vector);
  4515. this.max.add(vector);
  4516. return this;
  4517. },
  4518. expandByScalar: function (scalar) {
  4519. this.min.addScalar(-scalar);
  4520. this.max.addScalar(scalar);
  4521. return this;
  4522. },
  4523. expandByObject: function (object) {
  4524. var i, l; // Computes the world-axis-aligned bounding box of an object (including its children),
  4525. // accounting for both the object's, and children's, world transforms
  4526. object.updateWorldMatrix(false, false);
  4527. var geometry = object.geometry;
  4528. if (geometry !== undefined) {
  4529. if (geometry.isGeometry) {
  4530. var vertices = geometry.vertices;
  4531. for (i = 0, l = vertices.length; i < l; i++) {
  4532. _vector$2.copy(vertices[i]);
  4533. _vector$2.applyMatrix4(object.matrixWorld);
  4534. this.expandByPoint(_vector$2);
  4535. }
  4536. } else if (geometry.isBufferGeometry) {
  4537. var attribute = geometry.attributes.position;
  4538. if (attribute !== undefined) {
  4539. for (i = 0, l = attribute.count; i < l; i++) {
  4540. _vector$2.fromBufferAttribute(attribute, i).applyMatrix4(object.matrixWorld);
  4541. this.expandByPoint(_vector$2);
  4542. }
  4543. }
  4544. }
  4545. } //
  4546. var children = object.children;
  4547. for (i = 0, l = children.length; i < l; i++) {
  4548. this.expandByObject(children[i]);
  4549. }
  4550. return this;
  4551. },
  4552. containsPoint: function (point) {
  4553. 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;
  4554. },
  4555. containsBox: function (box) {
  4556. 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;
  4557. },
  4558. getParameter: function (point, target) {
  4559. // This can potentially have a divide by zero if the box
  4560. // has a size dimension of 0.
  4561. if (target === undefined) {
  4562. console.warn('THREE.Box3: .getParameter() target is now required');
  4563. target = new Vector3();
  4564. }
  4565. 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));
  4566. },
  4567. intersectsBox: function (box) {
  4568. // using 6 splitting planes to rule out intersections.
  4569. 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;
  4570. },
  4571. intersectsSphere: function (sphere) {
  4572. // Find the point on the AABB closest to the sphere center.
  4573. this.clampPoint(sphere.center, _vector$2); // If that point is inside the sphere, the AABB and sphere intersect.
  4574. return _vector$2.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  4575. },
  4576. intersectsPlane: function (plane) {
  4577. // We compute the minimum and maximum dot product values. If those values
  4578. // are on the same side (back or front) of the plane, then there is no intersection.
  4579. var min, max;
  4580. if (plane.normal.x > 0) {
  4581. min = plane.normal.x * this.min.x;
  4582. max = plane.normal.x * this.max.x;
  4583. } else {
  4584. min = plane.normal.x * this.max.x;
  4585. max = plane.normal.x * this.min.x;
  4586. }
  4587. if (plane.normal.y > 0) {
  4588. min += plane.normal.y * this.min.y;
  4589. max += plane.normal.y * this.max.y;
  4590. } else {
  4591. min += plane.normal.y * this.max.y;
  4592. max += plane.normal.y * this.min.y;
  4593. }
  4594. if (plane.normal.z > 0) {
  4595. min += plane.normal.z * this.min.z;
  4596. max += plane.normal.z * this.max.z;
  4597. } else {
  4598. min += plane.normal.z * this.max.z;
  4599. max += plane.normal.z * this.min.z;
  4600. }
  4601. return min <= -plane.constant && max >= -plane.constant;
  4602. },
  4603. intersectsTriangle: function (triangle) {
  4604. if (this.isEmpty()) {
  4605. return false;
  4606. } // compute box center and extents
  4607. this.getCenter(_center);
  4608. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  4609. _v0.subVectors(triangle.a, _center);
  4610. _v1$2.subVectors(triangle.b, _center);
  4611. _v2.subVectors(triangle.c, _center); // compute edge vectors for triangle
  4612. _f0.subVectors(_v1$2, _v0);
  4613. _f1.subVectors(_v2, _v1$2);
  4614. _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
  4615. // 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
  4616. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  4617. 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];
  4618. if (!satForAxes(axes, _v0, _v1$2, _v2, _extents)) {
  4619. return false;
  4620. } // test 3 face normals from the aabb
  4621. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  4622. if (!satForAxes(axes, _v0, _v1$2, _v2, _extents)) {
  4623. return false;
  4624. } // finally testing the face normal of the triangle
  4625. // use already existing triangle edge vectors here
  4626. _triangleNormal.crossVectors(_f0, _f1);
  4627. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  4628. return satForAxes(axes, _v0, _v1$2, _v2, _extents);
  4629. },
  4630. clampPoint: function (point, target) {
  4631. if (target === undefined) {
  4632. console.warn('THREE.Box3: .clampPoint() target is now required');
  4633. target = new Vector3();
  4634. }
  4635. return target.copy(point).clamp(this.min, this.max);
  4636. },
  4637. distanceToPoint: function (point) {
  4638. var clampedPoint = _vector$2.copy(point).clamp(this.min, this.max);
  4639. return clampedPoint.sub(point).length();
  4640. },
  4641. getBoundingSphere: function (target) {
  4642. if (target === undefined) {
  4643. console.error('THREE.Box3: .getBoundingSphere() target is now required'); //target = new Sphere(); // removed to avoid cyclic dependency
  4644. }
  4645. this.getCenter(target.center);
  4646. target.radius = this.getSize(_vector$2).length() * 0.5;
  4647. return target;
  4648. },
  4649. intersect: function (box) {
  4650. this.min.max(box.min);
  4651. 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.
  4652. if (this.isEmpty()) this.makeEmpty();
  4653. return this;
  4654. },
  4655. union: function (box) {
  4656. this.min.min(box.min);
  4657. this.max.max(box.max);
  4658. return this;
  4659. },
  4660. applyMatrix4: function (matrix) {
  4661. // transform of empty box is an empty box.
  4662. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  4663. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  4664. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  4665. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  4666. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  4667. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  4668. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  4669. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  4670. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  4671. this.setFromPoints(_points);
  4672. return this;
  4673. },
  4674. translate: function (offset) {
  4675. this.min.add(offset);
  4676. this.max.add(offset);
  4677. return this;
  4678. },
  4679. equals: function (box) {
  4680. return box.min.equals(this.min) && box.max.equals(this.max);
  4681. }
  4682. });
  4683. function satForAxes(axes, v0, v1, v2, extents) {
  4684. var i, j;
  4685. for (i = 0, j = axes.length - 3; i <= j; i += 3) {
  4686. _testAxis.fromArray(axes, i); // project the aabb onto the seperating axis
  4687. 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
  4688. var p0 = v0.dot(_testAxis);
  4689. var p1 = v1.dot(_testAxis);
  4690. var p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  4691. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  4692. // points of the projected triangle are outside the projected half-length of the aabb
  4693. // the axis is seperating and we can exit
  4694. return false;
  4695. }
  4696. }
  4697. return true;
  4698. }
  4699. var _box = new Box3();
  4700. /**
  4701. * @author bhouston / http://clara.io
  4702. * @author mrdoob / http://mrdoob.com/
  4703. */
  4704. function Sphere(center, radius) {
  4705. this.center = center !== undefined ? center : new Vector3();
  4706. this.radius = radius !== undefined ? radius : 0;
  4707. }
  4708. Object.assign(Sphere.prototype, {
  4709. set: function (center, radius) {
  4710. this.center.copy(center);
  4711. this.radius = radius;
  4712. return this;
  4713. },
  4714. setFromPoints: function (points, optionalCenter) {
  4715. var center = this.center;
  4716. if (optionalCenter !== undefined) {
  4717. center.copy(optionalCenter);
  4718. } else {
  4719. _box.setFromPoints(points).getCenter(center);
  4720. }
  4721. var maxRadiusSq = 0;
  4722. for (var i = 0, il = points.length; i < il; i++) {
  4723. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  4724. }
  4725. this.radius = Math.sqrt(maxRadiusSq);
  4726. return this;
  4727. },
  4728. clone: function () {
  4729. return new this.constructor().copy(this);
  4730. },
  4731. copy: function (sphere) {
  4732. this.center.copy(sphere.center);
  4733. this.radius = sphere.radius;
  4734. return this;
  4735. },
  4736. empty: function () {
  4737. return this.radius <= 0;
  4738. },
  4739. containsPoint: function (point) {
  4740. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  4741. },
  4742. distanceToPoint: function (point) {
  4743. return point.distanceTo(this.center) - this.radius;
  4744. },
  4745. intersectsSphere: function (sphere) {
  4746. var radiusSum = this.radius + sphere.radius;
  4747. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  4748. },
  4749. intersectsBox: function (box) {
  4750. return box.intersectsSphere(this);
  4751. },
  4752. intersectsPlane: function (plane) {
  4753. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  4754. },
  4755. clampPoint: function (point, target) {
  4756. var deltaLengthSq = this.center.distanceToSquared(point);
  4757. if (target === undefined) {
  4758. console.warn('THREE.Sphere: .clampPoint() target is now required');
  4759. target = new Vector3();
  4760. }
  4761. target.copy(point);
  4762. if (deltaLengthSq > this.radius * this.radius) {
  4763. target.sub(this.center).normalize();
  4764. target.multiplyScalar(this.radius).add(this.center);
  4765. }
  4766. return target;
  4767. },
  4768. getBoundingBox: function (target) {
  4769. if (target === undefined) {
  4770. console.warn('THREE.Sphere: .getBoundingBox() target is now required');
  4771. target = new Box3();
  4772. }
  4773. target.set(this.center, this.center);
  4774. target.expandByScalar(this.radius);
  4775. return target;
  4776. },
  4777. applyMatrix4: function (matrix) {
  4778. this.center.applyMatrix4(matrix);
  4779. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  4780. return this;
  4781. },
  4782. translate: function (offset) {
  4783. this.center.add(offset);
  4784. return this;
  4785. },
  4786. equals: function (sphere) {
  4787. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  4788. }
  4789. });
  4790. var _vector$3 = new Vector3();
  4791. var _segCenter = new Vector3();
  4792. var _segDir = new Vector3();
  4793. var _diff = new Vector3();
  4794. var _edge1 = new Vector3();
  4795. var _edge2 = new Vector3();
  4796. var _normal = new Vector3();
  4797. /**
  4798. * @author bhouston / http://clara.io
  4799. */
  4800. function Ray(origin, direction) {
  4801. this.origin = origin !== undefined ? origin : new Vector3();
  4802. this.direction = direction !== undefined ? direction : new Vector3();
  4803. }
  4804. Object.assign(Ray.prototype, {
  4805. set: function (origin, direction) {
  4806. this.origin.copy(origin);
  4807. this.direction.copy(direction);
  4808. return this;
  4809. },
  4810. clone: function () {
  4811. return new this.constructor().copy(this);
  4812. },
  4813. copy: function (ray) {
  4814. this.origin.copy(ray.origin);
  4815. this.direction.copy(ray.direction);
  4816. return this;
  4817. },
  4818. at: function (t, target) {
  4819. if (target === undefined) {
  4820. console.warn('THREE.Ray: .at() target is now required');
  4821. target = new Vector3();
  4822. }
  4823. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  4824. },
  4825. lookAt: function (v) {
  4826. this.direction.copy(v).sub(this.origin).normalize();
  4827. return this;
  4828. },
  4829. recast: function (t) {
  4830. this.origin.copy(this.at(t, _vector$3));
  4831. return this;
  4832. },
  4833. closestPointToPoint: function (point, target) {
  4834. if (target === undefined) {
  4835. console.warn('THREE.Ray: .closestPointToPoint() target is now required');
  4836. target = new Vector3();
  4837. }
  4838. target.subVectors(point, this.origin);
  4839. var directionDistance = target.dot(this.direction);
  4840. if (directionDistance < 0) {
  4841. return target.copy(this.origin);
  4842. }
  4843. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  4844. },
  4845. distanceToPoint: function (point) {
  4846. return Math.sqrt(this.distanceSqToPoint(point));
  4847. },
  4848. distanceSqToPoint: function (point) {
  4849. var directionDistance = _vector$3.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  4850. if (directionDistance < 0) {
  4851. return this.origin.distanceToSquared(point);
  4852. }
  4853. _vector$3.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  4854. return _vector$3.distanceToSquared(point);
  4855. },
  4856. distanceSqToSegment: function (v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  4857. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  4858. // It returns the min distance between the ray and the segment
  4859. // defined by v0 and v1
  4860. // It can also set two optional targets :
  4861. // - The closest point on the ray
  4862. // - The closest point on the segment
  4863. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  4864. _segDir.copy(v1).sub(v0).normalize();
  4865. _diff.copy(this.origin).sub(_segCenter);
  4866. var segExtent = v0.distanceTo(v1) * 0.5;
  4867. var a01 = -this.direction.dot(_segDir);
  4868. var b0 = _diff.dot(this.direction);
  4869. var b1 = -_diff.dot(_segDir);
  4870. var c = _diff.lengthSq();
  4871. var det = Math.abs(1 - a01 * a01);
  4872. var s0, s1, sqrDist, extDet;
  4873. if (det > 0) {
  4874. // The ray and segment are not parallel.
  4875. s0 = a01 * b1 - b0;
  4876. s1 = a01 * b0 - b1;
  4877. extDet = segExtent * det;
  4878. if (s0 >= 0) {
  4879. if (s1 >= -extDet) {
  4880. if (s1 <= extDet) {
  4881. // region 0
  4882. // Minimum at interior points of ray and segment.
  4883. var invDet = 1 / det;
  4884. s0 *= invDet;
  4885. s1 *= invDet;
  4886. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  4887. } else {
  4888. // region 1
  4889. s1 = segExtent;
  4890. s0 = Math.max(0, -(a01 * s1 + b0));
  4891. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  4892. }
  4893. } else {
  4894. // region 5
  4895. s1 = -segExtent;
  4896. s0 = Math.max(0, -(a01 * s1 + b0));
  4897. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  4898. }
  4899. } else {
  4900. if (s1 <= -extDet) {
  4901. // region 4
  4902. s0 = Math.max(0, -(-a01 * segExtent + b0));
  4903. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  4904. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  4905. } else if (s1 <= extDet) {
  4906. // region 3
  4907. s0 = 0;
  4908. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  4909. sqrDist = s1 * (s1 + 2 * b1) + c;
  4910. } else {
  4911. // region 2
  4912. s0 = Math.max(0, -(a01 * segExtent + b0));
  4913. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  4914. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  4915. }
  4916. }
  4917. } else {
  4918. // Ray and segment are parallel.
  4919. s1 = a01 > 0 ? -segExtent : segExtent;
  4920. s0 = Math.max(0, -(a01 * s1 + b0));
  4921. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  4922. }
  4923. if (optionalPointOnRay) {
  4924. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  4925. }
  4926. if (optionalPointOnSegment) {
  4927. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  4928. }
  4929. return sqrDist;
  4930. },
  4931. intersectSphere: function (sphere, target) {
  4932. _vector$3.subVectors(sphere.center, this.origin);
  4933. var tca = _vector$3.dot(this.direction);
  4934. var d2 = _vector$3.dot(_vector$3) - tca * tca;
  4935. var radius2 = sphere.radius * sphere.radius;
  4936. if (d2 > radius2) return null;
  4937. var thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  4938. var t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  4939. var t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  4940. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  4941. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  4942. // in order to always return an intersect point that is in front of the ray.
  4943. 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
  4944. return this.at(t0, target);
  4945. },
  4946. intersectsSphere: function (sphere) {
  4947. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  4948. },
  4949. distanceToPlane: function (plane) {
  4950. var denominator = plane.normal.dot(this.direction);
  4951. if (denominator === 0) {
  4952. // line is coplanar, return origin
  4953. if (plane.distanceToPoint(this.origin) === 0) {
  4954. return 0;
  4955. } // Null is preferable to undefined since undefined means.... it is undefined
  4956. return null;
  4957. }
  4958. var t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  4959. return t >= 0 ? t : null;
  4960. },
  4961. intersectPlane: function (plane, target) {
  4962. var t = this.distanceToPlane(plane);
  4963. if (t === null) {
  4964. return null;
  4965. }
  4966. return this.at(t, target);
  4967. },
  4968. intersectsPlane: function (plane) {
  4969. // check if the ray lies on the plane first
  4970. var distToPoint = plane.distanceToPoint(this.origin);
  4971. if (distToPoint === 0) {
  4972. return true;
  4973. }
  4974. var denominator = plane.normal.dot(this.direction);
  4975. if (denominator * distToPoint < 0) {
  4976. return true;
  4977. } // ray origin is behind the plane (and is pointing behind it)
  4978. return false;
  4979. },
  4980. intersectBox: function (box, target) {
  4981. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  4982. var invdirx = 1 / this.direction.x,
  4983. invdiry = 1 / this.direction.y,
  4984. invdirz = 1 / this.direction.z;
  4985. var origin = this.origin;
  4986. if (invdirx >= 0) {
  4987. tmin = (box.min.x - origin.x) * invdirx;
  4988. tmax = (box.max.x - origin.x) * invdirx;
  4989. } else {
  4990. tmin = (box.max.x - origin.x) * invdirx;
  4991. tmax = (box.min.x - origin.x) * invdirx;
  4992. }
  4993. if (invdiry >= 0) {
  4994. tymin = (box.min.y - origin.y) * invdiry;
  4995. tymax = (box.max.y - origin.y) * invdiry;
  4996. } else {
  4997. tymin = (box.max.y - origin.y) * invdiry;
  4998. tymax = (box.min.y - origin.y) * invdiry;
  4999. }
  5000. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  5001. // (result of 0 * Infinity). x !== x returns true if x is NaN
  5002. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  5003. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  5004. if (invdirz >= 0) {
  5005. tzmin = (box.min.z - origin.z) * invdirz;
  5006. tzmax = (box.max.z - origin.z) * invdirz;
  5007. } else {
  5008. tzmin = (box.max.z - origin.z) * invdirz;
  5009. tzmax = (box.min.z - origin.z) * invdirz;
  5010. }
  5011. if (tmin > tzmax || tzmin > tmax) return null;
  5012. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  5013. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  5014. if (tmax < 0) return null;
  5015. return this.at(tmin >= 0 ? tmin : tmax, target);
  5016. },
  5017. intersectsBox: function (box) {
  5018. return this.intersectBox(box, _vector$3) !== null;
  5019. },
  5020. intersectTriangle: function (a, b, c, backfaceCulling, target) {
  5021. // Compute the offset origin, edges, and normal.
  5022. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  5023. _edge1.subVectors(b, a);
  5024. _edge2.subVectors(c, a);
  5025. _normal.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  5026. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  5027. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  5028. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  5029. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  5030. var DdN = this.direction.dot(_normal);
  5031. var sign;
  5032. if (DdN > 0) {
  5033. if (backfaceCulling) return null;
  5034. sign = 1;
  5035. } else if (DdN < 0) {
  5036. sign = -1;
  5037. DdN = -DdN;
  5038. } else {
  5039. return null;
  5040. }
  5041. _diff.subVectors(this.origin, a);
  5042. var DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  5043. if (DdQxE2 < 0) {
  5044. return null;
  5045. }
  5046. var DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  5047. if (DdE1xQ < 0) {
  5048. return null;
  5049. } // b1+b2 > 1, no intersection
  5050. if (DdQxE2 + DdE1xQ > DdN) {
  5051. return null;
  5052. } // Line intersects triangle, check if ray does.
  5053. var QdN = -sign * _diff.dot(_normal); // t < 0, no intersection
  5054. if (QdN < 0) {
  5055. return null;
  5056. } // Ray intersects triangle.
  5057. return this.at(QdN / DdN, target);
  5058. },
  5059. applyMatrix4: function (matrix4) {
  5060. this.origin.applyMatrix4(matrix4);
  5061. this.direction.transformDirection(matrix4);
  5062. return this;
  5063. },
  5064. equals: function (ray) {
  5065. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  5066. }
  5067. });
  5068. /**
  5069. * @author bhouston / http://clara.io
  5070. * @author mrdoob / http://mrdoob.com/
  5071. */
  5072. var _v0$1 = new Vector3();
  5073. var _v1$3 = new Vector3();
  5074. var _v2$1 = new Vector3();
  5075. var _v3 = new Vector3();
  5076. var _vab = new Vector3();
  5077. var _vac = new Vector3();
  5078. var _vbc = new Vector3();
  5079. var _vap = new Vector3();
  5080. var _vbp = new Vector3();
  5081. var _vcp = new Vector3();
  5082. function Triangle(a, b, c) {
  5083. this.a = a !== undefined ? a : new Vector3();
  5084. this.b = b !== undefined ? b : new Vector3();
  5085. this.c = c !== undefined ? c : new Vector3();
  5086. }
  5087. Object.assign(Triangle, {
  5088. getNormal: function (a, b, c, target) {
  5089. if (target === undefined) {
  5090. console.warn('THREE.Triangle: .getNormal() target is now required');
  5091. target = new Vector3();
  5092. }
  5093. target.subVectors(c, b);
  5094. _v0$1.subVectors(a, b);
  5095. target.cross(_v0$1);
  5096. var targetLengthSq = target.lengthSq();
  5097. if (targetLengthSq > 0) {
  5098. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  5099. }
  5100. return target.set(0, 0, 0);
  5101. },
  5102. // static/instance method to calculate barycentric coordinates
  5103. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  5104. getBarycoord: function (point, a, b, c, target) {
  5105. _v0$1.subVectors(c, a);
  5106. _v1$3.subVectors(b, a);
  5107. _v2$1.subVectors(point, a);
  5108. var dot00 = _v0$1.dot(_v0$1);
  5109. var dot01 = _v0$1.dot(_v1$3);
  5110. var dot02 = _v0$1.dot(_v2$1);
  5111. var dot11 = _v1$3.dot(_v1$3);
  5112. var dot12 = _v1$3.dot(_v2$1);
  5113. var denom = dot00 * dot11 - dot01 * dot01;
  5114. if (target === undefined) {
  5115. console.warn('THREE.Triangle: .getBarycoord() target is now required');
  5116. target = new Vector3();
  5117. } // collinear or singular triangle
  5118. if (denom === 0) {
  5119. // arbitrary location outside of triangle?
  5120. // not sure if this is the best idea, maybe should be returning undefined
  5121. return target.set(-2, -1, -1);
  5122. }
  5123. var invDenom = 1 / denom;
  5124. var u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  5125. var v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  5126. return target.set(1 - u - v, v, u);
  5127. },
  5128. containsPoint: function (point, a, b, c) {
  5129. Triangle.getBarycoord(point, a, b, c, _v3);
  5130. return _v3.x >= 0 && _v3.y >= 0 && _v3.x + _v3.y <= 1;
  5131. },
  5132. getUV: function (point, p1, p2, p3, uv1, uv2, uv3, target) {
  5133. this.getBarycoord(point, p1, p2, p3, _v3);
  5134. target.set(0, 0);
  5135. target.addScaledVector(uv1, _v3.x);
  5136. target.addScaledVector(uv2, _v3.y);
  5137. target.addScaledVector(uv3, _v3.z);
  5138. return target;
  5139. },
  5140. isFrontFacing: function (a, b, c, direction) {
  5141. _v0$1.subVectors(c, b);
  5142. _v1$3.subVectors(a, b); // strictly front facing
  5143. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  5144. }
  5145. });
  5146. Object.assign(Triangle.prototype, {
  5147. set: function (a, b, c) {
  5148. this.a.copy(a);
  5149. this.b.copy(b);
  5150. this.c.copy(c);
  5151. return this;
  5152. },
  5153. setFromPointsAndIndices: function (points, i0, i1, i2) {
  5154. this.a.copy(points[i0]);
  5155. this.b.copy(points[i1]);
  5156. this.c.copy(points[i2]);
  5157. return this;
  5158. },
  5159. clone: function () {
  5160. return new this.constructor().copy(this);
  5161. },
  5162. copy: function (triangle) {
  5163. this.a.copy(triangle.a);
  5164. this.b.copy(triangle.b);
  5165. this.c.copy(triangle.c);
  5166. return this;
  5167. },
  5168. getArea: function () {
  5169. _v0$1.subVectors(this.c, this.b);
  5170. _v1$3.subVectors(this.a, this.b);
  5171. return _v0$1.cross(_v1$3).length() * 0.5;
  5172. },
  5173. getMidpoint: function (target) {
  5174. if (target === undefined) {
  5175. console.warn('THREE.Triangle: .getMidpoint() target is now required');
  5176. target = new Vector3();
  5177. }
  5178. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  5179. },
  5180. getNormal: function (target) {
  5181. return Triangle.getNormal(this.a, this.b, this.c, target);
  5182. },
  5183. getPlane: function (target) {
  5184. if (target === undefined) {
  5185. console.warn('THREE.Triangle: .getPlane() target is now required');
  5186. target = new Vector3();
  5187. }
  5188. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  5189. },
  5190. getBarycoord: function (point, target) {
  5191. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  5192. },
  5193. getUV: function (point, uv1, uv2, uv3, target) {
  5194. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  5195. },
  5196. containsPoint: function (point) {
  5197. return Triangle.containsPoint(point, this.a, this.b, this.c);
  5198. },
  5199. isFrontFacing: function (direction) {
  5200. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  5201. },
  5202. intersectsBox: function (box) {
  5203. return box.intersectsTriangle(this);
  5204. },
  5205. closestPointToPoint: function (p, target) {
  5206. if (target === undefined) {
  5207. console.warn('THREE.Triangle: .closestPointToPoint() target is now required');
  5208. target = new Vector3();
  5209. }
  5210. var a = this.a,
  5211. b = this.b,
  5212. c = this.c;
  5213. var v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5214. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5215. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5216. // basically, we're distinguishing which of the voronoi regions of the triangle
  5217. // the point lies in with the minimum amount of redundant computation.
  5218. _vab.subVectors(b, a);
  5219. _vac.subVectors(c, a);
  5220. _vap.subVectors(p, a);
  5221. var d1 = _vab.dot(_vap);
  5222. var d2 = _vac.dot(_vap);
  5223. if (d1 <= 0 && d2 <= 0) {
  5224. // vertex region of A; barycentric coords (1, 0, 0)
  5225. return target.copy(a);
  5226. }
  5227. _vbp.subVectors(p, b);
  5228. var d3 = _vab.dot(_vbp);
  5229. var d4 = _vac.dot(_vbp);
  5230. if (d3 >= 0 && d4 <= d3) {
  5231. // vertex region of B; barycentric coords (0, 1, 0)
  5232. return target.copy(b);
  5233. }
  5234. var vc = d1 * d4 - d3 * d2;
  5235. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  5236. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  5237. return target.copy(a).addScaledVector(_vab, v);
  5238. }
  5239. _vcp.subVectors(p, c);
  5240. var d5 = _vab.dot(_vcp);
  5241. var d6 = _vac.dot(_vcp);
  5242. if (d6 >= 0 && d5 <= d6) {
  5243. // vertex region of C; barycentric coords (0, 0, 1)
  5244. return target.copy(c);
  5245. }
  5246. var vb = d5 * d2 - d1 * d6;
  5247. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  5248. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  5249. return target.copy(a).addScaledVector(_vac, w);
  5250. }
  5251. var va = d3 * d6 - d5 * d4;
  5252. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  5253. _vbc.subVectors(c, b);
  5254. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  5255. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  5256. } // face region
  5257. var denom = 1 / (va + vb + vc); // u = va * denom
  5258. v = vb * denom;
  5259. w = vc * denom;
  5260. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  5261. },
  5262. equals: function (triangle) {
  5263. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  5264. }
  5265. });
  5266. /**
  5267. * @author mrdoob / http://mrdoob.com/
  5268. */
  5269. var _colorKeywords = {
  5270. 'aliceblue': 0xF0F8FF,
  5271. 'antiquewhite': 0xFAEBD7,
  5272. 'aqua': 0x00FFFF,
  5273. 'aquamarine': 0x7FFFD4,
  5274. 'azure': 0xF0FFFF,
  5275. 'beige': 0xF5F5DC,
  5276. 'bisque': 0xFFE4C4,
  5277. 'black': 0x000000,
  5278. 'blanchedalmond': 0xFFEBCD,
  5279. 'blue': 0x0000FF,
  5280. 'blueviolet': 0x8A2BE2,
  5281. 'brown': 0xA52A2A,
  5282. 'burlywood': 0xDEB887,
  5283. 'cadetblue': 0x5F9EA0,
  5284. 'chartreuse': 0x7FFF00,
  5285. 'chocolate': 0xD2691E,
  5286. 'coral': 0xFF7F50,
  5287. 'cornflowerblue': 0x6495ED,
  5288. 'cornsilk': 0xFFF8DC,
  5289. 'crimson': 0xDC143C,
  5290. 'cyan': 0x00FFFF,
  5291. 'darkblue': 0x00008B,
  5292. 'darkcyan': 0x008B8B,
  5293. 'darkgoldenrod': 0xB8860B,
  5294. 'darkgray': 0xA9A9A9,
  5295. 'darkgreen': 0x006400,
  5296. 'darkgrey': 0xA9A9A9,
  5297. 'darkkhaki': 0xBDB76B,
  5298. 'darkmagenta': 0x8B008B,
  5299. 'darkolivegreen': 0x556B2F,
  5300. 'darkorange': 0xFF8C00,
  5301. 'darkorchid': 0x9932CC,
  5302. 'darkred': 0x8B0000,
  5303. 'darksalmon': 0xE9967A,
  5304. 'darkseagreen': 0x8FBC8F,
  5305. 'darkslateblue': 0x483D8B,
  5306. 'darkslategray': 0x2F4F4F,
  5307. 'darkslategrey': 0x2F4F4F,
  5308. 'darkturquoise': 0x00CED1,
  5309. 'darkviolet': 0x9400D3,
  5310. 'deeppink': 0xFF1493,
  5311. 'deepskyblue': 0x00BFFF,
  5312. 'dimgray': 0x696969,
  5313. 'dimgrey': 0x696969,
  5314. 'dodgerblue': 0x1E90FF,
  5315. 'firebrick': 0xB22222,
  5316. 'floralwhite': 0xFFFAF0,
  5317. 'forestgreen': 0x228B22,
  5318. 'fuchsia': 0xFF00FF,
  5319. 'gainsboro': 0xDCDCDC,
  5320. 'ghostwhite': 0xF8F8FF,
  5321. 'gold': 0xFFD700,
  5322. 'goldenrod': 0xDAA520,
  5323. 'gray': 0x808080,
  5324. 'green': 0x008000,
  5325. 'greenyellow': 0xADFF2F,
  5326. 'grey': 0x808080,
  5327. 'honeydew': 0xF0FFF0,
  5328. 'hotpink': 0xFF69B4,
  5329. 'indianred': 0xCD5C5C,
  5330. 'indigo': 0x4B0082,
  5331. 'ivory': 0xFFFFF0,
  5332. 'khaki': 0xF0E68C,
  5333. 'lavender': 0xE6E6FA,
  5334. 'lavenderblush': 0xFFF0F5,
  5335. 'lawngreen': 0x7CFC00,
  5336. 'lemonchiffon': 0xFFFACD,
  5337. 'lightblue': 0xADD8E6,
  5338. 'lightcoral': 0xF08080,
  5339. 'lightcyan': 0xE0FFFF,
  5340. 'lightgoldenrodyellow': 0xFAFAD2,
  5341. 'lightgray': 0xD3D3D3,
  5342. 'lightgreen': 0x90EE90,
  5343. 'lightgrey': 0xD3D3D3,
  5344. 'lightpink': 0xFFB6C1,
  5345. 'lightsalmon': 0xFFA07A,
  5346. 'lightseagreen': 0x20B2AA,
  5347. 'lightskyblue': 0x87CEFA,
  5348. 'lightslategray': 0x778899,
  5349. 'lightslategrey': 0x778899,
  5350. 'lightsteelblue': 0xB0C4DE,
  5351. 'lightyellow': 0xFFFFE0,
  5352. 'lime': 0x00FF00,
  5353. 'limegreen': 0x32CD32,
  5354. 'linen': 0xFAF0E6,
  5355. 'magenta': 0xFF00FF,
  5356. 'maroon': 0x800000,
  5357. 'mediumaquamarine': 0x66CDAA,
  5358. 'mediumblue': 0x0000CD,
  5359. 'mediumorchid': 0xBA55D3,
  5360. 'mediumpurple': 0x9370DB,
  5361. 'mediumseagreen': 0x3CB371,
  5362. 'mediumslateblue': 0x7B68EE,
  5363. 'mediumspringgreen': 0x00FA9A,
  5364. 'mediumturquoise': 0x48D1CC,
  5365. 'mediumvioletred': 0xC71585,
  5366. 'midnightblue': 0x191970,
  5367. 'mintcream': 0xF5FFFA,
  5368. 'mistyrose': 0xFFE4E1,
  5369. 'moccasin': 0xFFE4B5,
  5370. 'navajowhite': 0xFFDEAD,
  5371. 'navy': 0x000080,
  5372. 'oldlace': 0xFDF5E6,
  5373. 'olive': 0x808000,
  5374. 'olivedrab': 0x6B8E23,
  5375. 'orange': 0xFFA500,
  5376. 'orangered': 0xFF4500,
  5377. 'orchid': 0xDA70D6,
  5378. 'palegoldenrod': 0xEEE8AA,
  5379. 'palegreen': 0x98FB98,
  5380. 'paleturquoise': 0xAFEEEE,
  5381. 'palevioletred': 0xDB7093,
  5382. 'papayawhip': 0xFFEFD5,
  5383. 'peachpuff': 0xFFDAB9,
  5384. 'peru': 0xCD853F,
  5385. 'pink': 0xFFC0CB,
  5386. 'plum': 0xDDA0DD,
  5387. 'powderblue': 0xB0E0E6,
  5388. 'purple': 0x800080,
  5389. 'rebeccapurple': 0x663399,
  5390. 'red': 0xFF0000,
  5391. 'rosybrown': 0xBC8F8F,
  5392. 'royalblue': 0x4169E1,
  5393. 'saddlebrown': 0x8B4513,
  5394. 'salmon': 0xFA8072,
  5395. 'sandybrown': 0xF4A460,
  5396. 'seagreen': 0x2E8B57,
  5397. 'seashell': 0xFFF5EE,
  5398. 'sienna': 0xA0522D,
  5399. 'silver': 0xC0C0C0,
  5400. 'skyblue': 0x87CEEB,
  5401. 'slateblue': 0x6A5ACD,
  5402. 'slategray': 0x708090,
  5403. 'slategrey': 0x708090,
  5404. 'snow': 0xFFFAFA,
  5405. 'springgreen': 0x00FF7F,
  5406. 'steelblue': 0x4682B4,
  5407. 'tan': 0xD2B48C,
  5408. 'teal': 0x008080,
  5409. 'thistle': 0xD8BFD8,
  5410. 'tomato': 0xFF6347,
  5411. 'turquoise': 0x40E0D0,
  5412. 'violet': 0xEE82EE,
  5413. 'wheat': 0xF5DEB3,
  5414. 'white': 0xFFFFFF,
  5415. 'whitesmoke': 0xF5F5F5,
  5416. 'yellow': 0xFFFF00,
  5417. 'yellowgreen': 0x9ACD32
  5418. };
  5419. var _hslA = {
  5420. h: 0,
  5421. s: 0,
  5422. l: 0
  5423. };
  5424. var _hslB = {
  5425. h: 0,
  5426. s: 0,
  5427. l: 0
  5428. };
  5429. function Color(r, g, b) {
  5430. if (g === undefined && b === undefined) {
  5431. // r is THREE.Color, hex or string
  5432. return this.set(r);
  5433. }
  5434. return this.setRGB(r, g, b);
  5435. }
  5436. function hue2rgb(p, q, t) {
  5437. if (t < 0) t += 1;
  5438. if (t > 1) t -= 1;
  5439. if (t < 1 / 6) return p + (q - p) * 6 * t;
  5440. if (t < 1 / 2) return q;
  5441. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  5442. return p;
  5443. }
  5444. function SRGBToLinear(c) {
  5445. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  5446. }
  5447. function LinearToSRGB(c) {
  5448. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  5449. }
  5450. Object.assign(Color.prototype, {
  5451. isColor: true,
  5452. r: 1,
  5453. g: 1,
  5454. b: 1,
  5455. set: function (value) {
  5456. if (value && value.isColor) {
  5457. this.copy(value);
  5458. } else if (typeof value === 'number') {
  5459. this.setHex(value);
  5460. } else if (typeof value === 'string') {
  5461. this.setStyle(value);
  5462. }
  5463. return this;
  5464. },
  5465. setScalar: function (scalar) {
  5466. this.r = scalar;
  5467. this.g = scalar;
  5468. this.b = scalar;
  5469. return this;
  5470. },
  5471. setHex: function (hex) {
  5472. hex = Math.floor(hex);
  5473. this.r = (hex >> 16 & 255) / 255;
  5474. this.g = (hex >> 8 & 255) / 255;
  5475. this.b = (hex & 255) / 255;
  5476. return this;
  5477. },
  5478. setRGB: function (r, g, b) {
  5479. this.r = r;
  5480. this.g = g;
  5481. this.b = b;
  5482. return this;
  5483. },
  5484. setHSL: function (h, s, l) {
  5485. // h,s,l ranges are in 0.0 - 1.0
  5486. h = _Math.euclideanModulo(h, 1);
  5487. s = _Math.clamp(s, 0, 1);
  5488. l = _Math.clamp(l, 0, 1);
  5489. if (s === 0) {
  5490. this.r = this.g = this.b = l;
  5491. } else {
  5492. var p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  5493. var q = 2 * l - p;
  5494. this.r = hue2rgb(q, p, h + 1 / 3);
  5495. this.g = hue2rgb(q, p, h);
  5496. this.b = hue2rgb(q, p, h - 1 / 3);
  5497. }
  5498. return this;
  5499. },
  5500. setStyle: function (style) {
  5501. function handleAlpha(string) {
  5502. if (string === undefined) return;
  5503. if (parseFloat(string) < 1) {
  5504. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  5505. }
  5506. }
  5507. var m;
  5508. if (m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(style)) {
  5509. // rgb / hsl
  5510. var color;
  5511. var name = m[1];
  5512. var components = m[2];
  5513. switch (name) {
  5514. case 'rgb':
  5515. case 'rgba':
  5516. if (color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  5517. // rgb(255,0,0) rgba(255,0,0,0.5)
  5518. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  5519. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  5520. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  5521. handleAlpha(color[5]);
  5522. return this;
  5523. }
  5524. if (color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  5525. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5526. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  5527. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  5528. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  5529. handleAlpha(color[5]);
  5530. return this;
  5531. }
  5532. break;
  5533. case 'hsl':
  5534. case 'hsla':
  5535. if (color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  5536. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5537. var h = parseFloat(color[1]) / 360;
  5538. var s = parseInt(color[2], 10) / 100;
  5539. var l = parseInt(color[3], 10) / 100;
  5540. handleAlpha(color[5]);
  5541. return this.setHSL(h, s, l);
  5542. }
  5543. break;
  5544. }
  5545. } else if (m = /^\#([A-Fa-f0-9]+)$/.exec(style)) {
  5546. // hex color
  5547. var hex = m[1];
  5548. var size = hex.length;
  5549. if (size === 3) {
  5550. // #ff0
  5551. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  5552. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  5553. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  5554. return this;
  5555. } else if (size === 6) {
  5556. // #ff0000
  5557. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  5558. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  5559. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  5560. return this;
  5561. }
  5562. }
  5563. if (style && style.length > 0) {
  5564. // color keywords
  5565. var hex = _colorKeywords[style];
  5566. if (hex !== undefined) {
  5567. // red
  5568. this.setHex(hex);
  5569. } else {
  5570. // unknown color
  5571. console.warn('THREE.Color: Unknown color ' + style);
  5572. }
  5573. }
  5574. return this;
  5575. },
  5576. clone: function () {
  5577. return new this.constructor(this.r, this.g, this.b);
  5578. },
  5579. copy: function (color) {
  5580. this.r = color.r;
  5581. this.g = color.g;
  5582. this.b = color.b;
  5583. return this;
  5584. },
  5585. copyGammaToLinear: function (color, gammaFactor) {
  5586. if (gammaFactor === undefined) gammaFactor = 2.0;
  5587. this.r = Math.pow(color.r, gammaFactor);
  5588. this.g = Math.pow(color.g, gammaFactor);
  5589. this.b = Math.pow(color.b, gammaFactor);
  5590. return this;
  5591. },
  5592. copyLinearToGamma: function (color, gammaFactor) {
  5593. if (gammaFactor === undefined) gammaFactor = 2.0;
  5594. var safeInverse = gammaFactor > 0 ? 1.0 / gammaFactor : 1.0;
  5595. this.r = Math.pow(color.r, safeInverse);
  5596. this.g = Math.pow(color.g, safeInverse);
  5597. this.b = Math.pow(color.b, safeInverse);
  5598. return this;
  5599. },
  5600. convertGammaToLinear: function (gammaFactor) {
  5601. this.copyGammaToLinear(this, gammaFactor);
  5602. return this;
  5603. },
  5604. convertLinearToGamma: function (gammaFactor) {
  5605. this.copyLinearToGamma(this, gammaFactor);
  5606. return this;
  5607. },
  5608. copySRGBToLinear: function (color) {
  5609. this.r = SRGBToLinear(color.r);
  5610. this.g = SRGBToLinear(color.g);
  5611. this.b = SRGBToLinear(color.b);
  5612. return this;
  5613. },
  5614. copyLinearToSRGB: function (color) {
  5615. this.r = LinearToSRGB(color.r);
  5616. this.g = LinearToSRGB(color.g);
  5617. this.b = LinearToSRGB(color.b);
  5618. return this;
  5619. },
  5620. convertSRGBToLinear: function () {
  5621. this.copySRGBToLinear(this);
  5622. return this;
  5623. },
  5624. convertLinearToSRGB: function () {
  5625. this.copyLinearToSRGB(this);
  5626. return this;
  5627. },
  5628. getHex: function () {
  5629. return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
  5630. },
  5631. getHexString: function () {
  5632. return ('000000' + this.getHex().toString(16)).slice(-6);
  5633. },
  5634. getHSL: function (target) {
  5635. // h,s,l ranges are in 0.0 - 1.0
  5636. if (target === undefined) {
  5637. console.warn('THREE.Color: .getHSL() target is now required');
  5638. target = {
  5639. h: 0,
  5640. s: 0,
  5641. l: 0
  5642. };
  5643. }
  5644. var r = this.r,
  5645. g = this.g,
  5646. b = this.b;
  5647. var max = Math.max(r, g, b);
  5648. var min = Math.min(r, g, b);
  5649. var hue, saturation;
  5650. var lightness = (min + max) / 2.0;
  5651. if (min === max) {
  5652. hue = 0;
  5653. saturation = 0;
  5654. } else {
  5655. var delta = max - min;
  5656. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  5657. switch (max) {
  5658. case r:
  5659. hue = (g - b) / delta + (g < b ? 6 : 0);
  5660. break;
  5661. case g:
  5662. hue = (b - r) / delta + 2;
  5663. break;
  5664. case b:
  5665. hue = (r - g) / delta + 4;
  5666. break;
  5667. }
  5668. hue /= 6;
  5669. }
  5670. target.h = hue;
  5671. target.s = saturation;
  5672. target.l = lightness;
  5673. return target;
  5674. },
  5675. getStyle: function () {
  5676. return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
  5677. },
  5678. offsetHSL: function (h, s, l) {
  5679. this.getHSL(_hslA);
  5680. _hslA.h += h;
  5681. _hslA.s += s;
  5682. _hslA.l += l;
  5683. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  5684. return this;
  5685. },
  5686. add: function (color) {
  5687. this.r += color.r;
  5688. this.g += color.g;
  5689. this.b += color.b;
  5690. return this;
  5691. },
  5692. addColors: function (color1, color2) {
  5693. this.r = color1.r + color2.r;
  5694. this.g = color1.g + color2.g;
  5695. this.b = color1.b + color2.b;
  5696. return this;
  5697. },
  5698. addScalar: function (s) {
  5699. this.r += s;
  5700. this.g += s;
  5701. this.b += s;
  5702. return this;
  5703. },
  5704. sub: function (color) {
  5705. this.r = Math.max(0, this.r - color.r);
  5706. this.g = Math.max(0, this.g - color.g);
  5707. this.b = Math.max(0, this.b - color.b);
  5708. return this;
  5709. },
  5710. multiply: function (color) {
  5711. this.r *= color.r;
  5712. this.g *= color.g;
  5713. this.b *= color.b;
  5714. return this;
  5715. },
  5716. multiplyScalar: function (s) {
  5717. this.r *= s;
  5718. this.g *= s;
  5719. this.b *= s;
  5720. return this;
  5721. },
  5722. lerp: function (color, alpha) {
  5723. this.r += (color.r - this.r) * alpha;
  5724. this.g += (color.g - this.g) * alpha;
  5725. this.b += (color.b - this.b) * alpha;
  5726. return this;
  5727. },
  5728. lerpHSL: function (color, alpha) {
  5729. this.getHSL(_hslA);
  5730. color.getHSL(_hslB);
  5731. var h = _Math.lerp(_hslA.h, _hslB.h, alpha);
  5732. var s = _Math.lerp(_hslA.s, _hslB.s, alpha);
  5733. var l = _Math.lerp(_hslA.l, _hslB.l, alpha);
  5734. this.setHSL(h, s, l);
  5735. return this;
  5736. },
  5737. equals: function (c) {
  5738. return c.r === this.r && c.g === this.g && c.b === this.b;
  5739. },
  5740. fromArray: function (array, offset) {
  5741. if (offset === undefined) offset = 0;
  5742. this.r = array[offset];
  5743. this.g = array[offset + 1];
  5744. this.b = array[offset + 2];
  5745. return this;
  5746. },
  5747. toArray: function (array, offset) {
  5748. if (array === undefined) array = [];
  5749. if (offset === undefined) offset = 0;
  5750. array[offset] = this.r;
  5751. array[offset + 1] = this.g;
  5752. array[offset + 2] = this.b;
  5753. return array;
  5754. },
  5755. toJSON: function () {
  5756. return this.getHex();
  5757. }
  5758. });
  5759. /**
  5760. * @author mrdoob / http://mrdoob.com/
  5761. * @author alteredq / http://alteredqualia.com/
  5762. */
  5763. function Face3(a, b, c, normal, color, materialIndex) {
  5764. this.a = a;
  5765. this.b = b;
  5766. this.c = c;
  5767. this.normal = normal && normal.isVector3 ? normal : new Vector3();
  5768. this.vertexNormals = Array.isArray(normal) ? normal : [];
  5769. this.color = color && color.isColor ? color : new Color();
  5770. this.vertexColors = Array.isArray(color) ? color : [];
  5771. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  5772. }
  5773. Object.assign(Face3.prototype, {
  5774. clone: function () {
  5775. return new this.constructor().copy(this);
  5776. },
  5777. copy: function (source) {
  5778. this.a = source.a;
  5779. this.b = source.b;
  5780. this.c = source.c;
  5781. this.normal.copy(source.normal);
  5782. this.color.copy(source.color);
  5783. this.materialIndex = source.materialIndex;
  5784. for (var i = 0, il = source.vertexNormals.length; i < il; i++) {
  5785. this.vertexNormals[i] = source.vertexNormals[i].clone();
  5786. }
  5787. for (var i = 0, il = source.vertexColors.length; i < il; i++) {
  5788. this.vertexColors[i] = source.vertexColors[i].clone();
  5789. }
  5790. return this;
  5791. }
  5792. });
  5793. /**
  5794. * @author mrdoob / http://mrdoob.com/
  5795. * @author alteredq / http://alteredqualia.com/
  5796. */
  5797. var materialId = 0;
  5798. function Material() {
  5799. Object.defineProperty(this, 'id', {
  5800. value: materialId++
  5801. });
  5802. this.uuid = _Math.generateUUID();
  5803. this.name = '';
  5804. this.type = 'Material';
  5805. this.fog = true;
  5806. this.blending = NormalBlending;
  5807. this.side = FrontSide;
  5808. this.flatShading = false;
  5809. this.vertexTangents = false;
  5810. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  5811. this.opacity = 1;
  5812. this.transparent = false;
  5813. this.blendSrc = SrcAlphaFactor;
  5814. this.blendDst = OneMinusSrcAlphaFactor;
  5815. this.blendEquation = AddEquation;
  5816. this.blendSrcAlpha = null;
  5817. this.blendDstAlpha = null;
  5818. this.blendEquationAlpha = null;
  5819. this.depthFunc = LessEqualDepth;
  5820. this.depthTest = true;
  5821. this.depthWrite = true;
  5822. this.stencilWriteMask = 0xff;
  5823. this.stencilFunc = AlwaysStencilFunc;
  5824. this.stencilRef = 0;
  5825. this.stencilFuncMask = 0xff;
  5826. this.stencilFail = KeepStencilOp;
  5827. this.stencilZFail = KeepStencilOp;
  5828. this.stencilZPass = KeepStencilOp;
  5829. this.stencilWrite = false;
  5830. this.clippingPlanes = null;
  5831. this.clipIntersection = false;
  5832. this.clipShadows = false;
  5833. this.shadowSide = null;
  5834. this.colorWrite = true;
  5835. this.precision = null; // override the renderer's default precision for this material
  5836. this.polygonOffset = false;
  5837. this.polygonOffsetFactor = 0;
  5838. this.polygonOffsetUnits = 0;
  5839. this.dithering = false;
  5840. this.alphaTest = 0;
  5841. this.premultipliedAlpha = false;
  5842. this.visible = true;
  5843. this.toneMapped = true;
  5844. this.userData = {};
  5845. this.needsUpdate = true;
  5846. }
  5847. Material.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  5848. constructor: Material,
  5849. isMaterial: true,
  5850. onBeforeCompile: function () {},
  5851. setValues: function (values) {
  5852. if (values === undefined) return;
  5853. for (var key in values) {
  5854. var newValue = values[key];
  5855. if (newValue === undefined) {
  5856. console.warn("THREE.Material: '" + key + "' parameter is undefined.");
  5857. continue;
  5858. } // for backward compatability if shading is set in the constructor
  5859. if (key === 'shading') {
  5860. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  5861. this.flatShading = newValue === FlatShading ? true : false;
  5862. continue;
  5863. }
  5864. var currentValue = this[key];
  5865. if (currentValue === undefined) {
  5866. console.warn("THREE." + this.type + ": '" + key + "' is not a property of this material.");
  5867. continue;
  5868. }
  5869. if (currentValue && currentValue.isColor) {
  5870. currentValue.set(newValue);
  5871. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  5872. currentValue.copy(newValue);
  5873. } else {
  5874. this[key] = newValue;
  5875. }
  5876. }
  5877. },
  5878. toJSON: function (meta) {
  5879. var isRoot = meta === undefined || typeof meta === 'string';
  5880. if (isRoot) {
  5881. meta = {
  5882. textures: {},
  5883. images: {}
  5884. };
  5885. }
  5886. var data = {
  5887. metadata: {
  5888. version: 4.5,
  5889. type: 'Material',
  5890. generator: 'Material.toJSON'
  5891. }
  5892. }; // standard Material serialization
  5893. data.uuid = this.uuid;
  5894. data.type = this.type;
  5895. if (this.name !== '') data.name = this.name;
  5896. if (this.color && this.color.isColor) data.color = this.color.getHex();
  5897. if (this.roughness !== undefined) data.roughness = this.roughness;
  5898. if (this.metalness !== undefined) data.metalness = this.metalness;
  5899. if (this.sheen && this.sheen.isColor) data.sheen = this.sheen.getHex();
  5900. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  5901. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  5902. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  5903. if (this.shininess !== undefined) data.shininess = this.shininess;
  5904. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  5905. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  5906. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  5907. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  5908. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5909. }
  5910. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  5911. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  5912. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  5913. if (this.lightMap && this.lightMap.isTexture) data.lightMap = this.lightMap.toJSON(meta).uuid;
  5914. if (this.aoMap && this.aoMap.isTexture) {
  5915. data.aoMap = this.aoMap.toJSON(meta).uuid;
  5916. data.aoMapIntensity = this.aoMapIntensity;
  5917. }
  5918. if (this.bumpMap && this.bumpMap.isTexture) {
  5919. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  5920. data.bumpScale = this.bumpScale;
  5921. }
  5922. if (this.normalMap && this.normalMap.isTexture) {
  5923. data.normalMap = this.normalMap.toJSON(meta).uuid;
  5924. data.normalMapType = this.normalMapType;
  5925. data.normalScale = this.normalScale.toArray();
  5926. }
  5927. if (this.displacementMap && this.displacementMap.isTexture) {
  5928. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  5929. data.displacementScale = this.displacementScale;
  5930. data.displacementBias = this.displacementBias;
  5931. }
  5932. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  5933. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  5934. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  5935. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  5936. if (this.envMap && this.envMap.isTexture) {
  5937. data.envMap = this.envMap.toJSON(meta).uuid;
  5938. data.reflectivity = this.reflectivity; // Scale behind envMap
  5939. data.refractionRatio = this.refractionRatio;
  5940. if (this.combine !== undefined) data.combine = this.combine;
  5941. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  5942. }
  5943. if (this.gradientMap && this.gradientMap.isTexture) {
  5944. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  5945. }
  5946. if (this.size !== undefined) data.size = this.size;
  5947. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  5948. if (this.blending !== NormalBlending) data.blending = this.blending;
  5949. if (this.flatShading === true) data.flatShading = this.flatShading;
  5950. if (this.side !== FrontSide) data.side = this.side;
  5951. if (this.vertexColors !== NoColors) data.vertexColors = this.vertexColors;
  5952. if (this.opacity < 1) data.opacity = this.opacity;
  5953. if (this.transparent === true) data.transparent = this.transparent;
  5954. data.depthFunc = this.depthFunc;
  5955. data.depthTest = this.depthTest;
  5956. data.depthWrite = this.depthWrite;
  5957. data.stencilWrite = this.stencilWrite;
  5958. data.stencilWriteMask = this.stencilWriteMask;
  5959. data.stencilFunc = this.stencilFunc;
  5960. data.stencilRef = this.stencilRef;
  5961. data.stencilFuncMask = this.stencilFuncMask;
  5962. data.stencilFail = this.stencilFail;
  5963. data.stencilZFail = this.stencilZFail;
  5964. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  5965. if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;
  5966. if (this.polygonOffset === true) data.polygonOffset = true;
  5967. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5968. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5969. if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;
  5970. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  5971. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  5972. if (this.scale !== undefined) data.scale = this.scale;
  5973. if (this.dithering === true) data.dithering = true;
  5974. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  5975. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  5976. if (this.wireframe === true) data.wireframe = this.wireframe;
  5977. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  5978. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  5979. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  5980. if (this.morphTargets === true) data.morphTargets = true;
  5981. if (this.morphNormals === true) data.morphNormals = true;
  5982. if (this.skinning === true) data.skinning = true;
  5983. if (this.visible === false) data.visible = false;
  5984. if (this.toneMapped === false) data.toneMapped = false;
  5985. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  5986. function extractFromCache(cache) {
  5987. var values = [];
  5988. for (var key in cache) {
  5989. var data = cache[key];
  5990. delete data.metadata;
  5991. values.push(data);
  5992. }
  5993. return values;
  5994. }
  5995. if (isRoot) {
  5996. var textures = extractFromCache(meta.textures);
  5997. var images = extractFromCache(meta.images);
  5998. if (textures.length > 0) data.textures = textures;
  5999. if (images.length > 0) data.images = images;
  6000. }
  6001. return data;
  6002. },
  6003. clone: function () {
  6004. return new this.constructor().copy(this);
  6005. },
  6006. copy: function (source) {
  6007. this.name = source.name;
  6008. this.fog = source.fog;
  6009. this.blending = source.blending;
  6010. this.side = source.side;
  6011. this.flatShading = source.flatShading;
  6012. this.vertexColors = source.vertexColors;
  6013. this.opacity = source.opacity;
  6014. this.transparent = source.transparent;
  6015. this.blendSrc = source.blendSrc;
  6016. this.blendDst = source.blendDst;
  6017. this.blendEquation = source.blendEquation;
  6018. this.blendSrcAlpha = source.blendSrcAlpha;
  6019. this.blendDstAlpha = source.blendDstAlpha;
  6020. this.blendEquationAlpha = source.blendEquationAlpha;
  6021. this.depthFunc = source.depthFunc;
  6022. this.depthTest = source.depthTest;
  6023. this.depthWrite = source.depthWrite;
  6024. this.stencilWrite = source.stencilWrite;
  6025. this.stencilWriteMask = source.stencilWriteMask;
  6026. this.stencilFunc = source.stencilFunc;
  6027. this.stencilRef = source.stencilRef;
  6028. this.stencilFuncMask = source.stencilFuncMask;
  6029. this.stencilFail = source.stencilFail;
  6030. this.stencilZFail = source.stencilZFail;
  6031. this.stencilZPass = source.stencilZPass;
  6032. this.colorWrite = source.colorWrite;
  6033. this.precision = source.precision;
  6034. this.polygonOffset = source.polygonOffset;
  6035. this.polygonOffsetFactor = source.polygonOffsetFactor;
  6036. this.polygonOffsetUnits = source.polygonOffsetUnits;
  6037. this.dithering = source.dithering;
  6038. this.alphaTest = source.alphaTest;
  6039. this.premultipliedAlpha = source.premultipliedAlpha;
  6040. this.visible = source.visible;
  6041. this.toneMapped = source.toneMapped;
  6042. this.userData = JSON.parse(JSON.stringify(source.userData));
  6043. this.clipShadows = source.clipShadows;
  6044. this.clipIntersection = source.clipIntersection;
  6045. var srcPlanes = source.clippingPlanes,
  6046. dstPlanes = null;
  6047. if (srcPlanes !== null) {
  6048. var n = srcPlanes.length;
  6049. dstPlanes = new Array(n);
  6050. for (var i = 0; i !== n; ++i) dstPlanes[i] = srcPlanes[i].clone();
  6051. }
  6052. this.clippingPlanes = dstPlanes;
  6053. this.shadowSide = source.shadowSide;
  6054. return this;
  6055. },
  6056. dispose: function () {
  6057. this.dispatchEvent({
  6058. type: 'dispose'
  6059. });
  6060. }
  6061. });
  6062. /**
  6063. * @author mrdoob / http://mrdoob.com/
  6064. * @author alteredq / http://alteredqualia.com/
  6065. *
  6066. * parameters = {
  6067. * color: <hex>,
  6068. * opacity: <float>,
  6069. * map: new THREE.Texture( <Image> ),
  6070. *
  6071. * lightMap: new THREE.Texture( <Image> ),
  6072. * lightMapIntensity: <float>
  6073. *
  6074. * aoMap: new THREE.Texture( <Image> ),
  6075. * aoMapIntensity: <float>
  6076. *
  6077. * specularMap: new THREE.Texture( <Image> ),
  6078. *
  6079. * alphaMap: new THREE.Texture( <Image> ),
  6080. *
  6081. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  6082. * combine: THREE.Multiply,
  6083. * reflectivity: <float>,
  6084. * refractionRatio: <float>,
  6085. *
  6086. * depthTest: <bool>,
  6087. * depthWrite: <bool>,
  6088. *
  6089. * wireframe: <boolean>,
  6090. * wireframeLinewidth: <float>,
  6091. *
  6092. * skinning: <bool>,
  6093. * morphTargets: <bool>
  6094. * }
  6095. */
  6096. function MeshBasicMaterial(parameters) {
  6097. Material.call(this);
  6098. this.type = 'MeshBasicMaterial';
  6099. this.color = new Color(0xffffff); // emissive
  6100. this.map = null;
  6101. this.lightMap = null;
  6102. this.lightMapIntensity = 1.0;
  6103. this.aoMap = null;
  6104. this.aoMapIntensity = 1.0;
  6105. this.specularMap = null;
  6106. this.alphaMap = null;
  6107. this.envMap = null;
  6108. this.combine = MultiplyOperation;
  6109. this.reflectivity = 1;
  6110. this.refractionRatio = 0.98;
  6111. this.wireframe = false;
  6112. this.wireframeLinewidth = 1;
  6113. this.wireframeLinecap = 'round';
  6114. this.wireframeLinejoin = 'round';
  6115. this.skinning = false;
  6116. this.morphTargets = false;
  6117. this.setValues(parameters);
  6118. }
  6119. MeshBasicMaterial.prototype = Object.create(Material.prototype);
  6120. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  6121. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  6122. MeshBasicMaterial.prototype.copy = function (source) {
  6123. Material.prototype.copy.call(this, source);
  6124. this.color.copy(source.color);
  6125. this.map = source.map;
  6126. this.lightMap = source.lightMap;
  6127. this.lightMapIntensity = source.lightMapIntensity;
  6128. this.aoMap = source.aoMap;
  6129. this.aoMapIntensity = source.aoMapIntensity;
  6130. this.specularMap = source.specularMap;
  6131. this.alphaMap = source.alphaMap;
  6132. this.envMap = source.envMap;
  6133. this.combine = source.combine;
  6134. this.reflectivity = source.reflectivity;
  6135. this.refractionRatio = source.refractionRatio;
  6136. this.wireframe = source.wireframe;
  6137. this.wireframeLinewidth = source.wireframeLinewidth;
  6138. this.wireframeLinecap = source.wireframeLinecap;
  6139. this.wireframeLinejoin = source.wireframeLinejoin;
  6140. this.skinning = source.skinning;
  6141. this.morphTargets = source.morphTargets;
  6142. return this;
  6143. };
  6144. /**
  6145. * @author mrdoob / http://mrdoob.com/
  6146. */
  6147. function BufferAttribute(array, itemSize, normalized) {
  6148. if (Array.isArray(array)) {
  6149. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  6150. }
  6151. this.name = '';
  6152. this.array = array;
  6153. this.itemSize = itemSize;
  6154. this.count = array !== undefined ? array.length / itemSize : 0;
  6155. this.normalized = normalized === true;
  6156. this.dynamic = false;
  6157. this.updateRange = {
  6158. offset: 0,
  6159. count: -1
  6160. };
  6161. this.version = 0;
  6162. }
  6163. Object.defineProperty(BufferAttribute.prototype, 'needsUpdate', {
  6164. set: function (value) {
  6165. if (value === true) this.version++;
  6166. }
  6167. });
  6168. Object.assign(BufferAttribute.prototype, {
  6169. isBufferAttribute: true,
  6170. onUploadCallback: function () {},
  6171. setDynamic: function (value) {
  6172. this.dynamic = value;
  6173. return this;
  6174. },
  6175. copy: function (source) {
  6176. this.name = source.name;
  6177. this.array = new source.array.constructor(source.array);
  6178. this.itemSize = source.itemSize;
  6179. this.count = source.count;
  6180. this.normalized = source.normalized;
  6181. this.dynamic = source.dynamic;
  6182. return this;
  6183. },
  6184. copyAt: function (index1, attribute, index2) {
  6185. index1 *= this.itemSize;
  6186. index2 *= attribute.itemSize;
  6187. for (var i = 0, l = this.itemSize; i < l; i++) {
  6188. this.array[index1 + i] = attribute.array[index2 + i];
  6189. }
  6190. return this;
  6191. },
  6192. copyArray: function (array) {
  6193. this.array.set(array);
  6194. return this;
  6195. },
  6196. copyColorsArray: function (colors) {
  6197. var array = this.array,
  6198. offset = 0;
  6199. for (var i = 0, l = colors.length; i < l; i++) {
  6200. var color = colors[i];
  6201. if (color === undefined) {
  6202. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  6203. color = new Color();
  6204. }
  6205. array[offset++] = color.r;
  6206. array[offset++] = color.g;
  6207. array[offset++] = color.b;
  6208. }
  6209. return this;
  6210. },
  6211. copyVector2sArray: function (vectors) {
  6212. var array = this.array,
  6213. offset = 0;
  6214. for (var i = 0, l = vectors.length; i < l; i++) {
  6215. var vector = vectors[i];
  6216. if (vector === undefined) {
  6217. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  6218. vector = new Vector2();
  6219. }
  6220. array[offset++] = vector.x;
  6221. array[offset++] = vector.y;
  6222. }
  6223. return this;
  6224. },
  6225. copyVector3sArray: function (vectors) {
  6226. var array = this.array,
  6227. offset = 0;
  6228. for (var i = 0, l = vectors.length; i < l; i++) {
  6229. var vector = vectors[i];
  6230. if (vector === undefined) {
  6231. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  6232. vector = new Vector3();
  6233. }
  6234. array[offset++] = vector.x;
  6235. array[offset++] = vector.y;
  6236. array[offset++] = vector.z;
  6237. }
  6238. return this;
  6239. },
  6240. copyVector4sArray: function (vectors) {
  6241. var array = this.array,
  6242. offset = 0;
  6243. for (var i = 0, l = vectors.length; i < l; i++) {
  6244. var vector = vectors[i];
  6245. if (vector === undefined) {
  6246. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  6247. vector = new Vector4();
  6248. }
  6249. array[offset++] = vector.x;
  6250. array[offset++] = vector.y;
  6251. array[offset++] = vector.z;
  6252. array[offset++] = vector.w;
  6253. }
  6254. return this;
  6255. },
  6256. set: function (value, offset) {
  6257. if (offset === undefined) offset = 0;
  6258. this.array.set(value, offset);
  6259. return this;
  6260. },
  6261. getX: function (index) {
  6262. return this.array[index * this.itemSize];
  6263. },
  6264. setX: function (index, x) {
  6265. this.array[index * this.itemSize] = x;
  6266. return this;
  6267. },
  6268. getY: function (index) {
  6269. return this.array[index * this.itemSize + 1];
  6270. },
  6271. setY: function (index, y) {
  6272. this.array[index * this.itemSize + 1] = y;
  6273. return this;
  6274. },
  6275. getZ: function (index) {
  6276. return this.array[index * this.itemSize + 2];
  6277. },
  6278. setZ: function (index, z) {
  6279. this.array[index * this.itemSize + 2] = z;
  6280. return this;
  6281. },
  6282. getW: function (index) {
  6283. return this.array[index * this.itemSize + 3];
  6284. },
  6285. setW: function (index, w) {
  6286. this.array[index * this.itemSize + 3] = w;
  6287. return this;
  6288. },
  6289. setXY: function (index, x, y) {
  6290. index *= this.itemSize;
  6291. this.array[index + 0] = x;
  6292. this.array[index + 1] = y;
  6293. return this;
  6294. },
  6295. setXYZ: function (index, x, y, z) {
  6296. index *= this.itemSize;
  6297. this.array[index + 0] = x;
  6298. this.array[index + 1] = y;
  6299. this.array[index + 2] = z;
  6300. return this;
  6301. },
  6302. setXYZW: function (index, x, y, z, w) {
  6303. index *= this.itemSize;
  6304. this.array[index + 0] = x;
  6305. this.array[index + 1] = y;
  6306. this.array[index + 2] = z;
  6307. this.array[index + 3] = w;
  6308. return this;
  6309. },
  6310. onUpload: function (callback) {
  6311. this.onUploadCallback = callback;
  6312. return this;
  6313. },
  6314. clone: function () {
  6315. return new this.constructor(this.array, this.itemSize).copy(this);
  6316. },
  6317. toJSON: function () {
  6318. return {
  6319. itemSize: this.itemSize,
  6320. type: this.array.constructor.name,
  6321. array: Array.prototype.slice.call(this.array),
  6322. normalized: this.normalized
  6323. };
  6324. }
  6325. }); //
  6326. function Int8BufferAttribute(array, itemSize, normalized) {
  6327. BufferAttribute.call(this, new Int8Array(array), itemSize, normalized);
  6328. }
  6329. Int8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6330. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  6331. function Uint8BufferAttribute(array, itemSize, normalized) {
  6332. BufferAttribute.call(this, new Uint8Array(array), itemSize, normalized);
  6333. }
  6334. Uint8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6335. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  6336. function Uint8ClampedBufferAttribute(array, itemSize, normalized) {
  6337. BufferAttribute.call(this, new Uint8ClampedArray(array), itemSize, normalized);
  6338. }
  6339. Uint8ClampedBufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6340. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  6341. function Int16BufferAttribute(array, itemSize, normalized) {
  6342. BufferAttribute.call(this, new Int16Array(array), itemSize, normalized);
  6343. }
  6344. Int16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6345. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  6346. function Uint16BufferAttribute(array, itemSize, normalized) {
  6347. BufferAttribute.call(this, new Uint16Array(array), itemSize, normalized);
  6348. }
  6349. Uint16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6350. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  6351. function Int32BufferAttribute(array, itemSize, normalized) {
  6352. BufferAttribute.call(this, new Int32Array(array), itemSize, normalized);
  6353. }
  6354. Int32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6355. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  6356. function Uint32BufferAttribute(array, itemSize, normalized) {
  6357. BufferAttribute.call(this, new Uint32Array(array), itemSize, normalized);
  6358. }
  6359. Uint32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6360. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  6361. function Float32BufferAttribute(array, itemSize, normalized) {
  6362. BufferAttribute.call(this, new Float32Array(array), itemSize, normalized);
  6363. }
  6364. Float32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6365. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  6366. function Float64BufferAttribute(array, itemSize, normalized) {
  6367. BufferAttribute.call(this, new Float64Array(array), itemSize, normalized);
  6368. }
  6369. Float64BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6370. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  6371. /**
  6372. * @author mrdoob / http://mrdoob.com/
  6373. */
  6374. function DirectGeometry() {
  6375. this.vertices = [];
  6376. this.normals = [];
  6377. this.colors = [];
  6378. this.uvs = [];
  6379. this.uvs2 = [];
  6380. this.groups = [];
  6381. this.morphTargets = {};
  6382. this.skinWeights = [];
  6383. this.skinIndices = []; // this.lineDistances = [];
  6384. this.boundingBox = null;
  6385. this.boundingSphere = null; // update flags
  6386. this.verticesNeedUpdate = false;
  6387. this.normalsNeedUpdate = false;
  6388. this.colorsNeedUpdate = false;
  6389. this.uvsNeedUpdate = false;
  6390. this.groupsNeedUpdate = false;
  6391. }
  6392. Object.assign(DirectGeometry.prototype, {
  6393. computeGroups: function (geometry) {
  6394. var group;
  6395. var groups = [];
  6396. var materialIndex = undefined;
  6397. var faces = geometry.faces;
  6398. for (var i = 0; i < faces.length; i++) {
  6399. var face = faces[i]; // materials
  6400. if (face.materialIndex !== materialIndex) {
  6401. materialIndex = face.materialIndex;
  6402. if (group !== undefined) {
  6403. group.count = i * 3 - group.start;
  6404. groups.push(group);
  6405. }
  6406. group = {
  6407. start: i * 3,
  6408. materialIndex: materialIndex
  6409. };
  6410. }
  6411. }
  6412. if (group !== undefined) {
  6413. group.count = i * 3 - group.start;
  6414. groups.push(group);
  6415. }
  6416. this.groups = groups;
  6417. },
  6418. fromGeometry: function (geometry) {
  6419. var faces = geometry.faces;
  6420. var vertices = geometry.vertices;
  6421. var faceVertexUvs = geometry.faceVertexUvs;
  6422. var hasFaceVertexUv = faceVertexUvs[0] && faceVertexUvs[0].length > 0;
  6423. var hasFaceVertexUv2 = faceVertexUvs[1] && faceVertexUvs[1].length > 0; // morphs
  6424. var morphTargets = geometry.morphTargets;
  6425. var morphTargetsLength = morphTargets.length;
  6426. var morphTargetsPosition;
  6427. if (morphTargetsLength > 0) {
  6428. morphTargetsPosition = [];
  6429. for (var i = 0; i < morphTargetsLength; i++) {
  6430. morphTargetsPosition[i] = {
  6431. name: morphTargets[i].name,
  6432. data: []
  6433. };
  6434. }
  6435. this.morphTargets.position = morphTargetsPosition;
  6436. }
  6437. var morphNormals = geometry.morphNormals;
  6438. var morphNormalsLength = morphNormals.length;
  6439. var morphTargetsNormal;
  6440. if (morphNormalsLength > 0) {
  6441. morphTargetsNormal = [];
  6442. for (var i = 0; i < morphNormalsLength; i++) {
  6443. morphTargetsNormal[i] = {
  6444. name: morphNormals[i].name,
  6445. data: []
  6446. };
  6447. }
  6448. this.morphTargets.normal = morphTargetsNormal;
  6449. } // skins
  6450. var skinIndices = geometry.skinIndices;
  6451. var skinWeights = geometry.skinWeights;
  6452. var hasSkinIndices = skinIndices.length === vertices.length;
  6453. var hasSkinWeights = skinWeights.length === vertices.length; //
  6454. if (vertices.length > 0 && faces.length === 0) {
  6455. console.error('THREE.DirectGeometry: Faceless geometries are not supported.');
  6456. }
  6457. for (var i = 0; i < faces.length; i++) {
  6458. var face = faces[i];
  6459. this.vertices.push(vertices[face.a], vertices[face.b], vertices[face.c]);
  6460. var vertexNormals = face.vertexNormals;
  6461. if (vertexNormals.length === 3) {
  6462. this.normals.push(vertexNormals[0], vertexNormals[1], vertexNormals[2]);
  6463. } else {
  6464. var normal = face.normal;
  6465. this.normals.push(normal, normal, normal);
  6466. }
  6467. var vertexColors = face.vertexColors;
  6468. if (vertexColors.length === 3) {
  6469. this.colors.push(vertexColors[0], vertexColors[1], vertexColors[2]);
  6470. } else {
  6471. var color = face.color;
  6472. this.colors.push(color, color, color);
  6473. }
  6474. if (hasFaceVertexUv === true) {
  6475. var vertexUvs = faceVertexUvs[0][i];
  6476. if (vertexUvs !== undefined) {
  6477. this.uvs.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]);
  6478. } else {
  6479. console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i);
  6480. this.uvs.push(new Vector2(), new Vector2(), new Vector2());
  6481. }
  6482. }
  6483. if (hasFaceVertexUv2 === true) {
  6484. var vertexUvs = faceVertexUvs[1][i];
  6485. if (vertexUvs !== undefined) {
  6486. this.uvs2.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]);
  6487. } else {
  6488. console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i);
  6489. this.uvs2.push(new Vector2(), new Vector2(), new Vector2());
  6490. }
  6491. } // morphs
  6492. for (var j = 0; j < morphTargetsLength; j++) {
  6493. var morphTarget = morphTargets[j].vertices;
  6494. morphTargetsPosition[j].data.push(morphTarget[face.a], morphTarget[face.b], morphTarget[face.c]);
  6495. }
  6496. for (var j = 0; j < morphNormalsLength; j++) {
  6497. var morphNormal = morphNormals[j].vertexNormals[i];
  6498. morphTargetsNormal[j].data.push(morphNormal.a, morphNormal.b, morphNormal.c);
  6499. } // skins
  6500. if (hasSkinIndices) {
  6501. this.skinIndices.push(skinIndices[face.a], skinIndices[face.b], skinIndices[face.c]);
  6502. }
  6503. if (hasSkinWeights) {
  6504. this.skinWeights.push(skinWeights[face.a], skinWeights[face.b], skinWeights[face.c]);
  6505. }
  6506. }
  6507. this.computeGroups(geometry);
  6508. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6509. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6510. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6511. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6512. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6513. if (geometry.boundingSphere !== null) {
  6514. this.boundingSphere = geometry.boundingSphere.clone();
  6515. }
  6516. if (geometry.boundingBox !== null) {
  6517. this.boundingBox = geometry.boundingBox.clone();
  6518. }
  6519. return this;
  6520. }
  6521. });
  6522. /**
  6523. * @author mrdoob / http://mrdoob.com/
  6524. */
  6525. function arrayMax(array) {
  6526. if (array.length === 0) return -Infinity;
  6527. var max = array[0];
  6528. for (var i = 1, l = array.length; i < l; ++i) {
  6529. if (array[i] > max) max = array[i];
  6530. }
  6531. return max;
  6532. }
  6533. /**
  6534. * @author alteredq / http://alteredqualia.com/
  6535. * @author mrdoob / http://mrdoob.com/
  6536. */
  6537. var _bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id
  6538. var _m1$2 = new Matrix4();
  6539. var _obj = new Object3D();
  6540. var _offset = new Vector3();
  6541. var _box$1 = new Box3();
  6542. var _boxMorphTargets = new Box3();
  6543. var _vector$4 = new Vector3();
  6544. function BufferGeometry() {
  6545. Object.defineProperty(this, 'id', {
  6546. value: _bufferGeometryId += 2
  6547. });
  6548. this.uuid = _Math.generateUUID();
  6549. this.name = '';
  6550. this.type = 'BufferGeometry';
  6551. this.index = null;
  6552. this.attributes = {};
  6553. this.morphAttributes = {};
  6554. this.groups = [];
  6555. this.boundingBox = null;
  6556. this.boundingSphere = null;
  6557. this.drawRange = {
  6558. start: 0,
  6559. count: Infinity
  6560. };
  6561. this.userData = {};
  6562. }
  6563. BufferGeometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  6564. constructor: BufferGeometry,
  6565. isBufferGeometry: true,
  6566. getIndex: function () {
  6567. return this.index;
  6568. },
  6569. setIndex: function (index) {
  6570. if (Array.isArray(index)) {
  6571. this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  6572. } else {
  6573. this.index = index;
  6574. }
  6575. },
  6576. addAttribute: function (name, attribute) {
  6577. if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
  6578. console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
  6579. return this.addAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
  6580. }
  6581. if (name === 'index') {
  6582. console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
  6583. this.setIndex(attribute);
  6584. return this;
  6585. }
  6586. return this.setAttribute(name, attribute);
  6587. },
  6588. getAttribute: function (name) {
  6589. return this.attributes[name];
  6590. },
  6591. setAttribute: function (name, attribute) {
  6592. this.attributes[name] = attribute;
  6593. return this;
  6594. },
  6595. removeAttribute: function (name) {
  6596. delete this.attributes[name];
  6597. return this;
  6598. },
  6599. addGroup: function (start, count, materialIndex) {
  6600. this.groups.push({
  6601. start: start,
  6602. count: count,
  6603. materialIndex: materialIndex !== undefined ? materialIndex : 0
  6604. });
  6605. },
  6606. clearGroups: function () {
  6607. this.groups = [];
  6608. },
  6609. setDrawRange: function (start, count) {
  6610. this.drawRange.start = start;
  6611. this.drawRange.count = count;
  6612. },
  6613. applyMatrix: function (matrix) {
  6614. var position = this.attributes.position;
  6615. if (position !== undefined) {
  6616. matrix.applyToBufferAttribute(position);
  6617. position.needsUpdate = true;
  6618. }
  6619. var normal = this.attributes.normal;
  6620. if (normal !== undefined) {
  6621. var normalMatrix = new Matrix3().getNormalMatrix(matrix);
  6622. normalMatrix.applyToBufferAttribute(normal);
  6623. normal.needsUpdate = true;
  6624. }
  6625. var tangent = this.attributes.tangent;
  6626. if (tangent !== undefined) {
  6627. var normalMatrix = new Matrix3().getNormalMatrix(matrix); // Tangent is vec4, but the '.w' component is a sign value (+1/-1).
  6628. normalMatrix.applyToBufferAttribute(tangent);
  6629. tangent.needsUpdate = true;
  6630. }
  6631. if (this.boundingBox !== null) {
  6632. this.computeBoundingBox();
  6633. }
  6634. if (this.boundingSphere !== null) {
  6635. this.computeBoundingSphere();
  6636. }
  6637. return this;
  6638. },
  6639. rotateX: function (angle) {
  6640. // rotate geometry around world x-axis
  6641. _m1$2.makeRotationX(angle);
  6642. this.applyMatrix(_m1$2);
  6643. return this;
  6644. },
  6645. rotateY: function (angle) {
  6646. // rotate geometry around world y-axis
  6647. _m1$2.makeRotationY(angle);
  6648. this.applyMatrix(_m1$2);
  6649. return this;
  6650. },
  6651. rotateZ: function (angle) {
  6652. // rotate geometry around world z-axis
  6653. _m1$2.makeRotationZ(angle);
  6654. this.applyMatrix(_m1$2);
  6655. return this;
  6656. },
  6657. translate: function (x, y, z) {
  6658. // translate geometry
  6659. _m1$2.makeTranslation(x, y, z);
  6660. this.applyMatrix(_m1$2);
  6661. return this;
  6662. },
  6663. scale: function (x, y, z) {
  6664. // scale geometry
  6665. _m1$2.makeScale(x, y, z);
  6666. this.applyMatrix(_m1$2);
  6667. return this;
  6668. },
  6669. lookAt: function (vector) {
  6670. _obj.lookAt(vector);
  6671. _obj.updateMatrix();
  6672. this.applyMatrix(_obj.matrix);
  6673. return this;
  6674. },
  6675. center: function () {
  6676. this.computeBoundingBox();
  6677. this.boundingBox.getCenter(_offset).negate();
  6678. this.translate(_offset.x, _offset.y, _offset.z);
  6679. return this;
  6680. },
  6681. setFromObject: function (object) {
  6682. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  6683. var geometry = object.geometry;
  6684. if (object.isPoints || object.isLine) {
  6685. var positions = new Float32BufferAttribute(geometry.vertices.length * 3, 3);
  6686. var colors = new Float32BufferAttribute(geometry.colors.length * 3, 3);
  6687. this.addAttribute('position', positions.copyVector3sArray(geometry.vertices));
  6688. this.addAttribute('color', colors.copyColorsArray(geometry.colors));
  6689. if (geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length) {
  6690. var lineDistances = new Float32BufferAttribute(geometry.lineDistances.length, 1);
  6691. this.addAttribute('lineDistance', lineDistances.copyArray(geometry.lineDistances));
  6692. }
  6693. if (geometry.boundingSphere !== null) {
  6694. this.boundingSphere = geometry.boundingSphere.clone();
  6695. }
  6696. if (geometry.boundingBox !== null) {
  6697. this.boundingBox = geometry.boundingBox.clone();
  6698. }
  6699. } else if (object.isMesh) {
  6700. if (geometry && geometry.isGeometry) {
  6701. this.fromGeometry(geometry);
  6702. }
  6703. }
  6704. return this;
  6705. },
  6706. setFromPoints: function (points) {
  6707. var position = [];
  6708. for (var i = 0, l = points.length; i < l; i++) {
  6709. var point = points[i];
  6710. position.push(point.x, point.y, point.z || 0);
  6711. }
  6712. this.addAttribute('position', new Float32BufferAttribute(position, 3));
  6713. return this;
  6714. },
  6715. updateFromObject: function (object) {
  6716. var geometry = object.geometry;
  6717. if (object.isMesh) {
  6718. var direct = geometry.__directGeometry;
  6719. if (geometry.elementsNeedUpdate === true) {
  6720. direct = undefined;
  6721. geometry.elementsNeedUpdate = false;
  6722. }
  6723. if (direct === undefined) {
  6724. return this.fromGeometry(geometry);
  6725. }
  6726. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6727. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6728. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6729. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6730. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6731. geometry.verticesNeedUpdate = false;
  6732. geometry.normalsNeedUpdate = false;
  6733. geometry.colorsNeedUpdate = false;
  6734. geometry.uvsNeedUpdate = false;
  6735. geometry.groupsNeedUpdate = false;
  6736. geometry = direct;
  6737. }
  6738. var attribute;
  6739. if (geometry.verticesNeedUpdate === true) {
  6740. attribute = this.attributes.position;
  6741. if (attribute !== undefined) {
  6742. attribute.copyVector3sArray(geometry.vertices);
  6743. attribute.needsUpdate = true;
  6744. }
  6745. geometry.verticesNeedUpdate = false;
  6746. }
  6747. if (geometry.normalsNeedUpdate === true) {
  6748. attribute = this.attributes.normal;
  6749. if (attribute !== undefined) {
  6750. attribute.copyVector3sArray(geometry.normals);
  6751. attribute.needsUpdate = true;
  6752. }
  6753. geometry.normalsNeedUpdate = false;
  6754. }
  6755. if (geometry.colorsNeedUpdate === true) {
  6756. attribute = this.attributes.color;
  6757. if (attribute !== undefined) {
  6758. attribute.copyColorsArray(geometry.colors);
  6759. attribute.needsUpdate = true;
  6760. }
  6761. geometry.colorsNeedUpdate = false;
  6762. }
  6763. if (geometry.uvsNeedUpdate) {
  6764. attribute = this.attributes.uv;
  6765. if (attribute !== undefined) {
  6766. attribute.copyVector2sArray(geometry.uvs);
  6767. attribute.needsUpdate = true;
  6768. }
  6769. geometry.uvsNeedUpdate = false;
  6770. }
  6771. if (geometry.lineDistancesNeedUpdate) {
  6772. attribute = this.attributes.lineDistance;
  6773. if (attribute !== undefined) {
  6774. attribute.copyArray(geometry.lineDistances);
  6775. attribute.needsUpdate = true;
  6776. }
  6777. geometry.lineDistancesNeedUpdate = false;
  6778. }
  6779. if (geometry.groupsNeedUpdate) {
  6780. geometry.computeGroups(object.geometry);
  6781. this.groups = geometry.groups;
  6782. geometry.groupsNeedUpdate = false;
  6783. }
  6784. return this;
  6785. },
  6786. fromGeometry: function (geometry) {
  6787. geometry.__directGeometry = new DirectGeometry().fromGeometry(geometry);
  6788. return this.fromDirectGeometry(geometry.__directGeometry);
  6789. },
  6790. fromDirectGeometry: function (geometry) {
  6791. var positions = new Float32Array(geometry.vertices.length * 3);
  6792. this.addAttribute('position', new BufferAttribute(positions, 3).copyVector3sArray(geometry.vertices));
  6793. if (geometry.normals.length > 0) {
  6794. var normals = new Float32Array(geometry.normals.length * 3);
  6795. this.addAttribute('normal', new BufferAttribute(normals, 3).copyVector3sArray(geometry.normals));
  6796. }
  6797. if (geometry.colors.length > 0) {
  6798. var colors = new Float32Array(geometry.colors.length * 3);
  6799. this.addAttribute('color', new BufferAttribute(colors, 3).copyColorsArray(geometry.colors));
  6800. }
  6801. if (geometry.uvs.length > 0) {
  6802. var uvs = new Float32Array(geometry.uvs.length * 2);
  6803. this.addAttribute('uv', new BufferAttribute(uvs, 2).copyVector2sArray(geometry.uvs));
  6804. }
  6805. if (geometry.uvs2.length > 0) {
  6806. var uvs2 = new Float32Array(geometry.uvs2.length * 2);
  6807. this.addAttribute('uv2', new BufferAttribute(uvs2, 2).copyVector2sArray(geometry.uvs2));
  6808. } // groups
  6809. this.groups = geometry.groups; // morphs
  6810. for (var name in geometry.morphTargets) {
  6811. var array = [];
  6812. var morphTargets = geometry.morphTargets[name];
  6813. for (var i = 0, l = morphTargets.length; i < l; i++) {
  6814. var morphTarget = morphTargets[i];
  6815. var attribute = new Float32BufferAttribute(morphTarget.data.length * 3, 3);
  6816. attribute.name = morphTarget.name;
  6817. array.push(attribute.copyVector3sArray(morphTarget.data));
  6818. }
  6819. this.morphAttributes[name] = array;
  6820. } // skinning
  6821. if (geometry.skinIndices.length > 0) {
  6822. var skinIndices = new Float32BufferAttribute(geometry.skinIndices.length * 4, 4);
  6823. this.addAttribute('skinIndex', skinIndices.copyVector4sArray(geometry.skinIndices));
  6824. }
  6825. if (geometry.skinWeights.length > 0) {
  6826. var skinWeights = new Float32BufferAttribute(geometry.skinWeights.length * 4, 4);
  6827. this.addAttribute('skinWeight', skinWeights.copyVector4sArray(geometry.skinWeights));
  6828. } //
  6829. if (geometry.boundingSphere !== null) {
  6830. this.boundingSphere = geometry.boundingSphere.clone();
  6831. }
  6832. if (geometry.boundingBox !== null) {
  6833. this.boundingBox = geometry.boundingBox.clone();
  6834. }
  6835. return this;
  6836. },
  6837. computeBoundingBox: function () {
  6838. if (this.boundingBox === null) {
  6839. this.boundingBox = new Box3();
  6840. }
  6841. var position = this.attributes.position;
  6842. var morphAttributesPosition = this.morphAttributes.position;
  6843. if (position !== undefined) {
  6844. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  6845. if (morphAttributesPosition) {
  6846. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6847. var morphAttribute = morphAttributesPosition[i];
  6848. _box$1.setFromBufferAttribute(morphAttribute);
  6849. this.boundingBox.expandByPoint(_box$1.min);
  6850. this.boundingBox.expandByPoint(_box$1.max);
  6851. }
  6852. }
  6853. } else {
  6854. this.boundingBox.makeEmpty();
  6855. }
  6856. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  6857. console.error('THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  6858. }
  6859. },
  6860. computeBoundingSphere: function () {
  6861. if (this.boundingSphere === null) {
  6862. this.boundingSphere = new Sphere();
  6863. }
  6864. var position = this.attributes.position;
  6865. var morphAttributesPosition = this.morphAttributes.position;
  6866. if (position) {
  6867. // first, find the center of the bounding sphere
  6868. var center = this.boundingSphere.center;
  6869. _box$1.setFromBufferAttribute(position); // process morph attributes if present
  6870. if (morphAttributesPosition) {
  6871. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6872. var morphAttribute = morphAttributesPosition[i];
  6873. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  6874. _box$1.expandByPoint(_boxMorphTargets.min);
  6875. _box$1.expandByPoint(_boxMorphTargets.max);
  6876. }
  6877. }
  6878. _box$1.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  6879. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6880. var maxRadiusSq = 0;
  6881. for (var i = 0, il = position.count; i < il; i++) {
  6882. _vector$4.fromBufferAttribute(position, i);
  6883. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
  6884. } // process morph attributes if present
  6885. if (morphAttributesPosition) {
  6886. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6887. var morphAttribute = morphAttributesPosition[i];
  6888. for (var j = 0, jl = morphAttribute.count; j < jl; j++) {
  6889. _vector$4.fromBufferAttribute(morphAttribute, j);
  6890. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
  6891. }
  6892. }
  6893. }
  6894. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  6895. if (isNaN(this.boundingSphere.radius)) {
  6896. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  6897. }
  6898. }
  6899. },
  6900. computeFaceNormals: function () {// backwards compatibility
  6901. },
  6902. computeVertexNormals: function () {
  6903. var index = this.index;
  6904. var attributes = this.attributes;
  6905. if (attributes.position) {
  6906. var positions = attributes.position.array;
  6907. if (attributes.normal === undefined) {
  6908. this.addAttribute('normal', new BufferAttribute(new Float32Array(positions.length), 3));
  6909. } else {
  6910. // reset existing normals to zero
  6911. var array = attributes.normal.array;
  6912. for (var i = 0, il = array.length; i < il; i++) {
  6913. array[i] = 0;
  6914. }
  6915. }
  6916. var normals = attributes.normal.array;
  6917. var vA, vB, vC;
  6918. var pA = new Vector3(),
  6919. pB = new Vector3(),
  6920. pC = new Vector3();
  6921. var cb = new Vector3(),
  6922. ab = new Vector3(); // indexed elements
  6923. if (index) {
  6924. var indices = index.array;
  6925. for (var i = 0, il = index.count; i < il; i += 3) {
  6926. vA = indices[i + 0] * 3;
  6927. vB = indices[i + 1] * 3;
  6928. vC = indices[i + 2] * 3;
  6929. pA.fromArray(positions, vA);
  6930. pB.fromArray(positions, vB);
  6931. pC.fromArray(positions, vC);
  6932. cb.subVectors(pC, pB);
  6933. ab.subVectors(pA, pB);
  6934. cb.cross(ab);
  6935. normals[vA] += cb.x;
  6936. normals[vA + 1] += cb.y;
  6937. normals[vA + 2] += cb.z;
  6938. normals[vB] += cb.x;
  6939. normals[vB + 1] += cb.y;
  6940. normals[vB + 2] += cb.z;
  6941. normals[vC] += cb.x;
  6942. normals[vC + 1] += cb.y;
  6943. normals[vC + 2] += cb.z;
  6944. }
  6945. } else {
  6946. // non-indexed elements (unconnected triangle soup)
  6947. for (var i = 0, il = positions.length; i < il; i += 9) {
  6948. pA.fromArray(positions, i);
  6949. pB.fromArray(positions, i + 3);
  6950. pC.fromArray(positions, i + 6);
  6951. cb.subVectors(pC, pB);
  6952. ab.subVectors(pA, pB);
  6953. cb.cross(ab);
  6954. normals[i] = cb.x;
  6955. normals[i + 1] = cb.y;
  6956. normals[i + 2] = cb.z;
  6957. normals[i + 3] = cb.x;
  6958. normals[i + 4] = cb.y;
  6959. normals[i + 5] = cb.z;
  6960. normals[i + 6] = cb.x;
  6961. normals[i + 7] = cb.y;
  6962. normals[i + 8] = cb.z;
  6963. }
  6964. }
  6965. this.normalizeNormals();
  6966. attributes.normal.needsUpdate = true;
  6967. }
  6968. },
  6969. merge: function (geometry, offset) {
  6970. if (!(geometry && geometry.isBufferGeometry)) {
  6971. console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
  6972. return;
  6973. }
  6974. if (offset === undefined) {
  6975. offset = 0;
  6976. console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
  6977. }
  6978. var attributes = this.attributes;
  6979. for (var key in attributes) {
  6980. if (geometry.attributes[key] === undefined) continue;
  6981. var attribute1 = attributes[key];
  6982. var attributeArray1 = attribute1.array;
  6983. var attribute2 = geometry.attributes[key];
  6984. var attributeArray2 = attribute2.array;
  6985. var attributeOffset = attribute2.itemSize * offset;
  6986. var length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
  6987. for (var i = 0, j = attributeOffset; i < length; i++, j++) {
  6988. attributeArray1[j] = attributeArray2[i];
  6989. }
  6990. }
  6991. return this;
  6992. },
  6993. normalizeNormals: function () {
  6994. var normals = this.attributes.normal;
  6995. for (var i = 0, il = normals.count; i < il; i++) {
  6996. _vector$4.x = normals.getX(i);
  6997. _vector$4.y = normals.getY(i);
  6998. _vector$4.z = normals.getZ(i);
  6999. _vector$4.normalize();
  7000. normals.setXYZ(i, _vector$4.x, _vector$4.y, _vector$4.z);
  7001. }
  7002. },
  7003. toNonIndexed: function () {
  7004. function convertBufferAttribute(attribute, indices) {
  7005. var array = attribute.array;
  7006. var itemSize = attribute.itemSize;
  7007. var array2 = new array.constructor(indices.length * itemSize);
  7008. var index = 0,
  7009. index2 = 0;
  7010. for (var i = 0, l = indices.length; i < l; i++) {
  7011. index = indices[i] * itemSize;
  7012. for (var j = 0; j < itemSize; j++) {
  7013. array2[index2++] = array[index++];
  7014. }
  7015. }
  7016. return new BufferAttribute(array2, itemSize);
  7017. } //
  7018. if (this.index === null) {
  7019. console.warn('THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.');
  7020. return this;
  7021. }
  7022. var geometry2 = new BufferGeometry();
  7023. var indices = this.index.array;
  7024. var attributes = this.attributes; // attributes
  7025. for (var name in attributes) {
  7026. var attribute = attributes[name];
  7027. var newAttribute = convertBufferAttribute(attribute, indices);
  7028. geometry2.addAttribute(name, newAttribute);
  7029. } // morph attributes
  7030. var morphAttributes = this.morphAttributes;
  7031. for (name in morphAttributes) {
  7032. var morphArray = [];
  7033. var morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  7034. for (var i = 0, il = morphAttribute.length; i < il; i++) {
  7035. var attribute = morphAttribute[i];
  7036. var newAttribute = convertBufferAttribute(attribute, indices);
  7037. morphArray.push(newAttribute);
  7038. }
  7039. geometry2.morphAttributes[name] = morphArray;
  7040. } // groups
  7041. var groups = this.groups;
  7042. for (var i = 0, l = groups.length; i < l; i++) {
  7043. var group = groups[i];
  7044. geometry2.addGroup(group.start, group.count, group.materialIndex);
  7045. }
  7046. return geometry2;
  7047. },
  7048. toJSON: function () {
  7049. var data = {
  7050. metadata: {
  7051. version: 4.5,
  7052. type: 'BufferGeometry',
  7053. generator: 'BufferGeometry.toJSON'
  7054. }
  7055. }; // standard BufferGeometry serialization
  7056. data.uuid = this.uuid;
  7057. data.type = this.type;
  7058. if (this.name !== '') data.name = this.name;
  7059. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  7060. if (this.parameters !== undefined) {
  7061. var parameters = this.parameters;
  7062. for (var key in parameters) {
  7063. if (parameters[key] !== undefined) data[key] = parameters[key];
  7064. }
  7065. return data;
  7066. }
  7067. data.data = {
  7068. attributes: {}
  7069. };
  7070. var index = this.index;
  7071. if (index !== null) {
  7072. data.data.index = {
  7073. type: index.array.constructor.name,
  7074. array: Array.prototype.slice.call(index.array)
  7075. };
  7076. }
  7077. var attributes = this.attributes;
  7078. for (var key in attributes) {
  7079. var attribute = attributes[key];
  7080. var attributeData = attribute.toJSON();
  7081. if (attribute.name !== '') attributeData.name = attribute.name;
  7082. data.data.attributes[key] = attributeData;
  7083. }
  7084. var morphAttributes = {};
  7085. var hasMorphAttributes = false;
  7086. for (var key in this.morphAttributes) {
  7087. var attributeArray = this.morphAttributes[key];
  7088. var array = [];
  7089. for (var i = 0, il = attributeArray.length; i < il; i++) {
  7090. var attribute = attributeArray[i];
  7091. var attributeData = attribute.toJSON();
  7092. if (attribute.name !== '') attributeData.name = attribute.name;
  7093. array.push(attributeData);
  7094. }
  7095. if (array.length > 0) {
  7096. morphAttributes[key] = array;
  7097. hasMorphAttributes = true;
  7098. }
  7099. }
  7100. if (hasMorphAttributes) data.data.morphAttributes = morphAttributes;
  7101. var groups = this.groups;
  7102. if (groups.length > 0) {
  7103. data.data.groups = JSON.parse(JSON.stringify(groups));
  7104. }
  7105. var boundingSphere = this.boundingSphere;
  7106. if (boundingSphere !== null) {
  7107. data.data.boundingSphere = {
  7108. center: boundingSphere.center.toArray(),
  7109. radius: boundingSphere.radius
  7110. };
  7111. }
  7112. return data;
  7113. },
  7114. clone: function () {
  7115. /*
  7116. // Handle primitives
  7117. var parameters = this.parameters;
  7118. if ( parameters !== undefined ) {
  7119. var values = [];
  7120. for ( var key in parameters ) {
  7121. values.push( parameters[ key ] );
  7122. }
  7123. var geometry = Object.create( this.constructor.prototype );
  7124. this.constructor.apply( geometry, values );
  7125. return geometry;
  7126. }
  7127. return new this.constructor().copy( this );
  7128. */
  7129. return new BufferGeometry().copy(this);
  7130. },
  7131. copy: function (source) {
  7132. var name, i, l; // reset
  7133. this.index = null;
  7134. this.attributes = {};
  7135. this.morphAttributes = {};
  7136. this.groups = [];
  7137. this.boundingBox = null;
  7138. this.boundingSphere = null; // name
  7139. this.name = source.name; // index
  7140. var index = source.index;
  7141. if (index !== null) {
  7142. this.setIndex(index.clone());
  7143. } // attributes
  7144. var attributes = source.attributes;
  7145. for (name in attributes) {
  7146. var attribute = attributes[name];
  7147. this.addAttribute(name, attribute.clone());
  7148. } // morph attributes
  7149. var morphAttributes = source.morphAttributes;
  7150. for (name in morphAttributes) {
  7151. var array = [];
  7152. var morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  7153. for (i = 0, l = morphAttribute.length; i < l; i++) {
  7154. array.push(morphAttribute[i].clone());
  7155. }
  7156. this.morphAttributes[name] = array;
  7157. } // groups
  7158. var groups = source.groups;
  7159. for (i = 0, l = groups.length; i < l; i++) {
  7160. var group = groups[i];
  7161. this.addGroup(group.start, group.count, group.materialIndex);
  7162. } // bounding box
  7163. var boundingBox = source.boundingBox;
  7164. if (boundingBox !== null) {
  7165. this.boundingBox = boundingBox.clone();
  7166. } // bounding sphere
  7167. var boundingSphere = source.boundingSphere;
  7168. if (boundingSphere !== null) {
  7169. this.boundingSphere = boundingSphere.clone();
  7170. } // draw range
  7171. this.drawRange.start = source.drawRange.start;
  7172. this.drawRange.count = source.drawRange.count; // user data
  7173. this.userData = source.userData;
  7174. return this;
  7175. },
  7176. dispose: function () {
  7177. this.dispatchEvent({
  7178. type: 'dispose'
  7179. });
  7180. }
  7181. });
  7182. /**
  7183. * @author mrdoob / http://mrdoob.com/
  7184. * @author alteredq / http://alteredqualia.com/
  7185. * @author mikael emtinger / http://gomo.se/
  7186. * @author jonobr1 / http://jonobr1.com/
  7187. */
  7188. var _inverseMatrix = new Matrix4();
  7189. var _ray = new Ray();
  7190. var _sphere = new Sphere();
  7191. var _vA = new Vector3();
  7192. var _vB = new Vector3();
  7193. var _vC = new Vector3();
  7194. var _tempA = new Vector3();
  7195. var _tempB = new Vector3();
  7196. var _tempC = new Vector3();
  7197. var _morphA = new Vector3();
  7198. var _morphB = new Vector3();
  7199. var _morphC = new Vector3();
  7200. var _uvA = new Vector2();
  7201. var _uvB = new Vector2();
  7202. var _uvC = new Vector2();
  7203. var _intersectionPoint = new Vector3();
  7204. var _intersectionPointWorld = new Vector3();
  7205. function Mesh(geometry, material) {
  7206. Object3D.call(this);
  7207. this.type = 'Mesh';
  7208. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  7209. this.material = material !== undefined ? material : new MeshBasicMaterial({
  7210. color: Math.random() * 0xffffff
  7211. });
  7212. this.drawMode = TrianglesDrawMode;
  7213. this.updateMorphTargets();
  7214. }
  7215. Mesh.prototype = Object.assign(Object.create(Object3D.prototype), {
  7216. constructor: Mesh,
  7217. isMesh: true,
  7218. setDrawMode: function (value) {
  7219. this.drawMode = value;
  7220. },
  7221. copy: function (source) {
  7222. Object3D.prototype.copy.call(this, source);
  7223. this.drawMode = source.drawMode;
  7224. if (source.morphTargetInfluences !== undefined) {
  7225. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  7226. }
  7227. if (source.morphTargetDictionary !== undefined) {
  7228. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  7229. }
  7230. return this;
  7231. },
  7232. updateMorphTargets: function () {
  7233. var geometry = this.geometry;
  7234. var m, ml, name;
  7235. if (geometry.isBufferGeometry) {
  7236. var morphAttributes = geometry.morphAttributes;
  7237. var keys = Object.keys(morphAttributes);
  7238. if (keys.length > 0) {
  7239. var morphAttribute = morphAttributes[keys[0]];
  7240. if (morphAttribute !== undefined) {
  7241. this.morphTargetInfluences = [];
  7242. this.morphTargetDictionary = {};
  7243. for (m = 0, ml = morphAttribute.length; m < ml; m++) {
  7244. name = morphAttribute[m].name || String(m);
  7245. this.morphTargetInfluences.push(0);
  7246. this.morphTargetDictionary[name] = m;
  7247. }
  7248. }
  7249. }
  7250. } else {
  7251. var morphTargets = geometry.morphTargets;
  7252. if (morphTargets !== undefined && morphTargets.length > 0) {
  7253. console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  7254. }
  7255. }
  7256. },
  7257. raycast: function (raycaster, intersects) {
  7258. var geometry = this.geometry;
  7259. var material = this.material;
  7260. var matrixWorld = this.matrixWorld;
  7261. if (material === undefined) return; // Checking boundingSphere distance to ray
  7262. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  7263. _sphere.copy(geometry.boundingSphere);
  7264. _sphere.applyMatrix4(matrixWorld);
  7265. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  7266. _inverseMatrix.getInverse(matrixWorld);
  7267. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix); // Check boundingBox before continuing
  7268. if (geometry.boundingBox !== null) {
  7269. if (_ray.intersectsBox(geometry.boundingBox) === false) return;
  7270. }
  7271. var intersection;
  7272. if (geometry.isBufferGeometry) {
  7273. var a, b, c;
  7274. var index = geometry.index;
  7275. var position = geometry.attributes.position;
  7276. var morphPosition = geometry.morphAttributes.position;
  7277. var uv = geometry.attributes.uv;
  7278. var uv2 = geometry.attributes.uv2;
  7279. var groups = geometry.groups;
  7280. var drawRange = geometry.drawRange;
  7281. var i, j, il, jl;
  7282. var group, groupMaterial;
  7283. var start, end;
  7284. if (index !== null) {
  7285. // indexed buffer geometry
  7286. if (Array.isArray(material)) {
  7287. for (i = 0, il = groups.length; i < il; i++) {
  7288. group = groups[i];
  7289. groupMaterial = material[group.materialIndex];
  7290. start = Math.max(group.start, drawRange.start);
  7291. end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  7292. for (j = start, jl = end; j < jl; j += 3) {
  7293. a = index.getX(j);
  7294. b = index.getX(j + 1);
  7295. c = index.getX(j + 2);
  7296. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);
  7297. if (intersection) {
  7298. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  7299. intersection.face.materialIndex = group.materialIndex;
  7300. intersects.push(intersection);
  7301. }
  7302. }
  7303. }
  7304. } else {
  7305. start = Math.max(0, drawRange.start);
  7306. end = Math.min(index.count, drawRange.start + drawRange.count);
  7307. for (i = start, il = end; i < il; i += 3) {
  7308. a = index.getX(i);
  7309. b = index.getX(i + 1);
  7310. c = index.getX(i + 2);
  7311. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);
  7312. if (intersection) {
  7313. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  7314. intersects.push(intersection);
  7315. }
  7316. }
  7317. }
  7318. } else if (position !== undefined) {
  7319. // non-indexed buffer geometry
  7320. if (Array.isArray(material)) {
  7321. for (i = 0, il = groups.length; i < il; i++) {
  7322. group = groups[i];
  7323. groupMaterial = material[group.materialIndex];
  7324. start = Math.max(group.start, drawRange.start);
  7325. end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  7326. for (j = start, jl = end; j < jl; j += 3) {
  7327. a = j;
  7328. b = j + 1;
  7329. c = j + 2;
  7330. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);
  7331. if (intersection) {
  7332. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  7333. intersection.face.materialIndex = group.materialIndex;
  7334. intersects.push(intersection);
  7335. }
  7336. }
  7337. }
  7338. } else {
  7339. start = Math.max(0, drawRange.start);
  7340. end = Math.min(position.count, drawRange.start + drawRange.count);
  7341. for (i = start, il = end; i < il; i += 3) {
  7342. a = i;
  7343. b = i + 1;
  7344. c = i + 2;
  7345. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);
  7346. if (intersection) {
  7347. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  7348. intersects.push(intersection);
  7349. }
  7350. }
  7351. }
  7352. }
  7353. } else if (geometry.isGeometry) {
  7354. var fvA, fvB, fvC;
  7355. var isMultiMaterial = Array.isArray(material);
  7356. var vertices = geometry.vertices;
  7357. var faces = geometry.faces;
  7358. var uvs;
  7359. var faceVertexUvs = geometry.faceVertexUvs[0];
  7360. if (faceVertexUvs.length > 0) uvs = faceVertexUvs;
  7361. for (var f = 0, fl = faces.length; f < fl; f++) {
  7362. var face = faces[f];
  7363. var faceMaterial = isMultiMaterial ? material[face.materialIndex] : material;
  7364. if (faceMaterial === undefined) continue;
  7365. fvA = vertices[face.a];
  7366. fvB = vertices[face.b];
  7367. fvC = vertices[face.c];
  7368. intersection = checkIntersection(this, faceMaterial, raycaster, _ray, fvA, fvB, fvC, _intersectionPoint);
  7369. if (intersection) {
  7370. if (uvs && uvs[f]) {
  7371. var uvs_f = uvs[f];
  7372. _uvA.copy(uvs_f[0]);
  7373. _uvB.copy(uvs_f[1]);
  7374. _uvC.copy(uvs_f[2]);
  7375. intersection.uv = Triangle.getUV(_intersectionPoint, fvA, fvB, fvC, _uvA, _uvB, _uvC, new Vector2());
  7376. }
  7377. intersection.face = face;
  7378. intersection.faceIndex = f;
  7379. intersects.push(intersection);
  7380. }
  7381. }
  7382. }
  7383. },
  7384. clone: function () {
  7385. return new this.constructor(this.geometry, this.material).copy(this);
  7386. }
  7387. });
  7388. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  7389. var intersect;
  7390. if (material.side === BackSide) {
  7391. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  7392. } else {
  7393. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  7394. }
  7395. if (intersect === null) return null;
  7396. _intersectionPointWorld.copy(point);
  7397. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  7398. var distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  7399. if (distance < raycaster.near || distance > raycaster.far) return null;
  7400. return {
  7401. distance: distance,
  7402. point: _intersectionPointWorld.clone(),
  7403. object: object
  7404. };
  7405. }
  7406. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, uv, uv2, a, b, c) {
  7407. _vA.fromBufferAttribute(position, a);
  7408. _vB.fromBufferAttribute(position, b);
  7409. _vC.fromBufferAttribute(position, c);
  7410. var morphInfluences = object.morphTargetInfluences;
  7411. if (material.morphTargets && morphPosition && morphInfluences) {
  7412. _morphA.set(0, 0, 0);
  7413. _morphB.set(0, 0, 0);
  7414. _morphC.set(0, 0, 0);
  7415. for (var i = 0, il = morphPosition.length; i < il; i++) {
  7416. var influence = morphInfluences[i];
  7417. var morphAttribute = morphPosition[i];
  7418. if (influence === 0) continue;
  7419. _tempA.fromBufferAttribute(morphAttribute, a);
  7420. _tempB.fromBufferAttribute(morphAttribute, b);
  7421. _tempC.fromBufferAttribute(morphAttribute, c);
  7422. _morphA.addScaledVector(_tempA.sub(_vA), influence);
  7423. _morphB.addScaledVector(_tempB.sub(_vB), influence);
  7424. _morphC.addScaledVector(_tempC.sub(_vC), influence);
  7425. }
  7426. _vA.add(_morphA);
  7427. _vB.add(_morphB);
  7428. _vC.add(_morphC);
  7429. }
  7430. var intersection = checkIntersection(object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint);
  7431. if (intersection) {
  7432. if (uv) {
  7433. _uvA.fromBufferAttribute(uv, a);
  7434. _uvB.fromBufferAttribute(uv, b);
  7435. _uvC.fromBufferAttribute(uv, c);
  7436. intersection.uv = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
  7437. }
  7438. if (uv2) {
  7439. _uvA.fromBufferAttribute(uv2, a);
  7440. _uvB.fromBufferAttribute(uv2, b);
  7441. _uvC.fromBufferAttribute(uv2, c);
  7442. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
  7443. }
  7444. var face = new Face3(a, b, c);
  7445. Triangle.getNormal(_vA, _vB, _vC, face.normal);
  7446. intersection.face = face;
  7447. }
  7448. return intersection;
  7449. }
  7450. /**
  7451. * @author mrdoob / http://mrdoob.com/
  7452. * @author kile / http://kile.stravaganza.org/
  7453. * @author alteredq / http://alteredqualia.com/
  7454. * @author mikael emtinger / http://gomo.se/
  7455. * @author zz85 / http://www.lab4games.net/zz85/blog
  7456. * @author bhouston / http://clara.io
  7457. */
  7458. var _geometryId = 0; // Geometry uses even numbers as Id
  7459. var _m1$3 = new Matrix4();
  7460. var _obj$1 = new Object3D();
  7461. var _offset$1 = new Vector3();
  7462. function Geometry() {
  7463. Object.defineProperty(this, 'id', {
  7464. value: _geometryId += 2
  7465. });
  7466. this.uuid = _Math.generateUUID();
  7467. this.name = '';
  7468. this.type = 'Geometry';
  7469. this.vertices = [];
  7470. this.colors = [];
  7471. this.faces = [];
  7472. this.faceVertexUvs = [[]];
  7473. this.morphTargets = [];
  7474. this.morphNormals = [];
  7475. this.skinWeights = [];
  7476. this.skinIndices = [];
  7477. this.lineDistances = [];
  7478. this.boundingBox = null;
  7479. this.boundingSphere = null; // update flags
  7480. this.elementsNeedUpdate = false;
  7481. this.verticesNeedUpdate = false;
  7482. this.uvsNeedUpdate = false;
  7483. this.normalsNeedUpdate = false;
  7484. this.colorsNeedUpdate = false;
  7485. this.lineDistancesNeedUpdate = false;
  7486. this.groupsNeedUpdate = false;
  7487. }
  7488. Geometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  7489. constructor: Geometry,
  7490. isGeometry: true,
  7491. applyMatrix: function (matrix) {
  7492. var normalMatrix = new Matrix3().getNormalMatrix(matrix);
  7493. for (var i = 0, il = this.vertices.length; i < il; i++) {
  7494. var vertex = this.vertices[i];
  7495. vertex.applyMatrix4(matrix);
  7496. }
  7497. for (var i = 0, il = this.faces.length; i < il; i++) {
  7498. var face = this.faces[i];
  7499. face.normal.applyMatrix3(normalMatrix).normalize();
  7500. for (var j = 0, jl = face.vertexNormals.length; j < jl; j++) {
  7501. face.vertexNormals[j].applyMatrix3(normalMatrix).normalize();
  7502. }
  7503. }
  7504. if (this.boundingBox !== null) {
  7505. this.computeBoundingBox();
  7506. }
  7507. if (this.boundingSphere !== null) {
  7508. this.computeBoundingSphere();
  7509. }
  7510. this.verticesNeedUpdate = true;
  7511. this.normalsNeedUpdate = true;
  7512. return this;
  7513. },
  7514. rotateX: function (angle) {
  7515. // rotate geometry around world x-axis
  7516. _m1$3.makeRotationX(angle);
  7517. this.applyMatrix(_m1$3);
  7518. return this;
  7519. },
  7520. rotateY: function (angle) {
  7521. // rotate geometry around world y-axis
  7522. _m1$3.makeRotationY(angle);
  7523. this.applyMatrix(_m1$3);
  7524. return this;
  7525. },
  7526. rotateZ: function (angle) {
  7527. // rotate geometry around world z-axis
  7528. _m1$3.makeRotationZ(angle);
  7529. this.applyMatrix(_m1$3);
  7530. return this;
  7531. },
  7532. translate: function (x, y, z) {
  7533. // translate geometry
  7534. _m1$3.makeTranslation(x, y, z);
  7535. this.applyMatrix(_m1$3);
  7536. return this;
  7537. },
  7538. scale: function (x, y, z) {
  7539. // scale geometry
  7540. _m1$3.makeScale(x, y, z);
  7541. this.applyMatrix(_m1$3);
  7542. return this;
  7543. },
  7544. lookAt: function (vector) {
  7545. _obj$1.lookAt(vector);
  7546. _obj$1.updateMatrix();
  7547. this.applyMatrix(_obj$1.matrix);
  7548. return this;
  7549. },
  7550. fromBufferGeometry: function (geometry) {
  7551. var scope = this;
  7552. var indices = geometry.index !== null ? geometry.index.array : undefined;
  7553. var attributes = geometry.attributes;
  7554. if (attributes.position === undefined) {
  7555. console.error('THREE.Geometry.fromBufferGeometry(): Position attribute required for conversion.');
  7556. return this;
  7557. }
  7558. var positions = attributes.position.array;
  7559. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  7560. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  7561. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  7562. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  7563. if (uvs2 !== undefined) this.faceVertexUvs[1] = [];
  7564. for (var i = 0; i < positions.length; i += 3) {
  7565. scope.vertices.push(new Vector3().fromArray(positions, i));
  7566. if (colors !== undefined) {
  7567. scope.colors.push(new Color().fromArray(colors, i));
  7568. }
  7569. }
  7570. function addFace(a, b, c, materialIndex) {
  7571. var vertexColors = colors === undefined ? [] : [scope.colors[a].clone(), scope.colors[b].clone(), scope.colors[c].clone()];
  7572. var vertexNormals = normals === undefined ? [] : [new Vector3().fromArray(normals, a * 3), new Vector3().fromArray(normals, b * 3), new Vector3().fromArray(normals, c * 3)];
  7573. var face = new Face3(a, b, c, vertexNormals, vertexColors, materialIndex);
  7574. scope.faces.push(face);
  7575. if (uvs !== undefined) {
  7576. scope.faceVertexUvs[0].push([new Vector2().fromArray(uvs, a * 2), new Vector2().fromArray(uvs, b * 2), new Vector2().fromArray(uvs, c * 2)]);
  7577. }
  7578. if (uvs2 !== undefined) {
  7579. scope.faceVertexUvs[1].push([new Vector2().fromArray(uvs2, a * 2), new Vector2().fromArray(uvs2, b * 2), new Vector2().fromArray(uvs2, c * 2)]);
  7580. }
  7581. }
  7582. var groups = geometry.groups;
  7583. if (groups.length > 0) {
  7584. for (var i = 0; i < groups.length; i++) {
  7585. var group = groups[i];
  7586. var start = group.start;
  7587. var count = group.count;
  7588. for (var j = start, jl = start + count; j < jl; j += 3) {
  7589. if (indices !== undefined) {
  7590. addFace(indices[j], indices[j + 1], indices[j + 2], group.materialIndex);
  7591. } else {
  7592. addFace(j, j + 1, j + 2, group.materialIndex);
  7593. }
  7594. }
  7595. }
  7596. } else {
  7597. if (indices !== undefined) {
  7598. for (var i = 0; i < indices.length; i += 3) {
  7599. addFace(indices[i], indices[i + 1], indices[i + 2]);
  7600. }
  7601. } else {
  7602. for (var i = 0; i < positions.length / 3; i += 3) {
  7603. addFace(i, i + 1, i + 2);
  7604. }
  7605. }
  7606. }
  7607. this.computeFaceNormals();
  7608. if (geometry.boundingBox !== null) {
  7609. this.boundingBox = geometry.boundingBox.clone();
  7610. }
  7611. if (geometry.boundingSphere !== null) {
  7612. this.boundingSphere = geometry.boundingSphere.clone();
  7613. }
  7614. return this;
  7615. },
  7616. center: function () {
  7617. this.computeBoundingBox();
  7618. this.boundingBox.getCenter(_offset$1).negate();
  7619. this.translate(_offset$1.x, _offset$1.y, _offset$1.z);
  7620. return this;
  7621. },
  7622. normalize: function () {
  7623. this.computeBoundingSphere();
  7624. var center = this.boundingSphere.center;
  7625. var radius = this.boundingSphere.radius;
  7626. var s = radius === 0 ? 1 : 1.0 / radius;
  7627. var matrix = new Matrix4();
  7628. matrix.set(s, 0, 0, -s * center.x, 0, s, 0, -s * center.y, 0, 0, s, -s * center.z, 0, 0, 0, 1);
  7629. this.applyMatrix(matrix);
  7630. return this;
  7631. },
  7632. computeFaceNormals: function () {
  7633. var cb = new Vector3(),
  7634. ab = new Vector3();
  7635. for (var f = 0, fl = this.faces.length; f < fl; f++) {
  7636. var face = this.faces[f];
  7637. var vA = this.vertices[face.a];
  7638. var vB = this.vertices[face.b];
  7639. var vC = this.vertices[face.c];
  7640. cb.subVectors(vC, vB);
  7641. ab.subVectors(vA, vB);
  7642. cb.cross(ab);
  7643. cb.normalize();
  7644. face.normal.copy(cb);
  7645. }
  7646. },
  7647. computeVertexNormals: function (areaWeighted) {
  7648. if (areaWeighted === undefined) areaWeighted = true;
  7649. var v, vl, f, fl, face, vertices;
  7650. vertices = new Array(this.vertices.length);
  7651. for (v = 0, vl = this.vertices.length; v < vl; v++) {
  7652. vertices[v] = new Vector3();
  7653. }
  7654. if (areaWeighted) {
  7655. // vertex normals weighted by triangle areas
  7656. // http://www.iquilezles.org/www/articles/normals/normals.htm
  7657. var vA, vB, vC;
  7658. var cb = new Vector3(),
  7659. ab = new Vector3();
  7660. for (f = 0, fl = this.faces.length; f < fl; f++) {
  7661. face = this.faces[f];
  7662. vA = this.vertices[face.a];
  7663. vB = this.vertices[face.b];
  7664. vC = this.vertices[face.c];
  7665. cb.subVectors(vC, vB);
  7666. ab.subVectors(vA, vB);
  7667. cb.cross(ab);
  7668. vertices[face.a].add(cb);
  7669. vertices[face.b].add(cb);
  7670. vertices[face.c].add(cb);
  7671. }
  7672. } else {
  7673. this.computeFaceNormals();
  7674. for (f = 0, fl = this.faces.length; f < fl; f++) {
  7675. face = this.faces[f];
  7676. vertices[face.a].add(face.normal);
  7677. vertices[face.b].add(face.normal);
  7678. vertices[face.c].add(face.normal);
  7679. }
  7680. }
  7681. for (v = 0, vl = this.vertices.length; v < vl; v++) {
  7682. vertices[v].normalize();
  7683. }
  7684. for (f = 0, fl = this.faces.length; f < fl; f++) {
  7685. face = this.faces[f];
  7686. var vertexNormals = face.vertexNormals;
  7687. if (vertexNormals.length === 3) {
  7688. vertexNormals[0].copy(vertices[face.a]);
  7689. vertexNormals[1].copy(vertices[face.b]);
  7690. vertexNormals[2].copy(vertices[face.c]);
  7691. } else {
  7692. vertexNormals[0] = vertices[face.a].clone();
  7693. vertexNormals[1] = vertices[face.b].clone();
  7694. vertexNormals[2] = vertices[face.c].clone();
  7695. }
  7696. }
  7697. if (this.faces.length > 0) {
  7698. this.normalsNeedUpdate = true;
  7699. }
  7700. },
  7701. computeFlatVertexNormals: function () {
  7702. var f, fl, face;
  7703. this.computeFaceNormals();
  7704. for (f = 0, fl = this.faces.length; f < fl; f++) {
  7705. face = this.faces[f];
  7706. var vertexNormals = face.vertexNormals;
  7707. if (vertexNormals.length === 3) {
  7708. vertexNormals[0].copy(face.normal);
  7709. vertexNormals[1].copy(face.normal);
  7710. vertexNormals[2].copy(face.normal);
  7711. } else {
  7712. vertexNormals[0] = face.normal.clone();
  7713. vertexNormals[1] = face.normal.clone();
  7714. vertexNormals[2] = face.normal.clone();
  7715. }
  7716. }
  7717. if (this.faces.length > 0) {
  7718. this.normalsNeedUpdate = true;
  7719. }
  7720. },
  7721. computeMorphNormals: function () {
  7722. var i, il, f, fl, face; // save original normals
  7723. // - create temp variables on first access
  7724. // otherwise just copy (for faster repeated calls)
  7725. for (f = 0, fl = this.faces.length; f < fl; f++) {
  7726. face = this.faces[f];
  7727. if (!face.__originalFaceNormal) {
  7728. face.__originalFaceNormal = face.normal.clone();
  7729. } else {
  7730. face.__originalFaceNormal.copy(face.normal);
  7731. }
  7732. if (!face.__originalVertexNormals) face.__originalVertexNormals = [];
  7733. for (i = 0, il = face.vertexNormals.length; i < il; i++) {
  7734. if (!face.__originalVertexNormals[i]) {
  7735. face.__originalVertexNormals[i] = face.vertexNormals[i].clone();
  7736. } else {
  7737. face.__originalVertexNormals[i].copy(face.vertexNormals[i]);
  7738. }
  7739. }
  7740. } // use temp geometry to compute face and vertex normals for each morph
  7741. var tmpGeo = new Geometry();
  7742. tmpGeo.faces = this.faces;
  7743. for (i = 0, il = this.morphTargets.length; i < il; i++) {
  7744. // create on first access
  7745. if (!this.morphNormals[i]) {
  7746. this.morphNormals[i] = {};
  7747. this.morphNormals[i].faceNormals = [];
  7748. this.morphNormals[i].vertexNormals = [];
  7749. var dstNormalsFace = this.morphNormals[i].faceNormals;
  7750. var dstNormalsVertex = this.morphNormals[i].vertexNormals;
  7751. var faceNormal, vertexNormals;
  7752. for (f = 0, fl = this.faces.length; f < fl; f++) {
  7753. faceNormal = new Vector3();
  7754. vertexNormals = {
  7755. a: new Vector3(),
  7756. b: new Vector3(),
  7757. c: new Vector3()
  7758. };
  7759. dstNormalsFace.push(faceNormal);
  7760. dstNormalsVertex.push(vertexNormals);
  7761. }
  7762. }
  7763. var morphNormals = this.morphNormals[i]; // set vertices to morph target
  7764. tmpGeo.vertices = this.morphTargets[i].vertices; // compute morph normals
  7765. tmpGeo.computeFaceNormals();
  7766. tmpGeo.computeVertexNormals(); // store morph normals
  7767. var faceNormal, vertexNormals;
  7768. for (f = 0, fl = this.faces.length; f < fl; f++) {
  7769. face = this.faces[f];
  7770. faceNormal = morphNormals.faceNormals[f];
  7771. vertexNormals = morphNormals.vertexNormals[f];
  7772. faceNormal.copy(face.normal);
  7773. vertexNormals.a.copy(face.vertexNormals[0]);
  7774. vertexNormals.b.copy(face.vertexNormals[1]);
  7775. vertexNormals.c.copy(face.vertexNormals[2]);
  7776. }
  7777. } // restore original normals
  7778. for (f = 0, fl = this.faces.length; f < fl; f++) {
  7779. face = this.faces[f];
  7780. face.normal = face.__originalFaceNormal;
  7781. face.vertexNormals = face.__originalVertexNormals;
  7782. }
  7783. },
  7784. computeBoundingBox: function () {
  7785. if (this.boundingBox === null) {
  7786. this.boundingBox = new Box3();
  7787. }
  7788. this.boundingBox.setFromPoints(this.vertices);
  7789. },
  7790. computeBoundingSphere: function () {
  7791. if (this.boundingSphere === null) {
  7792. this.boundingSphere = new Sphere();
  7793. }
  7794. this.boundingSphere.setFromPoints(this.vertices);
  7795. },
  7796. merge: function (geometry, matrix, materialIndexOffset) {
  7797. if (!(geometry && geometry.isGeometry)) {
  7798. console.error('THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry);
  7799. return;
  7800. }
  7801. var normalMatrix,
  7802. vertexOffset = this.vertices.length,
  7803. vertices1 = this.vertices,
  7804. vertices2 = geometry.vertices,
  7805. faces1 = this.faces,
  7806. faces2 = geometry.faces,
  7807. colors1 = this.colors,
  7808. colors2 = geometry.colors;
  7809. if (materialIndexOffset === undefined) materialIndexOffset = 0;
  7810. if (matrix !== undefined) {
  7811. normalMatrix = new Matrix3().getNormalMatrix(matrix);
  7812. } // vertices
  7813. for (var i = 0, il = vertices2.length; i < il; i++) {
  7814. var vertex = vertices2[i];
  7815. var vertexCopy = vertex.clone();
  7816. if (matrix !== undefined) vertexCopy.applyMatrix4(matrix);
  7817. vertices1.push(vertexCopy);
  7818. } // colors
  7819. for (var i = 0, il = colors2.length; i < il; i++) {
  7820. colors1.push(colors2[i].clone());
  7821. } // faces
  7822. for (i = 0, il = faces2.length; i < il; i++) {
  7823. var face = faces2[i],
  7824. faceCopy,
  7825. normal,
  7826. color,
  7827. faceVertexNormals = face.vertexNormals,
  7828. faceVertexColors = face.vertexColors;
  7829. faceCopy = new Face3(face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset);
  7830. faceCopy.normal.copy(face.normal);
  7831. if (normalMatrix !== undefined) {
  7832. faceCopy.normal.applyMatrix3(normalMatrix).normalize();
  7833. }
  7834. for (var j = 0, jl = faceVertexNormals.length; j < jl; j++) {
  7835. normal = faceVertexNormals[j].clone();
  7836. if (normalMatrix !== undefined) {
  7837. normal.applyMatrix3(normalMatrix).normalize();
  7838. }
  7839. faceCopy.vertexNormals.push(normal);
  7840. }
  7841. faceCopy.color.copy(face.color);
  7842. for (var j = 0, jl = faceVertexColors.length; j < jl; j++) {
  7843. color = faceVertexColors[j];
  7844. faceCopy.vertexColors.push(color.clone());
  7845. }
  7846. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  7847. faces1.push(faceCopy);
  7848. } // uvs
  7849. for (var i = 0, il = geometry.faceVertexUvs.length; i < il; i++) {
  7850. var faceVertexUvs2 = geometry.faceVertexUvs[i];
  7851. if (this.faceVertexUvs[i] === undefined) this.faceVertexUvs[i] = [];
  7852. for (var j = 0, jl = faceVertexUvs2.length; j < jl; j++) {
  7853. var uvs2 = faceVertexUvs2[j],
  7854. uvsCopy = [];
  7855. for (var k = 0, kl = uvs2.length; k < kl; k++) {
  7856. uvsCopy.push(uvs2[k].clone());
  7857. }
  7858. this.faceVertexUvs[i].push(uvsCopy);
  7859. }
  7860. }
  7861. },
  7862. mergeMesh: function (mesh) {
  7863. if (!(mesh && mesh.isMesh)) {
  7864. console.error('THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh);
  7865. return;
  7866. }
  7867. if (mesh.matrixAutoUpdate) mesh.updateMatrix();
  7868. this.merge(mesh.geometry, mesh.matrix);
  7869. },
  7870. /*
  7871. * Checks for duplicate vertices with hashmap.
  7872. * Duplicated vertices are removed
  7873. * and faces' vertices are updated.
  7874. */
  7875. mergeVertices: function () {
  7876. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  7877. var unique = [],
  7878. changes = [];
  7879. var v, key;
  7880. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  7881. var precision = Math.pow(10, precisionPoints);
  7882. var i, il, face;
  7883. var indices, j, jl;
  7884. for (i = 0, il = this.vertices.length; i < il; i++) {
  7885. v = this.vertices[i];
  7886. key = Math.round(v.x * precision) + '_' + Math.round(v.y * precision) + '_' + Math.round(v.z * precision);
  7887. if (verticesMap[key] === undefined) {
  7888. verticesMap[key] = i;
  7889. unique.push(this.vertices[i]);
  7890. changes[i] = unique.length - 1;
  7891. } else {
  7892. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  7893. changes[i] = changes[verticesMap[key]];
  7894. }
  7895. } // if faces are completely degenerate after merging vertices, we
  7896. // have to remove them from the geometry.
  7897. var faceIndicesToRemove = [];
  7898. for (i = 0, il = this.faces.length; i < il; i++) {
  7899. face = this.faces[i];
  7900. face.a = changes[face.a];
  7901. face.b = changes[face.b];
  7902. face.c = changes[face.c];
  7903. indices = [face.a, face.b, face.c]; // if any duplicate vertices are found in a Face3
  7904. // we have to remove the face as nothing can be saved
  7905. for (var n = 0; n < 3; n++) {
  7906. if (indices[n] === indices[(n + 1) % 3]) {
  7907. faceIndicesToRemove.push(i);
  7908. break;
  7909. }
  7910. }
  7911. }
  7912. for (i = faceIndicesToRemove.length - 1; i >= 0; i--) {
  7913. var idx = faceIndicesToRemove[i];
  7914. this.faces.splice(idx, 1);
  7915. for (j = 0, jl = this.faceVertexUvs.length; j < jl; j++) {
  7916. this.faceVertexUvs[j].splice(idx, 1);
  7917. }
  7918. } // Use unique set of vertices
  7919. var diff = this.vertices.length - unique.length;
  7920. this.vertices = unique;
  7921. return diff;
  7922. },
  7923. setFromPoints: function (points) {
  7924. this.vertices = [];
  7925. for (var i = 0, l = points.length; i < l; i++) {
  7926. var point = points[i];
  7927. this.vertices.push(new Vector3(point.x, point.y, point.z || 0));
  7928. }
  7929. return this;
  7930. },
  7931. sortFacesByMaterialIndex: function () {
  7932. var faces = this.faces;
  7933. var length = faces.length; // tag faces
  7934. for (var i = 0; i < length; i++) {
  7935. faces[i]._id = i;
  7936. } // sort faces
  7937. function materialIndexSort(a, b) {
  7938. return a.materialIndex - b.materialIndex;
  7939. }
  7940. faces.sort(materialIndexSort); // sort uvs
  7941. var uvs1 = this.faceVertexUvs[0];
  7942. var uvs2 = this.faceVertexUvs[1];
  7943. var newUvs1, newUvs2;
  7944. if (uvs1 && uvs1.length === length) newUvs1 = [];
  7945. if (uvs2 && uvs2.length === length) newUvs2 = [];
  7946. for (var i = 0; i < length; i++) {
  7947. var id = faces[i]._id;
  7948. if (newUvs1) newUvs1.push(uvs1[id]);
  7949. if (newUvs2) newUvs2.push(uvs2[id]);
  7950. }
  7951. if (newUvs1) this.faceVertexUvs[0] = newUvs1;
  7952. if (newUvs2) this.faceVertexUvs[1] = newUvs2;
  7953. },
  7954. toJSON: function () {
  7955. var data = {
  7956. metadata: {
  7957. version: 4.5,
  7958. type: 'Geometry',
  7959. generator: 'Geometry.toJSON'
  7960. }
  7961. }; // standard Geometry serialization
  7962. data.uuid = this.uuid;
  7963. data.type = this.type;
  7964. if (this.name !== '') data.name = this.name;
  7965. if (this.parameters !== undefined) {
  7966. var parameters = this.parameters;
  7967. for (var key in parameters) {
  7968. if (parameters[key] !== undefined) data[key] = parameters[key];
  7969. }
  7970. return data;
  7971. }
  7972. var vertices = [];
  7973. for (var i = 0; i < this.vertices.length; i++) {
  7974. var vertex = this.vertices[i];
  7975. vertices.push(vertex.x, vertex.y, vertex.z);
  7976. }
  7977. var faces = [];
  7978. var normals = [];
  7979. var normalsHash = {};
  7980. var colors = [];
  7981. var colorsHash = {};
  7982. var uvs = [];
  7983. var uvsHash = {};
  7984. for (var i = 0; i < this.faces.length; i++) {
  7985. var face = this.faces[i];
  7986. var hasMaterial = true;
  7987. var hasFaceUv = false; // deprecated
  7988. var hasFaceVertexUv = this.faceVertexUvs[0][i] !== undefined;
  7989. var hasFaceNormal = face.normal.length() > 0;
  7990. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  7991. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  7992. var hasFaceVertexColor = face.vertexColors.length > 0;
  7993. var faceType = 0;
  7994. faceType = setBit(faceType, 0, 0); // isQuad
  7995. faceType = setBit(faceType, 1, hasMaterial);
  7996. faceType = setBit(faceType, 2, hasFaceUv);
  7997. faceType = setBit(faceType, 3, hasFaceVertexUv);
  7998. faceType = setBit(faceType, 4, hasFaceNormal);
  7999. faceType = setBit(faceType, 5, hasFaceVertexNormal);
  8000. faceType = setBit(faceType, 6, hasFaceColor);
  8001. faceType = setBit(faceType, 7, hasFaceVertexColor);
  8002. faces.push(faceType);
  8003. faces.push(face.a, face.b, face.c);
  8004. faces.push(face.materialIndex);
  8005. if (hasFaceVertexUv) {
  8006. var faceVertexUvs = this.faceVertexUvs[0][i];
  8007. faces.push(getUvIndex(faceVertexUvs[0]), getUvIndex(faceVertexUvs[1]), getUvIndex(faceVertexUvs[2]));
  8008. }
  8009. if (hasFaceNormal) {
  8010. faces.push(getNormalIndex(face.normal));
  8011. }
  8012. if (hasFaceVertexNormal) {
  8013. var vertexNormals = face.vertexNormals;
  8014. faces.push(getNormalIndex(vertexNormals[0]), getNormalIndex(vertexNormals[1]), getNormalIndex(vertexNormals[2]));
  8015. }
  8016. if (hasFaceColor) {
  8017. faces.push(getColorIndex(face.color));
  8018. }
  8019. if (hasFaceVertexColor) {
  8020. var vertexColors = face.vertexColors;
  8021. faces.push(getColorIndex(vertexColors[0]), getColorIndex(vertexColors[1]), getColorIndex(vertexColors[2]));
  8022. }
  8023. }
  8024. function setBit(value, position, enabled) {
  8025. return enabled ? value | 1 << position : value & ~(1 << position);
  8026. }
  8027. function getNormalIndex(normal) {
  8028. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  8029. if (normalsHash[hash] !== undefined) {
  8030. return normalsHash[hash];
  8031. }
  8032. normalsHash[hash] = normals.length / 3;
  8033. normals.push(normal.x, normal.y, normal.z);
  8034. return normalsHash[hash];
  8035. }
  8036. function getColorIndex(color) {
  8037. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  8038. if (colorsHash[hash] !== undefined) {
  8039. return colorsHash[hash];
  8040. }
  8041. colorsHash[hash] = colors.length;
  8042. colors.push(color.getHex());
  8043. return colorsHash[hash];
  8044. }
  8045. function getUvIndex(uv) {
  8046. var hash = uv.x.toString() + uv.y.toString();
  8047. if (uvsHash[hash] !== undefined) {
  8048. return uvsHash[hash];
  8049. }
  8050. uvsHash[hash] = uvs.length / 2;
  8051. uvs.push(uv.x, uv.y);
  8052. return uvsHash[hash];
  8053. }
  8054. data.data = {};
  8055. data.data.vertices = vertices;
  8056. data.data.normals = normals;
  8057. if (colors.length > 0) data.data.colors = colors;
  8058. if (uvs.length > 0) data.data.uvs = [uvs]; // temporal backward compatibility
  8059. data.data.faces = faces;
  8060. return data;
  8061. },
  8062. clone: function () {
  8063. /*
  8064. // Handle primitives
  8065. var parameters = this.parameters;
  8066. if ( parameters !== undefined ) {
  8067. var values = [];
  8068. for ( var key in parameters ) {
  8069. values.push( parameters[ key ] );
  8070. }
  8071. var geometry = Object.create( this.constructor.prototype );
  8072. this.constructor.apply( geometry, values );
  8073. return geometry;
  8074. }
  8075. return new this.constructor().copy( this );
  8076. */
  8077. return new Geometry().copy(this);
  8078. },
  8079. copy: function (source) {
  8080. var i, il, j, jl, k, kl; // reset
  8081. this.vertices = [];
  8082. this.colors = [];
  8083. this.faces = [];
  8084. this.faceVertexUvs = [[]];
  8085. this.morphTargets = [];
  8086. this.morphNormals = [];
  8087. this.skinWeights = [];
  8088. this.skinIndices = [];
  8089. this.lineDistances = [];
  8090. this.boundingBox = null;
  8091. this.boundingSphere = null; // name
  8092. this.name = source.name; // vertices
  8093. var vertices = source.vertices;
  8094. for (i = 0, il = vertices.length; i < il; i++) {
  8095. this.vertices.push(vertices[i].clone());
  8096. } // colors
  8097. var colors = source.colors;
  8098. for (i = 0, il = colors.length; i < il; i++) {
  8099. this.colors.push(colors[i].clone());
  8100. } // faces
  8101. var faces = source.faces;
  8102. for (i = 0, il = faces.length; i < il; i++) {
  8103. this.faces.push(faces[i].clone());
  8104. } // face vertex uvs
  8105. for (i = 0, il = source.faceVertexUvs.length; i < il; i++) {
  8106. var faceVertexUvs = source.faceVertexUvs[i];
  8107. if (this.faceVertexUvs[i] === undefined) {
  8108. this.faceVertexUvs[i] = [];
  8109. }
  8110. for (j = 0, jl = faceVertexUvs.length; j < jl; j++) {
  8111. var uvs = faceVertexUvs[j],
  8112. uvsCopy = [];
  8113. for (k = 0, kl = uvs.length; k < kl; k++) {
  8114. var uv = uvs[k];
  8115. uvsCopy.push(uv.clone());
  8116. }
  8117. this.faceVertexUvs[i].push(uvsCopy);
  8118. }
  8119. } // morph targets
  8120. var morphTargets = source.morphTargets;
  8121. for (i = 0, il = morphTargets.length; i < il; i++) {
  8122. var morphTarget = {};
  8123. morphTarget.name = morphTargets[i].name; // vertices
  8124. if (morphTargets[i].vertices !== undefined) {
  8125. morphTarget.vertices = [];
  8126. for (j = 0, jl = morphTargets[i].vertices.length; j < jl; j++) {
  8127. morphTarget.vertices.push(morphTargets[i].vertices[j].clone());
  8128. }
  8129. } // normals
  8130. if (morphTargets[i].normals !== undefined) {
  8131. morphTarget.normals = [];
  8132. for (j = 0, jl = morphTargets[i].normals.length; j < jl; j++) {
  8133. morphTarget.normals.push(morphTargets[i].normals[j].clone());
  8134. }
  8135. }
  8136. this.morphTargets.push(morphTarget);
  8137. } // morph normals
  8138. var morphNormals = source.morphNormals;
  8139. for (i = 0, il = morphNormals.length; i < il; i++) {
  8140. var morphNormal = {}; // vertex normals
  8141. if (morphNormals[i].vertexNormals !== undefined) {
  8142. morphNormal.vertexNormals = [];
  8143. for (j = 0, jl = morphNormals[i].vertexNormals.length; j < jl; j++) {
  8144. var srcVertexNormal = morphNormals[i].vertexNormals[j];
  8145. var destVertexNormal = {};
  8146. destVertexNormal.a = srcVertexNormal.a.clone();
  8147. destVertexNormal.b = srcVertexNormal.b.clone();
  8148. destVertexNormal.c = srcVertexNormal.c.clone();
  8149. morphNormal.vertexNormals.push(destVertexNormal);
  8150. }
  8151. } // face normals
  8152. if (morphNormals[i].faceNormals !== undefined) {
  8153. morphNormal.faceNormals = [];
  8154. for (j = 0, jl = morphNormals[i].faceNormals.length; j < jl; j++) {
  8155. morphNormal.faceNormals.push(morphNormals[i].faceNormals[j].clone());
  8156. }
  8157. }
  8158. this.morphNormals.push(morphNormal);
  8159. } // skin weights
  8160. var skinWeights = source.skinWeights;
  8161. for (i = 0, il = skinWeights.length; i < il; i++) {
  8162. this.skinWeights.push(skinWeights[i].clone());
  8163. } // skin indices
  8164. var skinIndices = source.skinIndices;
  8165. for (i = 0, il = skinIndices.length; i < il; i++) {
  8166. this.skinIndices.push(skinIndices[i].clone());
  8167. } // line distances
  8168. var lineDistances = source.lineDistances;
  8169. for (i = 0, il = lineDistances.length; i < il; i++) {
  8170. this.lineDistances.push(lineDistances[i]);
  8171. } // bounding box
  8172. var boundingBox = source.boundingBox;
  8173. if (boundingBox !== null) {
  8174. this.boundingBox = boundingBox.clone();
  8175. } // bounding sphere
  8176. var boundingSphere = source.boundingSphere;
  8177. if (boundingSphere !== null) {
  8178. this.boundingSphere = boundingSphere.clone();
  8179. } // update flags
  8180. this.elementsNeedUpdate = source.elementsNeedUpdate;
  8181. this.verticesNeedUpdate = source.verticesNeedUpdate;
  8182. this.uvsNeedUpdate = source.uvsNeedUpdate;
  8183. this.normalsNeedUpdate = source.normalsNeedUpdate;
  8184. this.colorsNeedUpdate = source.colorsNeedUpdate;
  8185. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  8186. this.groupsNeedUpdate = source.groupsNeedUpdate;
  8187. return this;
  8188. },
  8189. dispose: function () {
  8190. this.dispatchEvent({
  8191. type: 'dispose'
  8192. });
  8193. }
  8194. });
  8195. /**
  8196. * @author mrdoob / http://mrdoob.com/
  8197. * @author Mugen87 / https://github.com/Mugen87
  8198. */
  8199. // BoxGeometry
  8200. class BoxGeometry extends Geometry {
  8201. constructor(width, height, depth, widthSegments, heightSegments, depthSegments) {
  8202. super();
  8203. this.type = 'BoxGeometry';
  8204. this.parameters = {
  8205. width: width,
  8206. height: height,
  8207. depth: depth,
  8208. widthSegments: widthSegments,
  8209. heightSegments: heightSegments,
  8210. depthSegments: depthSegments
  8211. };
  8212. this.fromBufferGeometry(new BoxBufferGeometry(width, height, depth, widthSegments, heightSegments, depthSegments));
  8213. this.mergeVertices();
  8214. }
  8215. } // BoxBufferGeometry
  8216. exports.CubeGeometry = exports.BoxGeometry = BoxGeometry;
  8217. class BoxBufferGeometry extends BufferGeometry {
  8218. constructor(width, height, depth, widthSegments, heightSegments, depthSegments) {
  8219. super();
  8220. this.type = 'BoxBufferGeometry';
  8221. this.parameters = {
  8222. width: width,
  8223. height: height,
  8224. depth: depth,
  8225. widthSegments: widthSegments,
  8226. heightSegments: heightSegments,
  8227. depthSegments: depthSegments
  8228. };
  8229. var scope = this;
  8230. width = width || 1;
  8231. height = height || 1;
  8232. depth = depth || 1; // segments
  8233. widthSegments = Math.floor(widthSegments) || 1;
  8234. heightSegments = Math.floor(heightSegments) || 1;
  8235. depthSegments = Math.floor(depthSegments) || 1; // buffers
  8236. var indices = [];
  8237. var vertices = [];
  8238. var normals = [];
  8239. var uvs = []; // helper variables
  8240. var numberOfVertices = 0;
  8241. var groupStart = 0; // build each side of the box geometry
  8242. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  8243. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  8244. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  8245. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  8246. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  8247. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  8248. // build geometry
  8249. this.setIndex(indices);
  8250. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  8251. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  8252. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  8253. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  8254. var segmentWidth = width / gridX;
  8255. var segmentHeight = height / gridY;
  8256. var widthHalf = width / 2;
  8257. var heightHalf = height / 2;
  8258. var depthHalf = depth / 2;
  8259. var gridX1 = gridX + 1;
  8260. var gridY1 = gridY + 1;
  8261. var vertexCounter = 0;
  8262. var groupCount = 0;
  8263. var ix, iy;
  8264. var vector = new Vector3(); // generate vertices, normals and uvs
  8265. for (iy = 0; iy < gridY1; iy++) {
  8266. var y = iy * segmentHeight - heightHalf;
  8267. for (ix = 0; ix < gridX1; ix++) {
  8268. var x = ix * segmentWidth - widthHalf; // set values to correct vector component
  8269. vector[u] = x * udir;
  8270. vector[v] = y * vdir;
  8271. vector[w] = depthHalf; // now apply vector to vertex buffer
  8272. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  8273. vector[u] = 0;
  8274. vector[v] = 0;
  8275. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  8276. normals.push(vector.x, vector.y, vector.z); // uvs
  8277. uvs.push(ix / gridX);
  8278. uvs.push(1 - iy / gridY); // counters
  8279. vertexCounter += 1;
  8280. }
  8281. } // indices
  8282. // 1. you need three indices to draw a single face
  8283. // 2. a single segment consists of two faces
  8284. // 3. so we need to generate six (2*3) indices per segment
  8285. for (iy = 0; iy < gridY; iy++) {
  8286. for (ix = 0; ix < gridX; ix++) {
  8287. var a = numberOfVertices + ix + gridX1 * iy;
  8288. var b = numberOfVertices + ix + gridX1 * (iy + 1);
  8289. var c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  8290. var d = numberOfVertices + (ix + 1) + gridX1 * iy; // faces
  8291. indices.push(a, b, d);
  8292. indices.push(b, c, d); // increase counter
  8293. groupCount += 6;
  8294. }
  8295. } // add a group to the geometry. this will ensure multi material support
  8296. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  8297. groupStart += groupCount; // update total number of vertices
  8298. numberOfVertices += vertexCounter;
  8299. }
  8300. }
  8301. }
  8302. /**
  8303. * Uniform Utilities
  8304. */
  8305. exports.BoxBufferGeometry = BoxBufferGeometry;
  8306. function cloneUniforms(src) {
  8307. var dst = {};
  8308. for (var u in src) {
  8309. dst[u] = {};
  8310. for (var p in src[u]) {
  8311. var property = src[u][p];
  8312. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture)) {
  8313. dst[u][p] = property.clone();
  8314. } else if (Array.isArray(property)) {
  8315. dst[u][p] = property.slice();
  8316. } else {
  8317. dst[u][p] = property;
  8318. }
  8319. }
  8320. }
  8321. return dst;
  8322. }
  8323. function mergeUniforms(uniforms) {
  8324. var merged = {};
  8325. for (var u = 0; u < uniforms.length; u++) {
  8326. var tmp = cloneUniforms(uniforms[u]);
  8327. for (var p in tmp) {
  8328. merged[p] = tmp[p];
  8329. }
  8330. }
  8331. return merged;
  8332. } // Legacy
  8333. var UniformsUtils = {
  8334. clone: cloneUniforms,
  8335. merge: mergeUniforms
  8336. };
  8337. exports.UniformsUtils = UniformsUtils;
  8338. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  8339. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  8340. /**
  8341. * @author alteredq / http://alteredqualia.com/
  8342. *
  8343. * parameters = {
  8344. * defines: { "label" : "value" },
  8345. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  8346. *
  8347. * fragmentShader: <string>,
  8348. * vertexShader: <string>,
  8349. *
  8350. * wireframe: <boolean>,
  8351. * wireframeLinewidth: <float>,
  8352. *
  8353. * lights: <bool>,
  8354. *
  8355. * skinning: <bool>,
  8356. * morphTargets: <bool>,
  8357. * morphNormals: <bool>
  8358. * }
  8359. */
  8360. function ShaderMaterial(parameters) {
  8361. Material.call(this);
  8362. this.type = 'ShaderMaterial';
  8363. this.defines = {};
  8364. this.uniforms = {};
  8365. this.vertexShader = default_vertex;
  8366. this.fragmentShader = default_fragment;
  8367. this.linewidth = 1;
  8368. this.wireframe = false;
  8369. this.wireframeLinewidth = 1;
  8370. this.fog = false; // set to use scene fog
  8371. this.lights = false; // set to use scene lights
  8372. this.clipping = false; // set to use user-defined clipping planes
  8373. this.skinning = false; // set to use skinning attribute streams
  8374. this.morphTargets = false; // set to use morph targets
  8375. this.morphNormals = false; // set to use morph normals
  8376. this.extensions = {
  8377. derivatives: false,
  8378. // set to use derivatives
  8379. fragDepth: false,
  8380. // set to use fragment depth values
  8381. drawBuffers: false,
  8382. // set to use draw buffers
  8383. shaderTextureLOD: false // set to use shader texture LOD
  8384. }; // When rendered geometry doesn't include these attributes but the material does,
  8385. // use these default values in WebGL. This avoids errors when buffer data is missing.
  8386. this.defaultAttributeValues = {
  8387. 'color': [1, 1, 1],
  8388. 'uv': [0, 0],
  8389. 'uv2': [0, 0]
  8390. };
  8391. this.index0AttributeName = undefined;
  8392. this.uniformsNeedUpdate = false;
  8393. if (parameters !== undefined) {
  8394. if (parameters.attributes !== undefined) {
  8395. console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
  8396. }
  8397. this.setValues(parameters);
  8398. }
  8399. }
  8400. ShaderMaterial.prototype = Object.create(Material.prototype);
  8401. ShaderMaterial.prototype.constructor = ShaderMaterial;
  8402. ShaderMaterial.prototype.isShaderMaterial = true;
  8403. ShaderMaterial.prototype.copy = function (source) {
  8404. Material.prototype.copy.call(this, source);
  8405. this.fragmentShader = source.fragmentShader;
  8406. this.vertexShader = source.vertexShader;
  8407. this.uniforms = cloneUniforms(source.uniforms);
  8408. this.defines = Object.assign({}, source.defines);
  8409. this.wireframe = source.wireframe;
  8410. this.wireframeLinewidth = source.wireframeLinewidth;
  8411. this.lights = source.lights;
  8412. this.clipping = source.clipping;
  8413. this.skinning = source.skinning;
  8414. this.morphTargets = source.morphTargets;
  8415. this.morphNormals = source.morphNormals;
  8416. this.extensions = source.extensions;
  8417. return this;
  8418. };
  8419. ShaderMaterial.prototype.toJSON = function (meta) {
  8420. var data = Material.prototype.toJSON.call(this, meta);
  8421. data.uniforms = {};
  8422. for (var name in this.uniforms) {
  8423. var uniform = this.uniforms[name];
  8424. var value = uniform.value;
  8425. if (value && value.isTexture) {
  8426. data.uniforms[name] = {
  8427. type: 't',
  8428. value: value.toJSON(meta).uuid
  8429. };
  8430. } else if (value && value.isColor) {
  8431. data.uniforms[name] = {
  8432. type: 'c',
  8433. value: value.getHex()
  8434. };
  8435. } else if (value && value.isVector2) {
  8436. data.uniforms[name] = {
  8437. type: 'v2',
  8438. value: value.toArray()
  8439. };
  8440. } else if (value && value.isVector3) {
  8441. data.uniforms[name] = {
  8442. type: 'v3',
  8443. value: value.toArray()
  8444. };
  8445. } else if (value && value.isVector4) {
  8446. data.uniforms[name] = {
  8447. type: 'v4',
  8448. value: value.toArray()
  8449. };
  8450. } else if (value && value.isMatrix3) {
  8451. data.uniforms[name] = {
  8452. type: 'm3',
  8453. value: value.toArray()
  8454. };
  8455. } else if (value && value.isMatrix4) {
  8456. data.uniforms[name] = {
  8457. type: 'm4',
  8458. value: value.toArray()
  8459. };
  8460. } else {
  8461. data.uniforms[name] = {
  8462. value: value
  8463. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  8464. }
  8465. }
  8466. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  8467. data.vertexShader = this.vertexShader;
  8468. data.fragmentShader = this.fragmentShader;
  8469. var extensions = {};
  8470. for (var key in this.extensions) {
  8471. if (this.extensions[key] === true) extensions[key] = true;
  8472. }
  8473. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  8474. return data;
  8475. };
  8476. /**
  8477. * @author mrdoob / http://mrdoob.com/
  8478. * @author mikael emtinger / http://gomo.se/
  8479. * @author WestLangley / http://github.com/WestLangley
  8480. */
  8481. function Camera() {
  8482. Object3D.call(this);
  8483. this.type = 'Camera';
  8484. this.matrixWorldInverse = new Matrix4();
  8485. this.projectionMatrix = new Matrix4();
  8486. this.projectionMatrixInverse = new Matrix4();
  8487. }
  8488. Camera.prototype = Object.assign(Object.create(Object3D.prototype), {
  8489. constructor: Camera,
  8490. isCamera: true,
  8491. copy: function (source, recursive) {
  8492. Object3D.prototype.copy.call(this, source, recursive);
  8493. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  8494. this.projectionMatrix.copy(source.projectionMatrix);
  8495. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  8496. return this;
  8497. },
  8498. getWorldDirection: function (target) {
  8499. if (target === undefined) {
  8500. console.warn('THREE.Camera: .getWorldDirection() target is now required');
  8501. target = new Vector3();
  8502. }
  8503. this.updateMatrixWorld(true);
  8504. var e = this.matrixWorld.elements;
  8505. return target.set(-e[8], -e[9], -e[10]).normalize();
  8506. },
  8507. updateMatrixWorld: function (force) {
  8508. Object3D.prototype.updateMatrixWorld.call(this, force);
  8509. this.matrixWorldInverse.getInverse(this.matrixWorld);
  8510. },
  8511. clone: function () {
  8512. return new this.constructor().copy(this);
  8513. }
  8514. });
  8515. /**
  8516. * @author mrdoob / http://mrdoob.com/
  8517. * @author greggman / http://games.greggman.com/
  8518. * @author zz85 / http://www.lab4games.net/zz85/blog
  8519. * @author tschw
  8520. */
  8521. function PerspectiveCamera(fov, aspect, near, far) {
  8522. Camera.call(this);
  8523. this.type = 'PerspectiveCamera';
  8524. this.fov = fov !== undefined ? fov : 50;
  8525. this.zoom = 1;
  8526. this.near = near !== undefined ? near : 0.1;
  8527. this.far = far !== undefined ? far : 2000;
  8528. this.focus = 10;
  8529. this.aspect = aspect !== undefined ? aspect : 1;
  8530. this.view = null;
  8531. this.filmGauge = 35; // width of the film (default in millimeters)
  8532. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  8533. this.updateProjectionMatrix();
  8534. }
  8535. PerspectiveCamera.prototype = Object.assign(Object.create(Camera.prototype), {
  8536. constructor: PerspectiveCamera,
  8537. isPerspectiveCamera: true,
  8538. copy: function (source, recursive) {
  8539. Camera.prototype.copy.call(this, source, recursive);
  8540. this.fov = source.fov;
  8541. this.zoom = source.zoom;
  8542. this.near = source.near;
  8543. this.far = source.far;
  8544. this.focus = source.focus;
  8545. this.aspect = source.aspect;
  8546. this.view = source.view === null ? null : Object.assign({}, source.view);
  8547. this.filmGauge = source.filmGauge;
  8548. this.filmOffset = source.filmOffset;
  8549. return this;
  8550. },
  8551. /**
  8552. * Sets the FOV by focal length in respect to the current .filmGauge.
  8553. *
  8554. * The default film gauge is 35, so that the focal length can be specified for
  8555. * a 35mm (full frame) camera.
  8556. *
  8557. * Values for focal length and film gauge must have the same unit.
  8558. */
  8559. setFocalLength: function (focalLength) {
  8560. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  8561. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  8562. this.fov = _Math.RAD2DEG * 2 * Math.atan(vExtentSlope);
  8563. this.updateProjectionMatrix();
  8564. },
  8565. /**
  8566. * Calculates the focal length from the current .fov and .filmGauge.
  8567. */
  8568. getFocalLength: function () {
  8569. var vExtentSlope = Math.tan(_Math.DEG2RAD * 0.5 * this.fov);
  8570. return 0.5 * this.getFilmHeight() / vExtentSlope;
  8571. },
  8572. getEffectiveFOV: function () {
  8573. return _Math.RAD2DEG * 2 * Math.atan(Math.tan(_Math.DEG2RAD * 0.5 * this.fov) / this.zoom);
  8574. },
  8575. getFilmWidth: function () {
  8576. // film not completely covered in portrait format (aspect < 1)
  8577. return this.filmGauge * Math.min(this.aspect, 1);
  8578. },
  8579. getFilmHeight: function () {
  8580. // film not completely covered in landscape format (aspect > 1)
  8581. return this.filmGauge / Math.max(this.aspect, 1);
  8582. },
  8583. /**
  8584. * Sets an offset in a larger frustum. This is useful for multi-window or
  8585. * multi-monitor/multi-machine setups.
  8586. *
  8587. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  8588. * the monitors are in grid like this
  8589. *
  8590. * +---+---+---+
  8591. * | A | B | C |
  8592. * +---+---+---+
  8593. * | D | E | F |
  8594. * +---+---+---+
  8595. *
  8596. * then for each monitor you would call it like this
  8597. *
  8598. * var w = 1920;
  8599. * var h = 1080;
  8600. * var fullWidth = w * 3;
  8601. * var fullHeight = h * 2;
  8602. *
  8603. * --A--
  8604. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  8605. * --B--
  8606. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  8607. * --C--
  8608. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  8609. * --D--
  8610. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  8611. * --E--
  8612. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  8613. * --F--
  8614. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  8615. *
  8616. * Note there is no reason monitors have to be the same size or in a grid.
  8617. */
  8618. setViewOffset: function (fullWidth, fullHeight, x, y, width, height) {
  8619. this.aspect = fullWidth / fullHeight;
  8620. if (this.view === null) {
  8621. this.view = {
  8622. enabled: true,
  8623. fullWidth: 1,
  8624. fullHeight: 1,
  8625. offsetX: 0,
  8626. offsetY: 0,
  8627. width: 1,
  8628. height: 1
  8629. };
  8630. }
  8631. this.view.enabled = true;
  8632. this.view.fullWidth = fullWidth;
  8633. this.view.fullHeight = fullHeight;
  8634. this.view.offsetX = x;
  8635. this.view.offsetY = y;
  8636. this.view.width = width;
  8637. this.view.height = height;
  8638. this.updateProjectionMatrix();
  8639. },
  8640. clearViewOffset: function () {
  8641. if (this.view !== null) {
  8642. this.view.enabled = false;
  8643. }
  8644. this.updateProjectionMatrix();
  8645. },
  8646. updateProjectionMatrix: function () {
  8647. var near = this.near,
  8648. top = near * Math.tan(_Math.DEG2RAD * 0.5 * this.fov) / this.zoom,
  8649. height = 2 * top,
  8650. width = this.aspect * height,
  8651. left = -0.5 * width,
  8652. view = this.view;
  8653. if (this.view !== null && this.view.enabled) {
  8654. var fullWidth = view.fullWidth,
  8655. fullHeight = view.fullHeight;
  8656. left += view.offsetX * width / fullWidth;
  8657. top -= view.offsetY * height / fullHeight;
  8658. width *= view.width / fullWidth;
  8659. height *= view.height / fullHeight;
  8660. }
  8661. var skew = this.filmOffset;
  8662. if (skew !== 0) left += near * skew / this.getFilmWidth();
  8663. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  8664. this.projectionMatrixInverse.getInverse(this.projectionMatrix);
  8665. },
  8666. toJSON: function (meta) {
  8667. var data = Object3D.prototype.toJSON.call(this, meta);
  8668. data.object.fov = this.fov;
  8669. data.object.zoom = this.zoom;
  8670. data.object.near = this.near;
  8671. data.object.far = this.far;
  8672. data.object.focus = this.focus;
  8673. data.object.aspect = this.aspect;
  8674. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  8675. data.object.filmGauge = this.filmGauge;
  8676. data.object.filmOffset = this.filmOffset;
  8677. return data;
  8678. }
  8679. });
  8680. /**
  8681. * Camera for rendering cube maps
  8682. * - renders scene into axis-aligned cube
  8683. *
  8684. * @author alteredq / http://alteredqualia.com/
  8685. */
  8686. var fov = 90,
  8687. aspect = 1;
  8688. function CubeCamera(near, far, cubeResolution, options) {
  8689. Object3D.call(this);
  8690. this.type = 'CubeCamera';
  8691. var cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  8692. cameraPX.up.set(0, -1, 0);
  8693. cameraPX.lookAt(new Vector3(1, 0, 0));
  8694. this.add(cameraPX);
  8695. var cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  8696. cameraNX.up.set(0, -1, 0);
  8697. cameraNX.lookAt(new Vector3(-1, 0, 0));
  8698. this.add(cameraNX);
  8699. var cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  8700. cameraPY.up.set(0, 0, 1);
  8701. cameraPY.lookAt(new Vector3(0, 1, 0));
  8702. this.add(cameraPY);
  8703. var cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  8704. cameraNY.up.set(0, 0, -1);
  8705. cameraNY.lookAt(new Vector3(0, -1, 0));
  8706. this.add(cameraNY);
  8707. var cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  8708. cameraPZ.up.set(0, -1, 0);
  8709. cameraPZ.lookAt(new Vector3(0, 0, 1));
  8710. this.add(cameraPZ);
  8711. var cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  8712. cameraNZ.up.set(0, -1, 0);
  8713. cameraNZ.lookAt(new Vector3(0, 0, -1));
  8714. this.add(cameraNZ);
  8715. options = options || {
  8716. format: RGBFormat,
  8717. magFilter: LinearFilter,
  8718. minFilter: LinearFilter
  8719. };
  8720. this.renderTarget = new WebGLRenderTargetCube(cubeResolution, cubeResolution, options);
  8721. this.renderTarget.texture.name = "CubeCamera";
  8722. this.update = function (renderer, scene) {
  8723. if (this.parent === null) this.updateMatrixWorld();
  8724. var currentRenderTarget = renderer.getRenderTarget();
  8725. var renderTarget = this.renderTarget;
  8726. var generateMipmaps = renderTarget.texture.generateMipmaps;
  8727. renderTarget.texture.generateMipmaps = false;
  8728. renderer.setRenderTarget(renderTarget, 0);
  8729. renderer.render(scene, cameraPX);
  8730. renderer.setRenderTarget(renderTarget, 1);
  8731. renderer.render(scene, cameraNX);
  8732. renderer.setRenderTarget(renderTarget, 2);
  8733. renderer.render(scene, cameraPY);
  8734. renderer.setRenderTarget(renderTarget, 3);
  8735. renderer.render(scene, cameraNY);
  8736. renderer.setRenderTarget(renderTarget, 4);
  8737. renderer.render(scene, cameraPZ);
  8738. renderTarget.texture.generateMipmaps = generateMipmaps;
  8739. renderer.setRenderTarget(renderTarget, 5);
  8740. renderer.render(scene, cameraNZ);
  8741. renderer.setRenderTarget(currentRenderTarget);
  8742. };
  8743. this.clear = function (renderer, color, depth, stencil) {
  8744. var currentRenderTarget = renderer.getRenderTarget();
  8745. var renderTarget = this.renderTarget;
  8746. for (var i = 0; i < 6; i++) {
  8747. renderer.setRenderTarget(renderTarget, i);
  8748. renderer.clear(color, depth, stencil);
  8749. }
  8750. renderer.setRenderTarget(currentRenderTarget);
  8751. };
  8752. }
  8753. CubeCamera.prototype = Object.create(Object3D.prototype);
  8754. CubeCamera.prototype.constructor = CubeCamera;
  8755. /**
  8756. * @author alteredq / http://alteredqualia.com
  8757. * @author WestLangley / http://github.com/WestLangley
  8758. */
  8759. function WebGLRenderTargetCube(width, height, options) {
  8760. WebGLRenderTarget.call(this, width, height, options);
  8761. }
  8762. WebGLRenderTargetCube.prototype = Object.create(WebGLRenderTarget.prototype);
  8763. WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;
  8764. WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;
  8765. WebGLRenderTargetCube.prototype.fromEquirectangularTexture = function (renderer, texture) {
  8766. this.texture.type = texture.type;
  8767. this.texture.format = texture.format;
  8768. this.texture.encoding = texture.encoding;
  8769. var scene = new Scene();
  8770. var shader = {
  8771. uniforms: {
  8772. tEquirect: {
  8773. value: null
  8774. }
  8775. },
  8776. 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'),
  8777. 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')
  8778. };
  8779. var material = new ShaderMaterial({
  8780. type: 'CubemapFromEquirect',
  8781. uniforms: cloneUniforms(shader.uniforms),
  8782. vertexShader: shader.vertexShader,
  8783. fragmentShader: shader.fragmentShader,
  8784. side: BackSide,
  8785. blending: NoBlending
  8786. });
  8787. material.uniforms.tEquirect.value = texture;
  8788. var mesh = new Mesh(new BoxBufferGeometry(5, 5, 5), material);
  8789. scene.add(mesh);
  8790. var camera = new CubeCamera(1, 10, 1);
  8791. camera.renderTarget = this;
  8792. camera.renderTarget.texture.name = 'CubeCameraTexture';
  8793. camera.update(renderer, scene);
  8794. mesh.geometry.dispose();
  8795. mesh.material.dispose();
  8796. return this;
  8797. };
  8798. /**
  8799. * @author alteredq / http://alteredqualia.com/
  8800. */
  8801. function DataTexture(data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  8802. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  8803. this.image = {
  8804. data: data || null,
  8805. width: width || 1,
  8806. height: height || 1
  8807. };
  8808. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  8809. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  8810. this.generateMipmaps = false;
  8811. this.flipY = false;
  8812. this.unpackAlignment = 1;
  8813. this.needsUpdate = true;
  8814. }
  8815. DataTexture.prototype = Object.create(Texture.prototype);
  8816. DataTexture.prototype.constructor = DataTexture;
  8817. DataTexture.prototype.isDataTexture = true;
  8818. /**
  8819. * @author bhouston / http://clara.io
  8820. */
  8821. var _vector1 = new Vector3();
  8822. var _vector2 = new Vector3();
  8823. var _normalMatrix = new Matrix3();
  8824. function Plane(normal, constant) {
  8825. // normal is assumed to be normalized
  8826. this.normal = normal !== undefined ? normal : new Vector3(1, 0, 0);
  8827. this.constant = constant !== undefined ? constant : 0;
  8828. }
  8829. Object.assign(Plane.prototype, {
  8830. isPlane: true,
  8831. set: function (normal, constant) {
  8832. this.normal.copy(normal);
  8833. this.constant = constant;
  8834. return this;
  8835. },
  8836. setComponents: function (x, y, z, w) {
  8837. this.normal.set(x, y, z);
  8838. this.constant = w;
  8839. return this;
  8840. },
  8841. setFromNormalAndCoplanarPoint: function (normal, point) {
  8842. this.normal.copy(normal);
  8843. this.constant = -point.dot(this.normal);
  8844. return this;
  8845. },
  8846. setFromCoplanarPoints: function (a, b, c) {
  8847. 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)?
  8848. this.setFromNormalAndCoplanarPoint(normal, a);
  8849. return this;
  8850. },
  8851. clone: function () {
  8852. return new this.constructor().copy(this);
  8853. },
  8854. copy: function (plane) {
  8855. this.normal.copy(plane.normal);
  8856. this.constant = plane.constant;
  8857. return this;
  8858. },
  8859. normalize: function () {
  8860. // Note: will lead to a divide by zero if the plane is invalid.
  8861. var inverseNormalLength = 1.0 / this.normal.length();
  8862. this.normal.multiplyScalar(inverseNormalLength);
  8863. this.constant *= inverseNormalLength;
  8864. return this;
  8865. },
  8866. negate: function () {
  8867. this.constant *= -1;
  8868. this.normal.negate();
  8869. return this;
  8870. },
  8871. distanceToPoint: function (point) {
  8872. return this.normal.dot(point) + this.constant;
  8873. },
  8874. distanceToSphere: function (sphere) {
  8875. return this.distanceToPoint(sphere.center) - sphere.radius;
  8876. },
  8877. projectPoint: function (point, target) {
  8878. if (target === undefined) {
  8879. console.warn('THREE.Plane: .projectPoint() target is now required');
  8880. target = new Vector3();
  8881. }
  8882. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  8883. },
  8884. intersectLine: function (line, target) {
  8885. if (target === undefined) {
  8886. console.warn('THREE.Plane: .intersectLine() target is now required');
  8887. target = new Vector3();
  8888. }
  8889. var direction = line.delta(_vector1);
  8890. var denominator = this.normal.dot(direction);
  8891. if (denominator === 0) {
  8892. // line is coplanar, return origin
  8893. if (this.distanceToPoint(line.start) === 0) {
  8894. return target.copy(line.start);
  8895. } // Unsure if this is the correct method to handle this case.
  8896. return undefined;
  8897. }
  8898. var t = -(line.start.dot(this.normal) + this.constant) / denominator;
  8899. if (t < 0 || t > 1) {
  8900. return undefined;
  8901. }
  8902. return target.copy(direction).multiplyScalar(t).add(line.start);
  8903. },
  8904. intersectsLine: function (line) {
  8905. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  8906. var startSign = this.distanceToPoint(line.start);
  8907. var endSign = this.distanceToPoint(line.end);
  8908. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  8909. },
  8910. intersectsBox: function (box) {
  8911. return box.intersectsPlane(this);
  8912. },
  8913. intersectsSphere: function (sphere) {
  8914. return sphere.intersectsPlane(this);
  8915. },
  8916. coplanarPoint: function (target) {
  8917. if (target === undefined) {
  8918. console.warn('THREE.Plane: .coplanarPoint() target is now required');
  8919. target = new Vector3();
  8920. }
  8921. return target.copy(this.normal).multiplyScalar(-this.constant);
  8922. },
  8923. applyMatrix4: function (matrix, optionalNormalMatrix) {
  8924. var normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  8925. var referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  8926. var normal = this.normal.applyMatrix3(normalMatrix).normalize();
  8927. this.constant = -referencePoint.dot(normal);
  8928. return this;
  8929. },
  8930. translate: function (offset) {
  8931. this.constant -= offset.dot(this.normal);
  8932. return this;
  8933. },
  8934. equals: function (plane) {
  8935. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  8936. }
  8937. });
  8938. /**
  8939. * @author mrdoob / http://mrdoob.com/
  8940. * @author alteredq / http://alteredqualia.com/
  8941. * @author bhouston / http://clara.io
  8942. */
  8943. var _sphere$1 = new Sphere();
  8944. var _vector$5 = new Vector3();
  8945. function Frustum(p0, p1, p2, p3, p4, p5) {
  8946. 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()];
  8947. }
  8948. Object.assign(Frustum.prototype, {
  8949. set: function (p0, p1, p2, p3, p4, p5) {
  8950. var planes = this.planes;
  8951. planes[0].copy(p0);
  8952. planes[1].copy(p1);
  8953. planes[2].copy(p2);
  8954. planes[3].copy(p3);
  8955. planes[4].copy(p4);
  8956. planes[5].copy(p5);
  8957. return this;
  8958. },
  8959. clone: function () {
  8960. return new this.constructor().copy(this);
  8961. },
  8962. copy: function (frustum) {
  8963. var planes = this.planes;
  8964. for (var i = 0; i < 6; i++) {
  8965. planes[i].copy(frustum.planes[i]);
  8966. }
  8967. return this;
  8968. },
  8969. setFromMatrix: function (m) {
  8970. var planes = this.planes;
  8971. var me = m.elements;
  8972. var me0 = me[0],
  8973. me1 = me[1],
  8974. me2 = me[2],
  8975. me3 = me[3];
  8976. var me4 = me[4],
  8977. me5 = me[5],
  8978. me6 = me[6],
  8979. me7 = me[7];
  8980. var me8 = me[8],
  8981. me9 = me[9],
  8982. me10 = me[10],
  8983. me11 = me[11];
  8984. var me12 = me[12],
  8985. me13 = me[13],
  8986. me14 = me[14],
  8987. me15 = me[15];
  8988. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  8989. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  8990. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  8991. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  8992. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  8993. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  8994. return this;
  8995. },
  8996. intersectsObject: function (object) {
  8997. var geometry = object.geometry;
  8998. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  8999. _sphere$1.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  9000. return this.intersectsSphere(_sphere$1);
  9001. },
  9002. intersectsSprite: function (sprite) {
  9003. _sphere$1.center.set(0, 0, 0);
  9004. _sphere$1.radius = 0.7071067811865476;
  9005. _sphere$1.applyMatrix4(sprite.matrixWorld);
  9006. return this.intersectsSphere(_sphere$1);
  9007. },
  9008. intersectsSphere: function (sphere) {
  9009. var planes = this.planes;
  9010. var center = sphere.center;
  9011. var negRadius = -sphere.radius;
  9012. for (var i = 0; i < 6; i++) {
  9013. var distance = planes[i].distanceToPoint(center);
  9014. if (distance < negRadius) {
  9015. return false;
  9016. }
  9017. }
  9018. return true;
  9019. },
  9020. intersectsBox: function (box) {
  9021. var planes = this.planes;
  9022. for (var i = 0; i < 6; i++) {
  9023. var plane = planes[i]; // corner at max distance
  9024. _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  9025. _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  9026. _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  9027. if (plane.distanceToPoint(_vector$5) < 0) {
  9028. return false;
  9029. }
  9030. }
  9031. return true;
  9032. },
  9033. containsPoint: function (point) {
  9034. var planes = this.planes;
  9035. for (var i = 0; i < 6; i++) {
  9036. if (planes[i].distanceToPoint(point) < 0) {
  9037. return false;
  9038. }
  9039. }
  9040. return true;
  9041. }
  9042. });
  9043. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  9044. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  9045. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  9046. 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";
  9047. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  9048. var begin_vertex = "vec3 transformed = vec3( position );";
  9049. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  9050. 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";
  9051. 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";
  9052. 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";
  9053. 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";
  9054. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\tvarying vec3 vViewPosition;\n#endif";
  9055. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif";
  9056. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  9057. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  9058. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  9059. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  9060. 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}";
  9061. 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";
  9062. 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";
  9063. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  9064. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  9065. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  9066. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  9067. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  9068. 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}";
  9069. 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";
  9070. 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";
  9071. 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";
  9072. 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";
  9073. 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";
  9074. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = -mvPosition.z;\n#endif";
  9075. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  9076. 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";
  9077. 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";
  9078. 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";
  9079. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif";
  9080. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  9081. 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";
  9082. 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";
  9083. 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";
  9084. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  9085. 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)";
  9086. 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";
  9087. 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}";
  9088. 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";
  9089. 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";
  9090. 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";
  9091. 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";
  9092. 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";
  9093. 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";
  9094. 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";
  9095. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  9096. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  9097. 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";
  9098. var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform mat3 uvTransform;\n\tuniform sampler2D map;\n#endif";
  9099. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  9100. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  9101. 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";
  9102. 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";
  9103. 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";
  9104. 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;";
  9105. 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";
  9106. 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";
  9107. var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  9108. 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";
  9109. var clearcoat_normalmap_pars_fragment = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif";
  9110. 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}";
  9111. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  9112. 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;";
  9113. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  9114. 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";
  9115. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  9116. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  9117. 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";
  9118. 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";
  9119. 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";
  9120. 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}";
  9121. 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";
  9122. 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";
  9123. 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";
  9124. 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";
  9125. 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";
  9126. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  9127. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  9128. 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}";
  9129. var uv_pars_fragment = "#ifdef USE_UV\n\tvarying vec2 vUv;\n#endif";
  9130. var uv_pars_vertex = "#ifdef USE_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif";
  9131. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  9132. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  9133. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";
  9134. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";
  9135. 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";
  9136. 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}";
  9137. 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}";
  9138. 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}";
  9139. 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}";
  9140. 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}";
  9141. 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}";
  9142. 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}";
  9143. 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}";
  9144. 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}";
  9145. 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}";
  9146. 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}";
  9147. 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}";
  9148. 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}";
  9149. 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}";
  9150. 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}";
  9151. 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}";
  9152. 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}";
  9153. 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}";
  9154. 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}";
  9155. 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}";
  9156. 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}";
  9157. 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}";
  9158. 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}";
  9159. 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}";
  9160. 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}";
  9161. 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}";
  9162. 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}";
  9163. 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}";
  9164. 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}";
  9165. 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}";
  9166. var ShaderChunk = {
  9167. alphamap_fragment: alphamap_fragment,
  9168. alphamap_pars_fragment: alphamap_pars_fragment,
  9169. alphatest_fragment: alphatest_fragment,
  9170. aomap_fragment: aomap_fragment,
  9171. aomap_pars_fragment: aomap_pars_fragment,
  9172. begin_vertex: begin_vertex,
  9173. beginnormal_vertex: beginnormal_vertex,
  9174. bsdfs: bsdfs,
  9175. bumpmap_pars_fragment: bumpmap_pars_fragment,
  9176. clipping_planes_fragment: clipping_planes_fragment,
  9177. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  9178. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  9179. clipping_planes_vertex: clipping_planes_vertex,
  9180. color_fragment: color_fragment,
  9181. color_pars_fragment: color_pars_fragment,
  9182. color_pars_vertex: color_pars_vertex,
  9183. color_vertex: color_vertex,
  9184. common: common,
  9185. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  9186. defaultnormal_vertex: defaultnormal_vertex,
  9187. displacementmap_pars_vertex: displacementmap_pars_vertex,
  9188. displacementmap_vertex: displacementmap_vertex,
  9189. emissivemap_fragment: emissivemap_fragment,
  9190. emissivemap_pars_fragment: emissivemap_pars_fragment,
  9191. encodings_fragment: encodings_fragment,
  9192. encodings_pars_fragment: encodings_pars_fragment,
  9193. envmap_fragment: envmap_fragment,
  9194. envmap_common_pars_fragment: envmap_common_pars_fragment,
  9195. envmap_pars_fragment: envmap_pars_fragment,
  9196. envmap_pars_vertex: envmap_pars_vertex,
  9197. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  9198. envmap_vertex: envmap_vertex,
  9199. fog_vertex: fog_vertex,
  9200. fog_pars_vertex: fog_pars_vertex,
  9201. fog_fragment: fog_fragment,
  9202. fog_pars_fragment: fog_pars_fragment,
  9203. gradientmap_pars_fragment: gradientmap_pars_fragment,
  9204. lightmap_fragment: lightmap_fragment,
  9205. lightmap_pars_fragment: lightmap_pars_fragment,
  9206. lights_lambert_vertex: lights_lambert_vertex,
  9207. lights_pars_begin: lights_pars_begin,
  9208. lights_phong_fragment: lights_phong_fragment,
  9209. lights_phong_pars_fragment: lights_phong_pars_fragment,
  9210. lights_physical_fragment: lights_physical_fragment,
  9211. lights_physical_pars_fragment: lights_physical_pars_fragment,
  9212. lights_fragment_begin: lights_fragment_begin,
  9213. lights_fragment_maps: lights_fragment_maps,
  9214. lights_fragment_end: lights_fragment_end,
  9215. logdepthbuf_fragment: logdepthbuf_fragment,
  9216. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  9217. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  9218. logdepthbuf_vertex: logdepthbuf_vertex,
  9219. map_fragment: map_fragment,
  9220. map_pars_fragment: map_pars_fragment,
  9221. map_particle_fragment: map_particle_fragment,
  9222. map_particle_pars_fragment: map_particle_pars_fragment,
  9223. metalnessmap_fragment: metalnessmap_fragment,
  9224. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  9225. morphnormal_vertex: morphnormal_vertex,
  9226. morphtarget_pars_vertex: morphtarget_pars_vertex,
  9227. morphtarget_vertex: morphtarget_vertex,
  9228. normal_fragment_begin: normal_fragment_begin,
  9229. normal_fragment_maps: normal_fragment_maps,
  9230. normalmap_pars_fragment: normalmap_pars_fragment,
  9231. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  9232. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  9233. clearcoat_normalmap_pars_fragment: clearcoat_normalmap_pars_fragment,
  9234. packing: packing,
  9235. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  9236. project_vertex: project_vertex,
  9237. dithering_fragment: dithering_fragment,
  9238. dithering_pars_fragment: dithering_pars_fragment,
  9239. roughnessmap_fragment: roughnessmap_fragment,
  9240. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  9241. shadowmap_pars_fragment: shadowmap_pars_fragment,
  9242. shadowmap_pars_vertex: shadowmap_pars_vertex,
  9243. shadowmap_vertex: shadowmap_vertex,
  9244. shadowmask_pars_fragment: shadowmask_pars_fragment,
  9245. skinbase_vertex: skinbase_vertex,
  9246. skinning_pars_vertex: skinning_pars_vertex,
  9247. skinning_vertex: skinning_vertex,
  9248. skinnormal_vertex: skinnormal_vertex,
  9249. specularmap_fragment: specularmap_fragment,
  9250. specularmap_pars_fragment: specularmap_pars_fragment,
  9251. tonemapping_fragment: tonemapping_fragment,
  9252. tonemapping_pars_fragment: tonemapping_pars_fragment,
  9253. uv_pars_fragment: uv_pars_fragment,
  9254. uv_pars_vertex: uv_pars_vertex,
  9255. uv_vertex: uv_vertex,
  9256. uv2_pars_fragment: uv2_pars_fragment,
  9257. uv2_pars_vertex: uv2_pars_vertex,
  9258. uv2_vertex: uv2_vertex,
  9259. worldpos_vertex: worldpos_vertex,
  9260. background_frag: background_frag,
  9261. background_vert: background_vert,
  9262. cube_frag: cube_frag,
  9263. cube_vert: cube_vert,
  9264. depth_frag: depth_frag,
  9265. depth_vert: depth_vert,
  9266. distanceRGBA_frag: distanceRGBA_frag,
  9267. distanceRGBA_vert: distanceRGBA_vert,
  9268. equirect_frag: equirect_frag,
  9269. equirect_vert: equirect_vert,
  9270. linedashed_frag: linedashed_frag,
  9271. linedashed_vert: linedashed_vert,
  9272. meshbasic_frag: meshbasic_frag,
  9273. meshbasic_vert: meshbasic_vert,
  9274. meshlambert_frag: meshlambert_frag,
  9275. meshlambert_vert: meshlambert_vert,
  9276. meshmatcap_frag: meshmatcap_frag,
  9277. meshmatcap_vert: meshmatcap_vert,
  9278. meshphong_frag: meshphong_frag,
  9279. meshphong_vert: meshphong_vert,
  9280. meshphysical_frag: meshphysical_frag,
  9281. meshphysical_vert: meshphysical_vert,
  9282. normal_frag: normal_frag,
  9283. normal_vert: normal_vert,
  9284. points_frag: points_frag,
  9285. points_vert: points_vert,
  9286. shadow_frag: shadow_frag,
  9287. shadow_vert: shadow_vert,
  9288. sprite_frag: sprite_frag,
  9289. sprite_vert: sprite_vert
  9290. };
  9291. /**
  9292. * Uniforms library for shared webgl shaders
  9293. */
  9294. exports.ShaderChunk = ShaderChunk;
  9295. var UniformsLib = {
  9296. common: {
  9297. diffuse: {
  9298. value: new Color(0xeeeeee)
  9299. },
  9300. opacity: {
  9301. value: 1.0
  9302. },
  9303. map: {
  9304. value: null
  9305. },
  9306. uvTransform: {
  9307. value: new Matrix3()
  9308. },
  9309. alphaMap: {
  9310. value: null
  9311. }
  9312. },
  9313. specularmap: {
  9314. specularMap: {
  9315. value: null
  9316. }
  9317. },
  9318. envmap: {
  9319. envMap: {
  9320. value: null
  9321. },
  9322. flipEnvMap: {
  9323. value: -1
  9324. },
  9325. reflectivity: {
  9326. value: 1.0
  9327. },
  9328. refractionRatio: {
  9329. value: 0.98
  9330. },
  9331. maxMipLevel: {
  9332. value: 0
  9333. }
  9334. },
  9335. aomap: {
  9336. aoMap: {
  9337. value: null
  9338. },
  9339. aoMapIntensity: {
  9340. value: 1
  9341. }
  9342. },
  9343. lightmap: {
  9344. lightMap: {
  9345. value: null
  9346. },
  9347. lightMapIntensity: {
  9348. value: 1
  9349. }
  9350. },
  9351. emissivemap: {
  9352. emissiveMap: {
  9353. value: null
  9354. }
  9355. },
  9356. bumpmap: {
  9357. bumpMap: {
  9358. value: null
  9359. },
  9360. bumpScale: {
  9361. value: 1
  9362. }
  9363. },
  9364. normalmap: {
  9365. normalMap: {
  9366. value: null
  9367. },
  9368. normalScale: {
  9369. value: new Vector2(1, 1)
  9370. }
  9371. },
  9372. displacementmap: {
  9373. displacementMap: {
  9374. value: null
  9375. },
  9376. displacementScale: {
  9377. value: 1
  9378. },
  9379. displacementBias: {
  9380. value: 0
  9381. }
  9382. },
  9383. roughnessmap: {
  9384. roughnessMap: {
  9385. value: null
  9386. }
  9387. },
  9388. metalnessmap: {
  9389. metalnessMap: {
  9390. value: null
  9391. }
  9392. },
  9393. gradientmap: {
  9394. gradientMap: {
  9395. value: null
  9396. }
  9397. },
  9398. fog: {
  9399. fogDensity: {
  9400. value: 0.00025
  9401. },
  9402. fogNear: {
  9403. value: 1
  9404. },
  9405. fogFar: {
  9406. value: 2000
  9407. },
  9408. fogColor: {
  9409. value: new Color(0xffffff)
  9410. }
  9411. },
  9412. lights: {
  9413. ambientLightColor: {
  9414. value: []
  9415. },
  9416. lightProbe: {
  9417. value: []
  9418. },
  9419. directionalLights: {
  9420. value: [],
  9421. properties: {
  9422. direction: {},
  9423. color: {},
  9424. shadow: {},
  9425. shadowBias: {},
  9426. shadowRadius: {},
  9427. shadowMapSize: {}
  9428. }
  9429. },
  9430. directionalShadowMap: {
  9431. value: []
  9432. },
  9433. directionalShadowMatrix: {
  9434. value: []
  9435. },
  9436. spotLights: {
  9437. value: [],
  9438. properties: {
  9439. color: {},
  9440. position: {},
  9441. direction: {},
  9442. distance: {},
  9443. coneCos: {},
  9444. penumbraCos: {},
  9445. decay: {},
  9446. shadow: {},
  9447. shadowBias: {},
  9448. shadowRadius: {},
  9449. shadowMapSize: {}
  9450. }
  9451. },
  9452. spotShadowMap: {
  9453. value: []
  9454. },
  9455. spotShadowMatrix: {
  9456. value: []
  9457. },
  9458. pointLights: {
  9459. value: [],
  9460. properties: {
  9461. color: {},
  9462. position: {},
  9463. decay: {},
  9464. distance: {},
  9465. shadow: {},
  9466. shadowBias: {},
  9467. shadowRadius: {},
  9468. shadowMapSize: {},
  9469. shadowCameraNear: {},
  9470. shadowCameraFar: {}
  9471. }
  9472. },
  9473. pointShadowMap: {
  9474. value: []
  9475. },
  9476. pointShadowMatrix: {
  9477. value: []
  9478. },
  9479. hemisphereLights: {
  9480. value: [],
  9481. properties: {
  9482. direction: {},
  9483. skyColor: {},
  9484. groundColor: {}
  9485. }
  9486. },
  9487. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  9488. rectAreaLights: {
  9489. value: [],
  9490. properties: {
  9491. color: {},
  9492. position: {},
  9493. width: {},
  9494. height: {}
  9495. }
  9496. }
  9497. },
  9498. points: {
  9499. diffuse: {
  9500. value: new Color(0xeeeeee)
  9501. },
  9502. opacity: {
  9503. value: 1.0
  9504. },
  9505. size: {
  9506. value: 1.0
  9507. },
  9508. scale: {
  9509. value: 1.0
  9510. },
  9511. map: {
  9512. value: null
  9513. },
  9514. uvTransform: {
  9515. value: new Matrix3()
  9516. }
  9517. },
  9518. sprite: {
  9519. diffuse: {
  9520. value: new Color(0xeeeeee)
  9521. },
  9522. opacity: {
  9523. value: 1.0
  9524. },
  9525. center: {
  9526. value: new Vector2(0.5, 0.5)
  9527. },
  9528. rotation: {
  9529. value: 0.0
  9530. },
  9531. map: {
  9532. value: null
  9533. },
  9534. uvTransform: {
  9535. value: new Matrix3()
  9536. }
  9537. }
  9538. };
  9539. /**
  9540. * @author alteredq / http://alteredqualia.com/
  9541. * @author mrdoob / http://mrdoob.com/
  9542. * @author mikael emtinger / http://gomo.se/
  9543. */
  9544. exports.UniformsLib = UniformsLib;
  9545. var ShaderLib = {
  9546. basic: {
  9547. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  9548. vertexShader: ShaderChunk.meshbasic_vert,
  9549. fragmentShader: ShaderChunk.meshbasic_frag
  9550. },
  9551. lambert: {
  9552. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
  9553. emissive: {
  9554. value: new Color(0x000000)
  9555. }
  9556. }]),
  9557. vertexShader: ShaderChunk.meshlambert_vert,
  9558. fragmentShader: ShaderChunk.meshlambert_frag
  9559. },
  9560. phong: {
  9561. 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, {
  9562. emissive: {
  9563. value: new Color(0x000000)
  9564. },
  9565. specular: {
  9566. value: new Color(0x111111)
  9567. },
  9568. shininess: {
  9569. value: 30
  9570. }
  9571. }]),
  9572. vertexShader: ShaderChunk.meshphong_vert,
  9573. fragmentShader: ShaderChunk.meshphong_frag
  9574. },
  9575. standard: {
  9576. 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, {
  9577. emissive: {
  9578. value: new Color(0x000000)
  9579. },
  9580. roughness: {
  9581. value: 0.5
  9582. },
  9583. metalness: {
  9584. value: 0.5
  9585. },
  9586. envMapIntensity: {
  9587. value: 1
  9588. } // temporary
  9589. }]),
  9590. vertexShader: ShaderChunk.meshphysical_vert,
  9591. fragmentShader: ShaderChunk.meshphysical_frag
  9592. },
  9593. matcap: {
  9594. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  9595. matcap: {
  9596. value: null
  9597. }
  9598. }]),
  9599. vertexShader: ShaderChunk.meshmatcap_vert,
  9600. fragmentShader: ShaderChunk.meshmatcap_frag
  9601. },
  9602. points: {
  9603. uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  9604. vertexShader: ShaderChunk.points_vert,
  9605. fragmentShader: ShaderChunk.points_frag
  9606. },
  9607. dashed: {
  9608. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  9609. scale: {
  9610. value: 1
  9611. },
  9612. dashSize: {
  9613. value: 1
  9614. },
  9615. totalSize: {
  9616. value: 2
  9617. }
  9618. }]),
  9619. vertexShader: ShaderChunk.linedashed_vert,
  9620. fragmentShader: ShaderChunk.linedashed_frag
  9621. },
  9622. depth: {
  9623. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  9624. vertexShader: ShaderChunk.depth_vert,
  9625. fragmentShader: ShaderChunk.depth_frag
  9626. },
  9627. normal: {
  9628. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  9629. opacity: {
  9630. value: 1.0
  9631. }
  9632. }]),
  9633. vertexShader: ShaderChunk.normal_vert,
  9634. fragmentShader: ShaderChunk.normal_frag
  9635. },
  9636. sprite: {
  9637. uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  9638. vertexShader: ShaderChunk.sprite_vert,
  9639. fragmentShader: ShaderChunk.sprite_frag
  9640. },
  9641. background: {
  9642. uniforms: {
  9643. uvTransform: {
  9644. value: new Matrix3()
  9645. },
  9646. t2D: {
  9647. value: null
  9648. }
  9649. },
  9650. vertexShader: ShaderChunk.background_vert,
  9651. fragmentShader: ShaderChunk.background_frag
  9652. },
  9653. /* -------------------------------------------------------------------------
  9654. // Cube map shader
  9655. ------------------------------------------------------------------------- */
  9656. cube: {
  9657. uniforms: {
  9658. tCube: {
  9659. value: null
  9660. },
  9661. tFlip: {
  9662. value: -1
  9663. },
  9664. opacity: {
  9665. value: 1.0
  9666. }
  9667. },
  9668. vertexShader: ShaderChunk.cube_vert,
  9669. fragmentShader: ShaderChunk.cube_frag
  9670. },
  9671. equirect: {
  9672. uniforms: {
  9673. tEquirect: {
  9674. value: null
  9675. }
  9676. },
  9677. vertexShader: ShaderChunk.equirect_vert,
  9678. fragmentShader: ShaderChunk.equirect_frag
  9679. },
  9680. distanceRGBA: {
  9681. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  9682. referencePosition: {
  9683. value: new Vector3()
  9684. },
  9685. nearDistance: {
  9686. value: 1
  9687. },
  9688. farDistance: {
  9689. value: 1000
  9690. }
  9691. }]),
  9692. vertexShader: ShaderChunk.distanceRGBA_vert,
  9693. fragmentShader: ShaderChunk.distanceRGBA_frag
  9694. },
  9695. shadow: {
  9696. uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  9697. color: {
  9698. value: new Color(0x00000)
  9699. },
  9700. opacity: {
  9701. value: 1.0
  9702. }
  9703. }]),
  9704. vertexShader: ShaderChunk.shadow_vert,
  9705. fragmentShader: ShaderChunk.shadow_frag
  9706. }
  9707. };
  9708. exports.ShaderLib = ShaderLib;
  9709. ShaderLib.physical = {
  9710. uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
  9711. transparency: {
  9712. value: 0
  9713. },
  9714. clearcoat: {
  9715. value: 0
  9716. },
  9717. clearcoatRoughness: {
  9718. value: 0
  9719. },
  9720. sheen: {
  9721. value: new Color(0x000000)
  9722. },
  9723. clearcoatNormalScale: {
  9724. value: new Vector2(1, 1)
  9725. },
  9726. clearcoatNormalMap: {
  9727. value: null
  9728. }
  9729. }]),
  9730. vertexShader: ShaderChunk.meshphysical_vert,
  9731. fragmentShader: ShaderChunk.meshphysical_frag
  9732. };
  9733. /**
  9734. * @author mrdoob / http://mrdoob.com/
  9735. */
  9736. function WebGLAnimation() {
  9737. var context = null;
  9738. var isAnimating = false;
  9739. var animationLoop = null;
  9740. function onAnimationFrame(time, frame) {
  9741. if (isAnimating === false) return;
  9742. animationLoop(time, frame);
  9743. context.requestAnimationFrame(onAnimationFrame);
  9744. }
  9745. return {
  9746. start: function () {
  9747. if (isAnimating === true) return;
  9748. if (animationLoop === null) return;
  9749. context.requestAnimationFrame(onAnimationFrame);
  9750. isAnimating = true;
  9751. },
  9752. stop: function () {
  9753. isAnimating = false;
  9754. },
  9755. setAnimationLoop: function (callback) {
  9756. animationLoop = callback;
  9757. },
  9758. setContext: function (value) {
  9759. context = value;
  9760. }
  9761. };
  9762. }
  9763. /**
  9764. * @author mrdoob / http://mrdoob.com/
  9765. */
  9766. function WebGLAttributes(gl) {
  9767. var buffers = new WeakMap();
  9768. function createBuffer(attribute, bufferType) {
  9769. var array = attribute.array;
  9770. var usage = attribute.dynamic ? 35048 : 35044;
  9771. var buffer = gl.createBuffer();
  9772. gl.bindBuffer(bufferType, buffer);
  9773. gl.bufferData(bufferType, array, usage);
  9774. attribute.onUploadCallback();
  9775. var type = 5126;
  9776. if (array instanceof Float32Array) {
  9777. type = 5126;
  9778. } else if (array instanceof Float64Array) {
  9779. console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
  9780. } else if (array instanceof Uint16Array) {
  9781. type = 5123;
  9782. } else if (array instanceof Int16Array) {
  9783. type = 5122;
  9784. } else if (array instanceof Uint32Array) {
  9785. type = 5125;
  9786. } else if (array instanceof Int32Array) {
  9787. type = 5124;
  9788. } else if (array instanceof Int8Array) {
  9789. type = 5120;
  9790. } else if (array instanceof Uint8Array) {
  9791. type = 5121;
  9792. }
  9793. return {
  9794. buffer: buffer,
  9795. type: type,
  9796. bytesPerElement: array.BYTES_PER_ELEMENT,
  9797. version: attribute.version
  9798. };
  9799. }
  9800. function updateBuffer(buffer, attribute, bufferType) {
  9801. var array = attribute.array;
  9802. var updateRange = attribute.updateRange;
  9803. gl.bindBuffer(bufferType, buffer);
  9804. if (attribute.dynamic === false) {
  9805. gl.bufferData(bufferType, array, 35044);
  9806. } else if (updateRange.count === -1) {
  9807. // Not using update ranges
  9808. gl.bufferSubData(bufferType, 0, array);
  9809. } else if (updateRange.count === 0) {
  9810. 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.');
  9811. } else {
  9812. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  9813. updateRange.count = -1; // reset range
  9814. }
  9815. } //
  9816. function get(attribute) {
  9817. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  9818. return buffers.get(attribute);
  9819. }
  9820. function remove(attribute) {
  9821. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  9822. var data = buffers.get(attribute);
  9823. if (data) {
  9824. gl.deleteBuffer(data.buffer);
  9825. buffers.delete(attribute);
  9826. }
  9827. }
  9828. function update(attribute, bufferType) {
  9829. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  9830. var data = buffers.get(attribute);
  9831. if (data === undefined) {
  9832. buffers.set(attribute, createBuffer(attribute, bufferType));
  9833. } else if (data.version < attribute.version) {
  9834. updateBuffer(data.buffer, attribute, bufferType);
  9835. data.version = attribute.version;
  9836. }
  9837. }
  9838. return {
  9839. get: get,
  9840. remove: remove,
  9841. update: update
  9842. };
  9843. }
  9844. /**
  9845. * @author mrdoob / http://mrdoob.com/
  9846. * @author Mugen87 / https://github.com/Mugen87
  9847. */
  9848. // PlaneGeometry
  9849. function PlaneGeometry(width, height, widthSegments, heightSegments) {
  9850. Geometry.call(this);
  9851. this.type = 'PlaneGeometry';
  9852. this.parameters = {
  9853. width: width,
  9854. height: height,
  9855. widthSegments: widthSegments,
  9856. heightSegments: heightSegments
  9857. };
  9858. this.fromBufferGeometry(new PlaneBufferGeometry(width, height, widthSegments, heightSegments));
  9859. this.mergeVertices();
  9860. }
  9861. PlaneGeometry.prototype = Object.create(Geometry.prototype);
  9862. PlaneGeometry.prototype.constructor = PlaneGeometry; // PlaneBufferGeometry
  9863. function PlaneBufferGeometry(width, height, widthSegments, heightSegments) {
  9864. BufferGeometry.call(this);
  9865. this.type = 'PlaneBufferGeometry';
  9866. this.parameters = {
  9867. width: width,
  9868. height: height,
  9869. widthSegments: widthSegments,
  9870. heightSegments: heightSegments
  9871. };
  9872. width = width || 1;
  9873. height = height || 1;
  9874. var width_half = width / 2;
  9875. var height_half = height / 2;
  9876. var gridX = Math.floor(widthSegments) || 1;
  9877. var gridY = Math.floor(heightSegments) || 1;
  9878. var gridX1 = gridX + 1;
  9879. var gridY1 = gridY + 1;
  9880. var segment_width = width / gridX;
  9881. var segment_height = height / gridY;
  9882. var ix, iy; // buffers
  9883. var indices = [];
  9884. var vertices = [];
  9885. var normals = [];
  9886. var uvs = []; // generate vertices, normals and uvs
  9887. for (iy = 0; iy < gridY1; iy++) {
  9888. var y = iy * segment_height - height_half;
  9889. for (ix = 0; ix < gridX1; ix++) {
  9890. var x = ix * segment_width - width_half;
  9891. vertices.push(x, -y, 0);
  9892. normals.push(0, 0, 1);
  9893. uvs.push(ix / gridX);
  9894. uvs.push(1 - iy / gridY);
  9895. }
  9896. } // indices
  9897. for (iy = 0; iy < gridY; iy++) {
  9898. for (ix = 0; ix < gridX; ix++) {
  9899. var a = ix + gridX1 * iy;
  9900. var b = ix + gridX1 * (iy + 1);
  9901. var c = ix + 1 + gridX1 * (iy + 1);
  9902. var d = ix + 1 + gridX1 * iy; // faces
  9903. indices.push(a, b, d);
  9904. indices.push(b, c, d);
  9905. }
  9906. } // build geometry
  9907. this.setIndex(indices);
  9908. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  9909. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  9910. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  9911. }
  9912. PlaneBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  9913. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  9914. /**
  9915. * @author mrdoob / http://mrdoob.com/
  9916. */
  9917. function WebGLBackground(renderer, state, objects, premultipliedAlpha) {
  9918. var clearColor = new Color(0x000000);
  9919. var clearAlpha = 0;
  9920. var planeMesh;
  9921. var boxMesh; // Store the current background texture and its `version`
  9922. // so we can recompile the material accordingly.
  9923. var currentBackground = null;
  9924. var currentBackgroundVersion = 0;
  9925. function render(renderList, scene, camera, forceClear) {
  9926. var background = scene.background; // Ignore background in AR
  9927. // TODO: Reconsider this.
  9928. var vr = renderer.vr;
  9929. var session = vr.getSession && vr.getSession();
  9930. if (session && session.environmentBlendMode === 'additive') {
  9931. background = null;
  9932. }
  9933. if (background === null) {
  9934. setClear(clearColor, clearAlpha);
  9935. currentBackground = null;
  9936. currentBackgroundVersion = 0;
  9937. } else if (background && background.isColor) {
  9938. setClear(background, 1);
  9939. forceClear = true;
  9940. currentBackground = null;
  9941. currentBackgroundVersion = 0;
  9942. }
  9943. if (renderer.autoClear || forceClear) {
  9944. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  9945. }
  9946. if (background && (background.isCubeTexture || background.isWebGLRenderTargetCube)) {
  9947. if (boxMesh === undefined) {
  9948. boxMesh = new Mesh(new BoxBufferGeometry(1, 1, 1), new ShaderMaterial({
  9949. type: 'BackgroundCubeMaterial',
  9950. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  9951. vertexShader: ShaderLib.cube.vertexShader,
  9952. fragmentShader: ShaderLib.cube.fragmentShader,
  9953. side: BackSide,
  9954. depthTest: false,
  9955. depthWrite: false,
  9956. fog: false
  9957. }));
  9958. boxMesh.geometry.removeAttribute('normal');
  9959. boxMesh.geometry.removeAttribute('uv');
  9960. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  9961. this.matrixWorld.copyPosition(camera.matrixWorld);
  9962. }; // enable code injection for non-built-in material
  9963. Object.defineProperty(boxMesh.material, 'map', {
  9964. get: function () {
  9965. return this.uniforms.tCube.value;
  9966. }
  9967. });
  9968. objects.update(boxMesh);
  9969. }
  9970. var texture = background.isWebGLRenderTargetCube ? background.texture : background;
  9971. boxMesh.material.uniforms.tCube.value = texture;
  9972. boxMesh.material.uniforms.tFlip.value = background.isWebGLRenderTargetCube ? 1 : -1;
  9973. if (currentBackground !== background || currentBackgroundVersion !== texture.version) {
  9974. boxMesh.material.needsUpdate = true;
  9975. currentBackground = background;
  9976. currentBackgroundVersion = texture.version;
  9977. } // push to the pre-sorted opaque render list
  9978. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  9979. } else if (background && background.isTexture) {
  9980. if (planeMesh === undefined) {
  9981. planeMesh = new Mesh(new PlaneBufferGeometry(2, 2), new ShaderMaterial({
  9982. type: 'BackgroundMaterial',
  9983. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  9984. vertexShader: ShaderLib.background.vertexShader,
  9985. fragmentShader: ShaderLib.background.fragmentShader,
  9986. side: FrontSide,
  9987. depthTest: false,
  9988. depthWrite: false,
  9989. fog: false
  9990. }));
  9991. planeMesh.geometry.removeAttribute('normal'); // enable code injection for non-built-in material
  9992. Object.defineProperty(planeMesh.material, 'map', {
  9993. get: function () {
  9994. return this.uniforms.t2D.value;
  9995. }
  9996. });
  9997. objects.update(planeMesh);
  9998. }
  9999. planeMesh.material.uniforms.t2D.value = background;
  10000. if (background.matrixAutoUpdate === true) {
  10001. background.updateMatrix();
  10002. }
  10003. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  10004. if (currentBackground !== background || currentBackgroundVersion !== background.version) {
  10005. planeMesh.material.needsUpdate = true;
  10006. currentBackground = background;
  10007. currentBackgroundVersion = background.version;
  10008. } // push to the pre-sorted opaque render list
  10009. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  10010. }
  10011. }
  10012. function setClear(color, alpha) {
  10013. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  10014. }
  10015. return {
  10016. getClearColor: function () {
  10017. return clearColor;
  10018. },
  10019. setClearColor: function (color, alpha) {
  10020. clearColor.set(color);
  10021. clearAlpha = alpha !== undefined ? alpha : 1;
  10022. setClear(clearColor, clearAlpha);
  10023. },
  10024. getClearAlpha: function () {
  10025. return clearAlpha;
  10026. },
  10027. setClearAlpha: function (alpha) {
  10028. clearAlpha = alpha;
  10029. setClear(clearColor, clearAlpha);
  10030. },
  10031. render: render
  10032. };
  10033. }
  10034. /**
  10035. * @author mrdoob / http://mrdoob.com/
  10036. */
  10037. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  10038. var mode;
  10039. function setMode(value) {
  10040. mode = value;
  10041. }
  10042. function render(start, count) {
  10043. gl.drawArrays(mode, start, count);
  10044. info.update(count, mode);
  10045. }
  10046. function renderInstances(geometry, start, count, primcount) {
  10047. if (primcount === 0) return;
  10048. var extension, methodName;
  10049. if (capabilities.isWebGL2) {
  10050. extension = gl;
  10051. methodName = 'drawArraysInstanced';
  10052. } else {
  10053. extension = extensions.get('ANGLE_instanced_arrays');
  10054. methodName = 'drawArraysInstancedANGLE';
  10055. if (extension === null) {
  10056. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  10057. return;
  10058. }
  10059. }
  10060. extension[methodName](mode, start, count, primcount);
  10061. info.update(count, mode, primcount);
  10062. } //
  10063. this.setMode = setMode;
  10064. this.render = render;
  10065. this.renderInstances = renderInstances;
  10066. }
  10067. /**
  10068. * @author mrdoob / http://mrdoob.com/
  10069. */
  10070. function WebGLCapabilities(gl, extensions, parameters) {
  10071. var maxAnisotropy;
  10072. function getMaxAnisotropy() {
  10073. if (maxAnisotropy !== undefined) return maxAnisotropy;
  10074. var extension = extensions.get('EXT_texture_filter_anisotropic');
  10075. if (extension !== null) {
  10076. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  10077. } else {
  10078. maxAnisotropy = 0;
  10079. }
  10080. return maxAnisotropy;
  10081. }
  10082. function getMaxPrecision(precision) {
  10083. if (precision === 'highp') {
  10084. if (gl.getShaderPrecisionFormat(35633, 36338).precision > 0 && gl.getShaderPrecisionFormat(35632, 36338).precision > 0) {
  10085. return 'highp';
  10086. }
  10087. precision = 'mediump';
  10088. }
  10089. if (precision === 'mediump') {
  10090. if (gl.getShaderPrecisionFormat(35633, 36337).precision > 0 && gl.getShaderPrecisionFormat(35632, 36337).precision > 0) {
  10091. return 'mediump';
  10092. }
  10093. }
  10094. return 'lowp';
  10095. }
  10096. var isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext;
  10097. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  10098. var maxPrecision = getMaxPrecision(precision);
  10099. if (maxPrecision !== precision) {
  10100. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  10101. precision = maxPrecision;
  10102. }
  10103. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  10104. var maxTextures = gl.getParameter(34930);
  10105. var maxVertexTextures = gl.getParameter(35660);
  10106. var maxTextureSize = gl.getParameter(3379);
  10107. var maxCubemapSize = gl.getParameter(34076);
  10108. var maxAttributes = gl.getParameter(34921);
  10109. var maxVertexUniforms = gl.getParameter(36347);
  10110. var maxVaryings = gl.getParameter(36348);
  10111. var maxFragmentUniforms = gl.getParameter(36349);
  10112. var vertexTextures = maxVertexTextures > 0;
  10113. var floatFragmentTextures = isWebGL2 || !!extensions.get('OES_texture_float');
  10114. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  10115. var maxSamples = isWebGL2 ? gl.getParameter(36183) : 0;
  10116. return {
  10117. isWebGL2: isWebGL2,
  10118. getMaxAnisotropy: getMaxAnisotropy,
  10119. getMaxPrecision: getMaxPrecision,
  10120. precision: precision,
  10121. logarithmicDepthBuffer: logarithmicDepthBuffer,
  10122. maxTextures: maxTextures,
  10123. maxVertexTextures: maxVertexTextures,
  10124. maxTextureSize: maxTextureSize,
  10125. maxCubemapSize: maxCubemapSize,
  10126. maxAttributes: maxAttributes,
  10127. maxVertexUniforms: maxVertexUniforms,
  10128. maxVaryings: maxVaryings,
  10129. maxFragmentUniforms: maxFragmentUniforms,
  10130. vertexTextures: vertexTextures,
  10131. floatFragmentTextures: floatFragmentTextures,
  10132. floatVertexTextures: floatVertexTextures,
  10133. maxSamples: maxSamples
  10134. };
  10135. }
  10136. /**
  10137. * @author tschw
  10138. */
  10139. function WebGLClipping() {
  10140. var scope = this,
  10141. globalState = null,
  10142. numGlobalPlanes = 0,
  10143. localClippingEnabled = false,
  10144. renderingShadows = false,
  10145. plane = new Plane(),
  10146. viewNormalMatrix = new Matrix3(),
  10147. uniform = {
  10148. value: null,
  10149. needsUpdate: false
  10150. };
  10151. this.uniform = uniform;
  10152. this.numPlanes = 0;
  10153. this.numIntersection = 0;
  10154. this.init = function (planes, enableLocalClipping, camera) {
  10155. var enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  10156. // run another frame in order to reset the state:
  10157. numGlobalPlanes !== 0 || localClippingEnabled;
  10158. localClippingEnabled = enableLocalClipping;
  10159. globalState = projectPlanes(planes, camera, 0);
  10160. numGlobalPlanes = planes.length;
  10161. return enabled;
  10162. };
  10163. this.beginShadows = function () {
  10164. renderingShadows = true;
  10165. projectPlanes(null);
  10166. };
  10167. this.endShadows = function () {
  10168. renderingShadows = false;
  10169. resetGlobalState();
  10170. };
  10171. this.setState = function (planes, clipIntersection, clipShadows, camera, cache, fromCache) {
  10172. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  10173. // there's no local clipping
  10174. if (renderingShadows) {
  10175. // there's no global clipping
  10176. projectPlanes(null);
  10177. } else {
  10178. resetGlobalState();
  10179. }
  10180. } else {
  10181. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  10182. lGlobal = nGlobal * 4,
  10183. dstArray = cache.clippingState || null;
  10184. uniform.value = dstArray; // ensure unique state
  10185. dstArray = projectPlanes(planes, camera, lGlobal, fromCache);
  10186. for (var i = 0; i !== lGlobal; ++i) {
  10187. dstArray[i] = globalState[i];
  10188. }
  10189. cache.clippingState = dstArray;
  10190. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  10191. this.numPlanes += nGlobal;
  10192. }
  10193. };
  10194. function resetGlobalState() {
  10195. if (uniform.value !== globalState) {
  10196. uniform.value = globalState;
  10197. uniform.needsUpdate = numGlobalPlanes > 0;
  10198. }
  10199. scope.numPlanes = numGlobalPlanes;
  10200. scope.numIntersection = 0;
  10201. }
  10202. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  10203. var nPlanes = planes !== null ? planes.length : 0,
  10204. dstArray = null;
  10205. if (nPlanes !== 0) {
  10206. dstArray = uniform.value;
  10207. if (skipTransform !== true || dstArray === null) {
  10208. var flatSize = dstOffset + nPlanes * 4,
  10209. viewMatrix = camera.matrixWorldInverse;
  10210. viewNormalMatrix.getNormalMatrix(viewMatrix);
  10211. if (dstArray === null || dstArray.length < flatSize) {
  10212. dstArray = new Float32Array(flatSize);
  10213. }
  10214. for (var i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  10215. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  10216. plane.normal.toArray(dstArray, i4);
  10217. dstArray[i4 + 3] = plane.constant;
  10218. }
  10219. }
  10220. uniform.value = dstArray;
  10221. uniform.needsUpdate = true;
  10222. }
  10223. scope.numPlanes = nPlanes;
  10224. return dstArray;
  10225. }
  10226. }
  10227. /**
  10228. * @author mrdoob / http://mrdoob.com/
  10229. */
  10230. function WebGLExtensions(gl) {
  10231. var extensions = {};
  10232. return {
  10233. get: function (name) {
  10234. if (extensions[name] !== undefined) {
  10235. return extensions[name];
  10236. }
  10237. var extension;
  10238. switch (name) {
  10239. case 'WEBGL_depth_texture':
  10240. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  10241. break;
  10242. case 'EXT_texture_filter_anisotropic':
  10243. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  10244. break;
  10245. case 'WEBGL_compressed_texture_s3tc':
  10246. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10247. break;
  10248. case 'WEBGL_compressed_texture_pvrtc':
  10249. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10250. break;
  10251. default:
  10252. extension = gl.getExtension(name);
  10253. }
  10254. if (extension === null) {
  10255. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  10256. }
  10257. extensions[name] = extension;
  10258. return extension;
  10259. }
  10260. };
  10261. }
  10262. /**
  10263. * @author mrdoob / http://mrdoob.com/
  10264. */
  10265. function WebGLGeometries(gl, attributes, info) {
  10266. var geometries = new WeakMap();
  10267. var wireframeAttributes = new WeakMap();
  10268. function onGeometryDispose(event) {
  10269. var geometry = event.target;
  10270. var buffergeometry = geometries.get(geometry);
  10271. if (buffergeometry.index !== null) {
  10272. attributes.remove(buffergeometry.index);
  10273. }
  10274. for (var name in buffergeometry.attributes) {
  10275. attributes.remove(buffergeometry.attributes[name]);
  10276. }
  10277. geometry.removeEventListener('dispose', onGeometryDispose);
  10278. geometries.delete(geometry);
  10279. var attribute = wireframeAttributes.get(buffergeometry);
  10280. if (attribute) {
  10281. attributes.remove(attribute);
  10282. wireframeAttributes.delete(buffergeometry);
  10283. } //
  10284. info.memory.geometries--;
  10285. }
  10286. function get(object, geometry) {
  10287. var buffergeometry = geometries.get(geometry);
  10288. if (buffergeometry) return buffergeometry;
  10289. geometry.addEventListener('dispose', onGeometryDispose);
  10290. if (geometry.isBufferGeometry) {
  10291. buffergeometry = geometry;
  10292. } else if (geometry.isGeometry) {
  10293. if (geometry._bufferGeometry === undefined) {
  10294. geometry._bufferGeometry = new BufferGeometry().setFromObject(object);
  10295. }
  10296. buffergeometry = geometry._bufferGeometry;
  10297. }
  10298. geometries.set(geometry, buffergeometry);
  10299. info.memory.geometries++;
  10300. return buffergeometry;
  10301. }
  10302. function update(geometry) {
  10303. var index = geometry.index;
  10304. var geometryAttributes = geometry.attributes;
  10305. if (index !== null) {
  10306. attributes.update(index, 34963);
  10307. }
  10308. for (var name in geometryAttributes) {
  10309. attributes.update(geometryAttributes[name], 34962);
  10310. } // morph targets
  10311. var morphAttributes = geometry.morphAttributes;
  10312. for (var name in morphAttributes) {
  10313. var array = morphAttributes[name];
  10314. for (var i = 0, l = array.length; i < l; i++) {
  10315. attributes.update(array[i], 34962);
  10316. }
  10317. }
  10318. }
  10319. function updateWireframeAttribute(geometry) {
  10320. var indices = [];
  10321. var geometryIndex = geometry.index;
  10322. var geometryPosition = geometry.attributes.position;
  10323. var version = 0;
  10324. if (geometryIndex !== null) {
  10325. var array = geometryIndex.array;
  10326. version = geometryIndex.version;
  10327. for (var i = 0, l = array.length; i < l; i += 3) {
  10328. var a = array[i + 0];
  10329. var b = array[i + 1];
  10330. var c = array[i + 2];
  10331. indices.push(a, b, b, c, c, a);
  10332. }
  10333. } else {
  10334. var array = geometryPosition.array;
  10335. version = geometryPosition.version;
  10336. for (var i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  10337. var a = i + 0;
  10338. var b = i + 1;
  10339. var c = i + 2;
  10340. indices.push(a, b, b, c, c, a);
  10341. }
  10342. }
  10343. var attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  10344. attribute.version = version;
  10345. attributes.update(attribute, 34963); //
  10346. var previousAttribute = wireframeAttributes.get(geometry);
  10347. if (previousAttribute) attributes.remove(previousAttribute); //
  10348. wireframeAttributes.set(geometry, attribute);
  10349. }
  10350. function getWireframeAttribute(geometry) {
  10351. var currentAttribute = wireframeAttributes.get(geometry);
  10352. if (currentAttribute) {
  10353. var geometryIndex = geometry.index;
  10354. if (geometryIndex !== null) {
  10355. // if the attribute is obsolete, create a new one
  10356. if (currentAttribute.version < geometryIndex.version) {
  10357. updateWireframeAttribute(geometry);
  10358. }
  10359. }
  10360. } else {
  10361. updateWireframeAttribute(geometry);
  10362. }
  10363. return wireframeAttributes.get(geometry);
  10364. }
  10365. return {
  10366. get: get,
  10367. update: update,
  10368. getWireframeAttribute: getWireframeAttribute
  10369. };
  10370. }
  10371. /**
  10372. * @author mrdoob / http://mrdoob.com/
  10373. */
  10374. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  10375. var mode;
  10376. function setMode(value) {
  10377. mode = value;
  10378. }
  10379. var type, bytesPerElement;
  10380. function setIndex(value) {
  10381. type = value.type;
  10382. bytesPerElement = value.bytesPerElement;
  10383. }
  10384. function render(start, count) {
  10385. gl.drawElements(mode, count, type, start * bytesPerElement);
  10386. info.update(count, mode);
  10387. }
  10388. function renderInstances(geometry, start, count, primcount) {
  10389. if (primcount === 0) return;
  10390. var extension, methodName;
  10391. if (capabilities.isWebGL2) {
  10392. extension = gl;
  10393. methodName = 'drawElementsInstanced';
  10394. } else {
  10395. extension = extensions.get('ANGLE_instanced_arrays');
  10396. methodName = 'drawElementsInstancedANGLE';
  10397. if (extension === null) {
  10398. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  10399. return;
  10400. }
  10401. }
  10402. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  10403. info.update(count, mode, primcount);
  10404. } //
  10405. this.setMode = setMode;
  10406. this.setIndex = setIndex;
  10407. this.render = render;
  10408. this.renderInstances = renderInstances;
  10409. }
  10410. /**
  10411. * @author Mugen87 / https://github.com/Mugen87
  10412. */
  10413. function WebGLInfo(gl) {
  10414. var memory = {
  10415. geometries: 0,
  10416. textures: 0
  10417. };
  10418. var render = {
  10419. frame: 0,
  10420. calls: 0,
  10421. triangles: 0,
  10422. points: 0,
  10423. lines: 0
  10424. };
  10425. function update(count, mode, instanceCount) {
  10426. instanceCount = instanceCount || 1;
  10427. render.calls++;
  10428. switch (mode) {
  10429. case 4:
  10430. render.triangles += instanceCount * (count / 3);
  10431. break;
  10432. case 5:
  10433. case 6:
  10434. render.triangles += instanceCount * (count - 2);
  10435. break;
  10436. case 1:
  10437. render.lines += instanceCount * (count / 2);
  10438. break;
  10439. case 3:
  10440. render.lines += instanceCount * (count - 1);
  10441. break;
  10442. case 2:
  10443. render.lines += instanceCount * count;
  10444. break;
  10445. case 0:
  10446. render.points += instanceCount * count;
  10447. break;
  10448. default:
  10449. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  10450. break;
  10451. }
  10452. }
  10453. function reset() {
  10454. render.frame++;
  10455. render.calls = 0;
  10456. render.triangles = 0;
  10457. render.points = 0;
  10458. render.lines = 0;
  10459. }
  10460. return {
  10461. memory: memory,
  10462. render: render,
  10463. programs: null,
  10464. autoReset: true,
  10465. reset: reset,
  10466. update: update
  10467. };
  10468. }
  10469. /**
  10470. * @author mrdoob / http://mrdoob.com/
  10471. */
  10472. function absNumericalSort(a, b) {
  10473. return Math.abs(b[1]) - Math.abs(a[1]);
  10474. }
  10475. function WebGLMorphtargets(gl) {
  10476. var influencesList = {};
  10477. var morphInfluences = new Float32Array(8);
  10478. function update(object, geometry, material, program) {
  10479. var objectInfluences = object.morphTargetInfluences;
  10480. var length = objectInfluences.length;
  10481. var influences = influencesList[geometry.id];
  10482. if (influences === undefined) {
  10483. // initialise list
  10484. influences = [];
  10485. for (var i = 0; i < length; i++) {
  10486. influences[i] = [i, 0];
  10487. }
  10488. influencesList[geometry.id] = influences;
  10489. }
  10490. var morphTargets = material.morphTargets && geometry.morphAttributes.position;
  10491. var morphNormals = material.morphNormals && geometry.morphAttributes.normal; // Remove current morphAttributes
  10492. for (var i = 0; i < length; i++) {
  10493. var influence = influences[i];
  10494. if (influence[1] !== 0) {
  10495. if (morphTargets) geometry.removeAttribute('morphTarget' + i);
  10496. if (morphNormals) geometry.removeAttribute('morphNormal' + i);
  10497. }
  10498. } // Collect influences
  10499. for (var i = 0; i < length; i++) {
  10500. var influence = influences[i];
  10501. influence[0] = i;
  10502. influence[1] = objectInfluences[i];
  10503. }
  10504. influences.sort(absNumericalSort); // Add morphAttributes
  10505. for (var i = 0; i < 8; i++) {
  10506. var influence = influences[i];
  10507. if (influence) {
  10508. var index = influence[0];
  10509. var value = influence[1];
  10510. if (value) {
  10511. if (morphTargets) geometry.addAttribute('morphTarget' + i, morphTargets[index]);
  10512. if (morphNormals) geometry.addAttribute('morphNormal' + i, morphNormals[index]);
  10513. morphInfluences[i] = value;
  10514. continue;
  10515. }
  10516. }
  10517. morphInfluences[i] = 0;
  10518. }
  10519. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  10520. }
  10521. return {
  10522. update: update
  10523. };
  10524. }
  10525. /**
  10526. * @author mrdoob / http://mrdoob.com/
  10527. */
  10528. function WebGLObjects(gl, geometries, attributes, info) {
  10529. var updateList = {};
  10530. function update(object) {
  10531. var frame = info.render.frame;
  10532. var geometry = object.geometry;
  10533. var buffergeometry = geometries.get(object, geometry); // Update once per frame
  10534. if (updateList[buffergeometry.id] !== frame) {
  10535. if (geometry.isGeometry) {
  10536. buffergeometry.updateFromObject(object);
  10537. }
  10538. geometries.update(buffergeometry);
  10539. updateList[buffergeometry.id] = frame;
  10540. }
  10541. if (object.isInstancedMesh) {
  10542. attributes.update(object.instanceMatrix, 34962);
  10543. }
  10544. return buffergeometry;
  10545. }
  10546. function dispose() {
  10547. updateList = {};
  10548. }
  10549. return {
  10550. update: update,
  10551. dispose: dispose
  10552. };
  10553. }
  10554. /**
  10555. * @author mrdoob / http://mrdoob.com/
  10556. */
  10557. function CubeTexture(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  10558. images = images !== undefined ? images : [];
  10559. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  10560. format = format !== undefined ? format : RGBFormat;
  10561. Texture.call(this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  10562. this.flipY = false;
  10563. }
  10564. CubeTexture.prototype = Object.create(Texture.prototype);
  10565. CubeTexture.prototype.constructor = CubeTexture;
  10566. CubeTexture.prototype.isCubeTexture = true;
  10567. Object.defineProperty(CubeTexture.prototype, 'images', {
  10568. get: function () {
  10569. return this.image;
  10570. },
  10571. set: function (value) {
  10572. this.image = value;
  10573. }
  10574. });
  10575. /**
  10576. * @author Takahiro https://github.com/takahirox
  10577. */
  10578. function DataTexture2DArray(data, width, height, depth) {
  10579. Texture.call(this, null);
  10580. this.image = {
  10581. data: data || null,
  10582. width: width || 1,
  10583. height: height || 1,
  10584. depth: depth || 1
  10585. };
  10586. this.magFilter = NearestFilter;
  10587. this.minFilter = NearestFilter;
  10588. this.wrapR = ClampToEdgeWrapping;
  10589. this.generateMipmaps = false;
  10590. this.flipY = false;
  10591. this.needsUpdate = true;
  10592. }
  10593. DataTexture2DArray.prototype = Object.create(Texture.prototype);
  10594. DataTexture2DArray.prototype.constructor = DataTexture2DArray;
  10595. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  10596. /**
  10597. * @author Artur Trzesiok
  10598. */
  10599. function DataTexture3D(data, width, height, depth) {
  10600. // We're going to add .setXXX() methods for setting properties later.
  10601. // Users can still set in DataTexture3D directly.
  10602. //
  10603. // var texture = new THREE.DataTexture3D( data, width, height, depth );
  10604. // texture.anisotropy = 16;
  10605. //
  10606. // See #14839
  10607. Texture.call(this, null);
  10608. this.image = {
  10609. data: data || null,
  10610. width: width || 1,
  10611. height: height || 1,
  10612. depth: depth || 1
  10613. };
  10614. this.magFilter = NearestFilter;
  10615. this.minFilter = NearestFilter;
  10616. this.wrapR = ClampToEdgeWrapping;
  10617. this.generateMipmaps = false;
  10618. this.flipY = false;
  10619. this.needsUpdate = true;
  10620. }
  10621. DataTexture3D.prototype = Object.create(Texture.prototype);
  10622. DataTexture3D.prototype.constructor = DataTexture3D;
  10623. DataTexture3D.prototype.isDataTexture3D = true;
  10624. /**
  10625. * @author tschw
  10626. * @author Mugen87 / https://github.com/Mugen87
  10627. * @author mrdoob / http://mrdoob.com/
  10628. *
  10629. * Uniforms of a program.
  10630. * Those form a tree structure with a special top-level container for the root,
  10631. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10632. *
  10633. *
  10634. * Properties of inner nodes including the top-level container:
  10635. *
  10636. * .seq - array of nested uniforms
  10637. * .map - nested uniforms by name
  10638. *
  10639. *
  10640. * Methods of all nodes except the top-level container:
  10641. *
  10642. * .setValue( gl, value, [textures] )
  10643. *
  10644. * uploads a uniform value(s)
  10645. * the 'textures' parameter is needed for sampler uniforms
  10646. *
  10647. *
  10648. * Static methods of the top-level container (textures factorizations):
  10649. *
  10650. * .upload( gl, seq, values, textures )
  10651. *
  10652. * sets uniforms in 'seq' to 'values[id].value'
  10653. *
  10654. * .seqWithValue( seq, values ) : filteredSeq
  10655. *
  10656. * filters 'seq' entries with corresponding entry in values
  10657. *
  10658. *
  10659. * Methods of the top-level container (textures factorizations):
  10660. *
  10661. * .setValue( gl, name, value, textures )
  10662. *
  10663. * sets uniform with name 'name' to 'value'
  10664. *
  10665. * .setOptional( gl, obj, prop )
  10666. *
  10667. * like .set for an optional property of the object
  10668. *
  10669. */
  10670. var emptyTexture = new Texture();
  10671. var emptyTexture2dArray = new DataTexture2DArray();
  10672. var emptyTexture3d = new DataTexture3D();
  10673. var emptyCubeTexture = new CubeTexture(); // --- Utilities ---
  10674. // Array Caches (provide typed arrays for temporary by size)
  10675. var arrayCacheF32 = [];
  10676. var arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  10677. var mat4array = new Float32Array(16);
  10678. var mat3array = new Float32Array(9);
  10679. var mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  10680. function flatten(array, nBlocks, blockSize) {
  10681. var firstElem = array[0];
  10682. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  10683. // see http://jacksondunstan.com/articles/983
  10684. var n = nBlocks * blockSize,
  10685. r = arrayCacheF32[n];
  10686. if (r === undefined) {
  10687. r = new Float32Array(n);
  10688. arrayCacheF32[n] = r;
  10689. }
  10690. if (nBlocks !== 0) {
  10691. firstElem.toArray(r, 0);
  10692. for (var i = 1, offset = 0; i !== nBlocks; ++i) {
  10693. offset += blockSize;
  10694. array[i].toArray(r, offset);
  10695. }
  10696. }
  10697. return r;
  10698. }
  10699. function arraysEqual(a, b) {
  10700. if (a.length !== b.length) return false;
  10701. for (var i = 0, l = a.length; i < l; i++) {
  10702. if (a[i] !== b[i]) return false;
  10703. }
  10704. return true;
  10705. }
  10706. function copyArray(a, b) {
  10707. for (var i = 0, l = b.length; i < l; i++) {
  10708. a[i] = b[i];
  10709. }
  10710. } // Texture unit allocation
  10711. function allocTexUnits(textures, n) {
  10712. var r = arrayCacheI32[n];
  10713. if (r === undefined) {
  10714. r = new Int32Array(n);
  10715. arrayCacheI32[n] = r;
  10716. }
  10717. for (var i = 0; i !== n; ++i) r[i] = textures.allocateTextureUnit();
  10718. return r;
  10719. } // --- Setters ---
  10720. // Note: Defining these methods externally, because they come in a bunch
  10721. // and this way their names minify.
  10722. // Single scalar
  10723. function setValueV1f(gl, v) {
  10724. var cache = this.cache;
  10725. if (cache[0] === v) return;
  10726. gl.uniform1f(this.addr, v);
  10727. cache[0] = v;
  10728. } // Single float vector (from flat array or THREE.VectorN)
  10729. function setValueV2f(gl, v) {
  10730. var cache = this.cache;
  10731. if (v.x !== undefined) {
  10732. if (cache[0] !== v.x || cache[1] !== v.y) {
  10733. gl.uniform2f(this.addr, v.x, v.y);
  10734. cache[0] = v.x;
  10735. cache[1] = v.y;
  10736. }
  10737. } else {
  10738. if (arraysEqual(cache, v)) return;
  10739. gl.uniform2fv(this.addr, v);
  10740. copyArray(cache, v);
  10741. }
  10742. }
  10743. function setValueV3f(gl, v) {
  10744. var cache = this.cache;
  10745. if (v.x !== undefined) {
  10746. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  10747. gl.uniform3f(this.addr, v.x, v.y, v.z);
  10748. cache[0] = v.x;
  10749. cache[1] = v.y;
  10750. cache[2] = v.z;
  10751. }
  10752. } else if (v.r !== undefined) {
  10753. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  10754. gl.uniform3f(this.addr, v.r, v.g, v.b);
  10755. cache[0] = v.r;
  10756. cache[1] = v.g;
  10757. cache[2] = v.b;
  10758. }
  10759. } else {
  10760. if (arraysEqual(cache, v)) return;
  10761. gl.uniform3fv(this.addr, v);
  10762. copyArray(cache, v);
  10763. }
  10764. }
  10765. function setValueV4f(gl, v) {
  10766. var cache = this.cache;
  10767. if (v.x !== undefined) {
  10768. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  10769. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  10770. cache[0] = v.x;
  10771. cache[1] = v.y;
  10772. cache[2] = v.z;
  10773. cache[3] = v.w;
  10774. }
  10775. } else {
  10776. if (arraysEqual(cache, v)) return;
  10777. gl.uniform4fv(this.addr, v);
  10778. copyArray(cache, v);
  10779. }
  10780. } // Single matrix (from flat array or MatrixN)
  10781. function setValueM2(gl, v) {
  10782. var cache = this.cache;
  10783. var elements = v.elements;
  10784. if (elements === undefined) {
  10785. if (arraysEqual(cache, v)) return;
  10786. gl.uniformMatrix2fv(this.addr, false, v);
  10787. copyArray(cache, v);
  10788. } else {
  10789. if (arraysEqual(cache, elements)) return;
  10790. mat2array.set(elements);
  10791. gl.uniformMatrix2fv(this.addr, false, mat2array);
  10792. copyArray(cache, elements);
  10793. }
  10794. }
  10795. function setValueM3(gl, v) {
  10796. var cache = this.cache;
  10797. var elements = v.elements;
  10798. if (elements === undefined) {
  10799. if (arraysEqual(cache, v)) return;
  10800. gl.uniformMatrix3fv(this.addr, false, v);
  10801. copyArray(cache, v);
  10802. } else {
  10803. if (arraysEqual(cache, elements)) return;
  10804. mat3array.set(elements);
  10805. gl.uniformMatrix3fv(this.addr, false, mat3array);
  10806. copyArray(cache, elements);
  10807. }
  10808. }
  10809. function setValueM4(gl, v) {
  10810. var cache = this.cache;
  10811. var elements = v.elements;
  10812. if (elements === undefined) {
  10813. if (arraysEqual(cache, v)) return;
  10814. gl.uniformMatrix4fv(this.addr, false, v);
  10815. copyArray(cache, v);
  10816. } else {
  10817. if (arraysEqual(cache, elements)) return;
  10818. mat4array.set(elements);
  10819. gl.uniformMatrix4fv(this.addr, false, mat4array);
  10820. copyArray(cache, elements);
  10821. }
  10822. } // Single texture (2D / Cube)
  10823. function setValueT1(gl, v, textures) {
  10824. var cache = this.cache;
  10825. var unit = textures.allocateTextureUnit();
  10826. if (cache[0] !== unit) {
  10827. gl.uniform1i(this.addr, unit);
  10828. cache[0] = unit;
  10829. }
  10830. textures.safeSetTexture2D(v || emptyTexture, unit);
  10831. }
  10832. function setValueT2DArray1(gl, v, textures) {
  10833. var cache = this.cache;
  10834. var unit = textures.allocateTextureUnit();
  10835. if (cache[0] !== unit) {
  10836. gl.uniform1i(this.addr, unit);
  10837. cache[0] = unit;
  10838. }
  10839. textures.setTexture2DArray(v || emptyTexture2dArray, unit);
  10840. }
  10841. function setValueT3D1(gl, v, textures) {
  10842. var cache = this.cache;
  10843. var unit = textures.allocateTextureUnit();
  10844. if (cache[0] !== unit) {
  10845. gl.uniform1i(this.addr, unit);
  10846. cache[0] = unit;
  10847. }
  10848. textures.setTexture3D(v || emptyTexture3d, unit);
  10849. }
  10850. function setValueT6(gl, v, textures) {
  10851. var cache = this.cache;
  10852. var unit = textures.allocateTextureUnit();
  10853. if (cache[0] !== unit) {
  10854. gl.uniform1i(this.addr, unit);
  10855. cache[0] = unit;
  10856. }
  10857. textures.safeSetTextureCube(v || emptyCubeTexture, unit);
  10858. } // Integer / Boolean vectors or arrays thereof (always flat arrays)
  10859. function setValueV1i(gl, v) {
  10860. var cache = this.cache;
  10861. if (cache[0] === v) return;
  10862. gl.uniform1i(this.addr, v);
  10863. cache[0] = v;
  10864. }
  10865. function setValueV2i(gl, v) {
  10866. var cache = this.cache;
  10867. if (arraysEqual(cache, v)) return;
  10868. gl.uniform2iv(this.addr, v);
  10869. copyArray(cache, v);
  10870. }
  10871. function setValueV3i(gl, v) {
  10872. var cache = this.cache;
  10873. if (arraysEqual(cache, v)) return;
  10874. gl.uniform3iv(this.addr, v);
  10875. copyArray(cache, v);
  10876. }
  10877. function setValueV4i(gl, v) {
  10878. var cache = this.cache;
  10879. if (arraysEqual(cache, v)) return;
  10880. gl.uniform4iv(this.addr, v);
  10881. copyArray(cache, v);
  10882. } // Helper to pick the right setter for the singular case
  10883. function getSingularSetter(type) {
  10884. switch (type) {
  10885. case 0x1406:
  10886. return setValueV1f;
  10887. // FLOAT
  10888. case 0x8b50:
  10889. return setValueV2f;
  10890. // _VEC2
  10891. case 0x8b51:
  10892. return setValueV3f;
  10893. // _VEC3
  10894. case 0x8b52:
  10895. return setValueV4f;
  10896. // _VEC4
  10897. case 0x8b5a:
  10898. return setValueM2;
  10899. // _MAT2
  10900. case 0x8b5b:
  10901. return setValueM3;
  10902. // _MAT3
  10903. case 0x8b5c:
  10904. return setValueM4;
  10905. // _MAT4
  10906. case 0x8b5e:
  10907. case 0x8d66:
  10908. return setValueT1;
  10909. // SAMPLER_2D, SAMPLER_EXTERNAL_OES
  10910. case 0x8b5f:
  10911. return setValueT3D1;
  10912. // SAMPLER_3D
  10913. case 0x8b60:
  10914. return setValueT6;
  10915. // SAMPLER_CUBE
  10916. case 0x8DC1:
  10917. return setValueT2DArray1;
  10918. // SAMPLER_2D_ARRAY
  10919. case 0x1404:
  10920. case 0x8b56:
  10921. return setValueV1i;
  10922. // INT, BOOL
  10923. case 0x8b53:
  10924. case 0x8b57:
  10925. return setValueV2i;
  10926. // _VEC2
  10927. case 0x8b54:
  10928. case 0x8b58:
  10929. return setValueV3i;
  10930. // _VEC3
  10931. case 0x8b55:
  10932. case 0x8b59:
  10933. return setValueV4i;
  10934. // _VEC4
  10935. }
  10936. } // Array of scalars
  10937. function setValueV1fArray(gl, v) {
  10938. gl.uniform1fv(this.addr, v);
  10939. } // Integer / Boolean vectors or arrays thereof (always flat arrays)
  10940. function setValueV1iArray(gl, v) {
  10941. gl.uniform1iv(this.addr, v);
  10942. }
  10943. function setValueV2iArray(gl, v) {
  10944. gl.uniform2iv(this.addr, v);
  10945. }
  10946. function setValueV3iArray(gl, v) {
  10947. gl.uniform3iv(this.addr, v);
  10948. }
  10949. function setValueV4iArray(gl, v) {
  10950. gl.uniform4iv(this.addr, v);
  10951. } // Array of vectors (flat or from THREE classes)
  10952. function setValueV2fArray(gl, v) {
  10953. var data = flatten(v, this.size, 2);
  10954. gl.uniform2fv(this.addr, data);
  10955. }
  10956. function setValueV3fArray(gl, v) {
  10957. var data = flatten(v, this.size, 3);
  10958. gl.uniform3fv(this.addr, data);
  10959. }
  10960. function setValueV4fArray(gl, v) {
  10961. var data = flatten(v, this.size, 4);
  10962. gl.uniform4fv(this.addr, data);
  10963. } // Array of matrices (flat or from THREE clases)
  10964. function setValueM2Array(gl, v) {
  10965. var data = flatten(v, this.size, 4);
  10966. gl.uniformMatrix2fv(this.addr, false, data);
  10967. }
  10968. function setValueM3Array(gl, v) {
  10969. var data = flatten(v, this.size, 9);
  10970. gl.uniformMatrix3fv(this.addr, false, data);
  10971. }
  10972. function setValueM4Array(gl, v) {
  10973. var data = flatten(v, this.size, 16);
  10974. gl.uniformMatrix4fv(this.addr, false, data);
  10975. } // Array of textures (2D / Cube)
  10976. function setValueT1Array(gl, v, textures) {
  10977. var n = v.length;
  10978. var units = allocTexUnits(textures, n);
  10979. gl.uniform1iv(this.addr, units);
  10980. for (var i = 0; i !== n; ++i) {
  10981. textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
  10982. }
  10983. }
  10984. function setValueT6Array(gl, v, textures) {
  10985. var n = v.length;
  10986. var units = allocTexUnits(textures, n);
  10987. gl.uniform1iv(this.addr, units);
  10988. for (var i = 0; i !== n; ++i) {
  10989. textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
  10990. }
  10991. } // Helper to pick the right setter for a pure (bottom-level) array
  10992. function getPureArraySetter(type) {
  10993. switch (type) {
  10994. case 0x1406:
  10995. return setValueV1fArray;
  10996. // FLOAT
  10997. case 0x8b50:
  10998. return setValueV2fArray;
  10999. // _VEC2
  11000. case 0x8b51:
  11001. return setValueV3fArray;
  11002. // _VEC3
  11003. case 0x8b52:
  11004. return setValueV4fArray;
  11005. // _VEC4
  11006. case 0x8b5a:
  11007. return setValueM2Array;
  11008. // _MAT2
  11009. case 0x8b5b:
  11010. return setValueM3Array;
  11011. // _MAT3
  11012. case 0x8b5c:
  11013. return setValueM4Array;
  11014. // _MAT4
  11015. case 0x8b5e:
  11016. return setValueT1Array;
  11017. // SAMPLER_2D
  11018. case 0x8b60:
  11019. return setValueT6Array;
  11020. // SAMPLER_CUBE
  11021. case 0x1404:
  11022. case 0x8b56:
  11023. return setValueV1iArray;
  11024. // INT, BOOL
  11025. case 0x8b53:
  11026. case 0x8b57:
  11027. return setValueV2iArray;
  11028. // _VEC2
  11029. case 0x8b54:
  11030. case 0x8b58:
  11031. return setValueV3iArray;
  11032. // _VEC3
  11033. case 0x8b55:
  11034. case 0x8b59:
  11035. return setValueV4iArray;
  11036. // _VEC4
  11037. }
  11038. } // --- Uniform Classes ---
  11039. function SingleUniform(id, activeInfo, addr) {
  11040. this.id = id;
  11041. this.addr = addr;
  11042. this.cache = [];
  11043. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  11044. }
  11045. function PureArrayUniform(id, activeInfo, addr) {
  11046. this.id = id;
  11047. this.addr = addr;
  11048. this.cache = [];
  11049. this.size = activeInfo.size;
  11050. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  11051. }
  11052. PureArrayUniform.prototype.updateCache = function (data) {
  11053. var cache = this.cache;
  11054. if (data instanceof Float32Array && cache.length !== data.length) {
  11055. this.cache = new Float32Array(data.length);
  11056. }
  11057. copyArray(cache, data);
  11058. };
  11059. function StructuredUniform(id) {
  11060. this.id = id;
  11061. this.seq = [];
  11062. this.map = {};
  11063. }
  11064. StructuredUniform.prototype.setValue = function (gl, value, textures) {
  11065. var seq = this.seq;
  11066. for (var i = 0, n = seq.length; i !== n; ++i) {
  11067. var u = seq[i];
  11068. u.setValue(gl, value[u.id], textures);
  11069. }
  11070. }; // --- Top-level ---
  11071. // Parser - builds up the property tree from the path strings
  11072. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g; // extracts
  11073. // - the identifier (member name or array index)
  11074. // - followed by an optional right bracket (found when array index)
  11075. // - followed by an optional left bracket or dot (type of subscript)
  11076. //
  11077. // Note: These portions can be read in a non-overlapping fashion and
  11078. // allow straightforward parsing of the hierarchy that WebGL encodes
  11079. // in the uniform names.
  11080. function addUniform(container, uniformObject) {
  11081. container.seq.push(uniformObject);
  11082. container.map[uniformObject.id] = uniformObject;
  11083. }
  11084. function parseUniform(activeInfo, addr, container) {
  11085. var path = activeInfo.name,
  11086. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  11087. RePathPart.lastIndex = 0;
  11088. while (true) {
  11089. var match = RePathPart.exec(path),
  11090. matchEnd = RePathPart.lastIndex,
  11091. id = match[1],
  11092. idIsIndex = match[2] === ']',
  11093. subscript = match[3];
  11094. if (idIsIndex) id = id | 0; // convert to integer
  11095. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  11096. // bare name or "pure" bottom-level array "[0]" suffix
  11097. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  11098. break;
  11099. } else {
  11100. // step into inner node / create it in case it doesn't exist
  11101. var map = container.map,
  11102. next = map[id];
  11103. if (next === undefined) {
  11104. next = new StructuredUniform(id);
  11105. addUniform(container, next);
  11106. }
  11107. container = next;
  11108. }
  11109. }
  11110. } // Root Container
  11111. function WebGLUniforms(gl, program) {
  11112. this.seq = [];
  11113. this.map = {};
  11114. var n = gl.getProgramParameter(program, 35718);
  11115. for (var i = 0; i < n; ++i) {
  11116. var info = gl.getActiveUniform(program, i),
  11117. addr = gl.getUniformLocation(program, info.name);
  11118. parseUniform(info, addr, this);
  11119. }
  11120. }
  11121. WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
  11122. var u = this.map[name];
  11123. if (u !== undefined) u.setValue(gl, value, textures);
  11124. };
  11125. WebGLUniforms.prototype.setOptional = function (gl, object, name) {
  11126. var v = object[name];
  11127. if (v !== undefined) this.setValue(gl, name, v);
  11128. }; // Static interface
  11129. WebGLUniforms.upload = function (gl, seq, values, textures) {
  11130. for (var i = 0, n = seq.length; i !== n; ++i) {
  11131. var u = seq[i],
  11132. v = values[u.id];
  11133. if (v.needsUpdate !== false) {
  11134. // note: always updating when .needsUpdate is undefined
  11135. u.setValue(gl, v.value, textures);
  11136. }
  11137. }
  11138. };
  11139. WebGLUniforms.seqWithValue = function (seq, values) {
  11140. var r = [];
  11141. for (var i = 0, n = seq.length; i !== n; ++i) {
  11142. var u = seq[i];
  11143. if (u.id in values) r.push(u);
  11144. }
  11145. return r;
  11146. };
  11147. /**
  11148. * @author mrdoob / http://mrdoob.com/
  11149. */
  11150. function WebGLShader(gl, type, string) {
  11151. var shader = gl.createShader(type);
  11152. gl.shaderSource(shader, string);
  11153. gl.compileShader(shader);
  11154. return shader;
  11155. }
  11156. /**
  11157. * @author mrdoob / http://mrdoob.com/
  11158. */
  11159. var programIdCount = 0;
  11160. function addLineNumbers(string) {
  11161. var lines = string.split('\n');
  11162. for (var i = 0; i < lines.length; i++) {
  11163. lines[i] = i + 1 + ': ' + lines[i];
  11164. }
  11165. return lines.join('\n');
  11166. }
  11167. function getEncodingComponents(encoding) {
  11168. switch (encoding) {
  11169. case LinearEncoding:
  11170. return ['Linear', '( value )'];
  11171. case sRGBEncoding:
  11172. return ['sRGB', '( value )'];
  11173. case RGBEEncoding:
  11174. return ['RGBE', '( value )'];
  11175. case RGBM7Encoding:
  11176. return ['RGBM', '( value, 7.0 )'];
  11177. case RGBM16Encoding:
  11178. return ['RGBM', '( value, 16.0 )'];
  11179. case RGBDEncoding:
  11180. return ['RGBD', '( value, 256.0 )'];
  11181. case GammaEncoding:
  11182. return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
  11183. case LogLuvEncoding:
  11184. return ['LogLuv', '( value )'];
  11185. default:
  11186. throw new Error('unsupported encoding: ' + encoding);
  11187. }
  11188. }
  11189. function getShaderErrors(gl, shader, type) {
  11190. var status = gl.getShaderParameter(shader, 35713);
  11191. var log = gl.getShaderInfoLog(shader).trim();
  11192. if (status && log === '') return ''; // --enable-privileged-webgl-extension
  11193. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11194. var source = gl.getShaderSource(shader);
  11195. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers(source);
  11196. }
  11197. function getTexelDecodingFunction(functionName, encoding) {
  11198. var components = getEncodingComponents(encoding);
  11199. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
  11200. }
  11201. function getTexelEncodingFunction(functionName, encoding) {
  11202. var components = getEncodingComponents(encoding);
  11203. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  11204. }
  11205. function getToneMappingFunction(functionName, toneMapping) {
  11206. var toneMappingName;
  11207. switch (toneMapping) {
  11208. case LinearToneMapping:
  11209. toneMappingName = 'Linear';
  11210. break;
  11211. case ReinhardToneMapping:
  11212. toneMappingName = 'Reinhard';
  11213. break;
  11214. case Uncharted2ToneMapping:
  11215. toneMappingName = 'Uncharted2';
  11216. break;
  11217. case CineonToneMapping:
  11218. toneMappingName = 'OptimizedCineon';
  11219. break;
  11220. case ACESFilmicToneMapping:
  11221. toneMappingName = 'ACESFilmic';
  11222. break;
  11223. default:
  11224. throw new Error('unsupported toneMapping: ' + toneMapping);
  11225. }
  11226. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11227. }
  11228. function generateExtensions(extensions, parameters, rendererExtensions) {
  11229. extensions = extensions || {};
  11230. 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' : ''];
  11231. return chunks.filter(filterEmptyLine).join('\n');
  11232. }
  11233. function generateDefines(defines) {
  11234. var chunks = [];
  11235. for (var name in defines) {
  11236. var value = defines[name];
  11237. if (value === false) continue;
  11238. chunks.push('#define ' + name + ' ' + value);
  11239. }
  11240. return chunks.join('\n');
  11241. }
  11242. function fetchAttributeLocations(gl, program) {
  11243. var attributes = {};
  11244. var n = gl.getProgramParameter(program, 35721);
  11245. for (var i = 0; i < n; i++) {
  11246. var info = gl.getActiveAttrib(program, i);
  11247. var name = info.name; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11248. attributes[name] = gl.getAttribLocation(program, name);
  11249. }
  11250. return attributes;
  11251. }
  11252. function filterEmptyLine(string) {
  11253. return string !== '';
  11254. }
  11255. function replaceLightNums(string, parameters) {
  11256. 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);
  11257. }
  11258. function replaceClippingPlaneNums(string, parameters) {
  11259. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  11260. } // Resolve Includes
  11261. var includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11262. function resolveIncludes(string) {
  11263. return string.replace(includePattern, includeReplacer);
  11264. }
  11265. function includeReplacer(match, include) {
  11266. var string = ShaderChunk[include];
  11267. if (string === undefined) {
  11268. throw new Error('Can not resolve #include <' + include + '>');
  11269. }
  11270. return resolveIncludes(string);
  11271. } // Unroll Loops
  11272. var loopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  11273. function unrollLoops(string) {
  11274. return string.replace(loopPattern, loopReplacer);
  11275. }
  11276. function loopReplacer(match, start, end, snippet) {
  11277. var string = '';
  11278. for (var i = parseInt(start); i < parseInt(end); i++) {
  11279. string += snippet.replace(/\[ i \]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  11280. }
  11281. return string;
  11282. } //
  11283. function generatePrecision(parameters) {
  11284. var precisionstring = "precision " + parameters.precision + " float;\nprecision " + parameters.precision + " int;";
  11285. if (parameters.precision === "highp") {
  11286. precisionstring += "\n#define HIGH_PRECISION";
  11287. } else if (parameters.precision === "mediump") {
  11288. precisionstring += "\n#define MEDIUM_PRECISION";
  11289. } else if (parameters.precision === "lowp") {
  11290. precisionstring += "\n#define LOW_PRECISION";
  11291. }
  11292. return precisionstring;
  11293. }
  11294. function generateShadowMapTypeDefine(parameters) {
  11295. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11296. if (parameters.shadowMapType === PCFShadowMap) {
  11297. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11298. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  11299. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11300. } else if (parameters.shadowMapType === VSMShadowMap) {
  11301. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11302. }
  11303. return shadowMapTypeDefine;
  11304. }
  11305. function generateEnvMapTypeDefine(parameters, material) {
  11306. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11307. if (parameters.envMap) {
  11308. switch (material.envMap.mapping) {
  11309. case CubeReflectionMapping:
  11310. case CubeRefractionMapping:
  11311. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11312. break;
  11313. case CubeUVReflectionMapping:
  11314. case CubeUVRefractionMapping:
  11315. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11316. break;
  11317. case EquirectangularReflectionMapping:
  11318. case EquirectangularRefractionMapping:
  11319. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  11320. break;
  11321. case SphericalReflectionMapping:
  11322. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  11323. break;
  11324. }
  11325. }
  11326. return envMapTypeDefine;
  11327. }
  11328. function generateEnvMapModeDefine(parameters, material) {
  11329. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11330. if (parameters.envMap) {
  11331. switch (material.envMap.mapping) {
  11332. case CubeRefractionMapping:
  11333. case EquirectangularRefractionMapping:
  11334. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11335. break;
  11336. }
  11337. }
  11338. return envMapModeDefine;
  11339. }
  11340. function generateEnvMapBlendingDefine(parameters, material) {
  11341. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11342. if (parameters.envMap) {
  11343. switch (material.combine) {
  11344. case MultiplyOperation:
  11345. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11346. break;
  11347. case MixOperation:
  11348. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11349. break;
  11350. case AddOperation:
  11351. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11352. break;
  11353. }
  11354. }
  11355. return envMapBlendingDefine;
  11356. }
  11357. function WebGLProgram(renderer, extensions, code, material, shader, parameters) {
  11358. var gl = renderer.getContext();
  11359. var defines = material.defines;
  11360. var vertexShader = shader.vertexShader;
  11361. var fragmentShader = shader.fragmentShader;
  11362. var shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  11363. var envMapTypeDefine = generateEnvMapTypeDefine(parameters, material);
  11364. var envMapModeDefine = generateEnvMapModeDefine(parameters, material);
  11365. var envMapBlendingDefine = generateEnvMapBlendingDefine(parameters, material);
  11366. var gammaFactorDefine = renderer.gammaFactor > 0 ? renderer.gammaFactor : 1.0;
  11367. var customExtensions = parameters.isWebGL2 ? '' : generateExtensions(material.extensions, parameters, extensions);
  11368. var customDefines = generateDefines(defines);
  11369. var program = gl.createProgram();
  11370. var prefixVertex, prefixFragment;
  11371. var renderTarget = renderer.getRenderTarget();
  11372. var numMultiviewViews = renderTarget && renderTarget.isWebGLMultiviewRenderTarget ? renderTarget.numViews : 0;
  11373. if (material.isRawShaderMaterial) {
  11374. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  11375. if (prefixVertex.length > 0) {
  11376. prefixVertex += '\n';
  11377. }
  11378. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  11379. if (prefixFragment.length > 0) {
  11380. prefixFragment += '\n';
  11381. }
  11382. } else {
  11383. 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');
  11384. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + shader.name, customDefines, parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + (parameters.alphaTest % 1 ? '' : '.0') : '', // add '.0' if integer
  11385. '#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
  11386. 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
  11387. 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');
  11388. }
  11389. vertexShader = resolveIncludes(vertexShader);
  11390. vertexShader = replaceLightNums(vertexShader, parameters);
  11391. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  11392. fragmentShader = resolveIncludes(fragmentShader);
  11393. fragmentShader = replaceLightNums(fragmentShader, parameters);
  11394. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  11395. vertexShader = unrollLoops(vertexShader);
  11396. fragmentShader = unrollLoops(fragmentShader);
  11397. if (parameters.isWebGL2 && !material.isRawShaderMaterial) {
  11398. var isGLSL3ShaderMaterial = false;
  11399. var versionRegex = /^\s*#version\s+300\s+es\s*\n/;
  11400. if (material.isShaderMaterial && vertexShader.match(versionRegex) !== null && fragmentShader.match(versionRegex) !== null) {
  11401. isGLSL3ShaderMaterial = true;
  11402. vertexShader = vertexShader.replace(versionRegex, '');
  11403. fragmentShader = fragmentShader.replace(versionRegex, '');
  11404. } // GLSL 3.0 conversion
  11405. prefixVertex = ['#version 300 es\n', '#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  11406. 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
  11407. if (numMultiviewViews > 0) {
  11408. 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'));
  11409. 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'));
  11410. prefixFragment = prefixFragment.replace('#version 300 es\n', ['#version 300 es\n', '#extension GL_OVR_multiview2 : require', '#define VIEW_ID gl_ViewID_OVR'].join('\n'));
  11411. prefixFragment = prefixFragment.replace('uniform mat4 viewMatrix;', ['uniform mat4 viewMatrices[' + numMultiviewViews + '];', '#define viewMatrix viewMatrices[VIEW_ID]'].join('\n'));
  11412. }
  11413. }
  11414. var vertexGlsl = prefixVertex + vertexShader;
  11415. var fragmentGlsl = prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  11416. // console.log( '*FRAGMENT*', fragmentGlsl );
  11417. var glVertexShader = WebGLShader(gl, 35633, vertexGlsl);
  11418. var glFragmentShader = WebGLShader(gl, 35632, fragmentGlsl);
  11419. gl.attachShader(program, glVertexShader);
  11420. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  11421. if (material.index0AttributeName !== undefined) {
  11422. gl.bindAttribLocation(program, 0, material.index0AttributeName);
  11423. } else if (parameters.morphTargets === true) {
  11424. // programs with morphTargets displace position out of attribute 0
  11425. gl.bindAttribLocation(program, 0, 'position');
  11426. }
  11427. gl.linkProgram(program); // check for link errors
  11428. if (renderer.debug.checkShaderErrors) {
  11429. var programLog = gl.getProgramInfoLog(program).trim();
  11430. var vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  11431. var fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  11432. var runnable = true;
  11433. var haveDiagnostics = true;
  11434. if (gl.getProgramParameter(program, 35714) === false) {
  11435. runnable = false;
  11436. var vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  11437. var fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  11438. console.error('THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter(program, 35715), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors);
  11439. } else if (programLog !== '') {
  11440. console.warn('THREE.WebGLProgram: gl.getProgramInfoLog()', programLog);
  11441. } else if (vertexLog === '' || fragmentLog === '') {
  11442. haveDiagnostics = false;
  11443. }
  11444. if (haveDiagnostics) {
  11445. this.diagnostics = {
  11446. runnable: runnable,
  11447. material: material,
  11448. programLog: programLog,
  11449. vertexShader: {
  11450. log: vertexLog,
  11451. prefix: prefixVertex
  11452. },
  11453. fragmentShader: {
  11454. log: fragmentLog,
  11455. prefix: prefixFragment
  11456. }
  11457. };
  11458. }
  11459. } // clean up
  11460. gl.deleteShader(glVertexShader);
  11461. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  11462. var cachedUniforms;
  11463. this.getUniforms = function () {
  11464. if (cachedUniforms === undefined) {
  11465. cachedUniforms = new WebGLUniforms(gl, program);
  11466. }
  11467. return cachedUniforms;
  11468. }; // set up caching for attribute locations
  11469. var cachedAttributes;
  11470. this.getAttributes = function () {
  11471. if (cachedAttributes === undefined) {
  11472. cachedAttributes = fetchAttributeLocations(gl, program);
  11473. }
  11474. return cachedAttributes;
  11475. }; // free resource
  11476. this.destroy = function () {
  11477. gl.deleteProgram(program);
  11478. this.program = undefined;
  11479. }; //
  11480. this.name = shader.name;
  11481. this.id = programIdCount++;
  11482. this.code = code;
  11483. this.usedTimes = 1;
  11484. this.program = program;
  11485. this.vertexShader = glVertexShader;
  11486. this.fragmentShader = glFragmentShader;
  11487. this.numMultiviewViews = numMultiviewViews;
  11488. return this;
  11489. }
  11490. /**
  11491. * @author mrdoob / http://mrdoob.com/
  11492. */
  11493. function WebGLPrograms(renderer, extensions, capabilities) {
  11494. var programs = [];
  11495. var shaderIDs = {
  11496. MeshDepthMaterial: 'depth',
  11497. MeshDistanceMaterial: 'distanceRGBA',
  11498. MeshNormalMaterial: 'normal',
  11499. MeshBasicMaterial: 'basic',
  11500. MeshLambertMaterial: 'lambert',
  11501. MeshPhongMaterial: 'phong',
  11502. MeshToonMaterial: 'phong',
  11503. MeshStandardMaterial: 'physical',
  11504. MeshPhysicalMaterial: 'physical',
  11505. MeshMatcapMaterial: 'matcap',
  11506. LineBasicMaterial: 'basic',
  11507. LineDashedMaterial: 'dashed',
  11508. PointsMaterial: 'points',
  11509. ShadowMaterial: 'shadow',
  11510. SpriteMaterial: 'sprite'
  11511. };
  11512. 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"];
  11513. function allocateBones(object) {
  11514. var skeleton = object.skeleton;
  11515. var bones = skeleton.bones;
  11516. if (capabilities.floatVertexTextures) {
  11517. return 1024;
  11518. } else {
  11519. // default for when object is not specified
  11520. // ( for example when prebuilding shader to be used with multiple objects )
  11521. //
  11522. // - leave some extra space for other uniforms
  11523. // - limit here is ANGLE's 254 max uniform vectors
  11524. // (up to 54 should be safe)
  11525. var nVertexUniforms = capabilities.maxVertexUniforms;
  11526. var nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
  11527. var maxBones = Math.min(nVertexMatrices, bones.length);
  11528. if (maxBones < bones.length) {
  11529. console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
  11530. return 0;
  11531. }
  11532. return maxBones;
  11533. }
  11534. }
  11535. function getTextureEncodingFromMap(map, gammaOverrideLinear) {
  11536. var encoding;
  11537. if (!map) {
  11538. encoding = LinearEncoding;
  11539. } else if (map.isTexture) {
  11540. encoding = map.encoding;
  11541. } else if (map.isWebGLRenderTarget) {
  11542. console.warn("THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead.");
  11543. encoding = map.texture.encoding;
  11544. } // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  11545. if (encoding === LinearEncoding && gammaOverrideLinear) {
  11546. encoding = GammaEncoding;
  11547. }
  11548. return encoding;
  11549. }
  11550. this.getParameters = function (material, lights, shadows, fog, nClipPlanes, nClipIntersection, object) {
  11551. var shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  11552. // (not to blow over maxLights budget)
  11553. var maxBones = object.isSkinnedMesh ? allocateBones(object) : 0;
  11554. var precision = capabilities.precision;
  11555. if (material.precision !== null) {
  11556. precision = capabilities.getMaxPrecision(material.precision);
  11557. if (precision !== material.precision) {
  11558. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  11559. }
  11560. }
  11561. var currentRenderTarget = renderer.getRenderTarget();
  11562. var parameters = {
  11563. isWebGL2: capabilities.isWebGL2,
  11564. shaderID: shaderID,
  11565. precision: precision,
  11566. instancing: object.isInstancedMesh === true,
  11567. supportsVertexTextures: capabilities.vertexTextures,
  11568. outputEncoding: getTextureEncodingFromMap(!currentRenderTarget ? null : currentRenderTarget.texture, renderer.gammaOutput),
  11569. map: !!material.map,
  11570. mapEncoding: getTextureEncodingFromMap(material.map, renderer.gammaInput),
  11571. matcap: !!material.matcap,
  11572. matcapEncoding: getTextureEncodingFromMap(material.matcap, renderer.gammaInput),
  11573. envMap: !!material.envMap,
  11574. envMapMode: material.envMap && material.envMap.mapping,
  11575. envMapEncoding: getTextureEncodingFromMap(material.envMap, renderer.gammaInput),
  11576. envMapCubeUV: !!material.envMap && (material.envMap.mapping === CubeUVReflectionMapping || material.envMap.mapping === CubeUVRefractionMapping),
  11577. lightMap: !!material.lightMap,
  11578. aoMap: !!material.aoMap,
  11579. emissiveMap: !!material.emissiveMap,
  11580. emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap, renderer.gammaInput),
  11581. bumpMap: !!material.bumpMap,
  11582. normalMap: !!material.normalMap,
  11583. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11584. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11585. clearcoatNormalMap: !!material.clearcoatNormalMap,
  11586. displacementMap: !!material.displacementMap,
  11587. roughnessMap: !!material.roughnessMap,
  11588. metalnessMap: !!material.metalnessMap,
  11589. specularMap: !!material.specularMap,
  11590. alphaMap: !!material.alphaMap,
  11591. gradientMap: !!material.gradientMap,
  11592. sheen: !!material.sheen,
  11593. combine: material.combine,
  11594. vertexTangents: material.normalMap && material.vertexTangents,
  11595. vertexColors: material.vertexColors,
  11596. vertexUvs: !!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap,
  11597. fog: !!fog,
  11598. useFog: material.fog,
  11599. fogExp2: fog && fog.isFogExp2,
  11600. flatShading: material.flatShading,
  11601. sizeAttenuation: material.sizeAttenuation,
  11602. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  11603. skinning: material.skinning && maxBones > 0,
  11604. maxBones: maxBones,
  11605. useVertexTexture: capabilities.floatVertexTextures,
  11606. morphTargets: material.morphTargets,
  11607. morphNormals: material.morphNormals,
  11608. maxMorphTargets: renderer.maxMorphTargets,
  11609. maxMorphNormals: renderer.maxMorphNormals,
  11610. numDirLights: lights.directional.length,
  11611. numPointLights: lights.point.length,
  11612. numSpotLights: lights.spot.length,
  11613. numRectAreaLights: lights.rectArea.length,
  11614. numHemiLights: lights.hemi.length,
  11615. numDirLightShadows: lights.directionalShadowMap.length,
  11616. numPointLightShadows: lights.pointShadowMap.length,
  11617. numSpotLightShadows: lights.spotShadowMap.length,
  11618. numClippingPlanes: nClipPlanes,
  11619. numClipIntersection: nClipIntersection,
  11620. dithering: material.dithering,
  11621. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11622. shadowMapType: renderer.shadowMap.type,
  11623. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11624. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11625. premultipliedAlpha: material.premultipliedAlpha,
  11626. alphaTest: material.alphaTest,
  11627. doubleSided: material.side === DoubleSide,
  11628. flipSided: material.side === BackSide,
  11629. depthPacking: material.depthPacking !== undefined ? material.depthPacking : false
  11630. };
  11631. return parameters;
  11632. };
  11633. this.getProgramCode = function (material, parameters) {
  11634. var array = [];
  11635. if (parameters.shaderID) {
  11636. array.push(parameters.shaderID);
  11637. } else {
  11638. array.push(material.fragmentShader);
  11639. array.push(material.vertexShader);
  11640. }
  11641. if (material.defines !== undefined) {
  11642. for (var name in material.defines) {
  11643. array.push(name);
  11644. array.push(material.defines[name]);
  11645. }
  11646. }
  11647. for (var i = 0; i < parameterNames.length; i++) {
  11648. array.push(parameters[parameterNames[i]]);
  11649. }
  11650. array.push(material.onBeforeCompile.toString());
  11651. array.push(renderer.gammaOutput);
  11652. array.push(renderer.gammaFactor);
  11653. return array.join();
  11654. };
  11655. this.acquireProgram = function (material, shader, parameters, code) {
  11656. var program; // Check if code has been already compiled
  11657. for (var p = 0, pl = programs.length; p < pl; p++) {
  11658. var programInfo = programs[p];
  11659. if (programInfo.code === code) {
  11660. program = programInfo;
  11661. ++program.usedTimes;
  11662. break;
  11663. }
  11664. }
  11665. if (program === undefined) {
  11666. program = new WebGLProgram(renderer, extensions, code, material, shader, parameters);
  11667. programs.push(program);
  11668. }
  11669. return program;
  11670. };
  11671. this.releaseProgram = function (program) {
  11672. if (--program.usedTimes === 0) {
  11673. // Remove from unordered set
  11674. var i = programs.indexOf(program);
  11675. programs[i] = programs[programs.length - 1];
  11676. programs.pop(); // Free WebGL resources
  11677. program.destroy();
  11678. }
  11679. }; // Exposed for resource monitoring & error feedback via renderer.info:
  11680. this.programs = programs;
  11681. }
  11682. /**
  11683. * @author fordacious / fordacious.github.io
  11684. */
  11685. function WebGLProperties() {
  11686. var properties = new WeakMap();
  11687. function get(object) {
  11688. var map = properties.get(object);
  11689. if (map === undefined) {
  11690. map = {};
  11691. properties.set(object, map);
  11692. }
  11693. return map;
  11694. }
  11695. function remove(object) {
  11696. properties.delete(object);
  11697. }
  11698. function update(object, key, value) {
  11699. properties.get(object)[key] = value;
  11700. }
  11701. function dispose() {
  11702. properties = new WeakMap();
  11703. }
  11704. return {
  11705. get: get,
  11706. remove: remove,
  11707. update: update,
  11708. dispose: dispose
  11709. };
  11710. }
  11711. /**
  11712. * @author mrdoob / http://mrdoob.com/
  11713. */
  11714. function painterSortStable(a, b) {
  11715. if (a.groupOrder !== b.groupOrder) {
  11716. return a.groupOrder - b.groupOrder;
  11717. } else if (a.renderOrder !== b.renderOrder) {
  11718. return a.renderOrder - b.renderOrder;
  11719. } else if (a.program !== b.program) {
  11720. return a.program.id - b.program.id;
  11721. } else if (a.material.id !== b.material.id) {
  11722. return a.material.id - b.material.id;
  11723. } else if (a.z !== b.z) {
  11724. return a.z - b.z;
  11725. } else {
  11726. return a.id - b.id;
  11727. }
  11728. }
  11729. function reversePainterSortStable(a, b) {
  11730. if (a.groupOrder !== b.groupOrder) {
  11731. return a.groupOrder - b.groupOrder;
  11732. } else if (a.renderOrder !== b.renderOrder) {
  11733. return a.renderOrder - b.renderOrder;
  11734. } else if (a.z !== b.z) {
  11735. return b.z - a.z;
  11736. } else {
  11737. return a.id - b.id;
  11738. }
  11739. }
  11740. function WebGLRenderList() {
  11741. var renderItems = [];
  11742. var renderItemsIndex = 0;
  11743. var opaque = [];
  11744. var transparent = [];
  11745. var defaultProgram = {
  11746. id: -1
  11747. };
  11748. function init() {
  11749. renderItemsIndex = 0;
  11750. opaque.length = 0;
  11751. transparent.length = 0;
  11752. }
  11753. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  11754. var renderItem = renderItems[renderItemsIndex];
  11755. if (renderItem === undefined) {
  11756. renderItem = {
  11757. id: object.id,
  11758. object: object,
  11759. geometry: geometry,
  11760. material: material,
  11761. program: material.program || defaultProgram,
  11762. groupOrder: groupOrder,
  11763. renderOrder: object.renderOrder,
  11764. z: z,
  11765. group: group
  11766. };
  11767. renderItems[renderItemsIndex] = renderItem;
  11768. } else {
  11769. renderItem.id = object.id;
  11770. renderItem.object = object;
  11771. renderItem.geometry = geometry;
  11772. renderItem.material = material;
  11773. renderItem.program = material.program || defaultProgram;
  11774. renderItem.groupOrder = groupOrder;
  11775. renderItem.renderOrder = object.renderOrder;
  11776. renderItem.z = z;
  11777. renderItem.group = group;
  11778. }
  11779. renderItemsIndex++;
  11780. return renderItem;
  11781. }
  11782. function push(object, geometry, material, groupOrder, z, group) {
  11783. var renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  11784. (material.transparent === true ? transparent : opaque).push(renderItem);
  11785. }
  11786. function unshift(object, geometry, material, groupOrder, z, group) {
  11787. var renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  11788. (material.transparent === true ? transparent : opaque).unshift(renderItem);
  11789. }
  11790. function sort() {
  11791. if (opaque.length > 1) opaque.sort(painterSortStable);
  11792. if (transparent.length > 1) transparent.sort(reversePainterSortStable);
  11793. }
  11794. return {
  11795. opaque: opaque,
  11796. transparent: transparent,
  11797. init: init,
  11798. push: push,
  11799. unshift: unshift,
  11800. sort: sort
  11801. };
  11802. }
  11803. function WebGLRenderLists() {
  11804. var lists = new WeakMap();
  11805. function onSceneDispose(event) {
  11806. var scene = event.target;
  11807. scene.removeEventListener('dispose', onSceneDispose);
  11808. lists.delete(scene);
  11809. }
  11810. function get(scene, camera) {
  11811. var cameras = lists.get(scene);
  11812. var list;
  11813. if (cameras === undefined) {
  11814. list = new WebGLRenderList();
  11815. lists.set(scene, new WeakMap());
  11816. lists.get(scene).set(camera, list);
  11817. scene.addEventListener('dispose', onSceneDispose);
  11818. } else {
  11819. list = cameras.get(camera);
  11820. if (list === undefined) {
  11821. list = new WebGLRenderList();
  11822. cameras.set(camera, list);
  11823. }
  11824. }
  11825. return list;
  11826. }
  11827. function dispose() {
  11828. lists = new WeakMap();
  11829. }
  11830. return {
  11831. get: get,
  11832. dispose: dispose
  11833. };
  11834. }
  11835. /**
  11836. * @author mrdoob / http://mrdoob.com/
  11837. */
  11838. function UniformsCache() {
  11839. var lights = {};
  11840. return {
  11841. get: function (light) {
  11842. if (lights[light.id] !== undefined) {
  11843. return lights[light.id];
  11844. }
  11845. var uniforms;
  11846. switch (light.type) {
  11847. case 'DirectionalLight':
  11848. uniforms = {
  11849. direction: new Vector3(),
  11850. color: new Color(),
  11851. shadow: false,
  11852. shadowBias: 0,
  11853. shadowRadius: 1,
  11854. shadowMapSize: new Vector2()
  11855. };
  11856. break;
  11857. case 'SpotLight':
  11858. uniforms = {
  11859. position: new Vector3(),
  11860. direction: new Vector3(),
  11861. color: new Color(),
  11862. distance: 0,
  11863. coneCos: 0,
  11864. penumbraCos: 0,
  11865. decay: 0,
  11866. shadow: false,
  11867. shadowBias: 0,
  11868. shadowRadius: 1,
  11869. shadowMapSize: new Vector2()
  11870. };
  11871. break;
  11872. case 'PointLight':
  11873. uniforms = {
  11874. position: new Vector3(),
  11875. color: new Color(),
  11876. distance: 0,
  11877. decay: 0,
  11878. shadow: false,
  11879. shadowBias: 0,
  11880. shadowRadius: 1,
  11881. shadowMapSize: new Vector2(),
  11882. shadowCameraNear: 1,
  11883. shadowCameraFar: 1000
  11884. };
  11885. break;
  11886. case 'HemisphereLight':
  11887. uniforms = {
  11888. direction: new Vector3(),
  11889. skyColor: new Color(),
  11890. groundColor: new Color()
  11891. };
  11892. break;
  11893. case 'RectAreaLight':
  11894. uniforms = {
  11895. color: new Color(),
  11896. position: new Vector3(),
  11897. halfWidth: new Vector3(),
  11898. halfHeight: new Vector3() // TODO (abelnation): set RectAreaLight shadow uniforms
  11899. };
  11900. break;
  11901. }
  11902. lights[light.id] = uniforms;
  11903. return uniforms;
  11904. }
  11905. };
  11906. }
  11907. var nextVersion = 0;
  11908. function shadowCastingLightsFirst(lightA, lightB) {
  11909. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  11910. }
  11911. function WebGLLights() {
  11912. var cache = new UniformsCache();
  11913. var state = {
  11914. version: 0,
  11915. hash: {
  11916. directionalLength: -1,
  11917. pointLength: -1,
  11918. spotLength: -1,
  11919. rectAreaLength: -1,
  11920. hemiLength: -1,
  11921. numDirectionalShadows: -1,
  11922. numPointShadows: -1,
  11923. numSpotShadows: -1
  11924. },
  11925. ambient: [0, 0, 0],
  11926. probe: [],
  11927. directional: [],
  11928. directionalShadowMap: [],
  11929. directionalShadowMatrix: [],
  11930. spot: [],
  11931. spotShadowMap: [],
  11932. spotShadowMatrix: [],
  11933. rectArea: [],
  11934. point: [],
  11935. pointShadowMap: [],
  11936. pointShadowMatrix: [],
  11937. hemi: [],
  11938. numDirectionalShadows: -1,
  11939. numPointShadows: -1,
  11940. numSpotShadows: -1
  11941. };
  11942. for (var i = 0; i < 9; i++) state.probe.push(new Vector3());
  11943. var vector3 = new Vector3();
  11944. var matrix4 = new Matrix4();
  11945. var matrix42 = new Matrix4();
  11946. function setup(lights, shadows, camera) {
  11947. var r = 0,
  11948. g = 0,
  11949. b = 0;
  11950. for (var i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  11951. var directionalLength = 0;
  11952. var pointLength = 0;
  11953. var spotLength = 0;
  11954. var rectAreaLength = 0;
  11955. var hemiLength = 0;
  11956. var numDirectionalShadows = 0;
  11957. var numPointShadows = 0;
  11958. var numSpotShadows = 0;
  11959. var viewMatrix = camera.matrixWorldInverse;
  11960. lights.sort(shadowCastingLightsFirst);
  11961. for (var i = 0, l = lights.length; i < l; i++) {
  11962. var light = lights[i];
  11963. var color = light.color;
  11964. var intensity = light.intensity;
  11965. var distance = light.distance;
  11966. var shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  11967. if (light.isAmbientLight) {
  11968. r += color.r * intensity;
  11969. g += color.g * intensity;
  11970. b += color.b * intensity;
  11971. } else if (light.isLightProbe) {
  11972. for (var j = 0; j < 9; j++) {
  11973. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  11974. }
  11975. } else if (light.isDirectionalLight) {
  11976. var uniforms = cache.get(light);
  11977. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  11978. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  11979. vector3.setFromMatrixPosition(light.target.matrixWorld);
  11980. uniforms.direction.sub(vector3);
  11981. uniforms.direction.transformDirection(viewMatrix);
  11982. uniforms.shadow = light.castShadow;
  11983. if (light.castShadow) {
  11984. var shadow = light.shadow;
  11985. uniforms.shadowBias = shadow.bias;
  11986. uniforms.shadowRadius = shadow.radius;
  11987. uniforms.shadowMapSize = shadow.mapSize;
  11988. state.directionalShadowMap[directionalLength] = shadowMap;
  11989. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  11990. numDirectionalShadows++;
  11991. }
  11992. state.directional[directionalLength] = uniforms;
  11993. directionalLength++;
  11994. } else if (light.isSpotLight) {
  11995. var uniforms = cache.get(light);
  11996. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11997. uniforms.position.applyMatrix4(viewMatrix);
  11998. uniforms.color.copy(color).multiplyScalar(intensity);
  11999. uniforms.distance = distance;
  12000. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12001. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12002. uniforms.direction.sub(vector3);
  12003. uniforms.direction.transformDirection(viewMatrix);
  12004. uniforms.coneCos = Math.cos(light.angle);
  12005. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  12006. uniforms.decay = light.decay;
  12007. uniforms.shadow = light.castShadow;
  12008. if (light.castShadow) {
  12009. var shadow = light.shadow;
  12010. uniforms.shadowBias = shadow.bias;
  12011. uniforms.shadowRadius = shadow.radius;
  12012. uniforms.shadowMapSize = shadow.mapSize;
  12013. state.spotShadowMap[spotLength] = shadowMap;
  12014. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  12015. numSpotShadows++;
  12016. }
  12017. state.spot[spotLength] = uniforms;
  12018. spotLength++;
  12019. } else if (light.isRectAreaLight) {
  12020. var uniforms = cache.get(light); // (a) intensity is the total visible light emitted
  12021. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  12022. // (b) intensity is the brightness of the light
  12023. uniforms.color.copy(color).multiplyScalar(intensity);
  12024. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12025. uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  12026. matrix42.identity();
  12027. matrix4.copy(light.matrixWorld);
  12028. matrix4.premultiply(viewMatrix);
  12029. matrix42.extractRotation(matrix4);
  12030. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  12031. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  12032. uniforms.halfWidth.applyMatrix4(matrix42);
  12033. uniforms.halfHeight.applyMatrix4(matrix42); // TODO (abelnation): RectAreaLight distance?
  12034. // uniforms.distance = distance;
  12035. state.rectArea[rectAreaLength] = uniforms;
  12036. rectAreaLength++;
  12037. } else if (light.isPointLight) {
  12038. var uniforms = cache.get(light);
  12039. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12040. uniforms.position.applyMatrix4(viewMatrix);
  12041. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  12042. uniforms.distance = light.distance;
  12043. uniforms.decay = light.decay;
  12044. uniforms.shadow = light.castShadow;
  12045. if (light.castShadow) {
  12046. var shadow = light.shadow;
  12047. uniforms.shadowBias = shadow.bias;
  12048. uniforms.shadowRadius = shadow.radius;
  12049. uniforms.shadowMapSize = shadow.mapSize;
  12050. uniforms.shadowCameraNear = shadow.camera.near;
  12051. uniforms.shadowCameraFar = shadow.camera.far;
  12052. state.pointShadowMap[pointLength] = shadowMap;
  12053. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  12054. numPointShadows++;
  12055. }
  12056. state.point[pointLength] = uniforms;
  12057. pointLength++;
  12058. } else if (light.isHemisphereLight) {
  12059. var uniforms = cache.get(light);
  12060. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12061. uniforms.direction.transformDirection(viewMatrix);
  12062. uniforms.direction.normalize();
  12063. uniforms.skyColor.copy(light.color).multiplyScalar(intensity);
  12064. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity);
  12065. state.hemi[hemiLength] = uniforms;
  12066. hemiLength++;
  12067. }
  12068. }
  12069. state.ambient[0] = r;
  12070. state.ambient[1] = g;
  12071. state.ambient[2] = b;
  12072. var hash = state.hash;
  12073. 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) {
  12074. state.directional.length = directionalLength;
  12075. state.spot.length = spotLength;
  12076. state.rectArea.length = rectAreaLength;
  12077. state.point.length = pointLength;
  12078. state.hemi.length = hemiLength;
  12079. state.directionalShadowMap.length = numDirectionalShadows;
  12080. state.pointShadowMap.length = numPointShadows;
  12081. state.spotShadowMap.length = numSpotShadows;
  12082. state.directionalShadowMatrix.length = numDirectionalShadows;
  12083. state.pointShadowMatrix.length = numPointShadows;
  12084. state.spotShadowMatrix.length = numSpotShadows;
  12085. hash.directionalLength = directionalLength;
  12086. hash.pointLength = pointLength;
  12087. hash.spotLength = spotLength;
  12088. hash.rectAreaLength = rectAreaLength;
  12089. hash.hemiLength = hemiLength;
  12090. hash.numDirectionalShadows = numDirectionalShadows;
  12091. hash.numPointShadows = numPointShadows;
  12092. hash.numSpotShadows = numSpotShadows;
  12093. state.version = nextVersion++;
  12094. }
  12095. }
  12096. return {
  12097. setup: setup,
  12098. state: state
  12099. };
  12100. }
  12101. /**
  12102. * @author Mugen87 / https://github.com/Mugen87
  12103. */
  12104. function WebGLRenderState() {
  12105. var lights = new WebGLLights();
  12106. var lightsArray = [];
  12107. var shadowsArray = [];
  12108. function init() {
  12109. lightsArray.length = 0;
  12110. shadowsArray.length = 0;
  12111. }
  12112. function pushLight(light) {
  12113. lightsArray.push(light);
  12114. }
  12115. function pushShadow(shadowLight) {
  12116. shadowsArray.push(shadowLight);
  12117. }
  12118. function setupLights(camera) {
  12119. lights.setup(lightsArray, shadowsArray, camera);
  12120. }
  12121. var state = {
  12122. lightsArray: lightsArray,
  12123. shadowsArray: shadowsArray,
  12124. lights: lights
  12125. };
  12126. return {
  12127. init: init,
  12128. state: state,
  12129. setupLights: setupLights,
  12130. pushLight: pushLight,
  12131. pushShadow: pushShadow
  12132. };
  12133. }
  12134. function WebGLRenderStates() {
  12135. var renderStates = new WeakMap();
  12136. function onSceneDispose(event) {
  12137. var scene = event.target;
  12138. scene.removeEventListener('dispose', onSceneDispose);
  12139. renderStates.delete(scene);
  12140. }
  12141. function get(scene, camera) {
  12142. var renderState;
  12143. if (renderStates.has(scene) === false) {
  12144. renderState = new WebGLRenderState();
  12145. renderStates.set(scene, new WeakMap());
  12146. renderStates.get(scene).set(camera, renderState);
  12147. scene.addEventListener('dispose', onSceneDispose);
  12148. } else {
  12149. if (renderStates.get(scene).has(camera) === false) {
  12150. renderState = new WebGLRenderState();
  12151. renderStates.get(scene).set(camera, renderState);
  12152. } else {
  12153. renderState = renderStates.get(scene).get(camera);
  12154. }
  12155. }
  12156. return renderState;
  12157. }
  12158. function dispose() {
  12159. renderStates = new WeakMap();
  12160. }
  12161. return {
  12162. get: get,
  12163. dispose: dispose
  12164. };
  12165. }
  12166. /**
  12167. * @author mrdoob / http://mrdoob.com/
  12168. * @author alteredq / http://alteredqualia.com/
  12169. * @author bhouston / https://clara.io
  12170. * @author WestLangley / http://github.com/WestLangley
  12171. *
  12172. * parameters = {
  12173. *
  12174. * opacity: <float>,
  12175. *
  12176. * map: new THREE.Texture( <Image> ),
  12177. *
  12178. * alphaMap: new THREE.Texture( <Image> ),
  12179. *
  12180. * displacementMap: new THREE.Texture( <Image> ),
  12181. * displacementScale: <float>,
  12182. * displacementBias: <float>,
  12183. *
  12184. * wireframe: <boolean>,
  12185. * wireframeLinewidth: <float>
  12186. * }
  12187. */
  12188. function MeshDepthMaterial(parameters) {
  12189. Material.call(this);
  12190. this.type = 'MeshDepthMaterial';
  12191. this.depthPacking = BasicDepthPacking;
  12192. this.skinning = false;
  12193. this.morphTargets = false;
  12194. this.map = null;
  12195. this.alphaMap = null;
  12196. this.displacementMap = null;
  12197. this.displacementScale = 1;
  12198. this.displacementBias = 0;
  12199. this.wireframe = false;
  12200. this.wireframeLinewidth = 1;
  12201. this.fog = false;
  12202. this.setValues(parameters);
  12203. }
  12204. MeshDepthMaterial.prototype = Object.create(Material.prototype);
  12205. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  12206. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  12207. MeshDepthMaterial.prototype.copy = function (source) {
  12208. Material.prototype.copy.call(this, source);
  12209. this.depthPacking = source.depthPacking;
  12210. this.skinning = source.skinning;
  12211. this.morphTargets = source.morphTargets;
  12212. this.map = source.map;
  12213. this.alphaMap = source.alphaMap;
  12214. this.displacementMap = source.displacementMap;
  12215. this.displacementScale = source.displacementScale;
  12216. this.displacementBias = source.displacementBias;
  12217. this.wireframe = source.wireframe;
  12218. this.wireframeLinewidth = source.wireframeLinewidth;
  12219. return this;
  12220. };
  12221. /**
  12222. * @author WestLangley / http://github.com/WestLangley
  12223. *
  12224. * parameters = {
  12225. *
  12226. * referencePosition: <float>,
  12227. * nearDistance: <float>,
  12228. * farDistance: <float>,
  12229. *
  12230. * skinning: <bool>,
  12231. * morphTargets: <bool>,
  12232. *
  12233. * map: new THREE.Texture( <Image> ),
  12234. *
  12235. * alphaMap: new THREE.Texture( <Image> ),
  12236. *
  12237. * displacementMap: new THREE.Texture( <Image> ),
  12238. * displacementScale: <float>,
  12239. * displacementBias: <float>
  12240. *
  12241. * }
  12242. */
  12243. function MeshDistanceMaterial(parameters) {
  12244. Material.call(this);
  12245. this.type = 'MeshDistanceMaterial';
  12246. this.referencePosition = new Vector3();
  12247. this.nearDistance = 1;
  12248. this.farDistance = 1000;
  12249. this.skinning = false;
  12250. this.morphTargets = false;
  12251. this.map = null;
  12252. this.alphaMap = null;
  12253. this.displacementMap = null;
  12254. this.displacementScale = 1;
  12255. this.displacementBias = 0;
  12256. this.fog = false;
  12257. this.setValues(parameters);
  12258. }
  12259. MeshDistanceMaterial.prototype = Object.create(Material.prototype);
  12260. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  12261. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  12262. MeshDistanceMaterial.prototype.copy = function (source) {
  12263. Material.prototype.copy.call(this, source);
  12264. this.referencePosition.copy(source.referencePosition);
  12265. this.nearDistance = source.nearDistance;
  12266. this.farDistance = source.farDistance;
  12267. this.skinning = source.skinning;
  12268. this.morphTargets = source.morphTargets;
  12269. this.map = source.map;
  12270. this.alphaMap = source.alphaMap;
  12271. this.displacementMap = source.displacementMap;
  12272. this.displacementScale = source.displacementScale;
  12273. this.displacementBias = source.displacementBias;
  12274. return this;
  12275. };
  12276. 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}";
  12277. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12278. /**
  12279. * @author alteredq / http://alteredqualia.com/
  12280. * @author mrdoob / http://mrdoob.com/
  12281. */
  12282. function WebGLShadowMap(_renderer, _objects, maxTextureSize) {
  12283. var _frustum = new Frustum(),
  12284. _shadowMapSize = new Vector2(),
  12285. _viewportSize = new Vector2(),
  12286. _viewport = new Vector4(),
  12287. _MorphingFlag = 1,
  12288. _SkinningFlag = 2,
  12289. _NumberOfMaterialVariants = (_MorphingFlag | _SkinningFlag) + 1,
  12290. _depthMaterials = new Array(_NumberOfMaterialVariants),
  12291. _distanceMaterials = new Array(_NumberOfMaterialVariants),
  12292. _materialCache = {};
  12293. var shadowSide = {
  12294. 0: BackSide,
  12295. 1: FrontSide,
  12296. 2: DoubleSide
  12297. };
  12298. var shadowMaterialVertical = new ShaderMaterial({
  12299. defines: {
  12300. SAMPLE_RATE: 2.0 / 8.0,
  12301. HALF_SAMPLE_RATE: 1.0 / 8.0
  12302. },
  12303. uniforms: {
  12304. shadow_pass: {
  12305. value: null
  12306. },
  12307. resolution: {
  12308. value: new Vector2()
  12309. },
  12310. radius: {
  12311. value: 4.0
  12312. }
  12313. },
  12314. vertexShader: vsm_vert,
  12315. fragmentShader: vsm_frag
  12316. });
  12317. var shadowMaterialHorizonal = shadowMaterialVertical.clone();
  12318. shadowMaterialHorizonal.defines.HORIZONAL_PASS = 1;
  12319. var fullScreenTri = new BufferGeometry();
  12320. fullScreenTri.addAttribute("position", new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  12321. var fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical); // init
  12322. for (var i = 0; i !== _NumberOfMaterialVariants; ++i) {
  12323. var useMorphing = (i & _MorphingFlag) !== 0;
  12324. var useSkinning = (i & _SkinningFlag) !== 0;
  12325. var depthMaterial = new MeshDepthMaterial({
  12326. depthPacking: RGBADepthPacking,
  12327. morphTargets: useMorphing,
  12328. skinning: useSkinning
  12329. });
  12330. _depthMaterials[i] = depthMaterial;
  12331. var distanceMaterial = new MeshDistanceMaterial({
  12332. morphTargets: useMorphing,
  12333. skinning: useSkinning
  12334. });
  12335. _distanceMaterials[i] = distanceMaterial;
  12336. }
  12337. var scope = this;
  12338. this.enabled = false;
  12339. this.autoUpdate = true;
  12340. this.needsUpdate = false;
  12341. this.type = PCFShadowMap;
  12342. this.render = function (lights, scene, camera) {
  12343. if (scope.enabled === false) return;
  12344. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  12345. if (lights.length === 0) return;
  12346. var currentRenderTarget = _renderer.getRenderTarget();
  12347. var activeCubeFace = _renderer.getActiveCubeFace();
  12348. var activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12349. var _state = _renderer.state; // Set GL state for depth map.
  12350. _state.setBlending(NoBlending);
  12351. _state.buffers.color.setClear(1, 1, 1, 1);
  12352. _state.buffers.depth.setTest(true);
  12353. _state.setScissorTest(false); // render depth map
  12354. for (var i = 0, il = lights.length; i < il; i++) {
  12355. var light = lights[i];
  12356. var shadow = light.shadow;
  12357. if (shadow === undefined) {
  12358. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  12359. continue;
  12360. }
  12361. _shadowMapSize.copy(shadow.mapSize);
  12362. var shadowFrameExtents = shadow.getFrameExtents();
  12363. _shadowMapSize.multiply(shadowFrameExtents);
  12364. _viewportSize.copy(shadow.mapSize);
  12365. if (_shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize) {
  12366. console.warn('THREE.WebGLShadowMap:', light, 'has shadow exceeding max texture size, reducing');
  12367. if (_shadowMapSize.x > maxTextureSize) {
  12368. _viewportSize.x = Math.floor(maxTextureSize / shadowFrameExtents.x);
  12369. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12370. shadow.mapSize.x = _viewportSize.x;
  12371. }
  12372. if (_shadowMapSize.y > maxTextureSize) {
  12373. _viewportSize.y = Math.floor(maxTextureSize / shadowFrameExtents.y);
  12374. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12375. shadow.mapSize.y = _viewportSize.y;
  12376. }
  12377. }
  12378. if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
  12379. var pars = {
  12380. minFilter: LinearFilter,
  12381. magFilter: LinearFilter,
  12382. format: RGBAFormat
  12383. };
  12384. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12385. shadow.map.texture.name = light.name + ".shadowMap";
  12386. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12387. shadow.camera.updateProjectionMatrix();
  12388. }
  12389. if (shadow.map === null) {
  12390. var pars = {
  12391. minFilter: NearestFilter,
  12392. magFilter: NearestFilter,
  12393. format: RGBAFormat
  12394. };
  12395. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12396. shadow.map.texture.name = light.name + ".shadowMap";
  12397. shadow.camera.updateProjectionMatrix();
  12398. }
  12399. _renderer.setRenderTarget(shadow.map);
  12400. _renderer.clear();
  12401. var viewportCount = shadow.getViewportCount();
  12402. for (var vp = 0; vp < viewportCount; vp++) {
  12403. var viewport = shadow.getViewport(vp);
  12404. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  12405. _state.viewport(_viewport);
  12406. shadow.updateMatrices(light, camera, vp);
  12407. _frustum = shadow.getFrustum();
  12408. renderObject(scene, camera, shadow.camera, light, this.type);
  12409. } // do blur pass for VSM
  12410. if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
  12411. VSMPass(shadow, camera);
  12412. }
  12413. }
  12414. scope.needsUpdate = false;
  12415. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  12416. };
  12417. function VSMPass(shadow, camera) {
  12418. var geometry = _objects.update(fullScreenMesh); // vertical pass
  12419. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12420. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12421. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12422. _renderer.setRenderTarget(shadow.mapPass);
  12423. _renderer.clear();
  12424. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizonal pass
  12425. shadowMaterialHorizonal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12426. shadowMaterialHorizonal.uniforms.resolution.value = shadow.mapSize;
  12427. shadowMaterialHorizonal.uniforms.radius.value = shadow.radius;
  12428. _renderer.setRenderTarget(shadow.map);
  12429. _renderer.clear();
  12430. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizonal, fullScreenMesh, null);
  12431. }
  12432. function getDepthMaterial(object, material, light, shadowCameraNear, shadowCameraFar, type) {
  12433. var geometry = object.geometry;
  12434. var result = null;
  12435. var materialVariants = _depthMaterials;
  12436. var customMaterial = object.customDepthMaterial;
  12437. if (light.isPointLight) {
  12438. materialVariants = _distanceMaterials;
  12439. customMaterial = object.customDistanceMaterial;
  12440. }
  12441. if (!customMaterial) {
  12442. var useMorphing = false;
  12443. if (material.morphTargets) {
  12444. if (geometry && geometry.isBufferGeometry) {
  12445. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  12446. } else if (geometry && geometry.isGeometry) {
  12447. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  12448. }
  12449. }
  12450. if (object.isSkinnedMesh && material.skinning === false) {
  12451. console.warn('THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object);
  12452. }
  12453. var useSkinning = object.isSkinnedMesh && material.skinning;
  12454. var variantIndex = 0;
  12455. if (useMorphing) variantIndex |= _MorphingFlag;
  12456. if (useSkinning) variantIndex |= _SkinningFlag;
  12457. result = materialVariants[variantIndex];
  12458. } else {
  12459. result = customMaterial;
  12460. }
  12461. if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0) {
  12462. // in this case we need a unique material instance reflecting the
  12463. // appropriate state
  12464. var keyA = result.uuid,
  12465. keyB = material.uuid;
  12466. var materialsForVariant = _materialCache[keyA];
  12467. if (materialsForVariant === undefined) {
  12468. materialsForVariant = {};
  12469. _materialCache[keyA] = materialsForVariant;
  12470. }
  12471. var cachedMaterial = materialsForVariant[keyB];
  12472. if (cachedMaterial === undefined) {
  12473. cachedMaterial = result.clone();
  12474. materialsForVariant[keyB] = cachedMaterial;
  12475. }
  12476. result = cachedMaterial;
  12477. }
  12478. result.visible = material.visible;
  12479. result.wireframe = material.wireframe;
  12480. if (type === VSMShadowMap) {
  12481. result.side = material.shadowSide != null ? material.shadowSide : material.side;
  12482. } else {
  12483. result.side = material.shadowSide != null ? material.shadowSide : shadowSide[material.side];
  12484. }
  12485. result.clipShadows = material.clipShadows;
  12486. result.clippingPlanes = material.clippingPlanes;
  12487. result.clipIntersection = material.clipIntersection;
  12488. result.wireframeLinewidth = material.wireframeLinewidth;
  12489. result.linewidth = material.linewidth;
  12490. if (light.isPointLight && result.isMeshDistanceMaterial) {
  12491. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  12492. result.nearDistance = shadowCameraNear;
  12493. result.farDistance = shadowCameraFar;
  12494. }
  12495. return result;
  12496. }
  12497. function renderObject(object, camera, shadowCamera, light, type) {
  12498. if (object.visible === false) return;
  12499. var visible = object.layers.test(camera.layers);
  12500. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  12501. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  12502. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  12503. var geometry = _objects.update(object);
  12504. var material = object.material;
  12505. if (Array.isArray(material)) {
  12506. var groups = geometry.groups;
  12507. for (var k = 0, kl = groups.length; k < kl; k++) {
  12508. var group = groups[k];
  12509. var groupMaterial = material[group.materialIndex];
  12510. if (groupMaterial && groupMaterial.visible) {
  12511. var depthMaterial = getDepthMaterial(object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  12512. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  12513. }
  12514. }
  12515. } else if (material.visible) {
  12516. var depthMaterial = getDepthMaterial(object, material, light, shadowCamera.near, shadowCamera.far, type);
  12517. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  12518. }
  12519. }
  12520. }
  12521. var children = object.children;
  12522. for (var i = 0, l = children.length; i < l; i++) {
  12523. renderObject(children[i], camera, shadowCamera, light, type);
  12524. }
  12525. }
  12526. }
  12527. /**
  12528. * @author mrdoob / http://mrdoob.com/
  12529. */
  12530. function WebGLState(gl, extensions, utils, capabilities) {
  12531. function ColorBuffer() {
  12532. var locked = false;
  12533. var color = new Vector4();
  12534. var currentColorMask = null;
  12535. var currentColorClear = new Vector4(0, 0, 0, 0);
  12536. return {
  12537. setMask: function (colorMask) {
  12538. if (currentColorMask !== colorMask && !locked) {
  12539. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  12540. currentColorMask = colorMask;
  12541. }
  12542. },
  12543. setLocked: function (lock) {
  12544. locked = lock;
  12545. },
  12546. setClear: function (r, g, b, a, premultipliedAlpha) {
  12547. if (premultipliedAlpha === true) {
  12548. r *= a;
  12549. g *= a;
  12550. b *= a;
  12551. }
  12552. color.set(r, g, b, a);
  12553. if (currentColorClear.equals(color) === false) {
  12554. gl.clearColor(r, g, b, a);
  12555. currentColorClear.copy(color);
  12556. }
  12557. },
  12558. reset: function () {
  12559. locked = false;
  12560. currentColorMask = null;
  12561. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  12562. }
  12563. };
  12564. }
  12565. function DepthBuffer() {
  12566. var locked = false;
  12567. var currentDepthMask = null;
  12568. var currentDepthFunc = null;
  12569. var currentDepthClear = null;
  12570. return {
  12571. setTest: function (depthTest) {
  12572. if (depthTest) {
  12573. enable(2929);
  12574. } else {
  12575. disable(2929);
  12576. }
  12577. },
  12578. setMask: function (depthMask) {
  12579. if (currentDepthMask !== depthMask && !locked) {
  12580. gl.depthMask(depthMask);
  12581. currentDepthMask = depthMask;
  12582. }
  12583. },
  12584. setFunc: function (depthFunc) {
  12585. if (currentDepthFunc !== depthFunc) {
  12586. if (depthFunc) {
  12587. switch (depthFunc) {
  12588. case NeverDepth:
  12589. gl.depthFunc(512);
  12590. break;
  12591. case AlwaysDepth:
  12592. gl.depthFunc(519);
  12593. break;
  12594. case LessDepth:
  12595. gl.depthFunc(513);
  12596. break;
  12597. case LessEqualDepth:
  12598. gl.depthFunc(515);
  12599. break;
  12600. case EqualDepth:
  12601. gl.depthFunc(514);
  12602. break;
  12603. case GreaterEqualDepth:
  12604. gl.depthFunc(518);
  12605. break;
  12606. case GreaterDepth:
  12607. gl.depthFunc(516);
  12608. break;
  12609. case NotEqualDepth:
  12610. gl.depthFunc(517);
  12611. break;
  12612. default:
  12613. gl.depthFunc(515);
  12614. }
  12615. } else {
  12616. gl.depthFunc(515);
  12617. }
  12618. currentDepthFunc = depthFunc;
  12619. }
  12620. },
  12621. setLocked: function (lock) {
  12622. locked = lock;
  12623. },
  12624. setClear: function (depth) {
  12625. if (currentDepthClear !== depth) {
  12626. gl.clearDepth(depth);
  12627. currentDepthClear = depth;
  12628. }
  12629. },
  12630. reset: function () {
  12631. locked = false;
  12632. currentDepthMask = null;
  12633. currentDepthFunc = null;
  12634. currentDepthClear = null;
  12635. }
  12636. };
  12637. }
  12638. function StencilBuffer() {
  12639. var locked = false;
  12640. var currentStencilMask = null;
  12641. var currentStencilFunc = null;
  12642. var currentStencilRef = null;
  12643. var currentStencilFuncMask = null;
  12644. var currentStencilFail = null;
  12645. var currentStencilZFail = null;
  12646. var currentStencilZPass = null;
  12647. var currentStencilClear = null;
  12648. return {
  12649. setTest: function (stencilTest) {
  12650. if (!locked) {
  12651. if (stencilTest) {
  12652. enable(2960);
  12653. } else {
  12654. disable(2960);
  12655. }
  12656. }
  12657. },
  12658. setMask: function (stencilMask) {
  12659. if (currentStencilMask !== stencilMask && !locked) {
  12660. gl.stencilMask(stencilMask);
  12661. currentStencilMask = stencilMask;
  12662. }
  12663. },
  12664. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  12665. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  12666. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  12667. currentStencilFunc = stencilFunc;
  12668. currentStencilRef = stencilRef;
  12669. currentStencilFuncMask = stencilMask;
  12670. }
  12671. },
  12672. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  12673. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  12674. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  12675. currentStencilFail = stencilFail;
  12676. currentStencilZFail = stencilZFail;
  12677. currentStencilZPass = stencilZPass;
  12678. }
  12679. },
  12680. setLocked: function (lock) {
  12681. locked = lock;
  12682. },
  12683. setClear: function (stencil) {
  12684. if (currentStencilClear !== stencil) {
  12685. gl.clearStencil(stencil);
  12686. currentStencilClear = stencil;
  12687. }
  12688. },
  12689. reset: function () {
  12690. locked = false;
  12691. currentStencilMask = null;
  12692. currentStencilFunc = null;
  12693. currentStencilRef = null;
  12694. currentStencilFuncMask = null;
  12695. currentStencilFail = null;
  12696. currentStencilZFail = null;
  12697. currentStencilZPass = null;
  12698. currentStencilClear = null;
  12699. }
  12700. };
  12701. } //
  12702. var colorBuffer = new ColorBuffer();
  12703. var depthBuffer = new DepthBuffer();
  12704. var stencilBuffer = new StencilBuffer();
  12705. var maxVertexAttributes = gl.getParameter(34921);
  12706. var newAttributes = new Uint8Array(maxVertexAttributes);
  12707. var enabledAttributes = new Uint8Array(maxVertexAttributes);
  12708. var attributeDivisors = new Uint8Array(maxVertexAttributes);
  12709. var enabledCapabilities = {};
  12710. var compressedTextureFormats = null;
  12711. var currentProgram = null;
  12712. var currentBlendingEnabled = null;
  12713. var currentBlending = null;
  12714. var currentBlendEquation = null;
  12715. var currentBlendSrc = null;
  12716. var currentBlendDst = null;
  12717. var currentBlendEquationAlpha = null;
  12718. var currentBlendSrcAlpha = null;
  12719. var currentBlendDstAlpha = null;
  12720. var currentPremultipledAlpha = false;
  12721. var currentFlipSided = null;
  12722. var currentCullFace = null;
  12723. var currentLineWidth = null;
  12724. var currentPolygonOffsetFactor = null;
  12725. var currentPolygonOffsetUnits = null;
  12726. var maxTextures = gl.getParameter(35661);
  12727. var lineWidthAvailable = false;
  12728. var version = 0;
  12729. var glVersion = gl.getParameter(7938);
  12730. if (glVersion.indexOf('WebGL') !== -1) {
  12731. version = parseFloat(/^WebGL\ ([0-9])/.exec(glVersion)[1]);
  12732. lineWidthAvailable = version >= 1.0;
  12733. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  12734. version = parseFloat(/^OpenGL\ ES\ ([0-9])/.exec(glVersion)[1]);
  12735. lineWidthAvailable = version >= 2.0;
  12736. }
  12737. var currentTextureSlot = null;
  12738. var currentBoundTextures = {};
  12739. var currentScissor = new Vector4();
  12740. var currentViewport = new Vector4();
  12741. function createTexture(type, target, count) {
  12742. var data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  12743. var texture = gl.createTexture();
  12744. gl.bindTexture(type, texture);
  12745. gl.texParameteri(type, 10241, 9728);
  12746. gl.texParameteri(type, 10240, 9728);
  12747. for (var i = 0; i < count; i++) {
  12748. gl.texImage2D(target + i, 0, 6408, 1, 1, 0, 6408, 5121, data);
  12749. }
  12750. return texture;
  12751. }
  12752. var emptyTextures = {};
  12753. emptyTextures[3553] = createTexture(3553, 3553, 1);
  12754. emptyTextures[34067] = createTexture(34067, 34069, 6); // init
  12755. colorBuffer.setClear(0, 0, 0, 1);
  12756. depthBuffer.setClear(1);
  12757. stencilBuffer.setClear(0);
  12758. enable(2929);
  12759. depthBuffer.setFunc(LessEqualDepth);
  12760. setFlipSided(false);
  12761. setCullFace(CullFaceBack);
  12762. enable(2884);
  12763. setBlending(NoBlending); //
  12764. function initAttributes() {
  12765. for (var i = 0, l = newAttributes.length; i < l; i++) {
  12766. newAttributes[i] = 0;
  12767. }
  12768. }
  12769. function enableAttribute(attribute) {
  12770. enableAttributeAndDivisor(attribute, 0);
  12771. }
  12772. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  12773. newAttributes[attribute] = 1;
  12774. if (enabledAttributes[attribute] === 0) {
  12775. gl.enableVertexAttribArray(attribute);
  12776. enabledAttributes[attribute] = 1;
  12777. }
  12778. if (attributeDivisors[attribute] !== meshPerAttribute) {
  12779. var extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  12780. extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  12781. attributeDivisors[attribute] = meshPerAttribute;
  12782. }
  12783. }
  12784. function disableUnusedAttributes() {
  12785. for (var i = 0, l = enabledAttributes.length; i !== l; ++i) {
  12786. if (enabledAttributes[i] !== newAttributes[i]) {
  12787. gl.disableVertexAttribArray(i);
  12788. enabledAttributes[i] = 0;
  12789. }
  12790. }
  12791. }
  12792. function enable(id) {
  12793. if (enabledCapabilities[id] !== true) {
  12794. gl.enable(id);
  12795. enabledCapabilities[id] = true;
  12796. }
  12797. }
  12798. function disable(id) {
  12799. if (enabledCapabilities[id] !== false) {
  12800. gl.disable(id);
  12801. enabledCapabilities[id] = false;
  12802. }
  12803. }
  12804. function getCompressedTextureFormats() {
  12805. if (compressedTextureFormats === null) {
  12806. compressedTextureFormats = [];
  12807. 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')) {
  12808. var formats = gl.getParameter(34467);
  12809. for (var i = 0; i < formats.length; i++) {
  12810. compressedTextureFormats.push(formats[i]);
  12811. }
  12812. }
  12813. }
  12814. return compressedTextureFormats;
  12815. }
  12816. function useProgram(program) {
  12817. if (currentProgram !== program) {
  12818. gl.useProgram(program);
  12819. currentProgram = program;
  12820. return true;
  12821. }
  12822. return false;
  12823. }
  12824. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  12825. if (blending === NoBlending) {
  12826. if (currentBlendingEnabled) {
  12827. disable(3042);
  12828. currentBlendingEnabled = false;
  12829. }
  12830. return;
  12831. }
  12832. if (!currentBlendingEnabled) {
  12833. enable(3042);
  12834. currentBlendingEnabled = true;
  12835. }
  12836. if (blending !== CustomBlending) {
  12837. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  12838. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  12839. gl.blendEquation(32774);
  12840. currentBlendEquation = AddEquation;
  12841. currentBlendEquationAlpha = AddEquation;
  12842. }
  12843. if (premultipliedAlpha) {
  12844. switch (blending) {
  12845. case NormalBlending:
  12846. gl.blendFuncSeparate(1, 771, 1, 771);
  12847. break;
  12848. case AdditiveBlending:
  12849. gl.blendFunc(1, 1);
  12850. break;
  12851. case SubtractiveBlending:
  12852. gl.blendFuncSeparate(0, 0, 769, 771);
  12853. break;
  12854. case MultiplyBlending:
  12855. gl.blendFuncSeparate(0, 768, 0, 770);
  12856. break;
  12857. default:
  12858. console.error('THREE.WebGLState: Invalid blending: ', blending);
  12859. break;
  12860. }
  12861. } else {
  12862. switch (blending) {
  12863. case NormalBlending:
  12864. gl.blendFuncSeparate(770, 771, 1, 771);
  12865. break;
  12866. case AdditiveBlending:
  12867. gl.blendFunc(770, 1);
  12868. break;
  12869. case SubtractiveBlending:
  12870. gl.blendFunc(0, 769);
  12871. break;
  12872. case MultiplyBlending:
  12873. gl.blendFunc(0, 768);
  12874. break;
  12875. default:
  12876. console.error('THREE.WebGLState: Invalid blending: ', blending);
  12877. break;
  12878. }
  12879. }
  12880. currentBlendSrc = null;
  12881. currentBlendDst = null;
  12882. currentBlendSrcAlpha = null;
  12883. currentBlendDstAlpha = null;
  12884. currentBlending = blending;
  12885. currentPremultipledAlpha = premultipliedAlpha;
  12886. }
  12887. return;
  12888. } // custom blending
  12889. blendEquationAlpha = blendEquationAlpha || blendEquation;
  12890. blendSrcAlpha = blendSrcAlpha || blendSrc;
  12891. blendDstAlpha = blendDstAlpha || blendDst;
  12892. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  12893. gl.blendEquationSeparate(utils.convert(blendEquation), utils.convert(blendEquationAlpha));
  12894. currentBlendEquation = blendEquation;
  12895. currentBlendEquationAlpha = blendEquationAlpha;
  12896. }
  12897. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  12898. gl.blendFuncSeparate(utils.convert(blendSrc), utils.convert(blendDst), utils.convert(blendSrcAlpha), utils.convert(blendDstAlpha));
  12899. currentBlendSrc = blendSrc;
  12900. currentBlendDst = blendDst;
  12901. currentBlendSrcAlpha = blendSrcAlpha;
  12902. currentBlendDstAlpha = blendDstAlpha;
  12903. }
  12904. currentBlending = blending;
  12905. currentPremultipledAlpha = null;
  12906. }
  12907. function setMaterial(material, frontFaceCW) {
  12908. material.side === DoubleSide ? disable(2884) : enable(2884);
  12909. var flipSided = material.side === BackSide;
  12910. if (frontFaceCW) flipSided = !flipSided;
  12911. setFlipSided(flipSided);
  12912. 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);
  12913. depthBuffer.setFunc(material.depthFunc);
  12914. depthBuffer.setTest(material.depthTest);
  12915. depthBuffer.setMask(material.depthWrite);
  12916. colorBuffer.setMask(material.colorWrite);
  12917. var stencilWrite = material.stencilWrite;
  12918. stencilBuffer.setTest(stencilWrite);
  12919. if (stencilWrite) {
  12920. stencilBuffer.setMask(material.stencilWriteMask);
  12921. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  12922. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  12923. }
  12924. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  12925. } //
  12926. function setFlipSided(flipSided) {
  12927. if (currentFlipSided !== flipSided) {
  12928. if (flipSided) {
  12929. gl.frontFace(2304);
  12930. } else {
  12931. gl.frontFace(2305);
  12932. }
  12933. currentFlipSided = flipSided;
  12934. }
  12935. }
  12936. function setCullFace(cullFace) {
  12937. if (cullFace !== CullFaceNone) {
  12938. enable(2884);
  12939. if (cullFace !== currentCullFace) {
  12940. if (cullFace === CullFaceBack) {
  12941. gl.cullFace(1029);
  12942. } else if (cullFace === CullFaceFront) {
  12943. gl.cullFace(1028);
  12944. } else {
  12945. gl.cullFace(1032);
  12946. }
  12947. }
  12948. } else {
  12949. disable(2884);
  12950. }
  12951. currentCullFace = cullFace;
  12952. }
  12953. function setLineWidth(width) {
  12954. if (width !== currentLineWidth) {
  12955. if (lineWidthAvailable) gl.lineWidth(width);
  12956. currentLineWidth = width;
  12957. }
  12958. }
  12959. function setPolygonOffset(polygonOffset, factor, units) {
  12960. if (polygonOffset) {
  12961. enable(32823);
  12962. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  12963. gl.polygonOffset(factor, units);
  12964. currentPolygonOffsetFactor = factor;
  12965. currentPolygonOffsetUnits = units;
  12966. }
  12967. } else {
  12968. disable(32823);
  12969. }
  12970. }
  12971. function setScissorTest(scissorTest) {
  12972. if (scissorTest) {
  12973. enable(3089);
  12974. } else {
  12975. disable(3089);
  12976. }
  12977. } // texture
  12978. function activeTexture(webglSlot) {
  12979. if (webglSlot === undefined) webglSlot = 33984 + maxTextures - 1;
  12980. if (currentTextureSlot !== webglSlot) {
  12981. gl.activeTexture(webglSlot);
  12982. currentTextureSlot = webglSlot;
  12983. }
  12984. }
  12985. function bindTexture(webglType, webglTexture) {
  12986. if (currentTextureSlot === null) {
  12987. activeTexture();
  12988. }
  12989. var boundTexture = currentBoundTextures[currentTextureSlot];
  12990. if (boundTexture === undefined) {
  12991. boundTexture = {
  12992. type: undefined,
  12993. texture: undefined
  12994. };
  12995. currentBoundTextures[currentTextureSlot] = boundTexture;
  12996. }
  12997. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  12998. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  12999. boundTexture.type = webglType;
  13000. boundTexture.texture = webglTexture;
  13001. }
  13002. }
  13003. function compressedTexImage2D() {
  13004. try {
  13005. gl.compressedTexImage2D.apply(gl, arguments);
  13006. } catch (error) {
  13007. console.error('THREE.WebGLState:', error);
  13008. }
  13009. }
  13010. function texImage2D() {
  13011. try {
  13012. gl.texImage2D.apply(gl, arguments);
  13013. } catch (error) {
  13014. console.error('THREE.WebGLState:', error);
  13015. }
  13016. }
  13017. function texImage3D() {
  13018. try {
  13019. gl.texImage3D.apply(gl, arguments);
  13020. } catch (error) {
  13021. console.error('THREE.WebGLState:', error);
  13022. }
  13023. } //
  13024. function scissor(scissor) {
  13025. if (currentScissor.equals(scissor) === false) {
  13026. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  13027. currentScissor.copy(scissor);
  13028. }
  13029. }
  13030. function viewport(viewport) {
  13031. if (currentViewport.equals(viewport) === false) {
  13032. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  13033. currentViewport.copy(viewport);
  13034. }
  13035. } //
  13036. function reset() {
  13037. for (var i = 0; i < enabledAttributes.length; i++) {
  13038. if (enabledAttributes[i] === 1) {
  13039. gl.disableVertexAttribArray(i);
  13040. enabledAttributes[i] = 0;
  13041. }
  13042. }
  13043. enabledCapabilities = {};
  13044. compressedTextureFormats = null;
  13045. currentTextureSlot = null;
  13046. currentBoundTextures = {};
  13047. currentProgram = null;
  13048. currentBlending = null;
  13049. currentFlipSided = null;
  13050. currentCullFace = null;
  13051. colorBuffer.reset();
  13052. depthBuffer.reset();
  13053. stencilBuffer.reset();
  13054. }
  13055. return {
  13056. buffers: {
  13057. color: colorBuffer,
  13058. depth: depthBuffer,
  13059. stencil: stencilBuffer
  13060. },
  13061. initAttributes: initAttributes,
  13062. enableAttribute: enableAttribute,
  13063. enableAttributeAndDivisor: enableAttributeAndDivisor,
  13064. disableUnusedAttributes: disableUnusedAttributes,
  13065. enable: enable,
  13066. disable: disable,
  13067. getCompressedTextureFormats: getCompressedTextureFormats,
  13068. useProgram: useProgram,
  13069. setBlending: setBlending,
  13070. setMaterial: setMaterial,
  13071. setFlipSided: setFlipSided,
  13072. setCullFace: setCullFace,
  13073. setLineWidth: setLineWidth,
  13074. setPolygonOffset: setPolygonOffset,
  13075. setScissorTest: setScissorTest,
  13076. activeTexture: activeTexture,
  13077. bindTexture: bindTexture,
  13078. compressedTexImage2D: compressedTexImage2D,
  13079. texImage2D: texImage2D,
  13080. texImage3D: texImage3D,
  13081. scissor: scissor,
  13082. viewport: viewport,
  13083. reset: reset
  13084. };
  13085. }
  13086. /**
  13087. * @author mrdoob / http://mrdoob.com/
  13088. */
  13089. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  13090. var _videoTextures = new WeakMap();
  13091. var _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13092. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13093. var useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext("2d") !== null;
  13094. function createCanvas(width, height) {
  13095. // Use OffscreenCanvas when available. Specially needed in web workers
  13096. return useOffscreenCanvas ? new OffscreenCanvas(width, height) : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  13097. }
  13098. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  13099. var scale = 1; // handle case if texture exceeds max size
  13100. if (image.width > maxSize || image.height > maxSize) {
  13101. scale = maxSize / Math.max(image.width, image.height);
  13102. } // only perform resize if necessary
  13103. if (scale < 1 || needsPowerOfTwo === true) {
  13104. // only perform resize for certain image types
  13105. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  13106. var floor = needsPowerOfTwo ? _Math.floorPowerOfTwo : Math.floor;
  13107. var width = floor(scale * image.width);
  13108. var height = floor(scale * image.height);
  13109. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  13110. var canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  13111. canvas.width = width;
  13112. canvas.height = height;
  13113. var context = canvas.getContext('2d');
  13114. context.drawImage(image, 0, 0, width, height);
  13115. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  13116. return canvas;
  13117. } else {
  13118. if ('data' in image) {
  13119. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  13120. }
  13121. return image;
  13122. }
  13123. }
  13124. return image;
  13125. }
  13126. function isPowerOfTwo(image) {
  13127. return _Math.isPowerOfTwo(image.width) && _Math.isPowerOfTwo(image.height);
  13128. }
  13129. function textureNeedsPowerOfTwo(texture) {
  13130. if (capabilities.isWebGL2) return false;
  13131. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13132. }
  13133. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  13134. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13135. }
  13136. function generateMipmap(target, texture, width, height) {
  13137. _gl.generateMipmap(target);
  13138. var textureProperties = properties.get(texture); // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
  13139. textureProperties.__maxMipLevel = Math.log(Math.max(width, height)) * Math.LOG2E;
  13140. }
  13141. function getInternalFormat(glFormat, glType) {
  13142. if (!capabilities.isWebGL2) return glFormat;
  13143. var internalFormat = glFormat;
  13144. if (glFormat === 6403) {
  13145. if (glType === 5126) internalFormat = 33326;
  13146. if (glType === 5131) internalFormat = 33325;
  13147. if (glType === 5121) internalFormat = 33321;
  13148. }
  13149. if (glFormat === 6407) {
  13150. if (glType === 5126) internalFormat = 34837;
  13151. if (glType === 5131) internalFormat = 34843;
  13152. if (glType === 5121) internalFormat = 32849;
  13153. }
  13154. if (glFormat === 6408) {
  13155. if (glType === 5126) internalFormat = 34836;
  13156. if (glType === 5131) internalFormat = 34842;
  13157. if (glType === 5121) internalFormat = 32856;
  13158. }
  13159. if (internalFormat === 33325 || internalFormat === 33326 || internalFormat === 34842 || internalFormat === 34836) {
  13160. extensions.get('EXT_color_buffer_float');
  13161. } else if (internalFormat === 34843 || internalFormat === 34837) {
  13162. console.warn('THREE.WebGLRenderer: Floating point textures with RGB format not supported. Please use RGBA instead.');
  13163. }
  13164. return internalFormat;
  13165. } // Fallback filters for non-power-of-2 textures
  13166. function filterFallback(f) {
  13167. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  13168. return 9728;
  13169. }
  13170. return 9729;
  13171. } //
  13172. function onTextureDispose(event) {
  13173. var texture = event.target;
  13174. texture.removeEventListener('dispose', onTextureDispose);
  13175. deallocateTexture(texture);
  13176. if (texture.isVideoTexture) {
  13177. _videoTextures.delete(texture);
  13178. }
  13179. info.memory.textures--;
  13180. }
  13181. function onRenderTargetDispose(event) {
  13182. var renderTarget = event.target;
  13183. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  13184. deallocateRenderTarget(renderTarget);
  13185. info.memory.textures--;
  13186. } //
  13187. function deallocateTexture(texture) {
  13188. var textureProperties = properties.get(texture);
  13189. if (textureProperties.__webglInit === undefined) return;
  13190. _gl.deleteTexture(textureProperties.__webglTexture);
  13191. properties.remove(texture);
  13192. }
  13193. function deallocateRenderTarget(renderTarget) {
  13194. var renderTargetProperties = properties.get(renderTarget);
  13195. var textureProperties = properties.get(renderTarget.texture);
  13196. if (!renderTarget) return;
  13197. if (textureProperties.__webglTexture !== undefined) {
  13198. _gl.deleteTexture(textureProperties.__webglTexture);
  13199. }
  13200. if (renderTarget.depthTexture) {
  13201. renderTarget.depthTexture.dispose();
  13202. }
  13203. if (renderTarget.isWebGLRenderTargetCube) {
  13204. for (var i = 0; i < 6; i++) {
  13205. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  13206. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  13207. }
  13208. } else {
  13209. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  13210. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  13211. }
  13212. if (renderTarget.isWebGLMultiviewRenderTarget) {
  13213. _gl.deleteTexture(renderTargetProperties.__webglColorTexture);
  13214. _gl.deleteTexture(renderTargetProperties.__webglDepthStencilTexture);
  13215. info.memory.textures -= 2;
  13216. for (var i = 0, il = renderTargetProperties.__webglViewFramebuffers.length; i < il; i++) {
  13217. _gl.deleteFramebuffer(renderTargetProperties.__webglViewFramebuffers[i]);
  13218. }
  13219. }
  13220. properties.remove(renderTarget.texture);
  13221. properties.remove(renderTarget);
  13222. } //
  13223. var textureUnits = 0;
  13224. function resetTextureUnits() {
  13225. textureUnits = 0;
  13226. }
  13227. function allocateTextureUnit() {
  13228. var textureUnit = textureUnits;
  13229. if (textureUnit >= capabilities.maxTextures) {
  13230. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures);
  13231. }
  13232. textureUnits += 1;
  13233. return textureUnit;
  13234. } //
  13235. function setTexture2D(texture, slot) {
  13236. var textureProperties = properties.get(texture);
  13237. if (texture.isVideoTexture) updateVideoTexture(texture);
  13238. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13239. var image = texture.image;
  13240. if (image === undefined) {
  13241. console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
  13242. } else if (image.complete === false) {
  13243. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  13244. } else {
  13245. uploadTexture(textureProperties, texture, slot);
  13246. return;
  13247. }
  13248. }
  13249. state.activeTexture(33984 + slot);
  13250. state.bindTexture(3553, textureProperties.__webglTexture);
  13251. }
  13252. function setTexture2DArray(texture, slot) {
  13253. var textureProperties = properties.get(texture);
  13254. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13255. uploadTexture(textureProperties, texture, slot);
  13256. return;
  13257. }
  13258. state.activeTexture(33984 + slot);
  13259. state.bindTexture(35866, textureProperties.__webglTexture);
  13260. }
  13261. function setTexture3D(texture, slot) {
  13262. var textureProperties = properties.get(texture);
  13263. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13264. uploadTexture(textureProperties, texture, slot);
  13265. return;
  13266. }
  13267. state.activeTexture(33984 + slot);
  13268. state.bindTexture(32879, textureProperties.__webglTexture);
  13269. }
  13270. function setTextureCube(texture, slot) {
  13271. if (texture.image.length !== 6) return;
  13272. var textureProperties = properties.get(texture);
  13273. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13274. initTexture(textureProperties, texture);
  13275. state.activeTexture(33984 + slot);
  13276. state.bindTexture(34067, textureProperties.__webglTexture);
  13277. _gl.pixelStorei(37440, texture.flipY);
  13278. var isCompressed = texture && texture.isCompressedTexture;
  13279. var isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  13280. var cubeImage = [];
  13281. for (var i = 0; i < 6; i++) {
  13282. if (!isCompressed && !isDataTexture) {
  13283. cubeImage[i] = resizeImage(texture.image[i], false, true, capabilities.maxCubemapSize);
  13284. } else {
  13285. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  13286. }
  13287. }
  13288. var image = cubeImage[0],
  13289. supportsMips = isPowerOfTwo(image) || capabilities.isWebGL2,
  13290. glFormat = utils.convert(texture.format),
  13291. glType = utils.convert(texture.type),
  13292. glInternalFormat = getInternalFormat(glFormat, glType);
  13293. setTextureParameters(34067, texture, supportsMips);
  13294. var mipmaps;
  13295. if (isCompressed) {
  13296. for (var i = 0; i < 6; i++) {
  13297. mipmaps = cubeImage[i].mipmaps;
  13298. for (var j = 0; j < mipmaps.length; j++) {
  13299. var mipmap = mipmaps[j];
  13300. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  13301. if (state.getCompressedTextureFormats().indexOf(glFormat) > -1) {
  13302. state.compressedTexImage2D(34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  13303. } else {
  13304. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  13305. }
  13306. } else {
  13307. state.texImage2D(34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13308. }
  13309. }
  13310. }
  13311. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13312. } else {
  13313. mipmaps = texture.mipmaps;
  13314. for (var i = 0; i < 6; i++) {
  13315. if (isDataTexture) {
  13316. state.texImage2D(34069 + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  13317. for (var j = 0; j < mipmaps.length; j++) {
  13318. var mipmap = mipmaps[j];
  13319. var mipmapImage = mipmap.image[i].image;
  13320. state.texImage2D(34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  13321. }
  13322. } else {
  13323. state.texImage2D(34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  13324. for (var j = 0; j < mipmaps.length; j++) {
  13325. var mipmap = mipmaps[j];
  13326. state.texImage2D(34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  13327. }
  13328. }
  13329. }
  13330. textureProperties.__maxMipLevel = mipmaps.length;
  13331. }
  13332. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13333. // We assume images for cube map have the same size.
  13334. generateMipmap(34067, texture, image.width, image.height);
  13335. }
  13336. textureProperties.__version = texture.version;
  13337. if (texture.onUpdate) texture.onUpdate(texture);
  13338. } else {
  13339. state.activeTexture(33984 + slot);
  13340. state.bindTexture(34067, textureProperties.__webglTexture);
  13341. }
  13342. }
  13343. function setTextureCubeDynamic(texture, slot) {
  13344. state.activeTexture(33984 + slot);
  13345. state.bindTexture(34067, properties.get(texture).__webglTexture);
  13346. }
  13347. function setTextureParameters(textureType, texture, supportsMips) {
  13348. var extension;
  13349. if (supportsMips) {
  13350. _gl.texParameteri(textureType, 10242, utils.convert(texture.wrapS));
  13351. _gl.texParameteri(textureType, 10243, utils.convert(texture.wrapT));
  13352. if (textureType === 32879 || textureType === 35866) {
  13353. _gl.texParameteri(textureType, 32882, utils.convert(texture.wrapR));
  13354. }
  13355. _gl.texParameteri(textureType, 10240, utils.convert(texture.magFilter));
  13356. _gl.texParameteri(textureType, 10241, utils.convert(texture.minFilter));
  13357. } else {
  13358. _gl.texParameteri(textureType, 10242, 33071);
  13359. _gl.texParameteri(textureType, 10243, 33071);
  13360. if (textureType === 32879 || textureType === 35866) {
  13361. _gl.texParameteri(textureType, 32882, 33071);
  13362. }
  13363. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  13364. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  13365. }
  13366. _gl.texParameteri(textureType, 10240, filterFallback(texture.magFilter));
  13367. _gl.texParameteri(textureType, 10241, filterFallback(texture.minFilter));
  13368. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  13369. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  13370. }
  13371. }
  13372. extension = extensions.get('EXT_texture_filter_anisotropic');
  13373. if (extension) {
  13374. if (texture.type === FloatType && extensions.get('OES_texture_float_linear') === null) return;
  13375. if (texture.type === HalfFloatType && (capabilities.isWebGL2 || extensions.get('OES_texture_half_float_linear')) === null) return;
  13376. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  13377. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  13378. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  13379. }
  13380. }
  13381. }
  13382. function initTexture(textureProperties, texture) {
  13383. if (textureProperties.__webglInit === undefined) {
  13384. textureProperties.__webglInit = true;
  13385. texture.addEventListener('dispose', onTextureDispose);
  13386. textureProperties.__webglTexture = _gl.createTexture();
  13387. info.memory.textures++;
  13388. }
  13389. }
  13390. function uploadTexture(textureProperties, texture, slot) {
  13391. var textureType = 3553;
  13392. if (texture.isDataTexture2DArray) textureType = 35866;
  13393. if (texture.isDataTexture3D) textureType = 32879;
  13394. initTexture(textureProperties, texture);
  13395. state.activeTexture(33984 + slot);
  13396. state.bindTexture(textureType, textureProperties.__webglTexture);
  13397. _gl.pixelStorei(37440, texture.flipY);
  13398. _gl.pixelStorei(37441, texture.premultiplyAlpha);
  13399. _gl.pixelStorei(3317, texture.unpackAlignment);
  13400. var needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo(texture.image) === false;
  13401. var image = resizeImage(texture.image, needsPowerOfTwo, false, capabilities.maxTextureSize);
  13402. var supportsMips = isPowerOfTwo(image) || capabilities.isWebGL2,
  13403. glFormat = utils.convert(texture.format),
  13404. glType = utils.convert(texture.type),
  13405. glInternalFormat = getInternalFormat(glFormat, glType);
  13406. setTextureParameters(textureType, texture, supportsMips);
  13407. var mipmap,
  13408. mipmaps = texture.mipmaps;
  13409. if (texture.isDepthTexture) {
  13410. // populate depth texture with dummy data
  13411. glInternalFormat = 6402;
  13412. if (texture.type === FloatType) {
  13413. if (!capabilities.isWebGL2) throw new Error('Float Depth Texture only supported in WebGL2.0');
  13414. glInternalFormat = 36012;
  13415. } else if (capabilities.isWebGL2) {
  13416. // WebGL 2.0 requires signed internalformat for glTexImage2D
  13417. glInternalFormat = 33189;
  13418. }
  13419. if (texture.format === DepthFormat && glInternalFormat === 6402) {
  13420. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13421. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13422. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13423. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  13424. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  13425. texture.type = UnsignedShortType;
  13426. glType = utils.convert(texture.type);
  13427. }
  13428. } // Depth stencil textures need the DEPTH_STENCIL internal format
  13429. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13430. if (texture.format === DepthStencilFormat) {
  13431. glInternalFormat = 34041; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13432. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13433. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13434. if (texture.type !== UnsignedInt248Type) {
  13435. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  13436. texture.type = UnsignedInt248Type;
  13437. glType = utils.convert(texture.type);
  13438. }
  13439. }
  13440. state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  13441. } else if (texture.isDataTexture) {
  13442. // use manually created mipmaps if available
  13443. // if there are no manual mipmaps
  13444. // set 0 level mipmap and then use GL to generate other mipmap levels
  13445. if (mipmaps.length > 0 && supportsMips) {
  13446. for (var i = 0, il = mipmaps.length; i < il; i++) {
  13447. mipmap = mipmaps[i];
  13448. state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13449. }
  13450. texture.generateMipmaps = false;
  13451. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13452. } else {
  13453. state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  13454. textureProperties.__maxMipLevel = 0;
  13455. }
  13456. } else if (texture.isCompressedTexture) {
  13457. for (var i = 0, il = mipmaps.length; i < il; i++) {
  13458. mipmap = mipmaps[i];
  13459. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  13460. if (state.getCompressedTextureFormats().indexOf(glFormat) > -1) {
  13461. state.compressedTexImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  13462. } else {
  13463. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  13464. }
  13465. } else {
  13466. state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13467. }
  13468. }
  13469. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13470. } else if (texture.isDataTexture2DArray) {
  13471. state.texImage3D(35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  13472. textureProperties.__maxMipLevel = 0;
  13473. } else if (texture.isDataTexture3D) {
  13474. state.texImage3D(32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  13475. textureProperties.__maxMipLevel = 0;
  13476. } else {
  13477. // regular Texture (image, video, canvas)
  13478. // use manually created mipmaps if available
  13479. // if there are no manual mipmaps
  13480. // set 0 level mipmap and then use GL to generate other mipmap levels
  13481. if (mipmaps.length > 0 && supportsMips) {
  13482. for (var i = 0, il = mipmaps.length; i < il; i++) {
  13483. mipmap = mipmaps[i];
  13484. state.texImage2D(3553, i, glInternalFormat, glFormat, glType, mipmap);
  13485. }
  13486. texture.generateMipmaps = false;
  13487. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13488. } else {
  13489. state.texImage2D(3553, 0, glInternalFormat, glFormat, glType, image);
  13490. textureProperties.__maxMipLevel = 0;
  13491. }
  13492. }
  13493. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13494. generateMipmap(3553, texture, image.width, image.height);
  13495. }
  13496. textureProperties.__version = texture.version;
  13497. if (texture.onUpdate) texture.onUpdate(texture);
  13498. } // Render targets
  13499. // Setup storage for target texture and bind it to correct framebuffer
  13500. function setupFrameBufferTexture(framebuffer, renderTarget, attachment, textureTarget) {
  13501. var glFormat = utils.convert(renderTarget.texture.format);
  13502. var glType = utils.convert(renderTarget.texture.type);
  13503. var glInternalFormat = getInternalFormat(glFormat, glType);
  13504. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  13505. _gl.bindFramebuffer(36160, framebuffer);
  13506. _gl.framebufferTexture2D(36160, attachment, textureTarget, properties.get(renderTarget.texture).__webglTexture, 0);
  13507. _gl.bindFramebuffer(36160, null);
  13508. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  13509. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  13510. _gl.bindRenderbuffer(36161, renderbuffer);
  13511. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  13512. if (isMultisample) {
  13513. var samples = getRenderTargetSamples(renderTarget);
  13514. _gl.renderbufferStorageMultisample(36161, samples, 33189, renderTarget.width, renderTarget.height);
  13515. } else {
  13516. _gl.renderbufferStorage(36161, 33189, renderTarget.width, renderTarget.height);
  13517. }
  13518. _gl.framebufferRenderbuffer(36160, 36096, 36161, renderbuffer);
  13519. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  13520. if (isMultisample) {
  13521. var samples = getRenderTargetSamples(renderTarget);
  13522. _gl.renderbufferStorageMultisample(36161, samples, 35056, renderTarget.width, renderTarget.height);
  13523. } else {
  13524. _gl.renderbufferStorage(36161, 34041, renderTarget.width, renderTarget.height);
  13525. }
  13526. _gl.framebufferRenderbuffer(36160, 33306, 36161, renderbuffer);
  13527. } else {
  13528. var glFormat = utils.convert(renderTarget.texture.format);
  13529. var glType = utils.convert(renderTarget.texture.type);
  13530. var glInternalFormat = getInternalFormat(glFormat, glType);
  13531. if (isMultisample) {
  13532. var samples = getRenderTargetSamples(renderTarget);
  13533. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13534. } else {
  13535. _gl.renderbufferStorage(36161, glInternalFormat, renderTarget.width, renderTarget.height);
  13536. }
  13537. }
  13538. _gl.bindRenderbuffer(36161, null);
  13539. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  13540. function setupDepthTexture(framebuffer, renderTarget) {
  13541. var isCube = renderTarget && renderTarget.isWebGLRenderTargetCube;
  13542. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  13543. _gl.bindFramebuffer(36160, framebuffer);
  13544. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  13545. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  13546. } // upload an empty depth texture with framebuffer size
  13547. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  13548. renderTarget.depthTexture.image.width = renderTarget.width;
  13549. renderTarget.depthTexture.image.height = renderTarget.height;
  13550. renderTarget.depthTexture.needsUpdate = true;
  13551. }
  13552. setTexture2D(renderTarget.depthTexture, 0);
  13553. var webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  13554. if (renderTarget.depthTexture.format === DepthFormat) {
  13555. _gl.framebufferTexture2D(36160, 36096, 3553, webglDepthTexture, 0);
  13556. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  13557. _gl.framebufferTexture2D(36160, 33306, 3553, webglDepthTexture, 0);
  13558. } else {
  13559. throw new Error('Unknown depthTexture format');
  13560. }
  13561. } // Setup GL resources for a non-texture depth buffer
  13562. function setupDepthRenderbuffer(renderTarget) {
  13563. var renderTargetProperties = properties.get(renderTarget);
  13564. var isCube = renderTarget.isWebGLRenderTargetCube === true;
  13565. if (renderTarget.depthTexture) {
  13566. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  13567. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  13568. } else {
  13569. if (isCube) {
  13570. renderTargetProperties.__webglDepthbuffer = [];
  13571. for (var i = 0; i < 6; i++) {
  13572. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer[i]);
  13573. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  13574. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget);
  13575. }
  13576. } else {
  13577. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer);
  13578. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  13579. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget);
  13580. }
  13581. }
  13582. _gl.bindFramebuffer(36160, null);
  13583. } // Set up GL resources for the render target
  13584. function setupRenderTarget(renderTarget) {
  13585. var renderTargetProperties = properties.get(renderTarget);
  13586. var textureProperties = properties.get(renderTarget.texture);
  13587. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  13588. textureProperties.__webglTexture = _gl.createTexture();
  13589. info.memory.textures++;
  13590. var isCube = renderTarget.isWebGLRenderTargetCube === true;
  13591. var isMultisample = renderTarget.isWebGLMultisampleRenderTarget === true;
  13592. var isMultiview = renderTarget.isWebGLMultiviewRenderTarget === true;
  13593. var supportsMips = isPowerOfTwo(renderTarget) || capabilities.isWebGL2; // Setup framebuffer
  13594. if (isCube) {
  13595. renderTargetProperties.__webglFramebuffer = [];
  13596. for (var i = 0; i < 6; i++) {
  13597. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  13598. }
  13599. } else {
  13600. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  13601. if (isMultisample) {
  13602. if (capabilities.isWebGL2) {
  13603. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  13604. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  13605. _gl.bindRenderbuffer(36161, renderTargetProperties.__webglColorRenderbuffer);
  13606. var glFormat = utils.convert(renderTarget.texture.format);
  13607. var glType = utils.convert(renderTarget.texture.type);
  13608. var glInternalFormat = getInternalFormat(glFormat, glType);
  13609. var samples = getRenderTargetSamples(renderTarget);
  13610. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13611. _gl.bindFramebuffer(36160, renderTargetProperties.__webglMultisampledFramebuffer);
  13612. _gl.framebufferRenderbuffer(36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer);
  13613. _gl.bindRenderbuffer(36161, null);
  13614. if (renderTarget.depthBuffer) {
  13615. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  13616. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  13617. }
  13618. _gl.bindFramebuffer(36160, null);
  13619. } else {
  13620. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  13621. }
  13622. } else if (isMultiview) {
  13623. var width = renderTarget.width;
  13624. var height = renderTarget.height;
  13625. var numViews = renderTarget.numViews;
  13626. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer);
  13627. var ext = extensions.get('OVR_multiview2');
  13628. info.memory.textures += 2;
  13629. var colorTexture = _gl.createTexture();
  13630. _gl.bindTexture(35866, colorTexture);
  13631. _gl.texParameteri(35866, 10240, 9728);
  13632. _gl.texParameteri(35866, 10241, 9728);
  13633. _gl.texImage3D(35866, 0, 32856, width, height, numViews, 0, 6408, 5121, null);
  13634. ext.framebufferTextureMultiviewOVR(36160, 36064, colorTexture, 0, 0, numViews);
  13635. var depthStencilTexture = _gl.createTexture();
  13636. _gl.bindTexture(35866, depthStencilTexture);
  13637. _gl.texParameteri(35866, 10240, 9728);
  13638. _gl.texParameteri(35866, 10241, 9728);
  13639. _gl.texImage3D(35866, 0, 35056, width, height, numViews, 0, 34041, 34042, null);
  13640. ext.framebufferTextureMultiviewOVR(36160, 33306, depthStencilTexture, 0, 0, numViews);
  13641. var viewFramebuffers = new Array(numViews);
  13642. for (var i = 0; i < numViews; ++i) {
  13643. viewFramebuffers[i] = _gl.createFramebuffer();
  13644. _gl.bindFramebuffer(36160, viewFramebuffers[i]);
  13645. _gl.framebufferTextureLayer(36160, 36064, colorTexture, 0, i);
  13646. }
  13647. renderTargetProperties.__webglColorTexture = colorTexture;
  13648. renderTargetProperties.__webglDepthStencilTexture = depthStencilTexture;
  13649. renderTargetProperties.__webglViewFramebuffers = viewFramebuffers;
  13650. _gl.bindFramebuffer(36160, null);
  13651. _gl.bindTexture(35866, null);
  13652. }
  13653. } // Setup color buffer
  13654. if (isCube) {
  13655. state.bindTexture(34067, textureProperties.__webglTexture);
  13656. setTextureParameters(34067, renderTarget.texture, supportsMips);
  13657. for (var i = 0; i < 6; i++) {
  13658. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, 36064, 34069 + i);
  13659. }
  13660. if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
  13661. generateMipmap(34067, renderTarget.texture, renderTarget.width, renderTarget.height);
  13662. }
  13663. state.bindTexture(34067, null);
  13664. } else if (!isMultiview) {
  13665. state.bindTexture(3553, textureProperties.__webglTexture);
  13666. setTextureParameters(3553, renderTarget.texture, supportsMips);
  13667. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553);
  13668. if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
  13669. generateMipmap(3553, renderTarget.texture, renderTarget.width, renderTarget.height);
  13670. }
  13671. state.bindTexture(3553, null);
  13672. } // Setup depth and stencil buffers
  13673. if (renderTarget.depthBuffer) {
  13674. setupDepthRenderbuffer(renderTarget);
  13675. }
  13676. }
  13677. function updateRenderTargetMipmap(renderTarget) {
  13678. var texture = renderTarget.texture;
  13679. var supportsMips = isPowerOfTwo(renderTarget) || capabilities.isWebGL2;
  13680. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13681. var target = renderTarget.isWebGLRenderTargetCube ? 34067 : 3553;
  13682. var webglTexture = properties.get(texture).__webglTexture;
  13683. state.bindTexture(target, webglTexture);
  13684. generateMipmap(target, texture, renderTarget.width, renderTarget.height);
  13685. state.bindTexture(target, null);
  13686. }
  13687. }
  13688. function updateMultisampleRenderTarget(renderTarget) {
  13689. if (renderTarget.isWebGLMultisampleRenderTarget) {
  13690. if (capabilities.isWebGL2) {
  13691. var renderTargetProperties = properties.get(renderTarget);
  13692. _gl.bindFramebuffer(36008, renderTargetProperties.__webglMultisampledFramebuffer);
  13693. _gl.bindFramebuffer(36009, renderTargetProperties.__webglFramebuffer);
  13694. var width = renderTarget.width;
  13695. var height = renderTarget.height;
  13696. var mask = 16384;
  13697. if (renderTarget.depthBuffer) mask |= 256;
  13698. if (renderTarget.stencilBuffer) mask |= 1024;
  13699. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, 9728);
  13700. } else {
  13701. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  13702. }
  13703. }
  13704. }
  13705. function getRenderTargetSamples(renderTarget) {
  13706. return capabilities.isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ? Math.min(capabilities.maxSamples, renderTarget.samples) : 0;
  13707. }
  13708. function updateVideoTexture(texture) {
  13709. var frame = info.render.frame; // Check the last frame we updated the VideoTexture
  13710. if (_videoTextures.get(texture) !== frame) {
  13711. _videoTextures.set(texture, frame);
  13712. texture.update();
  13713. }
  13714. } // backwards compatibility
  13715. var warnedTexture2D = false;
  13716. var warnedTextureCube = false;
  13717. function safeSetTexture2D(texture, slot) {
  13718. if (texture && texture.isWebGLRenderTarget) {
  13719. if (warnedTexture2D === false) {
  13720. console.warn("THREE.WebGLTextures.safeSetTexture2D: don't use render targets as textures. Use their .texture property instead.");
  13721. warnedTexture2D = true;
  13722. }
  13723. texture = texture.texture;
  13724. }
  13725. setTexture2D(texture, slot);
  13726. }
  13727. function safeSetTextureCube(texture, slot) {
  13728. if (texture && texture.isWebGLRenderTargetCube) {
  13729. if (warnedTextureCube === false) {
  13730. console.warn("THREE.WebGLTextures.safeSetTextureCube: don't use cube render targets as textures. Use their .texture property instead.");
  13731. warnedTextureCube = true;
  13732. }
  13733. texture = texture.texture;
  13734. } // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  13735. // TODO: unify these code paths
  13736. if (texture && texture.isCubeTexture || Array.isArray(texture.image) && texture.image.length === 6) {
  13737. // CompressedTexture can have Array in image :/
  13738. // this function alone should take care of cube textures
  13739. setTextureCube(texture, slot);
  13740. } else {
  13741. // assumed: texture property of THREE.WebGLRenderTargetCube
  13742. setTextureCubeDynamic(texture, slot);
  13743. }
  13744. } //
  13745. this.allocateTextureUnit = allocateTextureUnit;
  13746. this.resetTextureUnits = resetTextureUnits;
  13747. this.setTexture2D = setTexture2D;
  13748. this.setTexture2DArray = setTexture2DArray;
  13749. this.setTexture3D = setTexture3D;
  13750. this.setTextureCube = setTextureCube;
  13751. this.setTextureCubeDynamic = setTextureCubeDynamic;
  13752. this.setupRenderTarget = setupRenderTarget;
  13753. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  13754. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  13755. this.safeSetTexture2D = safeSetTexture2D;
  13756. this.safeSetTextureCube = safeSetTextureCube;
  13757. }
  13758. /**
  13759. * @author thespite / http://www.twitter.com/thespite
  13760. */
  13761. function WebGLUtils(gl, extensions, capabilities) {
  13762. function convert(p) {
  13763. var extension;
  13764. if (p === RepeatWrapping) return 10497;
  13765. if (p === ClampToEdgeWrapping) return 33071;
  13766. if (p === MirroredRepeatWrapping) return 33648;
  13767. if (p === NearestFilter) return 9728;
  13768. if (p === NearestMipmapNearestFilter) return 9984;
  13769. if (p === NearestMipmapLinearFilter) return 9986;
  13770. if (p === LinearFilter) return 9729;
  13771. if (p === LinearMipmapNearestFilter) return 9985;
  13772. if (p === LinearMipmapLinearFilter) return 9987;
  13773. if (p === UnsignedByteType) return 5121;
  13774. if (p === UnsignedShort4444Type) return 32819;
  13775. if (p === UnsignedShort5551Type) return 32820;
  13776. if (p === UnsignedShort565Type) return 33635;
  13777. if (p === ByteType) return 5120;
  13778. if (p === ShortType) return 5122;
  13779. if (p === UnsignedShortType) return 5123;
  13780. if (p === IntType) return 5124;
  13781. if (p === UnsignedIntType) return 5125;
  13782. if (p === FloatType) return 5126;
  13783. if (p === HalfFloatType) {
  13784. if (capabilities.isWebGL2) return 5131;
  13785. extension = extensions.get('OES_texture_half_float');
  13786. if (extension !== null) return extension.HALF_FLOAT_OES;
  13787. }
  13788. if (p === AlphaFormat) return 6406;
  13789. if (p === RGBFormat) return 6407;
  13790. if (p === RGBAFormat) return 6408;
  13791. if (p === LuminanceFormat) return 6409;
  13792. if (p === LuminanceAlphaFormat) return 6410;
  13793. if (p === DepthFormat) return 6402;
  13794. if (p === DepthStencilFormat) return 34041;
  13795. if (p === RedFormat) return 6403;
  13796. if (p === AddEquation) return 32774;
  13797. if (p === SubtractEquation) return 32778;
  13798. if (p === ReverseSubtractEquation) return 32779;
  13799. if (p === ZeroFactor) return 0;
  13800. if (p === OneFactor) return 1;
  13801. if (p === SrcColorFactor) return 768;
  13802. if (p === OneMinusSrcColorFactor) return 769;
  13803. if (p === SrcAlphaFactor) return 770;
  13804. if (p === OneMinusSrcAlphaFactor) return 771;
  13805. if (p === DstAlphaFactor) return 772;
  13806. if (p === OneMinusDstAlphaFactor) return 773;
  13807. if (p === DstColorFactor) return 774;
  13808. if (p === OneMinusDstColorFactor) return 775;
  13809. if (p === SrcAlphaSaturateFactor) return 776;
  13810. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  13811. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  13812. if (extension !== null) {
  13813. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13814. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13815. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13816. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13817. }
  13818. }
  13819. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  13820. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  13821. if (extension !== null) {
  13822. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13823. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13824. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13825. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13826. }
  13827. }
  13828. if (p === RGB_ETC1_Format) {
  13829. extension = extensions.get('WEBGL_compressed_texture_etc1');
  13830. if (extension !== null) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13831. }
  13832. 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) {
  13833. extension = extensions.get('WEBGL_compressed_texture_astc');
  13834. if (extension !== null) {
  13835. return p;
  13836. }
  13837. }
  13838. if (p === MinEquation || p === MaxEquation) {
  13839. if (capabilities.isWebGL2) {
  13840. if (p === MinEquation) return 32775;
  13841. if (p === MaxEquation) return 32776;
  13842. }
  13843. extension = extensions.get('EXT_blend_minmax');
  13844. if (extension !== null) {
  13845. if (p === MinEquation) return extension.MIN_EXT;
  13846. if (p === MaxEquation) return extension.MAX_EXT;
  13847. }
  13848. }
  13849. if (p === UnsignedInt248Type) {
  13850. if (capabilities.isWebGL2) return 34042;
  13851. extension = extensions.get('WEBGL_depth_texture');
  13852. if (extension !== null) return extension.UNSIGNED_INT_24_8_WEBGL;
  13853. }
  13854. return 0;
  13855. }
  13856. return {
  13857. convert: convert
  13858. };
  13859. }
  13860. /**
  13861. * @author fernandojsg / http://fernandojsg.com
  13862. * @author Takahiro https://github.com/takahirox
  13863. */
  13864. function WebGLMultiviewRenderTarget(width, height, numViews, options) {
  13865. WebGLRenderTarget.call(this, width, height, options);
  13866. this.depthBuffer = false;
  13867. this.stencilBuffer = false;
  13868. this.numViews = numViews;
  13869. }
  13870. WebGLMultiviewRenderTarget.prototype = Object.assign(Object.create(WebGLRenderTarget.prototype), {
  13871. constructor: WebGLMultiviewRenderTarget,
  13872. isWebGLMultiviewRenderTarget: true,
  13873. copy: function (source) {
  13874. WebGLRenderTarget.prototype.copy.call(this, source);
  13875. this.numViews = source.numViews;
  13876. return this;
  13877. },
  13878. setNumViews: function (numViews) {
  13879. if (this.numViews !== numViews) {
  13880. this.numViews = numViews;
  13881. this.dispose();
  13882. }
  13883. return this;
  13884. }
  13885. });
  13886. /**
  13887. * @author fernandojsg / http://fernandojsg.com
  13888. * @author Takahiro https://github.com/takahirox
  13889. */
  13890. function WebGLMultiview(renderer, gl) {
  13891. var DEFAULT_NUMVIEWS = 2;
  13892. var extensions = renderer.extensions;
  13893. var properties = renderer.properties;
  13894. var renderTarget, currentRenderTarget;
  13895. var mat3, mat4, cameraArray, renderSize;
  13896. var available;
  13897. var maxNumViews = 0; //
  13898. function isAvailable() {
  13899. if (available === undefined) {
  13900. var extension = extensions.get('OVR_multiview2');
  13901. available = extension !== null && gl.getContextAttributes().antialias === false;
  13902. if (available) {
  13903. maxNumViews = gl.getParameter(extension.MAX_VIEWS_OVR);
  13904. renderTarget = new WebGLMultiviewRenderTarget(0, 0, DEFAULT_NUMVIEWS);
  13905. renderSize = new Vector2();
  13906. mat4 = [];
  13907. mat3 = [];
  13908. cameraArray = [];
  13909. for (var i = 0; i < maxNumViews; i++) {
  13910. mat4[i] = new Matrix4();
  13911. mat3[i] = new Matrix3();
  13912. }
  13913. }
  13914. }
  13915. return available;
  13916. }
  13917. function getCameraArray(camera) {
  13918. if (camera.isArrayCamera) return camera.cameras;
  13919. cameraArray[0] = camera;
  13920. return cameraArray;
  13921. }
  13922. function updateCameraProjectionMatricesUniform(camera, uniforms) {
  13923. var cameras = getCameraArray(camera);
  13924. for (var i = 0; i < cameras.length; i++) {
  13925. mat4[i].copy(cameras[i].projectionMatrix);
  13926. }
  13927. uniforms.setValue(gl, 'projectionMatrices', mat4);
  13928. }
  13929. function updateCameraViewMatricesUniform(camera, uniforms) {
  13930. var cameras = getCameraArray(camera);
  13931. for (var i = 0; i < cameras.length; i++) {
  13932. mat4[i].copy(cameras[i].matrixWorldInverse);
  13933. }
  13934. uniforms.setValue(gl, 'viewMatrices', mat4);
  13935. }
  13936. function updateObjectMatricesUniforms(object, camera, uniforms) {
  13937. var cameras = getCameraArray(camera);
  13938. for (var i = 0; i < cameras.length; i++) {
  13939. mat4[i].multiplyMatrices(cameras[i].matrixWorldInverse, object.matrixWorld);
  13940. mat3[i].getNormalMatrix(mat4[i]);
  13941. }
  13942. uniforms.setValue(gl, 'modelViewMatrices', mat4);
  13943. uniforms.setValue(gl, 'normalMatrices', mat3);
  13944. }
  13945. function isMultiviewCompatible(camera) {
  13946. if (camera.isArrayCamera === undefined) return true;
  13947. var cameras = camera.cameras;
  13948. if (cameras.length > maxNumViews) return false;
  13949. for (var i = 1, il = cameras.length; i < il; i++) {
  13950. if (cameras[0].viewport.z !== cameras[i].viewport.z || cameras[0].viewport.w !== cameras[i].viewport.w) return false;
  13951. }
  13952. return true;
  13953. }
  13954. function resizeRenderTarget(camera) {
  13955. if (currentRenderTarget) {
  13956. renderSize.set(currentRenderTarget.width, currentRenderTarget.height);
  13957. } else {
  13958. renderer.getDrawingBufferSize(renderSize);
  13959. }
  13960. if (camera.isArrayCamera) {
  13961. var viewport = camera.cameras[0].viewport;
  13962. renderTarget.setSize(viewport.z, viewport.w);
  13963. renderTarget.setNumViews(camera.cameras.length);
  13964. } else {
  13965. renderTarget.setSize(renderSize.x, renderSize.y);
  13966. renderTarget.setNumViews(DEFAULT_NUMVIEWS);
  13967. }
  13968. }
  13969. function attachCamera(camera) {
  13970. if (isMultiviewCompatible(camera) === false) return;
  13971. currentRenderTarget = renderer.getRenderTarget();
  13972. resizeRenderTarget(camera);
  13973. renderer.setRenderTarget(renderTarget);
  13974. }
  13975. function detachCamera(camera) {
  13976. if (renderTarget !== renderer.getRenderTarget()) return;
  13977. renderer.setRenderTarget(currentRenderTarget);
  13978. flush(camera);
  13979. }
  13980. function flush(camera) {
  13981. var srcRenderTarget = renderTarget;
  13982. var numViews = srcRenderTarget.numViews;
  13983. var srcFramebuffers = properties.get(srcRenderTarget).__webglViewFramebuffers;
  13984. var viewWidth = srcRenderTarget.width;
  13985. var viewHeight = srcRenderTarget.height;
  13986. if (camera.isArrayCamera) {
  13987. for (var i = 0; i < numViews; i++) {
  13988. var viewport = camera.cameras[i].viewport;
  13989. var x1 = viewport.x;
  13990. var y1 = viewport.y;
  13991. var x2 = x1 + viewport.z;
  13992. var y2 = y1 + viewport.w;
  13993. gl.bindFramebuffer(36008, srcFramebuffers[i]);
  13994. gl.blitFramebuffer(0, 0, viewWidth, viewHeight, x1, y1, x2, y2, 16384, 9728);
  13995. }
  13996. } else {
  13997. gl.bindFramebuffer(36008, srcFramebuffers[0]);
  13998. gl.blitFramebuffer(0, 0, viewWidth, viewHeight, 0, 0, renderSize.x, renderSize.y, 16384, 9728);
  13999. }
  14000. }
  14001. this.isAvailable = isAvailable;
  14002. this.attachCamera = attachCamera;
  14003. this.detachCamera = detachCamera;
  14004. this.updateCameraProjectionMatricesUniform = updateCameraProjectionMatricesUniform;
  14005. this.updateCameraViewMatricesUniform = updateCameraViewMatricesUniform;
  14006. this.updateObjectMatricesUniforms = updateObjectMatricesUniforms;
  14007. }
  14008. /**
  14009. * @author mrdoob / http://mrdoob.com/
  14010. */
  14011. function Group() {
  14012. Object3D.call(this);
  14013. this.type = 'Group';
  14014. }
  14015. Group.prototype = Object.assign(Object.create(Object3D.prototype), {
  14016. constructor: Group,
  14017. isGroup: true
  14018. });
  14019. /**
  14020. * @author mrdoob / http://mrdoob.com/
  14021. */
  14022. function ArrayCamera(array) {
  14023. PerspectiveCamera.call(this);
  14024. this.cameras = array || [];
  14025. }
  14026. ArrayCamera.prototype = Object.assign(Object.create(PerspectiveCamera.prototype), {
  14027. constructor: ArrayCamera,
  14028. isArrayCamera: true
  14029. });
  14030. /**
  14031. * @author jsantell / https://www.jsantell.com/
  14032. * @author mrdoob / http://mrdoob.com/
  14033. */
  14034. var cameraLPos = new Vector3();
  14035. var cameraRPos = new Vector3();
  14036. /**
  14037. * Assumes 2 cameras that are parallel and share an X-axis, and that
  14038. * the cameras' projection and world matrices have already been set.
  14039. * And that near and far planes are identical for both cameras.
  14040. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  14041. */
  14042. function setProjectionFromUnion(camera, cameraL, cameraR) {
  14043. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  14044. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  14045. var ipd = cameraLPos.distanceTo(cameraRPos);
  14046. var projL = cameraL.projectionMatrix.elements;
  14047. var projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  14048. // most likely identical top and bottom frustum extents.
  14049. // Use the left camera for these values.
  14050. var near = projL[14] / (projL[10] - 1);
  14051. var far = projL[14] / (projL[10] + 1);
  14052. var topFov = (projL[9] + 1) / projL[5];
  14053. var bottomFov = (projL[9] - 1) / projL[5];
  14054. var leftFov = (projL[8] - 1) / projL[0];
  14055. var rightFov = (projR[8] + 1) / projR[0];
  14056. var left = near * leftFov;
  14057. var right = near * rightFov; // Calculate the new camera's position offset from the
  14058. // left camera. xOffset should be roughly half `ipd`.
  14059. var zOffset = ipd / (-leftFov + rightFov);
  14060. var xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  14061. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  14062. camera.translateX(xOffset);
  14063. camera.translateZ(zOffset);
  14064. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  14065. camera.matrixWorldInverse.getInverse(camera.matrixWorld); // Find the union of the frustum values of the cameras and scale
  14066. // the values so that the near plane's position does not change in world space,
  14067. // although must now be relative to the new union camera.
  14068. var near2 = near + zOffset;
  14069. var far2 = far + zOffset;
  14070. var left2 = left - xOffset;
  14071. var right2 = right + (ipd - xOffset);
  14072. var top2 = topFov * far / far2 * near2;
  14073. var bottom2 = bottomFov * far / far2 * near2;
  14074. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  14075. }
  14076. /**
  14077. * @author mrdoob / http://mrdoob.com/
  14078. */
  14079. function WebVRManager(renderer) {
  14080. var renderWidth, renderHeight;
  14081. var scope = this;
  14082. var device = null;
  14083. var frameData = null;
  14084. var poseTarget = null;
  14085. var controllers = [];
  14086. var standingMatrix = new Matrix4();
  14087. var standingMatrixInverse = new Matrix4();
  14088. var framebufferScaleFactor = 1.0;
  14089. var referenceSpaceType = 'local-floor';
  14090. if (typeof window !== 'undefined' && 'VRFrameData' in window) {
  14091. frameData = new window.VRFrameData();
  14092. window.addEventListener('vrdisplaypresentchange', onVRDisplayPresentChange, false);
  14093. }
  14094. var matrixWorldInverse = new Matrix4();
  14095. var tempQuaternion = new Quaternion();
  14096. var tempPosition = new Vector3();
  14097. var cameraL = new PerspectiveCamera();
  14098. cameraL.viewport = new Vector4();
  14099. cameraL.layers.enable(1);
  14100. var cameraR = new PerspectiveCamera();
  14101. cameraR.viewport = new Vector4();
  14102. cameraR.layers.enable(2);
  14103. var cameraVR = new ArrayCamera([cameraL, cameraR]);
  14104. cameraVR.layers.enable(1);
  14105. cameraVR.layers.enable(2); //
  14106. function isPresenting() {
  14107. return device !== null && device.isPresenting === true;
  14108. }
  14109. var currentSize = new Vector2(),
  14110. currentPixelRatio;
  14111. function onVRDisplayPresentChange() {
  14112. if (isPresenting()) {
  14113. var eyeParameters = device.getEyeParameters('left');
  14114. renderWidth = 2 * eyeParameters.renderWidth * framebufferScaleFactor;
  14115. renderHeight = eyeParameters.renderHeight * framebufferScaleFactor;
  14116. currentPixelRatio = renderer.getPixelRatio();
  14117. renderer.getSize(currentSize);
  14118. renderer.setDrawingBufferSize(renderWidth, renderHeight, 1);
  14119. cameraL.viewport.set(0, 0, renderWidth / 2, renderHeight);
  14120. cameraR.viewport.set(renderWidth / 2, 0, renderWidth / 2, renderHeight);
  14121. animation.start();
  14122. scope.dispatchEvent({
  14123. type: 'sessionstart'
  14124. });
  14125. } else {
  14126. if (scope.enabled) {
  14127. renderer.setDrawingBufferSize(currentSize.width, currentSize.height, currentPixelRatio);
  14128. }
  14129. animation.stop();
  14130. scope.dispatchEvent({
  14131. type: 'sessionend'
  14132. });
  14133. }
  14134. } //
  14135. var triggers = [];
  14136. function findGamepad(id) {
  14137. var gamepads = navigator.getGamepads && navigator.getGamepads();
  14138. for (var i = 0, j = 0, l = gamepads.length; i < l; i++) {
  14139. var gamepad = gamepads[i];
  14140. 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'))) {
  14141. if (j === id) return gamepad;
  14142. j++;
  14143. }
  14144. }
  14145. }
  14146. function updateControllers() {
  14147. for (var i = 0; i < controllers.length; i++) {
  14148. var controller = controllers[i];
  14149. var gamepad = findGamepad(i);
  14150. if (gamepad !== undefined && gamepad.pose !== undefined) {
  14151. if (gamepad.pose === null) return; // Pose
  14152. var pose = gamepad.pose;
  14153. if (pose.hasPosition === false) controller.position.set(0.2, -0.6, -0.05);
  14154. if (pose.position !== null) controller.position.fromArray(pose.position);
  14155. if (pose.orientation !== null) controller.quaternion.fromArray(pose.orientation);
  14156. controller.matrix.compose(controller.position, controller.quaternion, controller.scale);
  14157. controller.matrix.premultiply(standingMatrix);
  14158. controller.matrix.decompose(controller.position, controller.quaternion, controller.scale);
  14159. controller.matrixWorldNeedsUpdate = true;
  14160. controller.visible = true; // Trigger
  14161. var buttonId = gamepad.id === 'Daydream Controller' ? 0 : 1;
  14162. if (triggers[i] === undefined) triggers[i] = false;
  14163. if (triggers[i] !== gamepad.buttons[buttonId].pressed) {
  14164. triggers[i] = gamepad.buttons[buttonId].pressed;
  14165. if (triggers[i] === true) {
  14166. controller.dispatchEvent({
  14167. type: 'selectstart'
  14168. });
  14169. } else {
  14170. controller.dispatchEvent({
  14171. type: 'selectend'
  14172. });
  14173. controller.dispatchEvent({
  14174. type: 'select'
  14175. });
  14176. }
  14177. }
  14178. } else {
  14179. controller.visible = false;
  14180. }
  14181. }
  14182. }
  14183. function updateViewportFromBounds(viewport, bounds) {
  14184. if (bounds !== null && bounds.length === 4) {
  14185. viewport.set(bounds[0] * renderWidth, bounds[1] * renderHeight, bounds[2] * renderWidth, bounds[3] * renderHeight);
  14186. }
  14187. } //
  14188. this.enabled = false;
  14189. this.getController = function (id) {
  14190. var controller = controllers[id];
  14191. if (controller === undefined) {
  14192. controller = new Group();
  14193. controller.matrixAutoUpdate = false;
  14194. controller.visible = false;
  14195. controllers[id] = controller;
  14196. }
  14197. return controller;
  14198. };
  14199. this.getDevice = function () {
  14200. return device;
  14201. };
  14202. this.setDevice = function (value) {
  14203. if (value !== undefined) device = value;
  14204. animation.setContext(value);
  14205. };
  14206. this.setFramebufferScaleFactor = function (value) {
  14207. framebufferScaleFactor = value;
  14208. };
  14209. this.setReferenceSpaceType = function (value) {
  14210. referenceSpaceType = value;
  14211. };
  14212. this.setPoseTarget = function (object) {
  14213. if (object !== undefined) poseTarget = object;
  14214. };
  14215. this.getCamera = function (camera) {
  14216. var userHeight = referenceSpaceType === 'local-floor' ? 1.6 : 0;
  14217. if (isPresenting() === false) {
  14218. camera.position.set(0, userHeight, 0);
  14219. camera.rotation.set(0, 0, 0);
  14220. return camera;
  14221. }
  14222. device.depthNear = camera.near;
  14223. device.depthFar = camera.far;
  14224. device.getFrameData(frameData); //
  14225. if (referenceSpaceType === 'local-floor') {
  14226. var stageParameters = device.stageParameters;
  14227. if (stageParameters) {
  14228. standingMatrix.fromArray(stageParameters.sittingToStandingTransform);
  14229. } else {
  14230. standingMatrix.makeTranslation(0, userHeight, 0);
  14231. }
  14232. }
  14233. var pose = frameData.pose;
  14234. var poseObject = poseTarget !== null ? poseTarget : camera; // We want to manipulate poseObject by its position and quaternion components since users may rely on them.
  14235. poseObject.matrix.copy(standingMatrix);
  14236. poseObject.matrix.decompose(poseObject.position, poseObject.quaternion, poseObject.scale);
  14237. if (pose.orientation !== null) {
  14238. tempQuaternion.fromArray(pose.orientation);
  14239. poseObject.quaternion.multiply(tempQuaternion);
  14240. }
  14241. if (pose.position !== null) {
  14242. tempQuaternion.setFromRotationMatrix(standingMatrix);
  14243. tempPosition.fromArray(pose.position);
  14244. tempPosition.applyQuaternion(tempQuaternion);
  14245. poseObject.position.add(tempPosition);
  14246. }
  14247. poseObject.updateMatrixWorld(); //
  14248. cameraL.near = camera.near;
  14249. cameraR.near = camera.near;
  14250. cameraL.far = camera.far;
  14251. cameraR.far = camera.far;
  14252. cameraL.matrixWorldInverse.fromArray(frameData.leftViewMatrix);
  14253. cameraR.matrixWorldInverse.fromArray(frameData.rightViewMatrix); // TODO (mrdoob) Double check this code
  14254. standingMatrixInverse.getInverse(standingMatrix);
  14255. if (referenceSpaceType === 'local-floor') {
  14256. cameraL.matrixWorldInverse.multiply(standingMatrixInverse);
  14257. cameraR.matrixWorldInverse.multiply(standingMatrixInverse);
  14258. }
  14259. var parent = poseObject.parent;
  14260. if (parent !== null) {
  14261. matrixWorldInverse.getInverse(parent.matrixWorld);
  14262. cameraL.matrixWorldInverse.multiply(matrixWorldInverse);
  14263. cameraR.matrixWorldInverse.multiply(matrixWorldInverse);
  14264. } // envMap and Mirror needs camera.matrixWorld
  14265. cameraL.matrixWorld.getInverse(cameraL.matrixWorldInverse);
  14266. cameraR.matrixWorld.getInverse(cameraR.matrixWorldInverse);
  14267. cameraL.projectionMatrix.fromArray(frameData.leftProjectionMatrix);
  14268. cameraR.projectionMatrix.fromArray(frameData.rightProjectionMatrix);
  14269. setProjectionFromUnion(cameraVR, cameraL, cameraR); //
  14270. var layers = device.getLayers();
  14271. if (layers.length) {
  14272. var layer = layers[0];
  14273. updateViewportFromBounds(cameraL.viewport, layer.leftBounds);
  14274. updateViewportFromBounds(cameraR.viewport, layer.rightBounds);
  14275. }
  14276. updateControllers();
  14277. return cameraVR;
  14278. };
  14279. this.getStandingMatrix = function () {
  14280. return standingMatrix;
  14281. };
  14282. this.isPresenting = isPresenting; // Animation Loop
  14283. var animation = new WebGLAnimation();
  14284. this.setAnimationLoop = function (callback) {
  14285. animation.setAnimationLoop(callback);
  14286. if (isPresenting()) animation.start();
  14287. };
  14288. this.submitFrame = function () {
  14289. if (isPresenting()) device.submitFrame();
  14290. };
  14291. this.dispose = function () {
  14292. if (typeof window !== 'undefined') {
  14293. window.removeEventListener('vrdisplaypresentchange', onVRDisplayPresentChange);
  14294. }
  14295. }; // DEPRECATED
  14296. this.setFrameOfReferenceType = function () {
  14297. console.warn('THREE.WebVRManager: setFrameOfReferenceType() has been deprecated.');
  14298. };
  14299. }
  14300. Object.assign(WebVRManager.prototype, EventDispatcher.prototype);
  14301. /**
  14302. * @author mrdoob / http://mrdoob.com/
  14303. */
  14304. function WebXRManager(renderer, gl) {
  14305. var scope = this;
  14306. var session = null; // var framebufferScaleFactor = 1.0;
  14307. var referenceSpace = null;
  14308. var referenceSpaceType = 'local-floor';
  14309. var pose = null;
  14310. var controllers = [];
  14311. var inputSources = [];
  14312. function isPresenting() {
  14313. return session !== null && referenceSpace !== null;
  14314. } //
  14315. var cameraL = new PerspectiveCamera();
  14316. cameraL.layers.enable(1);
  14317. cameraL.viewport = new Vector4();
  14318. var cameraR = new PerspectiveCamera();
  14319. cameraR.layers.enable(2);
  14320. cameraR.viewport = new Vector4();
  14321. var cameraVR = new ArrayCamera([cameraL, cameraR]);
  14322. cameraVR.layers.enable(1);
  14323. cameraVR.layers.enable(2); //
  14324. this.enabled = false;
  14325. this.getController = function (id) {
  14326. var controller = controllers[id];
  14327. if (controller === undefined) {
  14328. controller = new Group();
  14329. controller.matrixAutoUpdate = false;
  14330. controller.visible = false;
  14331. controllers[id] = controller;
  14332. }
  14333. return controller;
  14334. }; //
  14335. function onSessionEvent(event) {
  14336. for (var i = 0; i < controllers.length; i++) {
  14337. if (inputSources[i] === event.inputSource) {
  14338. controllers[i].dispatchEvent({
  14339. type: event.type
  14340. });
  14341. }
  14342. }
  14343. }
  14344. function onSessionEnd() {
  14345. renderer.setFramebuffer(null);
  14346. renderer.setRenderTarget(renderer.getRenderTarget()); // Hack #15830
  14347. animation.stop();
  14348. scope.dispatchEvent({
  14349. type: 'sessionend'
  14350. });
  14351. }
  14352. function onRequestReferenceSpace(value) {
  14353. referenceSpace = value;
  14354. animation.setContext(session);
  14355. animation.start();
  14356. scope.dispatchEvent({
  14357. type: 'sessionstart'
  14358. });
  14359. }
  14360. this.setFramebufferScaleFactor = function ()
  14361. /* value */
  14362. {// framebufferScaleFactor = value;
  14363. };
  14364. this.setReferenceSpaceType = function (value) {
  14365. referenceSpaceType = value;
  14366. };
  14367. this.getSession = function () {
  14368. return session;
  14369. };
  14370. this.setSession = function (value) {
  14371. session = value;
  14372. if (session !== null) {
  14373. session.addEventListener('select', onSessionEvent);
  14374. session.addEventListener('selectstart', onSessionEvent);
  14375. session.addEventListener('selectend', onSessionEvent);
  14376. session.addEventListener('end', onSessionEnd); // eslint-disable-next-line no-undef
  14377. session.updateRenderState({
  14378. baseLayer: new XRWebGLLayer(session, gl)
  14379. });
  14380. session.requestReferenceSpace(referenceSpaceType).then(onRequestReferenceSpace); //
  14381. inputSources = session.inputSources;
  14382. session.addEventListener('inputsourceschange', function () {
  14383. inputSources = session.inputSources;
  14384. console.log(inputSources);
  14385. for (var i = 0; i < controllers.length; i++) {
  14386. var controller = controllers[i];
  14387. controller.userData.inputSource = inputSources[i];
  14388. }
  14389. });
  14390. }
  14391. };
  14392. function updateCamera(camera, parent) {
  14393. if (parent === null) {
  14394. camera.matrixWorld.copy(camera.matrix);
  14395. } else {
  14396. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  14397. }
  14398. camera.matrixWorldInverse.getInverse(camera.matrixWorld);
  14399. }
  14400. this.getCamera = function (camera) {
  14401. if (isPresenting()) {
  14402. var parent = camera.parent;
  14403. var cameras = cameraVR.cameras;
  14404. updateCamera(cameraVR, parent);
  14405. for (var i = 0; i < cameras.length; i++) {
  14406. updateCamera(cameras[i], parent);
  14407. } // update camera and its children
  14408. camera.matrixWorld.copy(cameraVR.matrixWorld);
  14409. var children = camera.children;
  14410. for (var i = 0, l = children.length; i < l; i++) {
  14411. children[i].updateMatrixWorld(true);
  14412. }
  14413. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  14414. return cameraVR;
  14415. }
  14416. return camera;
  14417. };
  14418. this.isPresenting = isPresenting; // Animation Loop
  14419. var onAnimationFrameCallback = null;
  14420. function onAnimationFrame(time, frame) {
  14421. pose = frame.getViewerPose(referenceSpace);
  14422. if (pose !== null) {
  14423. var views = pose.views;
  14424. var baseLayer = session.renderState.baseLayer;
  14425. renderer.setFramebuffer(baseLayer.framebuffer);
  14426. for (var i = 0; i < views.length; i++) {
  14427. var view = views[i];
  14428. var viewport = baseLayer.getViewport(view);
  14429. var viewMatrix = view.transform.inverse.matrix;
  14430. var camera = cameraVR.cameras[i];
  14431. camera.matrix.fromArray(viewMatrix).getInverse(camera.matrix);
  14432. camera.projectionMatrix.fromArray(view.projectionMatrix);
  14433. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  14434. if (i === 0) {
  14435. cameraVR.matrix.copy(camera.matrix);
  14436. }
  14437. }
  14438. } //
  14439. for (var i = 0; i < controllers.length; i++) {
  14440. var controller = controllers[i];
  14441. var inputSource = inputSources[i];
  14442. if (inputSource) {
  14443. var inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  14444. if (inputPose !== null) {
  14445. controller.matrix.fromArray(inputPose.transform.matrix);
  14446. controller.matrix.decompose(controller.position, controller.rotation, controller.scale);
  14447. controller.visible = true;
  14448. continue;
  14449. }
  14450. }
  14451. controller.visible = false;
  14452. }
  14453. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  14454. }
  14455. var animation = new WebGLAnimation();
  14456. animation.setAnimationLoop(onAnimationFrame);
  14457. this.setAnimationLoop = function (callback) {
  14458. onAnimationFrameCallback = callback;
  14459. };
  14460. this.dispose = function () {}; // DEPRECATED
  14461. this.getStandingMatrix = function () {
  14462. console.warn('THREE.WebXRManager: getStandingMatrix() is no longer needed.');
  14463. return new Matrix4();
  14464. };
  14465. this.getDevice = function () {
  14466. console.warn('THREE.WebXRManager: getDevice() has been deprecated.');
  14467. };
  14468. this.setDevice = function () {
  14469. console.warn('THREE.WebXRManager: setDevice() has been deprecated.');
  14470. };
  14471. this.setFrameOfReferenceType = function () {
  14472. console.warn('THREE.WebXRManager: setFrameOfReferenceType() has been deprecated.');
  14473. };
  14474. this.submitFrame = function () {};
  14475. }
  14476. Object.assign(WebXRManager.prototype, EventDispatcher.prototype);
  14477. /**
  14478. * @author supereggbert / http://www.paulbrunt.co.uk/
  14479. * @author mrdoob / http://mrdoob.com/
  14480. * @author alteredq / http://alteredqualia.com/
  14481. * @author szimek / https://github.com/szimek/
  14482. * @author tschw
  14483. */
  14484. function WebGLRenderer(parameters) {
  14485. parameters = parameters || {};
  14486. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas'),
  14487. _context = parameters.context !== undefined ? parameters.context : null,
  14488. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  14489. _depth = parameters.depth !== undefined ? parameters.depth : true,
  14490. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  14491. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  14492. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  14493. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  14494. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  14495. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  14496. var currentRenderList = null;
  14497. var currentRenderState = null; // public properties
  14498. this.domElement = _canvas; // Debug configuration container
  14499. this.debug = {
  14500. /**
  14501. * Enables error checking and reporting when shader programs are being compiled
  14502. * @type {boolean}
  14503. */
  14504. checkShaderErrors: true
  14505. }; // clearing
  14506. this.autoClear = true;
  14507. this.autoClearColor = true;
  14508. this.autoClearDepth = true;
  14509. this.autoClearStencil = true; // scene graph
  14510. this.sortObjects = true; // user-defined clipping
  14511. this.clippingPlanes = [];
  14512. this.localClippingEnabled = false; // physically based shading
  14513. this.gammaFactor = 2.0; // for backwards compatibility
  14514. this.gammaInput = false;
  14515. this.gammaOutput = false; // physical lights
  14516. this.physicallyCorrectLights = false; // tone mapping
  14517. this.toneMapping = LinearToneMapping;
  14518. this.toneMappingExposure = 1.0;
  14519. this.toneMappingWhitePoint = 1.0; // morphs
  14520. this.maxMorphTargets = 8;
  14521. this.maxMorphNormals = 4; // internal properties
  14522. var _this = this,
  14523. _isContextLost = false,
  14524. // internal state cache
  14525. _framebuffer = null,
  14526. _currentActiveCubeFace = 0,
  14527. _currentActiveMipmapLevel = 0,
  14528. _currentRenderTarget = null,
  14529. _currentFramebuffer = null,
  14530. _currentMaterialId = -1,
  14531. // geometry and program caching
  14532. _currentGeometryProgram = {
  14533. geometry: null,
  14534. program: null,
  14535. wireframe: false
  14536. },
  14537. _currentCamera = null,
  14538. _currentArrayCamera = null,
  14539. _currentViewport = new Vector4(),
  14540. _currentScissor = new Vector4(),
  14541. _currentScissorTest = null,
  14542. //
  14543. _width = _canvas.width,
  14544. _height = _canvas.height,
  14545. _pixelRatio = 1,
  14546. _viewport = new Vector4(0, 0, _width, _height),
  14547. _scissor = new Vector4(0, 0, _width, _height),
  14548. _scissorTest = false,
  14549. // frustum
  14550. _frustum = new Frustum(),
  14551. // clipping
  14552. _clipping = new WebGLClipping(),
  14553. _clippingEnabled = false,
  14554. _localClippingEnabled = false,
  14555. // camera matrices cache
  14556. _projScreenMatrix = new Matrix4(),
  14557. _vector3 = new Vector3();
  14558. function getTargetPixelRatio() {
  14559. return _currentRenderTarget === null ? _pixelRatio : 1;
  14560. } // initialize
  14561. var _gl;
  14562. try {
  14563. var contextAttributes = {
  14564. alpha: _alpha,
  14565. depth: _depth,
  14566. stencil: _stencil,
  14567. antialias: _antialias,
  14568. premultipliedAlpha: _premultipliedAlpha,
  14569. preserveDrawingBuffer: _preserveDrawingBuffer,
  14570. powerPreference: _powerPreference,
  14571. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat,
  14572. xrCompatible: true
  14573. }; // event listeners must be registered before WebGL context is created, see #12753
  14574. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  14575. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  14576. _gl = _context || _canvas.getContext('webgl', contextAttributes) || _canvas.getContext('experimental-webgl', contextAttributes);
  14577. if (_gl === null) {
  14578. if (_canvas.getContext('webgl') !== null) {
  14579. throw new Error('Error creating WebGL context with your selected attributes.');
  14580. } else {
  14581. throw new Error('Error creating WebGL context.');
  14582. }
  14583. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  14584. if (_gl.getShaderPrecisionFormat === undefined) {
  14585. _gl.getShaderPrecisionFormat = function () {
  14586. return {
  14587. 'rangeMin': 1,
  14588. 'rangeMax': 1,
  14589. 'precision': 1
  14590. };
  14591. };
  14592. }
  14593. } catch (error) {
  14594. console.error('THREE.WebGLRenderer: ' + error.message);
  14595. throw error;
  14596. }
  14597. var extensions, capabilities, state, info;
  14598. var properties, textures, attributes, geometries, objects;
  14599. var programCache, renderLists, renderStates;
  14600. var background, morphtargets, bufferRenderer, indexedBufferRenderer;
  14601. var utils;
  14602. function initGLContext() {
  14603. extensions = new WebGLExtensions(_gl);
  14604. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  14605. if (capabilities.isWebGL2 === false) {
  14606. extensions.get('WEBGL_depth_texture');
  14607. extensions.get('OES_texture_float');
  14608. extensions.get('OES_texture_half_float');
  14609. extensions.get('OES_texture_half_float_linear');
  14610. extensions.get('OES_standard_derivatives');
  14611. extensions.get('OES_element_index_uint');
  14612. extensions.get('ANGLE_instanced_arrays');
  14613. }
  14614. extensions.get('OES_texture_float_linear');
  14615. utils = new WebGLUtils(_gl, extensions, capabilities);
  14616. state = new WebGLState(_gl, extensions, utils, capabilities);
  14617. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  14618. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  14619. info = new WebGLInfo(_gl);
  14620. properties = new WebGLProperties();
  14621. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  14622. attributes = new WebGLAttributes(_gl);
  14623. geometries = new WebGLGeometries(_gl, attributes, info);
  14624. objects = new WebGLObjects(_gl, geometries, attributes, info);
  14625. morphtargets = new WebGLMorphtargets(_gl);
  14626. programCache = new WebGLPrograms(_this, extensions, capabilities);
  14627. renderLists = new WebGLRenderLists();
  14628. renderStates = new WebGLRenderStates();
  14629. background = new WebGLBackground(_this, state, objects, _premultipliedAlpha);
  14630. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  14631. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  14632. info.programs = programCache.programs;
  14633. _this.capabilities = capabilities;
  14634. _this.extensions = extensions;
  14635. _this.properties = properties;
  14636. _this.renderLists = renderLists;
  14637. _this.state = state;
  14638. _this.info = info;
  14639. }
  14640. initGLContext(); // vr
  14641. var vr = typeof navigator !== 'undefined' && 'xr' in navigator && 'supportsSession' in navigator.xr ? new WebXRManager(_this, _gl) : new WebVRManager(_this);
  14642. this.vr = vr; // Multiview
  14643. var multiview = new WebGLMultiview(_this, _gl); // shadow map
  14644. var shadowMap = new WebGLShadowMap(_this, objects, capabilities.maxTextureSize);
  14645. this.shadowMap = shadowMap; // API
  14646. this.getContext = function () {
  14647. return _gl;
  14648. };
  14649. this.getContextAttributes = function () {
  14650. return _gl.getContextAttributes();
  14651. };
  14652. this.forceContextLoss = function () {
  14653. var extension = extensions.get('WEBGL_lose_context');
  14654. if (extension) extension.loseContext();
  14655. };
  14656. this.forceContextRestore = function () {
  14657. var extension = extensions.get('WEBGL_lose_context');
  14658. if (extension) extension.restoreContext();
  14659. };
  14660. this.getPixelRatio = function () {
  14661. return _pixelRatio;
  14662. };
  14663. this.setPixelRatio = function (value) {
  14664. if (value === undefined) return;
  14665. _pixelRatio = value;
  14666. this.setSize(_width, _height, false);
  14667. };
  14668. this.getSize = function (target) {
  14669. if (target === undefined) {
  14670. console.warn('WebGLRenderer: .getsize() now requires a Vector2 as an argument');
  14671. target = new Vector2();
  14672. }
  14673. return target.set(_width, _height);
  14674. };
  14675. this.setSize = function (width, height, updateStyle) {
  14676. if (vr.isPresenting()) {
  14677. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  14678. return;
  14679. }
  14680. _width = width;
  14681. _height = height;
  14682. _canvas.width = Math.floor(width * _pixelRatio);
  14683. _canvas.height = Math.floor(height * _pixelRatio);
  14684. if (updateStyle !== false) {
  14685. _canvas.style.width = width + 'px';
  14686. _canvas.style.height = height + 'px';
  14687. }
  14688. this.setViewport(0, 0, width, height);
  14689. };
  14690. this.getDrawingBufferSize = function (target) {
  14691. if (target === undefined) {
  14692. console.warn('WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument');
  14693. target = new Vector2();
  14694. }
  14695. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  14696. };
  14697. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  14698. _width = width;
  14699. _height = height;
  14700. _pixelRatio = pixelRatio;
  14701. _canvas.width = Math.floor(width * pixelRatio);
  14702. _canvas.height = Math.floor(height * pixelRatio);
  14703. this.setViewport(0, 0, width, height);
  14704. };
  14705. this.getCurrentViewport = function (target) {
  14706. if (target === undefined) {
  14707. console.warn('WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument');
  14708. target = new Vector4();
  14709. }
  14710. return target.copy(_currentViewport);
  14711. };
  14712. this.getViewport = function (target) {
  14713. return target.copy(_viewport);
  14714. };
  14715. this.setViewport = function (x, y, width, height) {
  14716. if (x.isVector4) {
  14717. _viewport.set(x.x, x.y, x.z, x.w);
  14718. } else {
  14719. _viewport.set(x, y, width, height);
  14720. }
  14721. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  14722. };
  14723. this.getScissor = function (target) {
  14724. return target.copy(_scissor);
  14725. };
  14726. this.setScissor = function (x, y, width, height) {
  14727. if (x.isVector4) {
  14728. _scissor.set(x.x, x.y, x.z, x.w);
  14729. } else {
  14730. _scissor.set(x, y, width, height);
  14731. }
  14732. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  14733. };
  14734. this.getScissorTest = function () {
  14735. return _scissorTest;
  14736. };
  14737. this.setScissorTest = function (boolean) {
  14738. state.setScissorTest(_scissorTest = boolean);
  14739. }; // Clearing
  14740. this.getClearColor = function () {
  14741. return background.getClearColor();
  14742. };
  14743. this.setClearColor = function () {
  14744. background.setClearColor.apply(background, arguments);
  14745. };
  14746. this.getClearAlpha = function () {
  14747. return background.getClearAlpha();
  14748. };
  14749. this.setClearAlpha = function () {
  14750. background.setClearAlpha.apply(background, arguments);
  14751. };
  14752. this.clear = function (color, depth, stencil) {
  14753. var bits = 0;
  14754. if (color === undefined || color) bits |= 16384;
  14755. if (depth === undefined || depth) bits |= 256;
  14756. if (stencil === undefined || stencil) bits |= 1024;
  14757. _gl.clear(bits);
  14758. };
  14759. this.clearColor = function () {
  14760. this.clear(true, false, false);
  14761. };
  14762. this.clearDepth = function () {
  14763. this.clear(false, true, false);
  14764. };
  14765. this.clearStencil = function () {
  14766. this.clear(false, false, true);
  14767. }; //
  14768. this.dispose = function () {
  14769. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  14770. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  14771. renderLists.dispose();
  14772. renderStates.dispose();
  14773. properties.dispose();
  14774. objects.dispose();
  14775. vr.dispose();
  14776. animation.stop();
  14777. }; // Events
  14778. function onContextLost(event) {
  14779. event.preventDefault();
  14780. console.log('THREE.WebGLRenderer: Context Lost.');
  14781. _isContextLost = true;
  14782. }
  14783. function onContextRestore()
  14784. /* event */
  14785. {
  14786. console.log('THREE.WebGLRenderer: Context Restored.');
  14787. _isContextLost = false;
  14788. initGLContext();
  14789. }
  14790. function onMaterialDispose(event) {
  14791. var material = event.target;
  14792. material.removeEventListener('dispose', onMaterialDispose);
  14793. deallocateMaterial(material);
  14794. } // Buffer deallocation
  14795. function deallocateMaterial(material) {
  14796. releaseMaterialProgramReference(material);
  14797. properties.remove(material);
  14798. }
  14799. function releaseMaterialProgramReference(material) {
  14800. var programInfo = properties.get(material).program;
  14801. material.program = undefined;
  14802. if (programInfo !== undefined) {
  14803. programCache.releaseProgram(programInfo);
  14804. }
  14805. } // Buffer rendering
  14806. function renderObjectImmediate(object, program) {
  14807. object.render(function (object) {
  14808. _this.renderBufferImmediate(object, program);
  14809. });
  14810. }
  14811. this.renderBufferImmediate = function (object, program) {
  14812. state.initAttributes();
  14813. var buffers = properties.get(object);
  14814. if (object.hasPositions && !buffers.position) buffers.position = _gl.createBuffer();
  14815. if (object.hasNormals && !buffers.normal) buffers.normal = _gl.createBuffer();
  14816. if (object.hasUvs && !buffers.uv) buffers.uv = _gl.createBuffer();
  14817. if (object.hasColors && !buffers.color) buffers.color = _gl.createBuffer();
  14818. var programAttributes = program.getAttributes();
  14819. if (object.hasPositions) {
  14820. _gl.bindBuffer(34962, buffers.position);
  14821. _gl.bufferData(34962, object.positionArray, 35048);
  14822. state.enableAttribute(programAttributes.position);
  14823. _gl.vertexAttribPointer(programAttributes.position, 3, 5126, false, 0, 0);
  14824. }
  14825. if (object.hasNormals) {
  14826. _gl.bindBuffer(34962, buffers.normal);
  14827. _gl.bufferData(34962, object.normalArray, 35048);
  14828. state.enableAttribute(programAttributes.normal);
  14829. _gl.vertexAttribPointer(programAttributes.normal, 3, 5126, false, 0, 0);
  14830. }
  14831. if (object.hasUvs) {
  14832. _gl.bindBuffer(34962, buffers.uv);
  14833. _gl.bufferData(34962, object.uvArray, 35048);
  14834. state.enableAttribute(programAttributes.uv);
  14835. _gl.vertexAttribPointer(programAttributes.uv, 2, 5126, false, 0, 0);
  14836. }
  14837. if (object.hasColors) {
  14838. _gl.bindBuffer(34962, buffers.color);
  14839. _gl.bufferData(34962, object.colorArray, 35048);
  14840. state.enableAttribute(programAttributes.color);
  14841. _gl.vertexAttribPointer(programAttributes.color, 3, 5126, false, 0, 0);
  14842. }
  14843. state.disableUnusedAttributes();
  14844. _gl.drawArrays(4, 0, object.count);
  14845. object.count = 0;
  14846. };
  14847. this.renderBufferDirect = function (camera, fog, geometry, material, object, group) {
  14848. var frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  14849. state.setMaterial(material, frontFaceCW);
  14850. var program = setProgram(camera, fog, material, object);
  14851. var updateBuffers = false;
  14852. if (_currentGeometryProgram.geometry !== geometry.id || _currentGeometryProgram.program !== program.id || _currentGeometryProgram.wireframe !== (material.wireframe === true)) {
  14853. _currentGeometryProgram.geometry = geometry.id;
  14854. _currentGeometryProgram.program = program.id;
  14855. _currentGeometryProgram.wireframe = material.wireframe === true;
  14856. updateBuffers = true;
  14857. }
  14858. if (object.morphTargetInfluences) {
  14859. morphtargets.update(object, geometry, material, program);
  14860. updateBuffers = true;
  14861. } //
  14862. var index = geometry.index;
  14863. var position = geometry.attributes.position;
  14864. var rangeFactor = 1;
  14865. if (material.wireframe === true) {
  14866. index = geometries.getWireframeAttribute(geometry);
  14867. rangeFactor = 2;
  14868. }
  14869. var attribute;
  14870. var renderer = bufferRenderer;
  14871. if (index !== null) {
  14872. attribute = attributes.get(index);
  14873. renderer = indexedBufferRenderer;
  14874. renderer.setIndex(attribute);
  14875. }
  14876. if (updateBuffers) {
  14877. setupVertexAttributes(object, geometry, material, program);
  14878. if (index !== null) {
  14879. _gl.bindBuffer(34963, attribute.buffer);
  14880. }
  14881. } //
  14882. var dataCount = Infinity;
  14883. if (index !== null) {
  14884. dataCount = index.count;
  14885. } else if (position !== undefined) {
  14886. dataCount = position.count;
  14887. }
  14888. var rangeStart = geometry.drawRange.start * rangeFactor;
  14889. var rangeCount = geometry.drawRange.count * rangeFactor;
  14890. var groupStart = group !== null ? group.start * rangeFactor : 0;
  14891. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  14892. var drawStart = Math.max(rangeStart, groupStart);
  14893. var drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  14894. var drawCount = Math.max(0, drawEnd - drawStart + 1);
  14895. if (drawCount === 0) return; //
  14896. if (object.isMesh) {
  14897. if (material.wireframe === true) {
  14898. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  14899. renderer.setMode(1);
  14900. } else {
  14901. switch (object.drawMode) {
  14902. case TrianglesDrawMode:
  14903. renderer.setMode(4);
  14904. break;
  14905. case TriangleStripDrawMode:
  14906. renderer.setMode(5);
  14907. break;
  14908. case TriangleFanDrawMode:
  14909. renderer.setMode(6);
  14910. break;
  14911. }
  14912. }
  14913. } else if (object.isLine) {
  14914. var lineWidth = material.linewidth;
  14915. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  14916. state.setLineWidth(lineWidth * getTargetPixelRatio());
  14917. if (object.isLineSegments) {
  14918. renderer.setMode(1);
  14919. } else if (object.isLineLoop) {
  14920. renderer.setMode(2);
  14921. } else {
  14922. renderer.setMode(3);
  14923. }
  14924. } else if (object.isPoints) {
  14925. renderer.setMode(0);
  14926. } else if (object.isSprite) {
  14927. renderer.setMode(4);
  14928. }
  14929. if (object.isInstancedMesh) {
  14930. renderer.renderInstances(geometry, drawStart, drawCount, object.count);
  14931. } else if (geometry.isInstancedBufferGeometry) {
  14932. renderer.renderInstances(geometry, drawStart, drawCount, geometry.maxInstancedCount);
  14933. } else {
  14934. renderer.render(drawStart, drawCount);
  14935. }
  14936. };
  14937. function setupVertexAttributes(object, geometry, material, program) {
  14938. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  14939. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  14940. }
  14941. state.initAttributes();
  14942. var geometryAttributes = geometry.attributes;
  14943. var programAttributes = program.getAttributes();
  14944. var materialDefaultAttributeValues = material.defaultAttributeValues;
  14945. for (var name in programAttributes) {
  14946. var programAttribute = programAttributes[name];
  14947. if (programAttribute >= 0) {
  14948. var geometryAttribute = geometryAttributes[name];
  14949. if (geometryAttribute !== undefined) {
  14950. var normalized = geometryAttribute.normalized;
  14951. var size = geometryAttribute.itemSize;
  14952. var attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  14953. if (attribute === undefined) continue;
  14954. var buffer = attribute.buffer;
  14955. var type = attribute.type;
  14956. var bytesPerElement = attribute.bytesPerElement;
  14957. if (geometryAttribute.isInterleavedBufferAttribute) {
  14958. var data = geometryAttribute.data;
  14959. var stride = data.stride;
  14960. var offset = geometryAttribute.offset;
  14961. if (data && data.isInstancedInterleavedBuffer) {
  14962. state.enableAttributeAndDivisor(programAttribute, data.meshPerAttribute);
  14963. if (geometry.maxInstancedCount === undefined) {
  14964. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  14965. }
  14966. } else {
  14967. state.enableAttribute(programAttribute);
  14968. }
  14969. _gl.bindBuffer(34962, buffer);
  14970. _gl.vertexAttribPointer(programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement);
  14971. } else {
  14972. if (geometryAttribute.isInstancedBufferAttribute) {
  14973. state.enableAttributeAndDivisor(programAttribute, geometryAttribute.meshPerAttribute);
  14974. if (geometry.maxInstancedCount === undefined) {
  14975. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  14976. }
  14977. } else {
  14978. state.enableAttribute(programAttribute);
  14979. }
  14980. _gl.bindBuffer(34962, buffer);
  14981. _gl.vertexAttribPointer(programAttribute, size, type, normalized, 0, 0);
  14982. }
  14983. } else if (name === 'instanceMatrix') {
  14984. var attribute = attributes.get(object.instanceMatrix); // TODO Attribute may not be available on context restore
  14985. if (attribute === undefined) continue;
  14986. var buffer = attribute.buffer;
  14987. var type = attribute.type;
  14988. state.enableAttributeAndDivisor(programAttribute + 0, 1);
  14989. state.enableAttributeAndDivisor(programAttribute + 1, 1);
  14990. state.enableAttributeAndDivisor(programAttribute + 2, 1);
  14991. state.enableAttributeAndDivisor(programAttribute + 3, 1);
  14992. _gl.bindBuffer(34962, buffer);
  14993. _gl.vertexAttribPointer(programAttribute + 0, 4, type, false, 64, 0);
  14994. _gl.vertexAttribPointer(programAttribute + 1, 4, type, false, 64, 16);
  14995. _gl.vertexAttribPointer(programAttribute + 2, 4, type, false, 64, 32);
  14996. _gl.vertexAttribPointer(programAttribute + 3, 4, type, false, 64, 48);
  14997. } else if (materialDefaultAttributeValues !== undefined) {
  14998. var value = materialDefaultAttributeValues[name];
  14999. if (value !== undefined) {
  15000. switch (value.length) {
  15001. case 2:
  15002. _gl.vertexAttrib2fv(programAttribute, value);
  15003. break;
  15004. case 3:
  15005. _gl.vertexAttrib3fv(programAttribute, value);
  15006. break;
  15007. case 4:
  15008. _gl.vertexAttrib4fv(programAttribute, value);
  15009. break;
  15010. default:
  15011. _gl.vertexAttrib1fv(programAttribute, value);
  15012. }
  15013. }
  15014. }
  15015. }
  15016. }
  15017. state.disableUnusedAttributes();
  15018. } // Compile
  15019. this.compile = function (scene, camera) {
  15020. currentRenderState = renderStates.get(scene, camera);
  15021. currentRenderState.init();
  15022. scene.traverse(function (object) {
  15023. if (object.isLight) {
  15024. currentRenderState.pushLight(object);
  15025. if (object.castShadow) {
  15026. currentRenderState.pushShadow(object);
  15027. }
  15028. }
  15029. });
  15030. currentRenderState.setupLights(camera);
  15031. scene.traverse(function (object) {
  15032. if (object.material) {
  15033. if (Array.isArray(object.material)) {
  15034. for (var i = 0; i < object.material.length; i++) {
  15035. initMaterial(object.material[i], scene.fog, object);
  15036. }
  15037. } else {
  15038. initMaterial(object.material, scene.fog, object);
  15039. }
  15040. }
  15041. });
  15042. }; // Animation Loop
  15043. var onAnimationFrameCallback = null;
  15044. function onAnimationFrame(time) {
  15045. if (vr.isPresenting()) return;
  15046. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  15047. }
  15048. var animation = new WebGLAnimation();
  15049. animation.setAnimationLoop(onAnimationFrame);
  15050. if (typeof window !== 'undefined') animation.setContext(window);
  15051. this.setAnimationLoop = function (callback) {
  15052. onAnimationFrameCallback = callback;
  15053. vr.setAnimationLoop(callback);
  15054. animation.start();
  15055. }; // Rendering
  15056. this.render = function (scene, camera) {
  15057. var renderTarget, forceClear;
  15058. if (arguments[2] !== undefined) {
  15059. console.warn('THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.');
  15060. renderTarget = arguments[2];
  15061. }
  15062. if (arguments[3] !== undefined) {
  15063. console.warn('THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.');
  15064. forceClear = arguments[3];
  15065. }
  15066. if (!(camera && camera.isCamera)) {
  15067. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  15068. return;
  15069. }
  15070. if (_isContextLost) return; // reset caching for this frame
  15071. _currentGeometryProgram.geometry = null;
  15072. _currentGeometryProgram.program = null;
  15073. _currentGeometryProgram.wireframe = false;
  15074. _currentMaterialId = -1;
  15075. _currentCamera = null; // update scene graph
  15076. if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  15077. if (camera.parent === null) camera.updateMatrixWorld();
  15078. if (vr.enabled) {
  15079. camera = vr.getCamera(camera);
  15080. } //
  15081. currentRenderState = renderStates.get(scene, camera);
  15082. currentRenderState.init();
  15083. scene.onBeforeRender(_this, scene, camera, renderTarget || _currentRenderTarget);
  15084. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  15085. _frustum.setFromMatrix(_projScreenMatrix);
  15086. _localClippingEnabled = this.localClippingEnabled;
  15087. _clippingEnabled = _clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  15088. currentRenderList = renderLists.get(scene, camera);
  15089. currentRenderList.init();
  15090. projectObject(scene, camera, 0, _this.sortObjects);
  15091. if (_this.sortObjects === true) {
  15092. currentRenderList.sort();
  15093. } //
  15094. if (_clippingEnabled) _clipping.beginShadows();
  15095. var shadowsArray = currentRenderState.state.shadowsArray;
  15096. shadowMap.render(shadowsArray, scene, camera);
  15097. currentRenderState.setupLights(camera);
  15098. if (_clippingEnabled) _clipping.endShadows(); //
  15099. if (this.info.autoReset) this.info.reset();
  15100. if (renderTarget !== undefined) {
  15101. this.setRenderTarget(renderTarget);
  15102. }
  15103. if (vr.enabled && multiview.isAvailable()) {
  15104. multiview.attachCamera(camera);
  15105. } //
  15106. background.render(currentRenderList, scene, camera, forceClear); // render scene
  15107. var opaqueObjects = currentRenderList.opaque;
  15108. var transparentObjects = currentRenderList.transparent;
  15109. if (scene.overrideMaterial) {
  15110. var overrideMaterial = scene.overrideMaterial;
  15111. if (opaqueObjects.length) renderObjects(opaqueObjects, scene, camera, overrideMaterial);
  15112. if (transparentObjects.length) renderObjects(transparentObjects, scene, camera, overrideMaterial);
  15113. } else {
  15114. // opaque pass (front-to-back order)
  15115. if (opaqueObjects.length) renderObjects(opaqueObjects, scene, camera); // transparent pass (back-to-front order)
  15116. if (transparentObjects.length) renderObjects(transparentObjects, scene, camera);
  15117. } //
  15118. scene.onAfterRender(_this, scene, camera); //
  15119. if (_currentRenderTarget !== null) {
  15120. // Generate mipmap if we're using any kind of mipmap filtering
  15121. textures.updateRenderTargetMipmap(_currentRenderTarget); // resolve multisample renderbuffers to a single-sample texture if necessary
  15122. textures.updateMultisampleRenderTarget(_currentRenderTarget);
  15123. } // Ensure depth buffer writing is enabled so it can be cleared on next render
  15124. state.buffers.depth.setTest(true);
  15125. state.buffers.depth.setMask(true);
  15126. state.buffers.color.setMask(true);
  15127. state.setPolygonOffset(false);
  15128. if (vr.enabled) {
  15129. if (multiview.isAvailable()) {
  15130. multiview.detachCamera(camera);
  15131. }
  15132. vr.submitFrame();
  15133. } // _gl.finish();
  15134. currentRenderList = null;
  15135. currentRenderState = null;
  15136. };
  15137. function projectObject(object, camera, groupOrder, sortObjects) {
  15138. if (object.visible === false) return;
  15139. var visible = object.layers.test(camera.layers);
  15140. if (visible) {
  15141. if (object.isGroup) {
  15142. groupOrder = object.renderOrder;
  15143. } else if (object.isLOD) {
  15144. if (object.autoUpdate === true) object.update(camera);
  15145. } else if (object.isLight) {
  15146. currentRenderState.pushLight(object);
  15147. if (object.castShadow) {
  15148. currentRenderState.pushShadow(object);
  15149. }
  15150. } else if (object.isSprite) {
  15151. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  15152. if (sortObjects) {
  15153. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15154. }
  15155. var geometry = objects.update(object);
  15156. var material = object.material;
  15157. if (material.visible) {
  15158. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  15159. }
  15160. }
  15161. } else if (object.isImmediateRenderObject) {
  15162. if (sortObjects) {
  15163. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15164. }
  15165. currentRenderList.push(object, null, object.material, groupOrder, _vector3.z, null);
  15166. } else if (object.isMesh || object.isLine || object.isPoints) {
  15167. if (object.isSkinnedMesh) {
  15168. // update skeleton only once in a frame
  15169. if (object.skeleton.frame !== info.render.frame) {
  15170. object.skeleton.update();
  15171. object.skeleton.frame = info.render.frame;
  15172. }
  15173. }
  15174. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  15175. if (sortObjects) {
  15176. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15177. }
  15178. var geometry = objects.update(object);
  15179. var material = object.material;
  15180. if (Array.isArray(material)) {
  15181. var groups = geometry.groups;
  15182. for (var i = 0, l = groups.length; i < l; i++) {
  15183. var group = groups[i];
  15184. var groupMaterial = material[group.materialIndex];
  15185. if (groupMaterial && groupMaterial.visible) {
  15186. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  15187. }
  15188. }
  15189. } else if (material.visible) {
  15190. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  15191. }
  15192. }
  15193. }
  15194. }
  15195. var children = object.children;
  15196. for (var i = 0, l = children.length; i < l; i++) {
  15197. projectObject(children[i], camera, groupOrder, sortObjects);
  15198. }
  15199. }
  15200. function renderObjects(renderList, scene, camera, overrideMaterial) {
  15201. for (var i = 0, l = renderList.length; i < l; i++) {
  15202. var renderItem = renderList[i];
  15203. var object = renderItem.object;
  15204. var geometry = renderItem.geometry;
  15205. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  15206. var group = renderItem.group;
  15207. if (camera.isArrayCamera) {
  15208. _currentArrayCamera = camera;
  15209. if (vr.enabled && multiview.isAvailable()) {
  15210. renderObject(object, scene, camera, geometry, material, group);
  15211. } else {
  15212. var cameras = camera.cameras;
  15213. for (var j = 0, jl = cameras.length; j < jl; j++) {
  15214. var camera2 = cameras[j];
  15215. if (object.layers.test(camera2.layers)) {
  15216. state.viewport(_currentViewport.copy(camera2.viewport));
  15217. currentRenderState.setupLights(camera2);
  15218. renderObject(object, scene, camera2, geometry, material, group);
  15219. }
  15220. }
  15221. }
  15222. } else {
  15223. _currentArrayCamera = null;
  15224. renderObject(object, scene, camera, geometry, material, group);
  15225. }
  15226. }
  15227. }
  15228. function renderObject(object, scene, camera, geometry, material, group) {
  15229. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  15230. currentRenderState = renderStates.get(scene, _currentArrayCamera || camera);
  15231. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  15232. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  15233. if (object.isImmediateRenderObject) {
  15234. state.setMaterial(material);
  15235. var program = setProgram(camera, scene.fog, material, object);
  15236. _currentGeometryProgram.geometry = null;
  15237. _currentGeometryProgram.program = null;
  15238. _currentGeometryProgram.wireframe = false;
  15239. renderObjectImmediate(object, program);
  15240. } else {
  15241. _this.renderBufferDirect(camera, scene.fog, geometry, material, object, group);
  15242. }
  15243. object.onAfterRender(_this, scene, camera, geometry, material, group);
  15244. currentRenderState = renderStates.get(scene, _currentArrayCamera || camera);
  15245. }
  15246. function initMaterial(material, fog, object) {
  15247. var materialProperties = properties.get(material);
  15248. var lights = currentRenderState.state.lights;
  15249. var shadowsArray = currentRenderState.state.shadowsArray;
  15250. var lightsStateVersion = lights.state.version;
  15251. var parameters = programCache.getParameters(material, lights.state, shadowsArray, fog, _clipping.numPlanes, _clipping.numIntersection, object);
  15252. var code = programCache.getProgramCode(material, parameters);
  15253. var program = materialProperties.program;
  15254. var programChange = true;
  15255. if (program === undefined) {
  15256. // new material
  15257. material.addEventListener('dispose', onMaterialDispose);
  15258. } else if (program.code !== code) {
  15259. // changed glsl or parameters
  15260. releaseMaterialProgramReference(material);
  15261. } else if (materialProperties.lightsStateVersion !== lightsStateVersion) {
  15262. materialProperties.lightsStateVersion = lightsStateVersion;
  15263. programChange = false;
  15264. } else if (parameters.shaderID !== undefined) {
  15265. // same glsl and uniform list
  15266. return;
  15267. } else {
  15268. // only rebuild uniform list
  15269. programChange = false;
  15270. }
  15271. if (programChange) {
  15272. if (parameters.shaderID) {
  15273. var shader = ShaderLib[parameters.shaderID];
  15274. materialProperties.shader = {
  15275. name: material.type,
  15276. uniforms: cloneUniforms(shader.uniforms),
  15277. vertexShader: shader.vertexShader,
  15278. fragmentShader: shader.fragmentShader
  15279. };
  15280. } else {
  15281. materialProperties.shader = {
  15282. name: material.type,
  15283. uniforms: material.uniforms,
  15284. vertexShader: material.vertexShader,
  15285. fragmentShader: material.fragmentShader
  15286. };
  15287. }
  15288. material.onBeforeCompile(materialProperties.shader, _this); // Computing code again as onBeforeCompile may have changed the shaders
  15289. code = programCache.getProgramCode(material, parameters);
  15290. program = programCache.acquireProgram(material, materialProperties.shader, parameters, code);
  15291. materialProperties.program = program;
  15292. material.program = program;
  15293. }
  15294. var programAttributes = program.getAttributes();
  15295. if (material.morphTargets) {
  15296. material.numSupportedMorphTargets = 0;
  15297. for (var i = 0; i < _this.maxMorphTargets; i++) {
  15298. if (programAttributes['morphTarget' + i] >= 0) {
  15299. material.numSupportedMorphTargets++;
  15300. }
  15301. }
  15302. }
  15303. if (material.morphNormals) {
  15304. material.numSupportedMorphNormals = 0;
  15305. for (var i = 0; i < _this.maxMorphNormals; i++) {
  15306. if (programAttributes['morphNormal' + i] >= 0) {
  15307. material.numSupportedMorphNormals++;
  15308. }
  15309. }
  15310. }
  15311. var uniforms = materialProperties.shader.uniforms;
  15312. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  15313. materialProperties.numClippingPlanes = _clipping.numPlanes;
  15314. materialProperties.numIntersection = _clipping.numIntersection;
  15315. uniforms.clippingPlanes = _clipping.uniform;
  15316. }
  15317. materialProperties.fog = fog; // store the light setup it was created for
  15318. materialProperties.needsLights = materialNeedsLights(material);
  15319. materialProperties.lightsStateVersion = lightsStateVersion;
  15320. if (materialProperties.needsLights) {
  15321. // wire up the material to this renderer's lighting state
  15322. uniforms.ambientLightColor.value = lights.state.ambient;
  15323. uniforms.lightProbe.value = lights.state.probe;
  15324. uniforms.directionalLights.value = lights.state.directional;
  15325. uniforms.spotLights.value = lights.state.spot;
  15326. uniforms.rectAreaLights.value = lights.state.rectArea;
  15327. uniforms.pointLights.value = lights.state.point;
  15328. uniforms.hemisphereLights.value = lights.state.hemi;
  15329. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  15330. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  15331. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  15332. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  15333. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  15334. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  15335. }
  15336. var progUniforms = materialProperties.program.getUniforms(),
  15337. uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  15338. materialProperties.uniformsList = uniformsList;
  15339. }
  15340. function setProgram(camera, fog, material, object) {
  15341. textures.resetTextureUnits();
  15342. var materialProperties = properties.get(material);
  15343. var lights = currentRenderState.state.lights;
  15344. if (_clippingEnabled) {
  15345. if (_localClippingEnabled || camera !== _currentCamera) {
  15346. var useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  15347. // object instead of the material, once it becomes feasible
  15348. // (#8465, #8379)
  15349. _clipping.setState(material.clippingPlanes, material.clipIntersection, material.clipShadows, camera, materialProperties, useCache);
  15350. }
  15351. }
  15352. if (material.needsUpdate === false) {
  15353. if (materialProperties.program === undefined) {
  15354. material.needsUpdate = true;
  15355. } else if (material.fog && materialProperties.fog !== fog) {
  15356. material.needsUpdate = true;
  15357. } else if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  15358. material.needsUpdate = true;
  15359. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== _clipping.numPlanes || materialProperties.numIntersection !== _clipping.numIntersection)) {
  15360. material.needsUpdate = true;
  15361. }
  15362. }
  15363. if (material.needsUpdate) {
  15364. initMaterial(material, fog, object);
  15365. material.needsUpdate = false;
  15366. }
  15367. var refreshProgram = false;
  15368. var refreshMaterial = false;
  15369. var refreshLights = false;
  15370. var program = materialProperties.program,
  15371. p_uniforms = program.getUniforms(),
  15372. m_uniforms = materialProperties.shader.uniforms;
  15373. if (state.useProgram(program.program)) {
  15374. refreshProgram = true;
  15375. refreshMaterial = true;
  15376. refreshLights = true;
  15377. }
  15378. if (material.id !== _currentMaterialId) {
  15379. _currentMaterialId = material.id;
  15380. refreshMaterial = true;
  15381. }
  15382. if (refreshProgram || _currentCamera !== camera) {
  15383. if (program.numMultiviewViews > 0) {
  15384. multiview.updateCameraProjectionMatricesUniform(camera, p_uniforms);
  15385. } else {
  15386. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  15387. }
  15388. if (capabilities.logarithmicDepthBuffer) {
  15389. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  15390. }
  15391. if (_currentCamera !== camera) {
  15392. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  15393. // now, in case this material supports lights - or later, when
  15394. // the next material that does gets activated:
  15395. refreshMaterial = true; // set to true on material change
  15396. refreshLights = true; // remains set until update done
  15397. } // load material specific uniforms
  15398. // (shader material also gets them for the sake of genericity)
  15399. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.envMap) {
  15400. var uCamPos = p_uniforms.map.cameraPosition;
  15401. if (uCamPos !== undefined) {
  15402. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  15403. }
  15404. }
  15405. if (material.isMeshPhongMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.skinning) {
  15406. if (program.numMultiviewViews > 0) {
  15407. multiview.updateCameraViewMatricesUniform(camera, p_uniforms);
  15408. } else {
  15409. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  15410. }
  15411. }
  15412. } // skinning uniforms must be set even if material didn't change
  15413. // auto-setting of texture unit for bone texture must go before other textures
  15414. // not sure why, but otherwise weird things happen
  15415. if (material.skinning) {
  15416. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  15417. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  15418. var skeleton = object.skeleton;
  15419. if (skeleton) {
  15420. var bones = skeleton.bones;
  15421. if (capabilities.floatVertexTextures) {
  15422. if (skeleton.boneTexture === undefined) {
  15423. // layout (1 matrix = 4 pixels)
  15424. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  15425. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  15426. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  15427. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  15428. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  15429. var size = Math.sqrt(bones.length * 4); // 4 pixels needed for 1 matrix
  15430. size = _Math.ceilPowerOfTwo(size);
  15431. size = Math.max(size, 4);
  15432. var boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  15433. boneMatrices.set(skeleton.boneMatrices); // copy current values
  15434. var boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  15435. skeleton.boneMatrices = boneMatrices;
  15436. skeleton.boneTexture = boneTexture;
  15437. skeleton.boneTextureSize = size;
  15438. }
  15439. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  15440. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  15441. } else {
  15442. p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
  15443. }
  15444. }
  15445. }
  15446. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  15447. materialProperties.receiveShadow = object.receiveShadow;
  15448. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  15449. }
  15450. if (refreshMaterial) {
  15451. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  15452. p_uniforms.setValue(_gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint);
  15453. if (materialProperties.needsLights) {
  15454. // the current material requires lighting info
  15455. // note: all lighting uniforms are always set correctly
  15456. // they simply reference the renderer's state for their
  15457. // values
  15458. //
  15459. // use the current material's .needsUpdate flags to set
  15460. // the GL state when required
  15461. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  15462. } // refresh uniforms common to several materials
  15463. if (fog && material.fog) {
  15464. refreshUniformsFog(m_uniforms, fog);
  15465. }
  15466. if (material.isMeshBasicMaterial) {
  15467. refreshUniformsCommon(m_uniforms, material);
  15468. } else if (material.isMeshLambertMaterial) {
  15469. refreshUniformsCommon(m_uniforms, material);
  15470. refreshUniformsLambert(m_uniforms, material);
  15471. } else if (material.isMeshPhongMaterial) {
  15472. refreshUniformsCommon(m_uniforms, material);
  15473. if (material.isMeshToonMaterial) {
  15474. refreshUniformsToon(m_uniforms, material);
  15475. } else {
  15476. refreshUniformsPhong(m_uniforms, material);
  15477. }
  15478. } else if (material.isMeshStandardMaterial) {
  15479. refreshUniformsCommon(m_uniforms, material);
  15480. if (material.isMeshPhysicalMaterial) {
  15481. refreshUniformsPhysical(m_uniforms, material);
  15482. } else {
  15483. refreshUniformsStandard(m_uniforms, material);
  15484. }
  15485. } else if (material.isMeshMatcapMaterial) {
  15486. refreshUniformsCommon(m_uniforms, material);
  15487. refreshUniformsMatcap(m_uniforms, material);
  15488. } else if (material.isMeshDepthMaterial) {
  15489. refreshUniformsCommon(m_uniforms, material);
  15490. refreshUniformsDepth(m_uniforms, material);
  15491. } else if (material.isMeshDistanceMaterial) {
  15492. refreshUniformsCommon(m_uniforms, material);
  15493. refreshUniformsDistance(m_uniforms, material);
  15494. } else if (material.isMeshNormalMaterial) {
  15495. refreshUniformsCommon(m_uniforms, material);
  15496. refreshUniformsNormal(m_uniforms, material);
  15497. } else if (material.isLineBasicMaterial) {
  15498. refreshUniformsLine(m_uniforms, material);
  15499. if (material.isLineDashedMaterial) {
  15500. refreshUniformsDash(m_uniforms, material);
  15501. }
  15502. } else if (material.isPointsMaterial) {
  15503. refreshUniformsPoints(m_uniforms, material);
  15504. } else if (material.isSpriteMaterial) {
  15505. refreshUniformsSprites(m_uniforms, material);
  15506. } else if (material.isShadowMaterial) {
  15507. m_uniforms.color.value.copy(material.color);
  15508. m_uniforms.opacity.value = material.opacity;
  15509. } // RectAreaLight Texture
  15510. // TODO (mrdoob): Find a nicer implementation
  15511. if (m_uniforms.ltc_1 !== undefined) m_uniforms.ltc_1.value = UniformsLib.LTC_1;
  15512. if (m_uniforms.ltc_2 !== undefined) m_uniforms.ltc_2.value = UniformsLib.LTC_2;
  15513. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  15514. }
  15515. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  15516. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  15517. material.uniformsNeedUpdate = false;
  15518. }
  15519. if (material.isSpriteMaterial) {
  15520. p_uniforms.setValue(_gl, 'center', object.center);
  15521. } // common matrices
  15522. if (program.numMultiviewViews > 0) {
  15523. multiview.updateObjectMatricesUniforms(object, camera, p_uniforms);
  15524. } else {
  15525. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  15526. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  15527. }
  15528. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  15529. return program;
  15530. } // Uniforms (refresh uniforms objects)
  15531. function refreshUniformsCommon(uniforms, material) {
  15532. uniforms.opacity.value = material.opacity;
  15533. if (material.color) {
  15534. uniforms.diffuse.value.copy(material.color);
  15535. }
  15536. if (material.emissive) {
  15537. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  15538. }
  15539. if (material.map) {
  15540. uniforms.map.value = material.map;
  15541. }
  15542. if (material.alphaMap) {
  15543. uniforms.alphaMap.value = material.alphaMap;
  15544. }
  15545. if (material.specularMap) {
  15546. uniforms.specularMap.value = material.specularMap;
  15547. }
  15548. if (material.envMap) {
  15549. uniforms.envMap.value = material.envMap; // don't flip CubeTexture envMaps, flip everything else:
  15550. // WebGLRenderTargetCube will be flipped for backwards compatibility
  15551. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  15552. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  15553. uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? -1 : 1;
  15554. uniforms.reflectivity.value = material.reflectivity;
  15555. uniforms.refractionRatio.value = material.refractionRatio;
  15556. uniforms.maxMipLevel.value = properties.get(material.envMap).__maxMipLevel;
  15557. }
  15558. if (material.lightMap) {
  15559. uniforms.lightMap.value = material.lightMap;
  15560. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  15561. }
  15562. if (material.aoMap) {
  15563. uniforms.aoMap.value = material.aoMap;
  15564. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15565. } // uv repeat and offset setting priorities
  15566. // 1. color map
  15567. // 2. specular map
  15568. // 3. normal map
  15569. // 4. bump map
  15570. // 5. alpha map
  15571. // 6. emissive map
  15572. var uvScaleMap;
  15573. if (material.map) {
  15574. uvScaleMap = material.map;
  15575. } else if (material.specularMap) {
  15576. uvScaleMap = material.specularMap;
  15577. } else if (material.displacementMap) {
  15578. uvScaleMap = material.displacementMap;
  15579. } else if (material.normalMap) {
  15580. uvScaleMap = material.normalMap;
  15581. } else if (material.bumpMap) {
  15582. uvScaleMap = material.bumpMap;
  15583. } else if (material.roughnessMap) {
  15584. uvScaleMap = material.roughnessMap;
  15585. } else if (material.metalnessMap) {
  15586. uvScaleMap = material.metalnessMap;
  15587. } else if (material.alphaMap) {
  15588. uvScaleMap = material.alphaMap;
  15589. } else if (material.emissiveMap) {
  15590. uvScaleMap = material.emissiveMap;
  15591. }
  15592. if (uvScaleMap !== undefined) {
  15593. // backwards compatibility
  15594. if (uvScaleMap.isWebGLRenderTarget) {
  15595. uvScaleMap = uvScaleMap.texture;
  15596. }
  15597. if (uvScaleMap.matrixAutoUpdate === true) {
  15598. uvScaleMap.updateMatrix();
  15599. }
  15600. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  15601. }
  15602. }
  15603. function refreshUniformsLine(uniforms, material) {
  15604. uniforms.diffuse.value.copy(material.color);
  15605. uniforms.opacity.value = material.opacity;
  15606. }
  15607. function refreshUniformsDash(uniforms, material) {
  15608. uniforms.dashSize.value = material.dashSize;
  15609. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15610. uniforms.scale.value = material.scale;
  15611. }
  15612. function refreshUniformsPoints(uniforms, material) {
  15613. uniforms.diffuse.value.copy(material.color);
  15614. uniforms.opacity.value = material.opacity;
  15615. uniforms.size.value = material.size * _pixelRatio;
  15616. uniforms.scale.value = _height * 0.5;
  15617. uniforms.map.value = material.map;
  15618. if (material.map !== null) {
  15619. if (material.map.matrixAutoUpdate === true) {
  15620. material.map.updateMatrix();
  15621. }
  15622. uniforms.uvTransform.value.copy(material.map.matrix);
  15623. }
  15624. }
  15625. function refreshUniformsSprites(uniforms, material) {
  15626. uniforms.diffuse.value.copy(material.color);
  15627. uniforms.opacity.value = material.opacity;
  15628. uniforms.rotation.value = material.rotation;
  15629. uniforms.map.value = material.map;
  15630. if (material.map !== null) {
  15631. if (material.map.matrixAutoUpdate === true) {
  15632. material.map.updateMatrix();
  15633. }
  15634. uniforms.uvTransform.value.copy(material.map.matrix);
  15635. }
  15636. }
  15637. function refreshUniformsFog(uniforms, fog) {
  15638. uniforms.fogColor.value.copy(fog.color);
  15639. if (fog.isFog) {
  15640. uniforms.fogNear.value = fog.near;
  15641. uniforms.fogFar.value = fog.far;
  15642. } else if (fog.isFogExp2) {
  15643. uniforms.fogDensity.value = fog.density;
  15644. }
  15645. }
  15646. function refreshUniformsLambert(uniforms, material) {
  15647. if (material.emissiveMap) {
  15648. uniforms.emissiveMap.value = material.emissiveMap;
  15649. }
  15650. }
  15651. function refreshUniformsPhong(uniforms, material) {
  15652. uniforms.specular.value.copy(material.specular);
  15653. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  15654. if (material.emissiveMap) {
  15655. uniforms.emissiveMap.value = material.emissiveMap;
  15656. }
  15657. if (material.bumpMap) {
  15658. uniforms.bumpMap.value = material.bumpMap;
  15659. uniforms.bumpScale.value = material.bumpScale;
  15660. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15661. }
  15662. if (material.normalMap) {
  15663. uniforms.normalMap.value = material.normalMap;
  15664. uniforms.normalScale.value.copy(material.normalScale);
  15665. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15666. }
  15667. if (material.displacementMap) {
  15668. uniforms.displacementMap.value = material.displacementMap;
  15669. uniforms.displacementScale.value = material.displacementScale;
  15670. uniforms.displacementBias.value = material.displacementBias;
  15671. }
  15672. }
  15673. function refreshUniformsToon(uniforms, material) {
  15674. refreshUniformsPhong(uniforms, material);
  15675. if (material.gradientMap) {
  15676. uniforms.gradientMap.value = material.gradientMap;
  15677. }
  15678. }
  15679. function refreshUniformsStandard(uniforms, material) {
  15680. uniforms.roughness.value = material.roughness;
  15681. uniforms.metalness.value = material.metalness;
  15682. if (material.roughnessMap) {
  15683. uniforms.roughnessMap.value = material.roughnessMap;
  15684. }
  15685. if (material.metalnessMap) {
  15686. uniforms.metalnessMap.value = material.metalnessMap;
  15687. }
  15688. if (material.emissiveMap) {
  15689. uniforms.emissiveMap.value = material.emissiveMap;
  15690. }
  15691. if (material.bumpMap) {
  15692. uniforms.bumpMap.value = material.bumpMap;
  15693. uniforms.bumpScale.value = material.bumpScale;
  15694. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15695. }
  15696. if (material.normalMap) {
  15697. uniforms.normalMap.value = material.normalMap;
  15698. uniforms.normalScale.value.copy(material.normalScale);
  15699. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15700. }
  15701. if (material.displacementMap) {
  15702. uniforms.displacementMap.value = material.displacementMap;
  15703. uniforms.displacementScale.value = material.displacementScale;
  15704. uniforms.displacementBias.value = material.displacementBias;
  15705. }
  15706. if (material.envMap) {
  15707. //uniforms.envMap.value = material.envMap; // part of uniforms common
  15708. uniforms.envMapIntensity.value = material.envMapIntensity;
  15709. }
  15710. }
  15711. function refreshUniformsPhysical(uniforms, material) {
  15712. refreshUniformsStandard(uniforms, material);
  15713. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  15714. uniforms.clearcoat.value = material.clearcoat;
  15715. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  15716. if (material.sheen) uniforms.sheen.value.copy(material.sheen);
  15717. if (material.clearcoatNormalMap) {
  15718. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  15719. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  15720. if (material.side === BackSide) {
  15721. uniforms.clearcoatNormalScale.value.negate();
  15722. }
  15723. }
  15724. uniforms.transparency.value = material.transparency;
  15725. }
  15726. function refreshUniformsMatcap(uniforms, material) {
  15727. if (material.matcap) {
  15728. uniforms.matcap.value = material.matcap;
  15729. }
  15730. if (material.bumpMap) {
  15731. uniforms.bumpMap.value = material.bumpMap;
  15732. uniforms.bumpScale.value = material.bumpScale;
  15733. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15734. }
  15735. if (material.normalMap) {
  15736. uniforms.normalMap.value = material.normalMap;
  15737. uniforms.normalScale.value.copy(material.normalScale);
  15738. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15739. }
  15740. if (material.displacementMap) {
  15741. uniforms.displacementMap.value = material.displacementMap;
  15742. uniforms.displacementScale.value = material.displacementScale;
  15743. uniforms.displacementBias.value = material.displacementBias;
  15744. }
  15745. }
  15746. function refreshUniformsDepth(uniforms, material) {
  15747. if (material.displacementMap) {
  15748. uniforms.displacementMap.value = material.displacementMap;
  15749. uniforms.displacementScale.value = material.displacementScale;
  15750. uniforms.displacementBias.value = material.displacementBias;
  15751. }
  15752. }
  15753. function refreshUniformsDistance(uniforms, material) {
  15754. if (material.displacementMap) {
  15755. uniforms.displacementMap.value = material.displacementMap;
  15756. uniforms.displacementScale.value = material.displacementScale;
  15757. uniforms.displacementBias.value = material.displacementBias;
  15758. }
  15759. uniforms.referencePosition.value.copy(material.referencePosition);
  15760. uniforms.nearDistance.value = material.nearDistance;
  15761. uniforms.farDistance.value = material.farDistance;
  15762. }
  15763. function refreshUniformsNormal(uniforms, material) {
  15764. if (material.bumpMap) {
  15765. uniforms.bumpMap.value = material.bumpMap;
  15766. uniforms.bumpScale.value = material.bumpScale;
  15767. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15768. }
  15769. if (material.normalMap) {
  15770. uniforms.normalMap.value = material.normalMap;
  15771. uniforms.normalScale.value.copy(material.normalScale);
  15772. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15773. }
  15774. if (material.displacementMap) {
  15775. uniforms.displacementMap.value = material.displacementMap;
  15776. uniforms.displacementScale.value = material.displacementScale;
  15777. uniforms.displacementBias.value = material.displacementBias;
  15778. }
  15779. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  15780. function markUniformsLightsNeedsUpdate(uniforms, value) {
  15781. uniforms.ambientLightColor.needsUpdate = value;
  15782. uniforms.lightProbe.needsUpdate = value;
  15783. uniforms.directionalLights.needsUpdate = value;
  15784. uniforms.pointLights.needsUpdate = value;
  15785. uniforms.spotLights.needsUpdate = value;
  15786. uniforms.rectAreaLights.needsUpdate = value;
  15787. uniforms.hemisphereLights.needsUpdate = value;
  15788. }
  15789. function materialNeedsLights(material) {
  15790. return material.isMeshLambertMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  15791. } //
  15792. this.setFramebuffer = function (value) {
  15793. if (_framebuffer !== value) _gl.bindFramebuffer(36160, value);
  15794. _framebuffer = value;
  15795. };
  15796. this.getActiveCubeFace = function () {
  15797. return _currentActiveCubeFace;
  15798. };
  15799. this.getActiveMipmapLevel = function () {
  15800. return _currentActiveMipmapLevel;
  15801. };
  15802. this.getRenderTarget = function () {
  15803. return _currentRenderTarget;
  15804. };
  15805. this.setRenderTarget = function (renderTarget, activeCubeFace, activeMipmapLevel) {
  15806. _currentRenderTarget = renderTarget;
  15807. _currentActiveCubeFace = activeCubeFace;
  15808. _currentActiveMipmapLevel = activeMipmapLevel;
  15809. if (renderTarget && properties.get(renderTarget).__webglFramebuffer === undefined) {
  15810. textures.setupRenderTarget(renderTarget);
  15811. }
  15812. var framebuffer = _framebuffer;
  15813. var isCube = false;
  15814. if (renderTarget) {
  15815. var __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  15816. if (renderTarget.isWebGLRenderTargetCube) {
  15817. framebuffer = __webglFramebuffer[activeCubeFace || 0];
  15818. isCube = true;
  15819. } else if (renderTarget.isWebGLMultisampleRenderTarget) {
  15820. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  15821. } else {
  15822. framebuffer = __webglFramebuffer;
  15823. }
  15824. _currentViewport.copy(renderTarget.viewport);
  15825. _currentScissor.copy(renderTarget.scissor);
  15826. _currentScissorTest = renderTarget.scissorTest;
  15827. } else {
  15828. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  15829. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  15830. _currentScissorTest = _scissorTest;
  15831. }
  15832. if (_currentFramebuffer !== framebuffer) {
  15833. _gl.bindFramebuffer(36160, framebuffer);
  15834. _currentFramebuffer = framebuffer;
  15835. }
  15836. state.viewport(_currentViewport);
  15837. state.scissor(_currentScissor);
  15838. state.setScissorTest(_currentScissorTest);
  15839. if (isCube) {
  15840. var textureProperties = properties.get(renderTarget.texture);
  15841. _gl.framebufferTexture2D(36160, 36064, 34069 + (activeCubeFace || 0), textureProperties.__webglTexture, activeMipmapLevel || 0);
  15842. }
  15843. };
  15844. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  15845. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  15846. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  15847. return;
  15848. }
  15849. var framebuffer = properties.get(renderTarget).__webglFramebuffer;
  15850. if (renderTarget.isWebGLRenderTargetCube && activeCubeFaceIndex !== undefined) {
  15851. framebuffer = framebuffer[activeCubeFaceIndex];
  15852. }
  15853. if (framebuffer) {
  15854. var restore = false;
  15855. if (framebuffer !== _currentFramebuffer) {
  15856. _gl.bindFramebuffer(36160, framebuffer);
  15857. restore = true;
  15858. }
  15859. try {
  15860. var texture = renderTarget.texture;
  15861. var textureFormat = texture.format;
  15862. var textureType = texture.type;
  15863. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(35739)) {
  15864. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  15865. return;
  15866. }
  15867. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(35738) && // IE11, Edge and Chrome Mac < 52 (#9513)
  15868. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.get('OES_texture_float') || extensions.get('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  15869. !(textureType === HalfFloatType && (capabilities.isWebGL2 ? extensions.get('EXT_color_buffer_float') : extensions.get('EXT_color_buffer_half_float')))) {
  15870. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  15871. return;
  15872. }
  15873. if (_gl.checkFramebufferStatus(36160) === 36053) {
  15874. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  15875. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  15876. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  15877. }
  15878. } else {
  15879. console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
  15880. }
  15881. } finally {
  15882. if (restore) {
  15883. _gl.bindFramebuffer(36160, _currentFramebuffer);
  15884. }
  15885. }
  15886. }
  15887. };
  15888. this.copyFramebufferToTexture = function (position, texture, level) {
  15889. var width = texture.image.width;
  15890. var height = texture.image.height;
  15891. var glFormat = utils.convert(texture.format);
  15892. textures.setTexture2D(texture, 0);
  15893. _gl.copyTexImage2D(3553, level || 0, glFormat, position.x, position.y, width, height, 0);
  15894. };
  15895. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level) {
  15896. var width = srcTexture.image.width;
  15897. var height = srcTexture.image.height;
  15898. var glFormat = utils.convert(dstTexture.format);
  15899. var glType = utils.convert(dstTexture.type);
  15900. textures.setTexture2D(dstTexture, 0);
  15901. if (srcTexture.isDataTexture) {
  15902. _gl.texSubImage2D(3553, level || 0, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  15903. } else {
  15904. _gl.texSubImage2D(3553, level || 0, position.x, position.y, glFormat, glType, srcTexture.image);
  15905. }
  15906. };
  15907. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  15908. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  15909. detail: this
  15910. })); // eslint-disable-line no-undef
  15911. }
  15912. }
  15913. /**
  15914. * @author mrdoob / http://mrdoob.com/
  15915. * @author alteredq / http://alteredqualia.com/
  15916. */
  15917. function FogExp2(color, density) {
  15918. this.name = '';
  15919. this.color = new Color(color);
  15920. this.density = density !== undefined ? density : 0.00025;
  15921. }
  15922. Object.assign(FogExp2.prototype, {
  15923. isFogExp2: true,
  15924. clone: function () {
  15925. return new FogExp2(this.color, this.density);
  15926. },
  15927. toJSON: function ()
  15928. /* meta */
  15929. {
  15930. return {
  15931. type: 'FogExp2',
  15932. color: this.color.getHex(),
  15933. density: this.density
  15934. };
  15935. }
  15936. });
  15937. /**
  15938. * @author mrdoob / http://mrdoob.com/
  15939. * @author alteredq / http://alteredqualia.com/
  15940. */
  15941. function Fog(color, near, far) {
  15942. this.name = '';
  15943. this.color = new Color(color);
  15944. this.near = near !== undefined ? near : 1;
  15945. this.far = far !== undefined ? far : 1000;
  15946. }
  15947. Object.assign(Fog.prototype, {
  15948. isFog: true,
  15949. clone: function () {
  15950. return new Fog(this.color, this.near, this.far);
  15951. },
  15952. toJSON: function ()
  15953. /* meta */
  15954. {
  15955. return {
  15956. type: 'Fog',
  15957. color: this.color.getHex(),
  15958. near: this.near,
  15959. far: this.far
  15960. };
  15961. }
  15962. });
  15963. /**
  15964. * @author benaadams / https://twitter.com/ben_a_adams
  15965. */
  15966. function InterleavedBuffer(array, stride) {
  15967. this.array = array;
  15968. this.stride = stride;
  15969. this.count = array !== undefined ? array.length / stride : 0;
  15970. this.dynamic = false;
  15971. this.updateRange = {
  15972. offset: 0,
  15973. count: -1
  15974. };
  15975. this.version = 0;
  15976. }
  15977. Object.defineProperty(InterleavedBuffer.prototype, 'needsUpdate', {
  15978. set: function (value) {
  15979. if (value === true) this.version++;
  15980. }
  15981. });
  15982. Object.assign(InterleavedBuffer.prototype, {
  15983. isInterleavedBuffer: true,
  15984. onUploadCallback: function () {},
  15985. setDynamic: function (value) {
  15986. this.dynamic = value;
  15987. return this;
  15988. },
  15989. copy: function (source) {
  15990. this.array = new source.array.constructor(source.array);
  15991. this.count = source.count;
  15992. this.stride = source.stride;
  15993. this.dynamic = source.dynamic;
  15994. return this;
  15995. },
  15996. copyAt: function (index1, attribute, index2) {
  15997. index1 *= this.stride;
  15998. index2 *= attribute.stride;
  15999. for (var i = 0, l = this.stride; i < l; i++) {
  16000. this.array[index1 + i] = attribute.array[index2 + i];
  16001. }
  16002. return this;
  16003. },
  16004. set: function (value, offset) {
  16005. if (offset === undefined) offset = 0;
  16006. this.array.set(value, offset);
  16007. return this;
  16008. },
  16009. clone: function () {
  16010. return new this.constructor().copy(this);
  16011. },
  16012. onUpload: function (callback) {
  16013. this.onUploadCallback = callback;
  16014. return this;
  16015. }
  16016. });
  16017. /**
  16018. * @author benaadams / https://twitter.com/ben_a_adams
  16019. */
  16020. function InterleavedBufferAttribute(interleavedBuffer, itemSize, offset, normalized) {
  16021. this.data = interleavedBuffer;
  16022. this.itemSize = itemSize;
  16023. this.offset = offset;
  16024. this.normalized = normalized === true;
  16025. }
  16026. Object.defineProperties(InterleavedBufferAttribute.prototype, {
  16027. count: {
  16028. get: function () {
  16029. return this.data.count;
  16030. }
  16031. },
  16032. array: {
  16033. get: function () {
  16034. return this.data.array;
  16035. }
  16036. }
  16037. });
  16038. Object.assign(InterleavedBufferAttribute.prototype, {
  16039. isInterleavedBufferAttribute: true,
  16040. setX: function (index, x) {
  16041. this.data.array[index * this.data.stride + this.offset] = x;
  16042. return this;
  16043. },
  16044. setY: function (index, y) {
  16045. this.data.array[index * this.data.stride + this.offset + 1] = y;
  16046. return this;
  16047. },
  16048. setZ: function (index, z) {
  16049. this.data.array[index * this.data.stride + this.offset + 2] = z;
  16050. return this;
  16051. },
  16052. setW: function (index, w) {
  16053. this.data.array[index * this.data.stride + this.offset + 3] = w;
  16054. return this;
  16055. },
  16056. getX: function (index) {
  16057. return this.data.array[index * this.data.stride + this.offset];
  16058. },
  16059. getY: function (index) {
  16060. return this.data.array[index * this.data.stride + this.offset + 1];
  16061. },
  16062. getZ: function (index) {
  16063. return this.data.array[index * this.data.stride + this.offset + 2];
  16064. },
  16065. getW: function (index) {
  16066. return this.data.array[index * this.data.stride + this.offset + 3];
  16067. },
  16068. setXY: function (index, x, y) {
  16069. index = index * this.data.stride + this.offset;
  16070. this.data.array[index + 0] = x;
  16071. this.data.array[index + 1] = y;
  16072. return this;
  16073. },
  16074. setXYZ: function (index, x, y, z) {
  16075. index = index * this.data.stride + this.offset;
  16076. this.data.array[index + 0] = x;
  16077. this.data.array[index + 1] = y;
  16078. this.data.array[index + 2] = z;
  16079. return this;
  16080. },
  16081. setXYZW: function (index, x, y, z, w) {
  16082. index = index * this.data.stride + this.offset;
  16083. this.data.array[index + 0] = x;
  16084. this.data.array[index + 1] = y;
  16085. this.data.array[index + 2] = z;
  16086. this.data.array[index + 3] = w;
  16087. return this;
  16088. }
  16089. });
  16090. /**
  16091. * @author alteredq / http://alteredqualia.com/
  16092. *
  16093. * parameters = {
  16094. * color: <hex>,
  16095. * map: new THREE.Texture( <Image> ),
  16096. * rotation: <float>,
  16097. * sizeAttenuation: <bool>
  16098. * }
  16099. */
  16100. function SpriteMaterial(parameters) {
  16101. Material.call(this);
  16102. this.type = 'SpriteMaterial';
  16103. this.color = new Color(0xffffff);
  16104. this.map = null;
  16105. this.rotation = 0;
  16106. this.sizeAttenuation = true;
  16107. this.transparent = true;
  16108. this.setValues(parameters);
  16109. }
  16110. SpriteMaterial.prototype = Object.create(Material.prototype);
  16111. SpriteMaterial.prototype.constructor = SpriteMaterial;
  16112. SpriteMaterial.prototype.isSpriteMaterial = true;
  16113. SpriteMaterial.prototype.copy = function (source) {
  16114. Material.prototype.copy.call(this, source);
  16115. this.color.copy(source.color);
  16116. this.map = source.map;
  16117. this.rotation = source.rotation;
  16118. this.sizeAttenuation = source.sizeAttenuation;
  16119. return this;
  16120. };
  16121. /**
  16122. * @author mikael emtinger / http://gomo.se/
  16123. * @author alteredq / http://alteredqualia.com/
  16124. */
  16125. var _geometry;
  16126. var _intersectPoint = new Vector3();
  16127. var _worldScale = new Vector3();
  16128. var _mvPosition = new Vector3();
  16129. var _alignedPosition = new Vector2();
  16130. var _rotatedPosition = new Vector2();
  16131. var _viewWorldMatrix = new Matrix4();
  16132. var _vA$1 = new Vector3();
  16133. var _vB$1 = new Vector3();
  16134. var _vC$1 = new Vector3();
  16135. var _uvA$1 = new Vector2();
  16136. var _uvB$1 = new Vector2();
  16137. var _uvC$1 = new Vector2();
  16138. function Sprite(material) {
  16139. Object3D.call(this);
  16140. this.type = 'Sprite';
  16141. if (_geometry === undefined) {
  16142. _geometry = new BufferGeometry();
  16143. 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]);
  16144. var interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  16145. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  16146. _geometry.addAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  16147. _geometry.addAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  16148. }
  16149. this.geometry = _geometry;
  16150. this.material = material !== undefined ? material : new SpriteMaterial();
  16151. this.center = new Vector2(0.5, 0.5);
  16152. }
  16153. Sprite.prototype = Object.assign(Object.create(Object3D.prototype), {
  16154. constructor: Sprite,
  16155. isSprite: true,
  16156. raycast: function (raycaster, intersects) {
  16157. if (raycaster.camera === null) {
  16158. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  16159. }
  16160. _worldScale.setFromMatrixScale(this.matrixWorld);
  16161. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  16162. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  16163. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  16164. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  16165. _worldScale.multiplyScalar(-_mvPosition.z);
  16166. }
  16167. var rotation = this.material.rotation;
  16168. var sin, cos;
  16169. if (rotation !== 0) {
  16170. cos = Math.cos(rotation);
  16171. sin = Math.sin(rotation);
  16172. }
  16173. var center = this.center;
  16174. transformVertex(_vA$1.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16175. transformVertex(_vB$1.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16176. transformVertex(_vC$1.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16177. _uvA$1.set(0, 0);
  16178. _uvB$1.set(1, 0);
  16179. _uvC$1.set(1, 1); // check first triangle
  16180. var intersect = raycaster.ray.intersectTriangle(_vA$1, _vB$1, _vC$1, false, _intersectPoint);
  16181. if (intersect === null) {
  16182. // check second triangle
  16183. transformVertex(_vB$1.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16184. _uvB$1.set(0, 1);
  16185. intersect = raycaster.ray.intersectTriangle(_vA$1, _vC$1, _vB$1, false, _intersectPoint);
  16186. if (intersect === null) {
  16187. return;
  16188. }
  16189. }
  16190. var distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  16191. if (distance < raycaster.near || distance > raycaster.far) return;
  16192. intersects.push({
  16193. distance: distance,
  16194. point: _intersectPoint.clone(),
  16195. uv: Triangle.getUV(_intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2()),
  16196. face: null,
  16197. object: this
  16198. });
  16199. },
  16200. clone: function () {
  16201. return new this.constructor(this.material).copy(this);
  16202. },
  16203. copy: function (source) {
  16204. Object3D.prototype.copy.call(this, source);
  16205. if (source.center !== undefined) this.center.copy(source.center);
  16206. return this;
  16207. }
  16208. });
  16209. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  16210. // compute position in camera space
  16211. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  16212. if (sin !== undefined) {
  16213. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  16214. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  16215. } else {
  16216. _rotatedPosition.copy(_alignedPosition);
  16217. }
  16218. vertexPosition.copy(mvPosition);
  16219. vertexPosition.x += _rotatedPosition.x;
  16220. vertexPosition.y += _rotatedPosition.y; // transform to world space
  16221. vertexPosition.applyMatrix4(_viewWorldMatrix);
  16222. }
  16223. /**
  16224. * @author mikael emtinger / http://gomo.se/
  16225. * @author alteredq / http://alteredqualia.com/
  16226. * @author mrdoob / http://mrdoob.com/
  16227. */
  16228. var _v1$4 = new Vector3();
  16229. var _v2$2 = new Vector3();
  16230. function LOD() {
  16231. Object3D.call(this);
  16232. this.type = 'LOD';
  16233. Object.defineProperties(this, {
  16234. levels: {
  16235. enumerable: true,
  16236. value: []
  16237. }
  16238. });
  16239. this.autoUpdate = true;
  16240. }
  16241. LOD.prototype = Object.assign(Object.create(Object3D.prototype), {
  16242. constructor: LOD,
  16243. isLOD: true,
  16244. copy: function (source) {
  16245. Object3D.prototype.copy.call(this, source, false);
  16246. var levels = source.levels;
  16247. for (var i = 0, l = levels.length; i < l; i++) {
  16248. var level = levels[i];
  16249. this.addLevel(level.object.clone(), level.distance);
  16250. }
  16251. return this;
  16252. },
  16253. addLevel: function (object, distance) {
  16254. if (distance === undefined) distance = 0;
  16255. distance = Math.abs(distance);
  16256. var levels = this.levels;
  16257. for (var l = 0; l < levels.length; l++) {
  16258. if (distance < levels[l].distance) {
  16259. break;
  16260. }
  16261. }
  16262. levels.splice(l, 0, {
  16263. distance: distance,
  16264. object: object
  16265. });
  16266. this.add(object);
  16267. return this;
  16268. },
  16269. getObjectForDistance: function (distance) {
  16270. var levels = this.levels;
  16271. for (var i = 1, l = levels.length; i < l; i++) {
  16272. if (distance < levels[i].distance) {
  16273. break;
  16274. }
  16275. }
  16276. return levels[i - 1].object;
  16277. },
  16278. raycast: function (raycaster, intersects) {
  16279. _v1$4.setFromMatrixPosition(this.matrixWorld);
  16280. var distance = raycaster.ray.origin.distanceTo(_v1$4);
  16281. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  16282. },
  16283. update: function (camera) {
  16284. var levels = this.levels;
  16285. if (levels.length > 1) {
  16286. _v1$4.setFromMatrixPosition(camera.matrixWorld);
  16287. _v2$2.setFromMatrixPosition(this.matrixWorld);
  16288. var distance = _v1$4.distanceTo(_v2$2);
  16289. levels[0].object.visible = true;
  16290. for (var i = 1, l = levels.length; i < l; i++) {
  16291. if (distance >= levels[i].distance) {
  16292. levels[i - 1].object.visible = false;
  16293. levels[i].object.visible = true;
  16294. } else {
  16295. break;
  16296. }
  16297. }
  16298. for (; i < l; i++) {
  16299. levels[i].object.visible = false;
  16300. }
  16301. }
  16302. },
  16303. toJSON: function (meta) {
  16304. var data = Object3D.prototype.toJSON.call(this, meta);
  16305. data.object.levels = [];
  16306. var levels = this.levels;
  16307. for (var i = 0, l = levels.length; i < l; i++) {
  16308. var level = levels[i];
  16309. data.object.levels.push({
  16310. object: level.object.uuid,
  16311. distance: level.distance
  16312. });
  16313. }
  16314. return data;
  16315. }
  16316. });
  16317. /**
  16318. * @author mikael emtinger / http://gomo.se/
  16319. * @author alteredq / http://alteredqualia.com/
  16320. * @author ikerr / http://verold.com
  16321. */
  16322. function SkinnedMesh(geometry, material) {
  16323. if (geometry && geometry.isGeometry) {
  16324. console.error('THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16325. }
  16326. Mesh.call(this, geometry, material);
  16327. this.type = 'SkinnedMesh';
  16328. this.bindMode = 'attached';
  16329. this.bindMatrix = new Matrix4();
  16330. this.bindMatrixInverse = new Matrix4();
  16331. }
  16332. SkinnedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
  16333. constructor: SkinnedMesh,
  16334. isSkinnedMesh: true,
  16335. bind: function (skeleton, bindMatrix) {
  16336. this.skeleton = skeleton;
  16337. if (bindMatrix === undefined) {
  16338. this.updateMatrixWorld(true);
  16339. this.skeleton.calculateInverses();
  16340. bindMatrix = this.matrixWorld;
  16341. }
  16342. this.bindMatrix.copy(bindMatrix);
  16343. this.bindMatrixInverse.getInverse(bindMatrix);
  16344. },
  16345. pose: function () {
  16346. this.skeleton.pose();
  16347. },
  16348. normalizeSkinWeights: function () {
  16349. var vector = new Vector4();
  16350. var skinWeight = this.geometry.attributes.skinWeight;
  16351. for (var i = 0, l = skinWeight.count; i < l; i++) {
  16352. vector.x = skinWeight.getX(i);
  16353. vector.y = skinWeight.getY(i);
  16354. vector.z = skinWeight.getZ(i);
  16355. vector.w = skinWeight.getW(i);
  16356. var scale = 1.0 / vector.manhattanLength();
  16357. if (scale !== Infinity) {
  16358. vector.multiplyScalar(scale);
  16359. } else {
  16360. vector.set(1, 0, 0, 0); // do something reasonable
  16361. }
  16362. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  16363. }
  16364. },
  16365. updateMatrixWorld: function (force) {
  16366. Mesh.prototype.updateMatrixWorld.call(this, force);
  16367. if (this.bindMode === 'attached') {
  16368. this.bindMatrixInverse.getInverse(this.matrixWorld);
  16369. } else if (this.bindMode === 'detached') {
  16370. this.bindMatrixInverse.getInverse(this.bindMatrix);
  16371. } else {
  16372. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  16373. }
  16374. },
  16375. clone: function () {
  16376. return new this.constructor(this.geometry, this.material).copy(this);
  16377. }
  16378. });
  16379. /**
  16380. * @author mikael emtinger / http://gomo.se/
  16381. * @author alteredq / http://alteredqualia.com/
  16382. * @author michael guerrero / http://realitymeltdown.com
  16383. * @author ikerr / http://verold.com
  16384. */
  16385. var _offsetMatrix = new Matrix4();
  16386. var _identityMatrix = new Matrix4();
  16387. function Skeleton(bones, boneInverses) {
  16388. // copy the bone array
  16389. bones = bones || [];
  16390. this.bones = bones.slice(0);
  16391. this.boneMatrices = new Float32Array(this.bones.length * 16);
  16392. this.frame = -1; // use the supplied bone inverses or calculate the inverses
  16393. if (boneInverses === undefined) {
  16394. this.calculateInverses();
  16395. } else {
  16396. if (this.bones.length === boneInverses.length) {
  16397. this.boneInverses = boneInverses.slice(0);
  16398. } else {
  16399. console.warn('THREE.Skeleton boneInverses is the wrong length.');
  16400. this.boneInverses = [];
  16401. for (var i = 0, il = this.bones.length; i < il; i++) {
  16402. this.boneInverses.push(new Matrix4());
  16403. }
  16404. }
  16405. }
  16406. }
  16407. Object.assign(Skeleton.prototype, {
  16408. calculateInverses: function () {
  16409. this.boneInverses = [];
  16410. for (var i = 0, il = this.bones.length; i < il; i++) {
  16411. var inverse = new Matrix4();
  16412. if (this.bones[i]) {
  16413. inverse.getInverse(this.bones[i].matrixWorld);
  16414. }
  16415. this.boneInverses.push(inverse);
  16416. }
  16417. },
  16418. pose: function () {
  16419. var bone, i, il; // recover the bind-time world matrices
  16420. for (i = 0, il = this.bones.length; i < il; i++) {
  16421. bone = this.bones[i];
  16422. if (bone) {
  16423. bone.matrixWorld.getInverse(this.boneInverses[i]);
  16424. }
  16425. } // compute the local matrices, positions, rotations and scales
  16426. for (i = 0, il = this.bones.length; i < il; i++) {
  16427. bone = this.bones[i];
  16428. if (bone) {
  16429. if (bone.parent && bone.parent.isBone) {
  16430. bone.matrix.getInverse(bone.parent.matrixWorld);
  16431. bone.matrix.multiply(bone.matrixWorld);
  16432. } else {
  16433. bone.matrix.copy(bone.matrixWorld);
  16434. }
  16435. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  16436. }
  16437. }
  16438. },
  16439. update: function () {
  16440. var bones = this.bones;
  16441. var boneInverses = this.boneInverses;
  16442. var boneMatrices = this.boneMatrices;
  16443. var boneTexture = this.boneTexture; // flatten bone matrices to array
  16444. for (var i = 0, il = bones.length; i < il; i++) {
  16445. // compute the offset between the current and the original transform
  16446. var matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  16447. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  16448. _offsetMatrix.toArray(boneMatrices, i * 16);
  16449. }
  16450. if (boneTexture !== undefined) {
  16451. boneTexture.needsUpdate = true;
  16452. }
  16453. },
  16454. clone: function () {
  16455. return new Skeleton(this.bones, this.boneInverses);
  16456. },
  16457. getBoneByName: function (name) {
  16458. for (var i = 0, il = this.bones.length; i < il; i++) {
  16459. var bone = this.bones[i];
  16460. if (bone.name === name) {
  16461. return bone;
  16462. }
  16463. }
  16464. return undefined;
  16465. }
  16466. });
  16467. /**
  16468. * @author mikael emtinger / http://gomo.se/
  16469. * @author alteredq / http://alteredqualia.com/
  16470. * @author ikerr / http://verold.com
  16471. */
  16472. function Bone() {
  16473. Object3D.call(this);
  16474. this.type = 'Bone';
  16475. }
  16476. Bone.prototype = Object.assign(Object.create(Object3D.prototype), {
  16477. constructor: Bone,
  16478. isBone: true
  16479. });
  16480. /**
  16481. * @author mrdoob / http://mrdoob.com/
  16482. */
  16483. function InstancedMesh(geometry, material, count) {
  16484. Mesh.call(this, geometry, material);
  16485. this.instanceMatrix = new BufferAttribute(new Float32Array(count * 16), 16);
  16486. this.count = count;
  16487. }
  16488. InstancedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
  16489. constructor: InstancedMesh,
  16490. isInstancedMesh: true,
  16491. raycast: function () {},
  16492. setMatrixAt: function (index, matrix) {
  16493. matrix.toArray(this.instanceMatrix.array, index * 16);
  16494. },
  16495. updateMorphTargets: function () {}
  16496. });
  16497. /**
  16498. * @author mrdoob / http://mrdoob.com/
  16499. * @author alteredq / http://alteredqualia.com/
  16500. *
  16501. * parameters = {
  16502. * color: <hex>,
  16503. * opacity: <float>,
  16504. *
  16505. * linewidth: <float>,
  16506. * linecap: "round",
  16507. * linejoin: "round"
  16508. * }
  16509. */
  16510. function LineBasicMaterial(parameters) {
  16511. Material.call(this);
  16512. this.type = 'LineBasicMaterial';
  16513. this.color = new Color(0xffffff);
  16514. this.linewidth = 1;
  16515. this.linecap = 'round';
  16516. this.linejoin = 'round';
  16517. this.setValues(parameters);
  16518. }
  16519. LineBasicMaterial.prototype = Object.create(Material.prototype);
  16520. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  16521. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  16522. LineBasicMaterial.prototype.copy = function (source) {
  16523. Material.prototype.copy.call(this, source);
  16524. this.color.copy(source.color);
  16525. this.linewidth = source.linewidth;
  16526. this.linecap = source.linecap;
  16527. this.linejoin = source.linejoin;
  16528. return this;
  16529. };
  16530. /**
  16531. * @author mrdoob / http://mrdoob.com/
  16532. */
  16533. var _start = new Vector3();
  16534. var _end = new Vector3();
  16535. var _inverseMatrix$1 = new Matrix4();
  16536. var _ray$1 = new Ray();
  16537. var _sphere$2 = new Sphere();
  16538. function Line(geometry, material, mode) {
  16539. if (mode === 1) {
  16540. console.error('THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.');
  16541. }
  16542. Object3D.call(this);
  16543. this.type = 'Line';
  16544. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  16545. this.material = material !== undefined ? material : new LineBasicMaterial({
  16546. color: Math.random() * 0xffffff
  16547. });
  16548. }
  16549. Line.prototype = Object.assign(Object.create(Object3D.prototype), {
  16550. constructor: Line,
  16551. isLine: true,
  16552. computeLineDistances: function () {
  16553. var geometry = this.geometry;
  16554. if (geometry.isBufferGeometry) {
  16555. // we assume non-indexed geometry
  16556. if (geometry.index === null) {
  16557. var positionAttribute = geometry.attributes.position;
  16558. var lineDistances = [0];
  16559. for (var i = 1, l = positionAttribute.count; i < l; i++) {
  16560. _start.fromBufferAttribute(positionAttribute, i - 1);
  16561. _end.fromBufferAttribute(positionAttribute, i);
  16562. lineDistances[i] = lineDistances[i - 1];
  16563. lineDistances[i] += _start.distanceTo(_end);
  16564. }
  16565. geometry.addAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  16566. } else {
  16567. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  16568. }
  16569. } else if (geometry.isGeometry) {
  16570. var vertices = geometry.vertices;
  16571. var lineDistances = geometry.lineDistances;
  16572. lineDistances[0] = 0;
  16573. for (var i = 1, l = vertices.length; i < l; i++) {
  16574. lineDistances[i] = lineDistances[i - 1];
  16575. lineDistances[i] += vertices[i - 1].distanceTo(vertices[i]);
  16576. }
  16577. }
  16578. return this;
  16579. },
  16580. raycast: function (raycaster, intersects) {
  16581. var precision = raycaster.linePrecision;
  16582. var geometry = this.geometry;
  16583. var matrixWorld = this.matrixWorld; // Checking boundingSphere distance to ray
  16584. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  16585. _sphere$2.copy(geometry.boundingSphere);
  16586. _sphere$2.applyMatrix4(matrixWorld);
  16587. _sphere$2.radius += precision;
  16588. if (raycaster.ray.intersectsSphere(_sphere$2) === false) return; //
  16589. _inverseMatrix$1.getInverse(matrixWorld);
  16590. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  16591. var localPrecision = precision / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  16592. var localPrecisionSq = localPrecision * localPrecision;
  16593. var vStart = new Vector3();
  16594. var vEnd = new Vector3();
  16595. var interSegment = new Vector3();
  16596. var interRay = new Vector3();
  16597. var step = this && this.isLineSegments ? 2 : 1;
  16598. if (geometry.isBufferGeometry) {
  16599. var index = geometry.index;
  16600. var attributes = geometry.attributes;
  16601. var positions = attributes.position.array;
  16602. if (index !== null) {
  16603. var indices = index.array;
  16604. for (var i = 0, l = indices.length - 1; i < l; i += step) {
  16605. var a = indices[i];
  16606. var b = indices[i + 1];
  16607. vStart.fromArray(positions, a * 3);
  16608. vEnd.fromArray(positions, b * 3);
  16609. var distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  16610. if (distSq > localPrecisionSq) continue;
  16611. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16612. var distance = raycaster.ray.origin.distanceTo(interRay);
  16613. if (distance < raycaster.near || distance > raycaster.far) continue;
  16614. intersects.push({
  16615. distance: distance,
  16616. // What do we want? intersection point on the ray or on the segment??
  16617. // point: raycaster.ray.at( distance ),
  16618. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16619. index: i,
  16620. face: null,
  16621. faceIndex: null,
  16622. object: this
  16623. });
  16624. }
  16625. } else {
  16626. for (var i = 0, l = positions.length / 3 - 1; i < l; i += step) {
  16627. vStart.fromArray(positions, 3 * i);
  16628. vEnd.fromArray(positions, 3 * i + 3);
  16629. var distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  16630. if (distSq > localPrecisionSq) continue;
  16631. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16632. var distance = raycaster.ray.origin.distanceTo(interRay);
  16633. if (distance < raycaster.near || distance > raycaster.far) continue;
  16634. intersects.push({
  16635. distance: distance,
  16636. // What do we want? intersection point on the ray or on the segment??
  16637. // point: raycaster.ray.at( distance ),
  16638. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16639. index: i,
  16640. face: null,
  16641. faceIndex: null,
  16642. object: this
  16643. });
  16644. }
  16645. }
  16646. } else if (geometry.isGeometry) {
  16647. var vertices = geometry.vertices;
  16648. var nbVertices = vertices.length;
  16649. for (var i = 0; i < nbVertices - 1; i += step) {
  16650. var distSq = _ray$1.distanceSqToSegment(vertices[i], vertices[i + 1], interRay, interSegment);
  16651. if (distSq > localPrecisionSq) continue;
  16652. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16653. var distance = raycaster.ray.origin.distanceTo(interRay);
  16654. if (distance < raycaster.near || distance > raycaster.far) continue;
  16655. intersects.push({
  16656. distance: distance,
  16657. // What do we want? intersection point on the ray or on the segment??
  16658. // point: raycaster.ray.at( distance ),
  16659. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16660. index: i,
  16661. face: null,
  16662. faceIndex: null,
  16663. object: this
  16664. });
  16665. }
  16666. }
  16667. },
  16668. clone: function () {
  16669. return new this.constructor(this.geometry, this.material).copy(this);
  16670. }
  16671. });
  16672. /**
  16673. * @author mrdoob / http://mrdoob.com/
  16674. */
  16675. var _start$1 = new Vector3();
  16676. var _end$1 = new Vector3();
  16677. function LineSegments(geometry, material) {
  16678. Line.call(this, geometry, material);
  16679. this.type = 'LineSegments';
  16680. }
  16681. LineSegments.prototype = Object.assign(Object.create(Line.prototype), {
  16682. constructor: LineSegments,
  16683. isLineSegments: true,
  16684. computeLineDistances: function () {
  16685. var geometry = this.geometry;
  16686. if (geometry.isBufferGeometry) {
  16687. // we assume non-indexed geometry
  16688. if (geometry.index === null) {
  16689. var positionAttribute = geometry.attributes.position;
  16690. var lineDistances = [];
  16691. for (var i = 0, l = positionAttribute.count; i < l; i += 2) {
  16692. _start$1.fromBufferAttribute(positionAttribute, i);
  16693. _end$1.fromBufferAttribute(positionAttribute, i + 1);
  16694. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  16695. lineDistances[i + 1] = lineDistances[i] + _start$1.distanceTo(_end$1);
  16696. }
  16697. geometry.addAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  16698. } else {
  16699. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  16700. }
  16701. } else if (geometry.isGeometry) {
  16702. var vertices = geometry.vertices;
  16703. var lineDistances = geometry.lineDistances;
  16704. for (var i = 0, l = vertices.length; i < l; i += 2) {
  16705. _start$1.copy(vertices[i]);
  16706. _end$1.copy(vertices[i + 1]);
  16707. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  16708. lineDistances[i + 1] = lineDistances[i] + _start$1.distanceTo(_end$1);
  16709. }
  16710. }
  16711. return this;
  16712. }
  16713. });
  16714. /**
  16715. * @author mgreter / http://github.com/mgreter
  16716. */
  16717. function LineLoop(geometry, material) {
  16718. Line.call(this, geometry, material);
  16719. this.type = 'LineLoop';
  16720. }
  16721. LineLoop.prototype = Object.assign(Object.create(Line.prototype), {
  16722. constructor: LineLoop,
  16723. isLineLoop: true
  16724. });
  16725. /**
  16726. * @author mrdoob / http://mrdoob.com/
  16727. * @author alteredq / http://alteredqualia.com/
  16728. *
  16729. * parameters = {
  16730. * color: <hex>,
  16731. * opacity: <float>,
  16732. * map: new THREE.Texture( <Image> ),
  16733. *
  16734. * size: <float>,
  16735. * sizeAttenuation: <bool>
  16736. *
  16737. * morphTargets: <bool>
  16738. * }
  16739. */
  16740. function PointsMaterial(parameters) {
  16741. Material.call(this);
  16742. this.type = 'PointsMaterial';
  16743. this.color = new Color(0xffffff);
  16744. this.map = null;
  16745. this.size = 1;
  16746. this.sizeAttenuation = true;
  16747. this.morphTargets = false;
  16748. this.setValues(parameters);
  16749. }
  16750. PointsMaterial.prototype = Object.create(Material.prototype);
  16751. PointsMaterial.prototype.constructor = PointsMaterial;
  16752. PointsMaterial.prototype.isPointsMaterial = true;
  16753. PointsMaterial.prototype.copy = function (source) {
  16754. Material.prototype.copy.call(this, source);
  16755. this.color.copy(source.color);
  16756. this.map = source.map;
  16757. this.size = source.size;
  16758. this.sizeAttenuation = source.sizeAttenuation;
  16759. this.morphTargets = source.morphTargets;
  16760. return this;
  16761. };
  16762. /**
  16763. * @author alteredq / http://alteredqualia.com/
  16764. */
  16765. var _inverseMatrix$2 = new Matrix4();
  16766. var _ray$2 = new Ray();
  16767. var _sphere$3 = new Sphere();
  16768. var _position$1 = new Vector3();
  16769. function Points(geometry, material) {
  16770. Object3D.call(this);
  16771. this.type = 'Points';
  16772. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  16773. this.material = material !== undefined ? material : new PointsMaterial({
  16774. color: Math.random() * 0xffffff
  16775. });
  16776. this.updateMorphTargets();
  16777. }
  16778. Points.prototype = Object.assign(Object.create(Object3D.prototype), {
  16779. constructor: Points,
  16780. isPoints: true,
  16781. raycast: function (raycaster, intersects) {
  16782. var geometry = this.geometry;
  16783. var matrixWorld = this.matrixWorld;
  16784. var threshold = raycaster.params.Points.threshold; // Checking boundingSphere distance to ray
  16785. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  16786. _sphere$3.copy(geometry.boundingSphere);
  16787. _sphere$3.applyMatrix4(matrixWorld);
  16788. _sphere$3.radius += threshold;
  16789. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  16790. _inverseMatrix$2.getInverse(matrixWorld);
  16791. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2);
  16792. var localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  16793. var localThresholdSq = localThreshold * localThreshold;
  16794. if (geometry.isBufferGeometry) {
  16795. var index = geometry.index;
  16796. var attributes = geometry.attributes;
  16797. var positions = attributes.position.array;
  16798. if (index !== null) {
  16799. var indices = index.array;
  16800. for (var i = 0, il = indices.length; i < il; i++) {
  16801. var a = indices[i];
  16802. _position$1.fromArray(positions, a * 3);
  16803. testPoint(_position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  16804. }
  16805. } else {
  16806. for (var i = 0, l = positions.length / 3; i < l; i++) {
  16807. _position$1.fromArray(positions, i * 3);
  16808. testPoint(_position$1, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  16809. }
  16810. }
  16811. } else {
  16812. var vertices = geometry.vertices;
  16813. for (var i = 0, l = vertices.length; i < l; i++) {
  16814. testPoint(vertices[i], i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  16815. }
  16816. }
  16817. },
  16818. updateMorphTargets: function () {
  16819. var geometry = this.geometry;
  16820. var m, ml, name;
  16821. if (geometry.isBufferGeometry) {
  16822. var morphAttributes = geometry.morphAttributes;
  16823. var keys = Object.keys(morphAttributes);
  16824. if (keys.length > 0) {
  16825. var morphAttribute = morphAttributes[keys[0]];
  16826. if (morphAttribute !== undefined) {
  16827. this.morphTargetInfluences = [];
  16828. this.morphTargetDictionary = {};
  16829. for (m = 0, ml = morphAttribute.length; m < ml; m++) {
  16830. name = morphAttribute[m].name || String(m);
  16831. this.morphTargetInfluences.push(0);
  16832. this.morphTargetDictionary[name] = m;
  16833. }
  16834. }
  16835. }
  16836. } else {
  16837. var morphTargets = geometry.morphTargets;
  16838. if (morphTargets !== undefined && morphTargets.length > 0) {
  16839. console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  16840. }
  16841. }
  16842. },
  16843. clone: function () {
  16844. return new this.constructor(this.geometry, this.material).copy(this);
  16845. }
  16846. });
  16847. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  16848. var rayPointDistanceSq = _ray$2.distanceSqToPoint(point);
  16849. if (rayPointDistanceSq < localThresholdSq) {
  16850. var intersectPoint = new Vector3();
  16851. _ray$2.closestPointToPoint(point, intersectPoint);
  16852. intersectPoint.applyMatrix4(matrixWorld);
  16853. var distance = raycaster.ray.origin.distanceTo(intersectPoint);
  16854. if (distance < raycaster.near || distance > raycaster.far) return;
  16855. intersects.push({
  16856. distance: distance,
  16857. distanceToRay: Math.sqrt(rayPointDistanceSq),
  16858. point: intersectPoint,
  16859. index: index,
  16860. face: null,
  16861. object: object
  16862. });
  16863. }
  16864. }
  16865. /**
  16866. * @author mrdoob / http://mrdoob.com/
  16867. */
  16868. function VideoTexture(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  16869. Texture.call(this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16870. this.format = format !== undefined ? format : RGBFormat;
  16871. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  16872. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  16873. this.generateMipmaps = false;
  16874. }
  16875. VideoTexture.prototype = Object.assign(Object.create(Texture.prototype), {
  16876. constructor: VideoTexture,
  16877. isVideoTexture: true,
  16878. update: function () {
  16879. var video = this.image;
  16880. if (video.readyState >= video.HAVE_CURRENT_DATA) {
  16881. this.needsUpdate = true;
  16882. }
  16883. }
  16884. });
  16885. /**
  16886. * @author alteredq / http://alteredqualia.com/
  16887. */
  16888. function CompressedTexture(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  16889. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  16890. this.image = {
  16891. width: width,
  16892. height: height
  16893. };
  16894. this.mipmaps = mipmaps; // no flipping for cube textures
  16895. // (also flipping doesn't work for compressed textures )
  16896. this.flipY = false; // can't generate mipmaps for compressed textures
  16897. // mips must be embedded in DDS files
  16898. this.generateMipmaps = false;
  16899. }
  16900. CompressedTexture.prototype = Object.create(Texture.prototype);
  16901. CompressedTexture.prototype.constructor = CompressedTexture;
  16902. CompressedTexture.prototype.isCompressedTexture = true;
  16903. /**
  16904. * @author mrdoob / http://mrdoob.com/
  16905. */
  16906. function CanvasTexture(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  16907. Texture.call(this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16908. this.needsUpdate = true;
  16909. }
  16910. CanvasTexture.prototype = Object.create(Texture.prototype);
  16911. CanvasTexture.prototype.constructor = CanvasTexture;
  16912. CanvasTexture.prototype.isCanvasTexture = true;
  16913. /**
  16914. * @author Matt DesLauriers / @mattdesl
  16915. * @author atix / arthursilber.de
  16916. */
  16917. function DepthTexture(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  16918. format = format !== undefined ? format : DepthFormat;
  16919. if (format !== DepthFormat && format !== DepthStencilFormat) {
  16920. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  16921. }
  16922. if (type === undefined && format === DepthFormat) type = UnsignedShortType;
  16923. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  16924. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16925. this.image = {
  16926. width: width,
  16927. height: height
  16928. };
  16929. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  16930. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  16931. this.flipY = false;
  16932. this.generateMipmaps = false;
  16933. }
  16934. DepthTexture.prototype = Object.create(Texture.prototype);
  16935. DepthTexture.prototype.constructor = DepthTexture;
  16936. DepthTexture.prototype.isDepthTexture = true;
  16937. /**
  16938. * @author mrdoob / http://mrdoob.com/
  16939. * @author Mugen87 / https://github.com/Mugen87
  16940. */
  16941. function WireframeGeometry(geometry) {
  16942. BufferGeometry.call(this);
  16943. this.type = 'WireframeGeometry'; // buffer
  16944. var vertices = []; // helper variables
  16945. var i, j, l, o, ol;
  16946. var edge = [0, 0],
  16947. edges = {},
  16948. e,
  16949. edge1,
  16950. edge2;
  16951. var key,
  16952. keys = ['a', 'b', 'c'];
  16953. var vertex; // different logic for Geometry and BufferGeometry
  16954. if (geometry && geometry.isGeometry) {
  16955. // create a data structure that contains all edges without duplicates
  16956. var faces = geometry.faces;
  16957. for (i = 0, l = faces.length; i < l; i++) {
  16958. var face = faces[i];
  16959. for (j = 0; j < 3; j++) {
  16960. edge1 = face[keys[j]];
  16961. edge2 = face[keys[(j + 1) % 3]];
  16962. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  16963. edge[1] = Math.max(edge1, edge2);
  16964. key = edge[0] + ',' + edge[1];
  16965. if (edges[key] === undefined) {
  16966. edges[key] = {
  16967. index1: edge[0],
  16968. index2: edge[1]
  16969. };
  16970. }
  16971. }
  16972. } // generate vertices
  16973. for (key in edges) {
  16974. e = edges[key];
  16975. vertex = geometry.vertices[e.index1];
  16976. vertices.push(vertex.x, vertex.y, vertex.z);
  16977. vertex = geometry.vertices[e.index2];
  16978. vertices.push(vertex.x, vertex.y, vertex.z);
  16979. }
  16980. } else if (geometry && geometry.isBufferGeometry) {
  16981. var position, indices, groups;
  16982. var group, start, count;
  16983. var index1, index2;
  16984. vertex = new Vector3();
  16985. if (geometry.index !== null) {
  16986. // indexed BufferGeometry
  16987. position = geometry.attributes.position;
  16988. indices = geometry.index;
  16989. groups = geometry.groups;
  16990. if (groups.length === 0) {
  16991. groups = [{
  16992. start: 0,
  16993. count: indices.count,
  16994. materialIndex: 0
  16995. }];
  16996. } // create a data structure that contains all eges without duplicates
  16997. for (o = 0, ol = groups.length; o < ol; ++o) {
  16998. group = groups[o];
  16999. start = group.start;
  17000. count = group.count;
  17001. for (i = start, l = start + count; i < l; i += 3) {
  17002. for (j = 0; j < 3; j++) {
  17003. edge1 = indices.getX(i + j);
  17004. edge2 = indices.getX(i + (j + 1) % 3);
  17005. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  17006. edge[1] = Math.max(edge1, edge2);
  17007. key = edge[0] + ',' + edge[1];
  17008. if (edges[key] === undefined) {
  17009. edges[key] = {
  17010. index1: edge[0],
  17011. index2: edge[1]
  17012. };
  17013. }
  17014. }
  17015. }
  17016. } // generate vertices
  17017. for (key in edges) {
  17018. e = edges[key];
  17019. vertex.fromBufferAttribute(position, e.index1);
  17020. vertices.push(vertex.x, vertex.y, vertex.z);
  17021. vertex.fromBufferAttribute(position, e.index2);
  17022. vertices.push(vertex.x, vertex.y, vertex.z);
  17023. }
  17024. } else {
  17025. // non-indexed BufferGeometry
  17026. position = geometry.attributes.position;
  17027. for (i = 0, l = position.count / 3; i < l; i++) {
  17028. for (j = 0; j < 3; j++) {
  17029. // three edges per triangle, an edge is represented as (index1, index2)
  17030. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  17031. index1 = 3 * i + j;
  17032. vertex.fromBufferAttribute(position, index1);
  17033. vertices.push(vertex.x, vertex.y, vertex.z);
  17034. index2 = 3 * i + (j + 1) % 3;
  17035. vertex.fromBufferAttribute(position, index2);
  17036. vertices.push(vertex.x, vertex.y, vertex.z);
  17037. }
  17038. }
  17039. }
  17040. } // build geometry
  17041. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  17042. }
  17043. WireframeGeometry.prototype = Object.create(BufferGeometry.prototype);
  17044. WireframeGeometry.prototype.constructor = WireframeGeometry;
  17045. /**
  17046. * @author zz85 / https://github.com/zz85
  17047. * @author Mugen87 / https://github.com/Mugen87
  17048. *
  17049. * Parametric Surfaces Geometry
  17050. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  17051. */
  17052. // ParametricGeometry
  17053. function ParametricGeometry(func, slices, stacks) {
  17054. Geometry.call(this);
  17055. this.type = 'ParametricGeometry';
  17056. this.parameters = {
  17057. func: func,
  17058. slices: slices,
  17059. stacks: stacks
  17060. };
  17061. this.fromBufferGeometry(new ParametricBufferGeometry(func, slices, stacks));
  17062. this.mergeVertices();
  17063. }
  17064. ParametricGeometry.prototype = Object.create(Geometry.prototype);
  17065. ParametricGeometry.prototype.constructor = ParametricGeometry; // ParametricBufferGeometry
  17066. function ParametricBufferGeometry(func, slices, stacks) {
  17067. BufferGeometry.call(this);
  17068. this.type = 'ParametricBufferGeometry';
  17069. this.parameters = {
  17070. func: func,
  17071. slices: slices,
  17072. stacks: stacks
  17073. }; // buffers
  17074. var indices = [];
  17075. var vertices = [];
  17076. var normals = [];
  17077. var uvs = [];
  17078. var EPS = 0.00001;
  17079. var normal = new Vector3();
  17080. var p0 = new Vector3(),
  17081. p1 = new Vector3();
  17082. var pu = new Vector3(),
  17083. pv = new Vector3();
  17084. var i, j;
  17085. if (func.length < 3) {
  17086. console.error('THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.');
  17087. } // generate vertices, normals and uvs
  17088. var sliceCount = slices + 1;
  17089. for (i = 0; i <= stacks; i++) {
  17090. var v = i / stacks;
  17091. for (j = 0; j <= slices; j++) {
  17092. var u = j / slices; // vertex
  17093. func(u, v, p0);
  17094. vertices.push(p0.x, p0.y, p0.z); // normal
  17095. // approximate tangent vectors via finite differences
  17096. if (u - EPS >= 0) {
  17097. func(u - EPS, v, p1);
  17098. pu.subVectors(p0, p1);
  17099. } else {
  17100. func(u + EPS, v, p1);
  17101. pu.subVectors(p1, p0);
  17102. }
  17103. if (v - EPS >= 0) {
  17104. func(u, v - EPS, p1);
  17105. pv.subVectors(p0, p1);
  17106. } else {
  17107. func(u, v + EPS, p1);
  17108. pv.subVectors(p1, p0);
  17109. } // cross product of tangent vectors returns surface normal
  17110. normal.crossVectors(pu, pv).normalize();
  17111. normals.push(normal.x, normal.y, normal.z); // uv
  17112. uvs.push(u, v);
  17113. }
  17114. } // generate indices
  17115. for (i = 0; i < stacks; i++) {
  17116. for (j = 0; j < slices; j++) {
  17117. var a = i * sliceCount + j;
  17118. var b = i * sliceCount + j + 1;
  17119. var c = (i + 1) * sliceCount + j + 1;
  17120. var d = (i + 1) * sliceCount + j; // faces one and two
  17121. indices.push(a, b, d);
  17122. indices.push(b, c, d);
  17123. }
  17124. } // build geometry
  17125. this.setIndex(indices);
  17126. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  17127. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  17128. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  17129. }
  17130. ParametricBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  17131. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  17132. /**
  17133. * @author clockworkgeek / https://github.com/clockworkgeek
  17134. * @author timothypratley / https://github.com/timothypratley
  17135. * @author WestLangley / http://github.com/WestLangley
  17136. * @author Mugen87 / https://github.com/Mugen87
  17137. */
  17138. // PolyhedronGeometry
  17139. function PolyhedronGeometry(vertices, indices, radius, detail) {
  17140. Geometry.call(this);
  17141. this.type = 'PolyhedronGeometry';
  17142. this.parameters = {
  17143. vertices: vertices,
  17144. indices: indices,
  17145. radius: radius,
  17146. detail: detail
  17147. };
  17148. this.fromBufferGeometry(new PolyhedronBufferGeometry(vertices, indices, radius, detail));
  17149. this.mergeVertices();
  17150. }
  17151. PolyhedronGeometry.prototype = Object.create(Geometry.prototype);
  17152. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry; // PolyhedronBufferGeometry
  17153. function PolyhedronBufferGeometry(vertices, indices, radius, detail) {
  17154. BufferGeometry.call(this);
  17155. this.type = 'PolyhedronBufferGeometry';
  17156. this.parameters = {
  17157. vertices: vertices,
  17158. indices: indices,
  17159. radius: radius,
  17160. detail: detail
  17161. };
  17162. radius = radius || 1;
  17163. detail = detail || 0; // default buffer data
  17164. var vertexBuffer = [];
  17165. var uvBuffer = []; // the subdivision creates the vertex buffer data
  17166. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  17167. applyRadius(radius); // finally, create the uv data
  17168. generateUVs(); // build non-indexed geometry
  17169. this.addAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  17170. this.addAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  17171. this.addAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  17172. if (detail === 0) {
  17173. this.computeVertexNormals(); // flat normals
  17174. } else {
  17175. this.normalizeNormals(); // smooth normals
  17176. } // helper functions
  17177. function subdivide(detail) {
  17178. var a = new Vector3();
  17179. var b = new Vector3();
  17180. var c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  17181. for (var i = 0; i < indices.length; i += 3) {
  17182. // get the vertices of the face
  17183. getVertexByIndex(indices[i + 0], a);
  17184. getVertexByIndex(indices[i + 1], b);
  17185. getVertexByIndex(indices[i + 2], c); // perform subdivision
  17186. subdivideFace(a, b, c, detail);
  17187. }
  17188. }
  17189. function subdivideFace(a, b, c, detail) {
  17190. var cols = Math.pow(2, detail); // we use this multidimensional array as a data structure for creating the subdivision
  17191. var v = [];
  17192. var i, j; // construct all of the vertices for this subdivision
  17193. for (i = 0; i <= cols; i++) {
  17194. v[i] = [];
  17195. var aj = a.clone().lerp(c, i / cols);
  17196. var bj = b.clone().lerp(c, i / cols);
  17197. var rows = cols - i;
  17198. for (j = 0; j <= rows; j++) {
  17199. if (j === 0 && i === cols) {
  17200. v[i][j] = aj;
  17201. } else {
  17202. v[i][j] = aj.clone().lerp(bj, j / rows);
  17203. }
  17204. }
  17205. } // construct all of the faces
  17206. for (i = 0; i < cols; i++) {
  17207. for (j = 0; j < 2 * (cols - i) - 1; j++) {
  17208. var k = Math.floor(j / 2);
  17209. if (j % 2 === 0) {
  17210. pushVertex(v[i][k + 1]);
  17211. pushVertex(v[i + 1][k]);
  17212. pushVertex(v[i][k]);
  17213. } else {
  17214. pushVertex(v[i][k + 1]);
  17215. pushVertex(v[i + 1][k + 1]);
  17216. pushVertex(v[i + 1][k]);
  17217. }
  17218. }
  17219. }
  17220. }
  17221. function applyRadius(radius) {
  17222. var vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  17223. for (var i = 0; i < vertexBuffer.length; i += 3) {
  17224. vertex.x = vertexBuffer[i + 0];
  17225. vertex.y = vertexBuffer[i + 1];
  17226. vertex.z = vertexBuffer[i + 2];
  17227. vertex.normalize().multiplyScalar(radius);
  17228. vertexBuffer[i + 0] = vertex.x;
  17229. vertexBuffer[i + 1] = vertex.y;
  17230. vertexBuffer[i + 2] = vertex.z;
  17231. }
  17232. }
  17233. function generateUVs() {
  17234. var vertex = new Vector3();
  17235. for (var i = 0; i < vertexBuffer.length; i += 3) {
  17236. vertex.x = vertexBuffer[i + 0];
  17237. vertex.y = vertexBuffer[i + 1];
  17238. vertex.z = vertexBuffer[i + 2];
  17239. var u = azimuth(vertex) / 2 / Math.PI + 0.5;
  17240. var v = inclination(vertex) / Math.PI + 0.5;
  17241. uvBuffer.push(u, 1 - v);
  17242. }
  17243. correctUVs();
  17244. correctSeam();
  17245. }
  17246. function correctSeam() {
  17247. // handle case when face straddles the seam, see #3269
  17248. for (var i = 0; i < uvBuffer.length; i += 6) {
  17249. // uv data of a single face
  17250. var x0 = uvBuffer[i + 0];
  17251. var x1 = uvBuffer[i + 2];
  17252. var x2 = uvBuffer[i + 4];
  17253. var max = Math.max(x0, x1, x2);
  17254. var min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  17255. if (max > 0.9 && min < 0.1) {
  17256. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  17257. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  17258. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  17259. }
  17260. }
  17261. }
  17262. function pushVertex(vertex) {
  17263. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  17264. }
  17265. function getVertexByIndex(index, vertex) {
  17266. var stride = index * 3;
  17267. vertex.x = vertices[stride + 0];
  17268. vertex.y = vertices[stride + 1];
  17269. vertex.z = vertices[stride + 2];
  17270. }
  17271. function correctUVs() {
  17272. var a = new Vector3();
  17273. var b = new Vector3();
  17274. var c = new Vector3();
  17275. var centroid = new Vector3();
  17276. var uvA = new Vector2();
  17277. var uvB = new Vector2();
  17278. var uvC = new Vector2();
  17279. for (var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  17280. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  17281. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  17282. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  17283. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  17284. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  17285. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  17286. centroid.copy(a).add(b).add(c).divideScalar(3);
  17287. var azi = azimuth(centroid);
  17288. correctUV(uvA, j + 0, a, azi);
  17289. correctUV(uvB, j + 2, b, azi);
  17290. correctUV(uvC, j + 4, c, azi);
  17291. }
  17292. }
  17293. function correctUV(uv, stride, vector, azimuth) {
  17294. if (azimuth < 0 && uv.x === 1) {
  17295. uvBuffer[stride] = uv.x - 1;
  17296. }
  17297. if (vector.x === 0 && vector.z === 0) {
  17298. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  17299. }
  17300. } // Angle around the Y axis, counter-clockwise when looking from above.
  17301. function azimuth(vector) {
  17302. return Math.atan2(vector.z, -vector.x);
  17303. } // Angle above the XZ plane.
  17304. function inclination(vector) {
  17305. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  17306. }
  17307. }
  17308. PolyhedronBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  17309. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  17310. /**
  17311. * @author timothypratley / https://github.com/timothypratley
  17312. * @author Mugen87 / https://github.com/Mugen87
  17313. */
  17314. // TetrahedronGeometry
  17315. function TetrahedronGeometry(radius, detail) {
  17316. Geometry.call(this);
  17317. this.type = 'TetrahedronGeometry';
  17318. this.parameters = {
  17319. radius: radius,
  17320. detail: detail
  17321. };
  17322. this.fromBufferGeometry(new TetrahedronBufferGeometry(radius, detail));
  17323. this.mergeVertices();
  17324. }
  17325. TetrahedronGeometry.prototype = Object.create(Geometry.prototype);
  17326. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry; // TetrahedronBufferGeometry
  17327. function TetrahedronBufferGeometry(radius, detail) {
  17328. var vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  17329. var indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  17330. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  17331. this.type = 'TetrahedronBufferGeometry';
  17332. this.parameters = {
  17333. radius: radius,
  17334. detail: detail
  17335. };
  17336. }
  17337. TetrahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  17338. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  17339. /**
  17340. * @author timothypratley / https://github.com/timothypratley
  17341. * @author Mugen87 / https://github.com/Mugen87
  17342. */
  17343. // OctahedronGeometry
  17344. function OctahedronGeometry(radius, detail) {
  17345. Geometry.call(this);
  17346. this.type = 'OctahedronGeometry';
  17347. this.parameters = {
  17348. radius: radius,
  17349. detail: detail
  17350. };
  17351. this.fromBufferGeometry(new OctahedronBufferGeometry(radius, detail));
  17352. this.mergeVertices();
  17353. }
  17354. OctahedronGeometry.prototype = Object.create(Geometry.prototype);
  17355. OctahedronGeometry.prototype.constructor = OctahedronGeometry; // OctahedronBufferGeometry
  17356. function OctahedronBufferGeometry(radius, detail) {
  17357. var vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  17358. 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];
  17359. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  17360. this.type = 'OctahedronBufferGeometry';
  17361. this.parameters = {
  17362. radius: radius,
  17363. detail: detail
  17364. };
  17365. }
  17366. OctahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  17367. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  17368. /**
  17369. * @author timothypratley / https://github.com/timothypratley
  17370. * @author Mugen87 / https://github.com/Mugen87
  17371. */
  17372. // IcosahedronGeometry
  17373. function IcosahedronGeometry(radius, detail) {
  17374. Geometry.call(this);
  17375. this.type = 'IcosahedronGeometry';
  17376. this.parameters = {
  17377. radius: radius,
  17378. detail: detail
  17379. };
  17380. this.fromBufferGeometry(new IcosahedronBufferGeometry(radius, detail));
  17381. this.mergeVertices();
  17382. }
  17383. IcosahedronGeometry.prototype = Object.create(Geometry.prototype);
  17384. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry; // IcosahedronBufferGeometry
  17385. function IcosahedronBufferGeometry(radius, detail) {
  17386. var t = (1 + Math.sqrt(5)) / 2;
  17387. 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];
  17388. 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];
  17389. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  17390. this.type = 'IcosahedronBufferGeometry';
  17391. this.parameters = {
  17392. radius: radius,
  17393. detail: detail
  17394. };
  17395. }
  17396. IcosahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  17397. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  17398. /**
  17399. * @author Abe Pazos / https://hamoid.com
  17400. * @author Mugen87 / https://github.com/Mugen87
  17401. */
  17402. // DodecahedronGeometry
  17403. function DodecahedronGeometry(radius, detail) {
  17404. Geometry.call(this);
  17405. this.type = 'DodecahedronGeometry';
  17406. this.parameters = {
  17407. radius: radius,
  17408. detail: detail
  17409. };
  17410. this.fromBufferGeometry(new DodecahedronBufferGeometry(radius, detail));
  17411. this.mergeVertices();
  17412. }
  17413. DodecahedronGeometry.prototype = Object.create(Geometry.prototype);
  17414. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry; // DodecahedronBufferGeometry
  17415. function DodecahedronBufferGeometry(radius, detail) {
  17416. var t = (1 + Math.sqrt(5)) / 2;
  17417. var r = 1 / t;
  17418. var vertices = [// (±1, ±1, ±1)
  17419. -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/φ, ±φ)
  17420. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  17421. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  17422. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  17423. 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];
  17424. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  17425. this.type = 'DodecahedronBufferGeometry';
  17426. this.parameters = {
  17427. radius: radius,
  17428. detail: detail
  17429. };
  17430. }
  17431. DodecahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  17432. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  17433. /**
  17434. * @author oosmoxiecode / https://github.com/oosmoxiecode
  17435. * @author WestLangley / https://github.com/WestLangley
  17436. * @author zz85 / https://github.com/zz85
  17437. * @author miningold / https://github.com/miningold
  17438. * @author jonobr1 / https://github.com/jonobr1
  17439. * @author Mugen87 / https://github.com/Mugen87
  17440. *
  17441. */
  17442. // TubeGeometry
  17443. function TubeGeometry(path, tubularSegments, radius, radialSegments, closed, taper) {
  17444. Geometry.call(this);
  17445. this.type = 'TubeGeometry';
  17446. this.parameters = {
  17447. path: path,
  17448. tubularSegments: tubularSegments,
  17449. radius: radius,
  17450. radialSegments: radialSegments,
  17451. closed: closed
  17452. };
  17453. if (taper !== undefined) console.warn('THREE.TubeGeometry: taper has been removed.');
  17454. var bufferGeometry = new TubeBufferGeometry(path, tubularSegments, radius, radialSegments, closed); // expose internals
  17455. this.tangents = bufferGeometry.tangents;
  17456. this.normals = bufferGeometry.normals;
  17457. this.binormals = bufferGeometry.binormals; // create geometry
  17458. this.fromBufferGeometry(bufferGeometry);
  17459. this.mergeVertices();
  17460. }
  17461. TubeGeometry.prototype = Object.create(Geometry.prototype);
  17462. TubeGeometry.prototype.constructor = TubeGeometry; // TubeBufferGeometry
  17463. function TubeBufferGeometry(path, tubularSegments, radius, radialSegments, closed) {
  17464. BufferGeometry.call(this);
  17465. this.type = 'TubeBufferGeometry';
  17466. this.parameters = {
  17467. path: path,
  17468. tubularSegments: tubularSegments,
  17469. radius: radius,
  17470. radialSegments: radialSegments,
  17471. closed: closed
  17472. };
  17473. tubularSegments = tubularSegments || 64;
  17474. radius = radius || 1;
  17475. radialSegments = radialSegments || 8;
  17476. closed = closed || false;
  17477. var frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  17478. this.tangents = frames.tangents;
  17479. this.normals = frames.normals;
  17480. this.binormals = frames.binormals; // helper variables
  17481. var vertex = new Vector3();
  17482. var normal = new Vector3();
  17483. var uv = new Vector2();
  17484. var P = new Vector3();
  17485. var i, j; // buffer
  17486. var vertices = [];
  17487. var normals = [];
  17488. var uvs = [];
  17489. var indices = []; // create buffer data
  17490. generateBufferData(); // build geometry
  17491. this.setIndex(indices);
  17492. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  17493. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  17494. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  17495. function generateBufferData() {
  17496. for (i = 0; i < tubularSegments; i++) {
  17497. generateSegment(i);
  17498. } // if the geometry is not closed, generate the last row of vertices and normals
  17499. // at the regular position on the given path
  17500. //
  17501. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  17502. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  17503. // this makes it easy compute correct values for closed geometries
  17504. generateUVs(); // finally create faces
  17505. generateIndices();
  17506. }
  17507. function generateSegment(i) {
  17508. // we use getPointAt to sample evenly distributed points from the given path
  17509. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  17510. var N = frames.normals[i];
  17511. var B = frames.binormals[i]; // generate normals and vertices for the current segment
  17512. for (j = 0; j <= radialSegments; j++) {
  17513. var v = j / radialSegments * Math.PI * 2;
  17514. var sin = Math.sin(v);
  17515. var cos = -Math.cos(v); // normal
  17516. normal.x = cos * N.x + sin * B.x;
  17517. normal.y = cos * N.y + sin * B.y;
  17518. normal.z = cos * N.z + sin * B.z;
  17519. normal.normalize();
  17520. normals.push(normal.x, normal.y, normal.z); // vertex
  17521. vertex.x = P.x + radius * normal.x;
  17522. vertex.y = P.y + radius * normal.y;
  17523. vertex.z = P.z + radius * normal.z;
  17524. vertices.push(vertex.x, vertex.y, vertex.z);
  17525. }
  17526. }
  17527. function generateIndices() {
  17528. for (j = 1; j <= tubularSegments; j++) {
  17529. for (i = 1; i <= radialSegments; i++) {
  17530. var a = (radialSegments + 1) * (j - 1) + (i - 1);
  17531. var b = (radialSegments + 1) * j + (i - 1);
  17532. var c = (radialSegments + 1) * j + i;
  17533. var d = (radialSegments + 1) * (j - 1) + i; // faces
  17534. indices.push(a, b, d);
  17535. indices.push(b, c, d);
  17536. }
  17537. }
  17538. }
  17539. function generateUVs() {
  17540. for (i = 0; i <= tubularSegments; i++) {
  17541. for (j = 0; j <= radialSegments; j++) {
  17542. uv.x = i / tubularSegments;
  17543. uv.y = j / radialSegments;
  17544. uvs.push(uv.x, uv.y);
  17545. }
  17546. }
  17547. }
  17548. }
  17549. TubeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  17550. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  17551. TubeBufferGeometry.prototype.toJSON = function () {
  17552. var data = BufferGeometry.prototype.toJSON.call(this);
  17553. data.path = this.parameters.path.toJSON();
  17554. return data;
  17555. };
  17556. /**
  17557. * @author oosmoxiecode
  17558. * @author Mugen87 / https://github.com/Mugen87
  17559. *
  17560. * based on http://www.blackpawn.com/texts/pqtorus/
  17561. */
  17562. // TorusKnotGeometry
  17563. function TorusKnotGeometry(radius, tube, tubularSegments, radialSegments, p, q, heightScale) {
  17564. Geometry.call(this);
  17565. this.type = 'TorusKnotGeometry';
  17566. this.parameters = {
  17567. radius: radius,
  17568. tube: tube,
  17569. tubularSegments: tubularSegments,
  17570. radialSegments: radialSegments,
  17571. p: p,
  17572. q: q
  17573. };
  17574. if (heightScale !== undefined) console.warn('THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.');
  17575. this.fromBufferGeometry(new TorusKnotBufferGeometry(radius, tube, tubularSegments, radialSegments, p, q));
  17576. this.mergeVertices();
  17577. }
  17578. TorusKnotGeometry.prototype = Object.create(Geometry.prototype);
  17579. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry; // TorusKnotBufferGeometry
  17580. function TorusKnotBufferGeometry(radius, tube, tubularSegments, radialSegments, p, q) {
  17581. BufferGeometry.call(this);
  17582. this.type = 'TorusKnotBufferGeometry';
  17583. this.parameters = {
  17584. radius: radius,
  17585. tube: tube,
  17586. tubularSegments: tubularSegments,
  17587. radialSegments: radialSegments,
  17588. p: p,
  17589. q: q
  17590. };
  17591. radius = radius || 1;
  17592. tube = tube || 0.4;
  17593. tubularSegments = Math.floor(tubularSegments) || 64;
  17594. radialSegments = Math.floor(radialSegments) || 8;
  17595. p = p || 2;
  17596. q = q || 3; // buffers
  17597. var indices = [];
  17598. var vertices = [];
  17599. var normals = [];
  17600. var uvs = []; // helper variables
  17601. var i, j;
  17602. var vertex = new Vector3();
  17603. var normal = new Vector3();
  17604. var P1 = new Vector3();
  17605. var P2 = new Vector3();
  17606. var B = new Vector3();
  17607. var T = new Vector3();
  17608. var N = new Vector3(); // generate vertices, normals and uvs
  17609. for (i = 0; i <= tubularSegments; ++i) {
  17610. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  17611. 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.
  17612. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  17613. calculatePositionOnCurve(u, p, q, radius, P1);
  17614. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  17615. T.subVectors(P2, P1);
  17616. N.addVectors(P2, P1);
  17617. B.crossVectors(T, N);
  17618. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  17619. B.normalize();
  17620. N.normalize();
  17621. for (j = 0; j <= radialSegments; ++j) {
  17622. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  17623. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  17624. var v = j / radialSegments * Math.PI * 2;
  17625. var cx = -tube * Math.cos(v);
  17626. var cy = tube * Math.sin(v); // now calculate the final vertex position.
  17627. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  17628. vertex.x = P1.x + (cx * N.x + cy * B.x);
  17629. vertex.y = P1.y + (cx * N.y + cy * B.y);
  17630. vertex.z = P1.z + (cx * N.z + cy * B.z);
  17631. 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)
  17632. normal.subVectors(vertex, P1).normalize();
  17633. normals.push(normal.x, normal.y, normal.z); // uv
  17634. uvs.push(i / tubularSegments);
  17635. uvs.push(j / radialSegments);
  17636. }
  17637. } // generate indices
  17638. for (j = 1; j <= tubularSegments; j++) {
  17639. for (i = 1; i <= radialSegments; i++) {
  17640. // indices
  17641. var a = (radialSegments + 1) * (j - 1) + (i - 1);
  17642. var b = (radialSegments + 1) * j + (i - 1);
  17643. var c = (radialSegments + 1) * j + i;
  17644. var d = (radialSegments + 1) * (j - 1) + i; // faces
  17645. indices.push(a, b, d);
  17646. indices.push(b, c, d);
  17647. }
  17648. } // build geometry
  17649. this.setIndex(indices);
  17650. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  17651. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  17652. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  17653. function calculatePositionOnCurve(u, p, q, radius, position) {
  17654. var cu = Math.cos(u);
  17655. var su = Math.sin(u);
  17656. var quOverP = q / p * u;
  17657. var cs = Math.cos(quOverP);
  17658. position.x = radius * (2 + cs) * 0.5 * cu;
  17659. position.y = radius * (2 + cs) * su * 0.5;
  17660. position.z = radius * Math.sin(quOverP) * 0.5;
  17661. }
  17662. }
  17663. TorusKnotBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  17664. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  17665. /**
  17666. * @author oosmoxiecode
  17667. * @author mrdoob / http://mrdoob.com/
  17668. * @author Mugen87 / https://github.com/Mugen87
  17669. */
  17670. // TorusGeometry
  17671. function TorusGeometry(radius, tube, radialSegments, tubularSegments, arc) {
  17672. Geometry.call(this);
  17673. this.type = 'TorusGeometry';
  17674. this.parameters = {
  17675. radius: radius,
  17676. tube: tube,
  17677. radialSegments: radialSegments,
  17678. tubularSegments: tubularSegments,
  17679. arc: arc
  17680. };
  17681. this.fromBufferGeometry(new TorusBufferGeometry(radius, tube, radialSegments, tubularSegments, arc));
  17682. this.mergeVertices();
  17683. }
  17684. TorusGeometry.prototype = Object.create(Geometry.prototype);
  17685. TorusGeometry.prototype.constructor = TorusGeometry; // TorusBufferGeometry
  17686. function TorusBufferGeometry(radius, tube, radialSegments, tubularSegments, arc) {
  17687. BufferGeometry.call(this);
  17688. this.type = 'TorusBufferGeometry';
  17689. this.parameters = {
  17690. radius: radius,
  17691. tube: tube,
  17692. radialSegments: radialSegments,
  17693. tubularSegments: tubularSegments,
  17694. arc: arc
  17695. };
  17696. radius = radius || 1;
  17697. tube = tube || 0.4;
  17698. radialSegments = Math.floor(radialSegments) || 8;
  17699. tubularSegments = Math.floor(tubularSegments) || 6;
  17700. arc = arc || Math.PI * 2; // buffers
  17701. var indices = [];
  17702. var vertices = [];
  17703. var normals = [];
  17704. var uvs = []; // helper variables
  17705. var center = new Vector3();
  17706. var vertex = new Vector3();
  17707. var normal = new Vector3();
  17708. var j, i; // generate vertices, normals and uvs
  17709. for (j = 0; j <= radialSegments; j++) {
  17710. for (i = 0; i <= tubularSegments; i++) {
  17711. var u = i / tubularSegments * arc;
  17712. var v = j / radialSegments * Math.PI * 2; // vertex
  17713. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  17714. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  17715. vertex.z = tube * Math.sin(v);
  17716. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  17717. center.x = radius * Math.cos(u);
  17718. center.y = radius * Math.sin(u);
  17719. normal.subVectors(vertex, center).normalize();
  17720. normals.push(normal.x, normal.y, normal.z); // uv
  17721. uvs.push(i / tubularSegments);
  17722. uvs.push(j / radialSegments);
  17723. }
  17724. } // generate indices
  17725. for (j = 1; j <= radialSegments; j++) {
  17726. for (i = 1; i <= tubularSegments; i++) {
  17727. // indices
  17728. var a = (tubularSegments + 1) * j + i - 1;
  17729. var b = (tubularSegments + 1) * (j - 1) + i - 1;
  17730. var c = (tubularSegments + 1) * (j - 1) + i;
  17731. var d = (tubularSegments + 1) * j + i; // faces
  17732. indices.push(a, b, d);
  17733. indices.push(b, c, d);
  17734. }
  17735. } // build geometry
  17736. this.setIndex(indices);
  17737. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  17738. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  17739. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  17740. }
  17741. TorusBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  17742. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  17743. /**
  17744. * @author Mugen87 / https://github.com/Mugen87
  17745. * Port from https://github.com/mapbox/earcut (v2.1.5)
  17746. */
  17747. var Earcut = {
  17748. triangulate: function (data, holeIndices, dim) {
  17749. dim = dim || 2;
  17750. var hasHoles = holeIndices && holeIndices.length,
  17751. outerLen = hasHoles ? holeIndices[0] * dim : data.length,
  17752. outerNode = linkedList(data, 0, outerLen, dim, true),
  17753. triangles = [];
  17754. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  17755. var minX, minY, maxX, maxY, x, y, invSize;
  17756. 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
  17757. if (data.length > 80 * dim) {
  17758. minX = maxX = data[0];
  17759. minY = maxY = data[1];
  17760. for (var i = dim; i < outerLen; i += dim) {
  17761. x = data[i];
  17762. y = data[i + 1];
  17763. if (x < minX) minX = x;
  17764. if (y < minY) minY = y;
  17765. if (x > maxX) maxX = x;
  17766. if (y > maxY) maxY = y;
  17767. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  17768. invSize = Math.max(maxX - minX, maxY - minY);
  17769. invSize = invSize !== 0 ? 1 / invSize : 0;
  17770. }
  17771. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  17772. return triangles;
  17773. }
  17774. }; // create a circular doubly linked list from polygon points in the specified winding order
  17775. function linkedList(data, start, end, dim, clockwise) {
  17776. var i, last;
  17777. if (clockwise === signedArea(data, start, end, dim) > 0) {
  17778. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  17779. } else {
  17780. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  17781. }
  17782. if (last && equals(last, last.next)) {
  17783. removeNode(last);
  17784. last = last.next;
  17785. }
  17786. return last;
  17787. } // eliminate colinear or duplicate points
  17788. function filterPoints(start, end) {
  17789. if (!start) return start;
  17790. if (!end) end = start;
  17791. var p = start,
  17792. again;
  17793. do {
  17794. again = false;
  17795. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  17796. removeNode(p);
  17797. p = end = p.prev;
  17798. if (p === p.next) break;
  17799. again = true;
  17800. } else {
  17801. p = p.next;
  17802. }
  17803. } while (again || p !== end);
  17804. return end;
  17805. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  17806. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  17807. if (!ear) return; // interlink polygon nodes in z-order
  17808. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  17809. var stop = ear,
  17810. prev,
  17811. next; // iterate through ears, slicing them one by one
  17812. while (ear.prev !== ear.next) {
  17813. prev = ear.prev;
  17814. next = ear.next;
  17815. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  17816. // cut off the triangle
  17817. triangles.push(prev.i / dim);
  17818. triangles.push(ear.i / dim);
  17819. triangles.push(next.i / dim);
  17820. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  17821. ear = next.next;
  17822. stop = next.next;
  17823. continue;
  17824. }
  17825. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  17826. if (ear === stop) {
  17827. // try filtering points and slicing again
  17828. if (!pass) {
  17829. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  17830. } else if (pass === 1) {
  17831. ear = cureLocalIntersections(ear, triangles, dim);
  17832. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  17833. } else if (pass === 2) {
  17834. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  17835. }
  17836. break;
  17837. }
  17838. }
  17839. } // check whether a polygon node forms a valid ear with adjacent nodes
  17840. function isEar(ear) {
  17841. var a = ear.prev,
  17842. b = ear,
  17843. c = ear.next;
  17844. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  17845. // now make sure we don't have other points inside the potential ear
  17846. var p = ear.next.next;
  17847. while (p !== ear.prev) {
  17848. 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;
  17849. p = p.next;
  17850. }
  17851. return true;
  17852. }
  17853. function isEarHashed(ear, minX, minY, invSize) {
  17854. var a = ear.prev,
  17855. b = ear,
  17856. c = ear.next;
  17857. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  17858. // triangle bbox; min & max are calculated like this for speed
  17859. var minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  17860. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  17861. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  17862. 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;
  17863. var minZ = zOrder(minTX, minTY, minX, minY, invSize),
  17864. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  17865. var p = ear.prevZ,
  17866. n = ear.nextZ; // look for points inside the triangle in both directions
  17867. while (p && p.z >= minZ && n && n.z <= maxZ) {
  17868. 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;
  17869. p = p.prevZ;
  17870. 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;
  17871. n = n.nextZ;
  17872. } // look for remaining points in decreasing z-order
  17873. while (p && p.z >= minZ) {
  17874. 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;
  17875. p = p.prevZ;
  17876. } // look for remaining points in increasing z-order
  17877. while (n && n.z <= maxZ) {
  17878. 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;
  17879. n = n.nextZ;
  17880. }
  17881. return true;
  17882. } // go through all polygon nodes and cure small local self-intersections
  17883. function cureLocalIntersections(start, triangles, dim) {
  17884. var p = start;
  17885. do {
  17886. var a = p.prev,
  17887. b = p.next.next;
  17888. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  17889. triangles.push(a.i / dim);
  17890. triangles.push(p.i / dim);
  17891. triangles.push(b.i / dim); // remove two nodes involved
  17892. removeNode(p);
  17893. removeNode(p.next);
  17894. p = start = b;
  17895. }
  17896. p = p.next;
  17897. } while (p !== start);
  17898. return p;
  17899. } // try splitting polygon into two and triangulate them independently
  17900. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  17901. // look for a valid diagonal that divides the polygon into two
  17902. var a = start;
  17903. do {
  17904. var b = a.next.next;
  17905. while (b !== a.prev) {
  17906. if (a.i !== b.i && isValidDiagonal(a, b)) {
  17907. // split the polygon in two by the diagonal
  17908. var c = splitPolygon(a, b); // filter colinear points around the cuts
  17909. a = filterPoints(a, a.next);
  17910. c = filterPoints(c, c.next); // run earcut on each half
  17911. earcutLinked(a, triangles, dim, minX, minY, invSize);
  17912. earcutLinked(c, triangles, dim, minX, minY, invSize);
  17913. return;
  17914. }
  17915. b = b.next;
  17916. }
  17917. a = a.next;
  17918. } while (a !== start);
  17919. } // link every hole into the outer loop, producing a single-ring polygon without holes
  17920. function eliminateHoles(data, holeIndices, outerNode, dim) {
  17921. var queue = [],
  17922. i,
  17923. len,
  17924. start,
  17925. end,
  17926. list;
  17927. for (i = 0, len = holeIndices.length; i < len; i++) {
  17928. start = holeIndices[i] * dim;
  17929. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  17930. list = linkedList(data, start, end, dim, false);
  17931. if (list === list.next) list.steiner = true;
  17932. queue.push(getLeftmost(list));
  17933. }
  17934. queue.sort(compareX); // process holes from left to right
  17935. for (i = 0; i < queue.length; i++) {
  17936. eliminateHole(queue[i], outerNode);
  17937. outerNode = filterPoints(outerNode, outerNode.next);
  17938. }
  17939. return outerNode;
  17940. }
  17941. function compareX(a, b) {
  17942. return a.x - b.x;
  17943. } // find a bridge between vertices that connects hole with an outer ring and and link it
  17944. function eliminateHole(hole, outerNode) {
  17945. outerNode = findHoleBridge(hole, outerNode);
  17946. if (outerNode) {
  17947. var b = splitPolygon(outerNode, hole);
  17948. filterPoints(b, b.next);
  17949. }
  17950. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  17951. function findHoleBridge(hole, outerNode) {
  17952. var p = outerNode,
  17953. hx = hole.x,
  17954. hy = hole.y,
  17955. qx = -Infinity,
  17956. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  17957. // segment's endpoint with lesser x will be potential connection point
  17958. do {
  17959. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  17960. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  17961. if (x <= hx && x > qx) {
  17962. qx = x;
  17963. if (x === hx) {
  17964. if (hy === p.y) return p;
  17965. if (hy === p.next.y) return p.next;
  17966. }
  17967. m = p.x < p.next.x ? p : p.next;
  17968. }
  17969. }
  17970. p = p.next;
  17971. } while (p !== outerNode);
  17972. if (!m) return null;
  17973. if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint
  17974. // look for points inside the triangle of hole point, segment intersection and endpoint;
  17975. // if there are no points found, we have a valid connection;
  17976. // otherwise choose the point of the minimum angle with the ray as connection point
  17977. var stop = m,
  17978. mx = m.x,
  17979. my = m.y,
  17980. tanMin = Infinity,
  17981. tan;
  17982. p = m.next;
  17983. while (p !== stop) {
  17984. 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)) {
  17985. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  17986. if ((tan < tanMin || tan === tanMin && p.x > m.x) && locallyInside(p, hole)) {
  17987. m = p;
  17988. tanMin = tan;
  17989. }
  17990. }
  17991. p = p.next;
  17992. }
  17993. return m;
  17994. } // interlink polygon nodes in z-order
  17995. function indexCurve(start, minX, minY, invSize) {
  17996. var p = start;
  17997. do {
  17998. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  17999. p.prevZ = p.prev;
  18000. p.nextZ = p.next;
  18001. p = p.next;
  18002. } while (p !== start);
  18003. p.prevZ.nextZ = null;
  18004. p.prevZ = null;
  18005. sortLinked(p);
  18006. } // Simon Tatham's linked list merge sort algorithm
  18007. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  18008. function sortLinked(list) {
  18009. var i,
  18010. p,
  18011. q,
  18012. e,
  18013. tail,
  18014. numMerges,
  18015. pSize,
  18016. qSize,
  18017. inSize = 1;
  18018. do {
  18019. p = list;
  18020. list = null;
  18021. tail = null;
  18022. numMerges = 0;
  18023. while (p) {
  18024. numMerges++;
  18025. q = p;
  18026. pSize = 0;
  18027. for (i = 0; i < inSize; i++) {
  18028. pSize++;
  18029. q = q.nextZ;
  18030. if (!q) break;
  18031. }
  18032. qSize = inSize;
  18033. while (pSize > 0 || qSize > 0 && q) {
  18034. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  18035. e = p;
  18036. p = p.nextZ;
  18037. pSize--;
  18038. } else {
  18039. e = q;
  18040. q = q.nextZ;
  18041. qSize--;
  18042. }
  18043. if (tail) tail.nextZ = e;else list = e;
  18044. e.prevZ = tail;
  18045. tail = e;
  18046. }
  18047. p = q;
  18048. }
  18049. tail.nextZ = null;
  18050. inSize *= 2;
  18051. } while (numMerges > 1);
  18052. return list;
  18053. } // z-order of a point given coords and inverse of the longer side of data bbox
  18054. function zOrder(x, y, minX, minY, invSize) {
  18055. // coords are transformed into non-negative 15-bit integer range
  18056. x = 32767 * (x - minX) * invSize;
  18057. y = 32767 * (y - minY) * invSize;
  18058. x = (x | x << 8) & 0x00FF00FF;
  18059. x = (x | x << 4) & 0x0F0F0F0F;
  18060. x = (x | x << 2) & 0x33333333;
  18061. x = (x | x << 1) & 0x55555555;
  18062. y = (y | y << 8) & 0x00FF00FF;
  18063. y = (y | y << 4) & 0x0F0F0F0F;
  18064. y = (y | y << 2) & 0x33333333;
  18065. y = (y | y << 1) & 0x55555555;
  18066. return x | y << 1;
  18067. } // find the leftmost node of a polygon ring
  18068. function getLeftmost(start) {
  18069. var p = start,
  18070. leftmost = start;
  18071. do {
  18072. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  18073. p = p.next;
  18074. } while (p !== start);
  18075. return leftmost;
  18076. } // check if a point lies within a convex triangle
  18077. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  18078. 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;
  18079. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  18080. function isValidDiagonal(a, b) {
  18081. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
  18082. } // signed area of a triangle
  18083. function area(p, q, r) {
  18084. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  18085. } // check if two points are equal
  18086. function equals(p1, p2) {
  18087. return p1.x === p2.x && p1.y === p2.y;
  18088. } // check if two segments intersect
  18089. function intersects(p1, q1, p2, q2) {
  18090. if (equals(p1, p2) && equals(q1, q2) || equals(p1, q2) && equals(p2, q1)) return true;
  18091. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  18092. } // check if a polygon diagonal intersects any polygon segments
  18093. function intersectsPolygon(a, b) {
  18094. var p = a;
  18095. do {
  18096. 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;
  18097. p = p.next;
  18098. } while (p !== a);
  18099. return false;
  18100. } // check if a polygon diagonal is locally inside the polygon
  18101. function locallyInside(a, b) {
  18102. 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;
  18103. } // check if the middle point of a polygon diagonal is inside the polygon
  18104. function middleInside(a, b) {
  18105. var p = a,
  18106. inside = false,
  18107. px = (a.x + b.x) / 2,
  18108. py = (a.y + b.y) / 2;
  18109. do {
  18110. 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;
  18111. p = p.next;
  18112. } while (p !== a);
  18113. return inside;
  18114. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  18115. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  18116. function splitPolygon(a, b) {
  18117. var a2 = new Node(a.i, a.x, a.y),
  18118. b2 = new Node(b.i, b.x, b.y),
  18119. an = a.next,
  18120. bp = b.prev;
  18121. a.next = b;
  18122. b.prev = a;
  18123. a2.next = an;
  18124. an.prev = a2;
  18125. b2.next = a2;
  18126. a2.prev = b2;
  18127. bp.next = b2;
  18128. b2.prev = bp;
  18129. return b2;
  18130. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  18131. function insertNode(i, x, y, last) {
  18132. var p = new Node(i, x, y);
  18133. if (!last) {
  18134. p.prev = p;
  18135. p.next = p;
  18136. } else {
  18137. p.next = last.next;
  18138. p.prev = last;
  18139. last.next.prev = p;
  18140. last.next = p;
  18141. }
  18142. return p;
  18143. }
  18144. function removeNode(p) {
  18145. p.next.prev = p.prev;
  18146. p.prev.next = p.next;
  18147. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  18148. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  18149. }
  18150. function Node(i, x, y) {
  18151. // vertex index in coordinates array
  18152. this.i = i; // vertex coordinates
  18153. this.x = x;
  18154. this.y = y; // previous and next vertex nodes in a polygon ring
  18155. this.prev = null;
  18156. this.next = null; // z-order curve value
  18157. this.z = null; // previous and next nodes in z-order
  18158. this.prevZ = null;
  18159. this.nextZ = null; // indicates whether this is a steiner point
  18160. this.steiner = false;
  18161. }
  18162. function signedArea(data, start, end, dim) {
  18163. var sum = 0;
  18164. for (var i = start, j = end - dim; i < end; i += dim) {
  18165. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  18166. j = i;
  18167. }
  18168. return sum;
  18169. }
  18170. /**
  18171. * @author zz85 / http://www.lab4games.net/zz85/blog
  18172. */
  18173. var ShapeUtils = {
  18174. // calculate area of the contour polygon
  18175. area: function (contour) {
  18176. var n = contour.length;
  18177. var a = 0.0;
  18178. for (var p = n - 1, q = 0; q < n; p = q++) {
  18179. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  18180. }
  18181. return a * 0.5;
  18182. },
  18183. isClockWise: function (pts) {
  18184. return ShapeUtils.area(pts) < 0;
  18185. },
  18186. triangulateShape: function (contour, holes) {
  18187. var vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  18188. var holeIndices = []; // array of hole indices
  18189. var faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  18190. removeDupEndPts(contour);
  18191. addContour(vertices, contour); //
  18192. var holeIndex = contour.length;
  18193. holes.forEach(removeDupEndPts);
  18194. for (var i = 0; i < holes.length; i++) {
  18195. holeIndices.push(holeIndex);
  18196. holeIndex += holes[i].length;
  18197. addContour(vertices, holes[i]);
  18198. } //
  18199. var triangles = Earcut.triangulate(vertices, holeIndices); //
  18200. for (var i = 0; i < triangles.length; i += 3) {
  18201. faces.push(triangles.slice(i, i + 3));
  18202. }
  18203. return faces;
  18204. }
  18205. };
  18206. exports.ShapeUtils = ShapeUtils;
  18207. function removeDupEndPts(points) {
  18208. var l = points.length;
  18209. if (l > 2 && points[l - 1].equals(points[0])) {
  18210. points.pop();
  18211. }
  18212. }
  18213. function addContour(vertices, contour) {
  18214. for (var i = 0; i < contour.length; i++) {
  18215. vertices.push(contour[i].x);
  18216. vertices.push(contour[i].y);
  18217. }
  18218. }
  18219. /**
  18220. * @author zz85 / http://www.lab4games.net/zz85/blog
  18221. *
  18222. * Creates extruded geometry from a path shape.
  18223. *
  18224. * parameters = {
  18225. *
  18226. * curveSegments: <int>, // number of points on the curves
  18227. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  18228. * depth: <float>, // Depth to extrude the shape
  18229. *
  18230. * bevelEnabled: <bool>, // turn on bevel
  18231. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18232. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  18233. * bevelOffset: <float>, // how far from shape outline does bevel start
  18234. * bevelSegments: <int>, // number of bevel layers
  18235. *
  18236. * extrudePath: <THREE.Curve> // curve to extrude shape along
  18237. *
  18238. * UVGenerator: <Object> // object that provides UV generator functions
  18239. *
  18240. * }
  18241. */
  18242. // ExtrudeGeometry
  18243. function ExtrudeGeometry(shapes, options) {
  18244. Geometry.call(this);
  18245. this.type = 'ExtrudeGeometry';
  18246. this.parameters = {
  18247. shapes: shapes,
  18248. options: options
  18249. };
  18250. this.fromBufferGeometry(new ExtrudeBufferGeometry(shapes, options));
  18251. this.mergeVertices();
  18252. }
  18253. ExtrudeGeometry.prototype = Object.create(Geometry.prototype);
  18254. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  18255. ExtrudeGeometry.prototype.toJSON = function () {
  18256. var data = Geometry.prototype.toJSON.call(this);
  18257. var shapes = this.parameters.shapes;
  18258. var options = this.parameters.options;
  18259. return toJSON(shapes, options, data);
  18260. }; // ExtrudeBufferGeometry
  18261. function ExtrudeBufferGeometry(shapes, options) {
  18262. BufferGeometry.call(this);
  18263. this.type = 'ExtrudeBufferGeometry';
  18264. this.parameters = {
  18265. shapes: shapes,
  18266. options: options
  18267. };
  18268. shapes = Array.isArray(shapes) ? shapes : [shapes];
  18269. var scope = this;
  18270. var verticesArray = [];
  18271. var uvArray = [];
  18272. for (var i = 0, l = shapes.length; i < l; i++) {
  18273. var shape = shapes[i];
  18274. addShape(shape);
  18275. } // build geometry
  18276. this.addAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  18277. this.addAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  18278. this.computeVertexNormals(); // functions
  18279. function addShape(shape) {
  18280. var placeholder = []; // options
  18281. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18282. var steps = options.steps !== undefined ? options.steps : 1;
  18283. var depth = options.depth !== undefined ? options.depth : 100;
  18284. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  18285. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  18286. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  18287. var bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  18288. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18289. var extrudePath = options.extrudePath;
  18290. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
  18291. if (options.amount !== undefined) {
  18292. console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
  18293. depth = options.amount;
  18294. } //
  18295. var extrudePts,
  18296. extrudeByPath = false;
  18297. var splineTube, binormal, normal, position2;
  18298. if (extrudePath) {
  18299. extrudePts = extrudePath.getSpacedPoints(steps);
  18300. extrudeByPath = true;
  18301. bevelEnabled = false; // bevels not supported for path extrusion
  18302. // SETUP TNB variables
  18303. // TODO1 - have a .isClosed in spline?
  18304. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18305. binormal = new Vector3();
  18306. normal = new Vector3();
  18307. position2 = new Vector3();
  18308. } // Safeguards if bevels are not enabled
  18309. if (!bevelEnabled) {
  18310. bevelSegments = 0;
  18311. bevelThickness = 0;
  18312. bevelSize = 0;
  18313. bevelOffset = 0;
  18314. } // Variables initialization
  18315. var ahole, h, hl; // looping of holes
  18316. var shapePoints = shape.extractPoints(curveSegments);
  18317. var vertices = shapePoints.shape;
  18318. var holes = shapePoints.holes;
  18319. var reverse = !ShapeUtils.isClockWise(vertices);
  18320. if (reverse) {
  18321. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18322. for (h = 0, hl = holes.length; h < hl; h++) {
  18323. ahole = holes[h];
  18324. if (ShapeUtils.isClockWise(ahole)) {
  18325. holes[h] = ahole.reverse();
  18326. }
  18327. }
  18328. }
  18329. var faces = ShapeUtils.triangulateShape(vertices, holes);
  18330. /* Vertices */
  18331. var contour = vertices; // vertices has all points but contour has only points of circumference
  18332. for (h = 0, hl = holes.length; h < hl; h++) {
  18333. ahole = holes[h];
  18334. vertices = vertices.concat(ahole);
  18335. }
  18336. function scalePt2(pt, vec, size) {
  18337. if (!vec) console.error("THREE.ExtrudeGeometry: vec does not exist");
  18338. return vec.clone().multiplyScalar(size).add(pt);
  18339. }
  18340. var b,
  18341. bs,
  18342. t,
  18343. z,
  18344. vert,
  18345. vlen = vertices.length,
  18346. face,
  18347. flen = faces.length; // Find directions for point movement
  18348. function getBevelVec(inPt, inPrev, inNext) {
  18349. // computes for inPt the corresponding point inPt' on a new contour
  18350. // shifted by 1 unit (length of normalized vector) to the left
  18351. // if we walk along contour clockwise, this new contour is outside the old one
  18352. //
  18353. // inPt' is the intersection of the two lines parallel to the two
  18354. // adjacent edges of inPt at a distance of 1 unit on the left side.
  18355. var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  18356. // good reading for geometry algorithms (here: line-line intersection)
  18357. // http://geomalgorithms.com/a05-_intersect-1.html
  18358. var v_prev_x = inPt.x - inPrev.x,
  18359. v_prev_y = inPt.y - inPrev.y;
  18360. var v_next_x = inNext.x - inPt.x,
  18361. v_next_y = inNext.y - inPt.y;
  18362. var v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  18363. var collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  18364. if (Math.abs(collinear0) > Number.EPSILON) {
  18365. // not collinear
  18366. // length of vectors for normalizing
  18367. var v_prev_len = Math.sqrt(v_prev_lensq);
  18368. 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
  18369. var ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  18370. var ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  18371. var ptNextShift_x = inNext.x - v_next_y / v_next_len;
  18372. var ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  18373. 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
  18374. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  18375. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  18376. // but prevent crazy spikes
  18377. var v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  18378. if (v_trans_lensq <= 2) {
  18379. return new Vector2(v_trans_x, v_trans_y);
  18380. } else {
  18381. shrink_by = Math.sqrt(v_trans_lensq / 2);
  18382. }
  18383. } else {
  18384. // handle special case of collinear edges
  18385. var direction_eq = false; // assumes: opposite
  18386. if (v_prev_x > Number.EPSILON) {
  18387. if (v_next_x > Number.EPSILON) {
  18388. direction_eq = true;
  18389. }
  18390. } else {
  18391. if (v_prev_x < -Number.EPSILON) {
  18392. if (v_next_x < -Number.EPSILON) {
  18393. direction_eq = true;
  18394. }
  18395. } else {
  18396. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  18397. direction_eq = true;
  18398. }
  18399. }
  18400. }
  18401. if (direction_eq) {
  18402. // console.log("Warning: lines are a straight sequence");
  18403. v_trans_x = -v_prev_y;
  18404. v_trans_y = v_prev_x;
  18405. shrink_by = Math.sqrt(v_prev_lensq);
  18406. } else {
  18407. // console.log("Warning: lines are a straight spike");
  18408. v_trans_x = v_prev_x;
  18409. v_trans_y = v_prev_y;
  18410. shrink_by = Math.sqrt(v_prev_lensq / 2);
  18411. }
  18412. }
  18413. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  18414. }
  18415. var contourMovements = [];
  18416. for (var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  18417. if (j === il) j = 0;
  18418. if (k === il) k = 0; // (j)---(i)---(k)
  18419. // console.log('i,j,k', i, j , k)
  18420. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  18421. }
  18422. var holesMovements = [],
  18423. oneHoleMovements,
  18424. verticesMovements = contourMovements.concat();
  18425. for (h = 0, hl = holes.length; h < hl; h++) {
  18426. ahole = holes[h];
  18427. oneHoleMovements = [];
  18428. for (i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  18429. if (j === il) j = 0;
  18430. if (k === il) k = 0; // (j)---(i)---(k)
  18431. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  18432. }
  18433. holesMovements.push(oneHoleMovements);
  18434. verticesMovements = verticesMovements.concat(oneHoleMovements);
  18435. } // Loop bevelSegments, 1 for the front, 1 for the back
  18436. for (b = 0; b < bevelSegments; b++) {
  18437. //for ( b = bevelSegments; b > 0; b -- ) {
  18438. t = b / bevelSegments;
  18439. z = bevelThickness * Math.cos(t * Math.PI / 2);
  18440. bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  18441. for (i = 0, il = contour.length; i < il; i++) {
  18442. vert = scalePt2(contour[i], contourMovements[i], bs);
  18443. v(vert.x, vert.y, -z);
  18444. } // expand holes
  18445. for (h = 0, hl = holes.length; h < hl; h++) {
  18446. ahole = holes[h];
  18447. oneHoleMovements = holesMovements[h];
  18448. for (i = 0, il = ahole.length; i < il; i++) {
  18449. vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  18450. v(vert.x, vert.y, -z);
  18451. }
  18452. }
  18453. }
  18454. bs = bevelSize + bevelOffset; // Back facing vertices
  18455. for (i = 0; i < vlen; i++) {
  18456. vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  18457. if (!extrudeByPath) {
  18458. v(vert.x, vert.y, 0);
  18459. } else {
  18460. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18461. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  18462. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  18463. position2.copy(extrudePts[0]).add(normal).add(binormal);
  18464. v(position2.x, position2.y, position2.z);
  18465. }
  18466. } // Add stepped vertices...
  18467. // Including front facing vertices
  18468. var s;
  18469. for (s = 1; s <= steps; s++) {
  18470. for (i = 0; i < vlen; i++) {
  18471. vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  18472. if (!extrudeByPath) {
  18473. v(vert.x, vert.y, depth / steps * s);
  18474. } else {
  18475. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18476. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  18477. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  18478. position2.copy(extrudePts[s]).add(normal).add(binormal);
  18479. v(position2.x, position2.y, position2.z);
  18480. }
  18481. }
  18482. } // Add bevel segments planes
  18483. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18484. for (b = bevelSegments - 1; b >= 0; b--) {
  18485. t = b / bevelSegments;
  18486. z = bevelThickness * Math.cos(t * Math.PI / 2);
  18487. bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  18488. for (i = 0, il = contour.length; i < il; i++) {
  18489. vert = scalePt2(contour[i], contourMovements[i], bs);
  18490. v(vert.x, vert.y, depth + z);
  18491. } // expand holes
  18492. for (h = 0, hl = holes.length; h < hl; h++) {
  18493. ahole = holes[h];
  18494. oneHoleMovements = holesMovements[h];
  18495. for (i = 0, il = ahole.length; i < il; i++) {
  18496. vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  18497. if (!extrudeByPath) {
  18498. v(vert.x, vert.y, depth + z);
  18499. } else {
  18500. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  18501. }
  18502. }
  18503. }
  18504. }
  18505. /* Faces */
  18506. // Top and bottom faces
  18507. buildLidFaces(); // Sides faces
  18508. buildSideFaces(); ///// Internal functions
  18509. function buildLidFaces() {
  18510. var start = verticesArray.length / 3;
  18511. if (bevelEnabled) {
  18512. var layer = 0; // steps + 1
  18513. var offset = vlen * layer; // Bottom faces
  18514. for (i = 0; i < flen; i++) {
  18515. face = faces[i];
  18516. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  18517. }
  18518. layer = steps + bevelSegments * 2;
  18519. offset = vlen * layer; // Top faces
  18520. for (i = 0; i < flen; i++) {
  18521. face = faces[i];
  18522. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  18523. }
  18524. } else {
  18525. // Bottom faces
  18526. for (i = 0; i < flen; i++) {
  18527. face = faces[i];
  18528. f3(face[2], face[1], face[0]);
  18529. } // Top faces
  18530. for (i = 0; i < flen; i++) {
  18531. face = faces[i];
  18532. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  18533. }
  18534. }
  18535. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  18536. } // Create faces for the z-sides of the shape
  18537. function buildSideFaces() {
  18538. var start = verticesArray.length / 3;
  18539. var layeroffset = 0;
  18540. sidewalls(contour, layeroffset);
  18541. layeroffset += contour.length;
  18542. for (h = 0, hl = holes.length; h < hl; h++) {
  18543. ahole = holes[h];
  18544. sidewalls(ahole, layeroffset); //, true
  18545. layeroffset += ahole.length;
  18546. }
  18547. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  18548. }
  18549. function sidewalls(contour, layeroffset) {
  18550. var j, k;
  18551. i = contour.length;
  18552. while (--i >= 0) {
  18553. j = i;
  18554. k = i - 1;
  18555. if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  18556. var s = 0,
  18557. sl = steps + bevelSegments * 2;
  18558. for (s = 0; s < sl; s++) {
  18559. var slen1 = vlen * s;
  18560. var slen2 = vlen * (s + 1);
  18561. var a = layeroffset + j + slen1,
  18562. b = layeroffset + k + slen1,
  18563. c = layeroffset + k + slen2,
  18564. d = layeroffset + j + slen2;
  18565. f4(a, b, c, d);
  18566. }
  18567. }
  18568. }
  18569. function v(x, y, z) {
  18570. placeholder.push(x);
  18571. placeholder.push(y);
  18572. placeholder.push(z);
  18573. }
  18574. function f3(a, b, c) {
  18575. addVertex(a);
  18576. addVertex(b);
  18577. addVertex(c);
  18578. var nextIndex = verticesArray.length / 3;
  18579. var uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  18580. addUV(uvs[0]);
  18581. addUV(uvs[1]);
  18582. addUV(uvs[2]);
  18583. }
  18584. function f4(a, b, c, d) {
  18585. addVertex(a);
  18586. addVertex(b);
  18587. addVertex(d);
  18588. addVertex(b);
  18589. addVertex(c);
  18590. addVertex(d);
  18591. var nextIndex = verticesArray.length / 3;
  18592. var uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  18593. addUV(uvs[0]);
  18594. addUV(uvs[1]);
  18595. addUV(uvs[3]);
  18596. addUV(uvs[1]);
  18597. addUV(uvs[2]);
  18598. addUV(uvs[3]);
  18599. }
  18600. function addVertex(index) {
  18601. verticesArray.push(placeholder[index * 3 + 0]);
  18602. verticesArray.push(placeholder[index * 3 + 1]);
  18603. verticesArray.push(placeholder[index * 3 + 2]);
  18604. }
  18605. function addUV(vector2) {
  18606. uvArray.push(vector2.x);
  18607. uvArray.push(vector2.y);
  18608. }
  18609. }
  18610. }
  18611. ExtrudeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18612. ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry;
  18613. ExtrudeBufferGeometry.prototype.toJSON = function () {
  18614. var data = BufferGeometry.prototype.toJSON.call(this);
  18615. var shapes = this.parameters.shapes;
  18616. var options = this.parameters.options;
  18617. return toJSON(shapes, options, data);
  18618. }; //
  18619. var WorldUVGenerator = {
  18620. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  18621. var a_x = vertices[indexA * 3];
  18622. var a_y = vertices[indexA * 3 + 1];
  18623. var b_x = vertices[indexB * 3];
  18624. var b_y = vertices[indexB * 3 + 1];
  18625. var c_x = vertices[indexC * 3];
  18626. var c_y = vertices[indexC * 3 + 1];
  18627. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  18628. },
  18629. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  18630. var a_x = vertices[indexA * 3];
  18631. var a_y = vertices[indexA * 3 + 1];
  18632. var a_z = vertices[indexA * 3 + 2];
  18633. var b_x = vertices[indexB * 3];
  18634. var b_y = vertices[indexB * 3 + 1];
  18635. var b_z = vertices[indexB * 3 + 2];
  18636. var c_x = vertices[indexC * 3];
  18637. var c_y = vertices[indexC * 3 + 1];
  18638. var c_z = vertices[indexC * 3 + 2];
  18639. var d_x = vertices[indexD * 3];
  18640. var d_y = vertices[indexD * 3 + 1];
  18641. var d_z = vertices[indexD * 3 + 2];
  18642. if (Math.abs(a_y - b_y) < 0.01) {
  18643. 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)];
  18644. } else {
  18645. 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)];
  18646. }
  18647. }
  18648. };
  18649. function toJSON(shapes, options, data) {
  18650. //
  18651. data.shapes = [];
  18652. if (Array.isArray(shapes)) {
  18653. for (var i = 0, l = shapes.length; i < l; i++) {
  18654. var shape = shapes[i];
  18655. data.shapes.push(shape.uuid);
  18656. }
  18657. } else {
  18658. data.shapes.push(shapes.uuid);
  18659. } //
  18660. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  18661. return data;
  18662. }
  18663. /**
  18664. * @author zz85 / http://www.lab4games.net/zz85/blog
  18665. * @author alteredq / http://alteredqualia.com/
  18666. *
  18667. * Text = 3D Text
  18668. *
  18669. * parameters = {
  18670. * font: <THREE.Font>, // font
  18671. *
  18672. * size: <float>, // size of the text
  18673. * height: <float>, // thickness to extrude text
  18674. * curveSegments: <int>, // number of points on the curves
  18675. *
  18676. * bevelEnabled: <bool>, // turn on bevel
  18677. * bevelThickness: <float>, // how deep into text bevel goes
  18678. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  18679. * bevelOffset: <float> // how far from text outline does bevel start
  18680. * }
  18681. */
  18682. // TextGeometry
  18683. function TextGeometry(text, parameters) {
  18684. Geometry.call(this);
  18685. this.type = 'TextGeometry';
  18686. this.parameters = {
  18687. text: text,
  18688. parameters: parameters
  18689. };
  18690. this.fromBufferGeometry(new TextBufferGeometry(text, parameters));
  18691. this.mergeVertices();
  18692. }
  18693. TextGeometry.prototype = Object.create(Geometry.prototype);
  18694. TextGeometry.prototype.constructor = TextGeometry; // TextBufferGeometry
  18695. function TextBufferGeometry(text, parameters) {
  18696. parameters = parameters || {};
  18697. var font = parameters.font;
  18698. if (!(font && font.isFont)) {
  18699. console.error('THREE.TextGeometry: font parameter is not an instance of THREE.Font.');
  18700. return new Geometry();
  18701. }
  18702. var shapes = font.generateShapes(text, parameters.size); // translate parameters to ExtrudeGeometry API
  18703. parameters.depth = parameters.height !== undefined ? parameters.height : 50; // defaults
  18704. if (parameters.bevelThickness === undefined) parameters.bevelThickness = 10;
  18705. if (parameters.bevelSize === undefined) parameters.bevelSize = 8;
  18706. if (parameters.bevelEnabled === undefined) parameters.bevelEnabled = false;
  18707. ExtrudeBufferGeometry.call(this, shapes, parameters);
  18708. this.type = 'TextBufferGeometry';
  18709. }
  18710. TextBufferGeometry.prototype = Object.create(ExtrudeBufferGeometry.prototype);
  18711. TextBufferGeometry.prototype.constructor = TextBufferGeometry;
  18712. /**
  18713. * @author mrdoob / http://mrdoob.com/
  18714. * @author benaadams / https://twitter.com/ben_a_adams
  18715. * @author Mugen87 / https://github.com/Mugen87
  18716. */
  18717. // SphereGeometry
  18718. function SphereGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
  18719. Geometry.call(this);
  18720. this.type = 'SphereGeometry';
  18721. this.parameters = {
  18722. radius: radius,
  18723. widthSegments: widthSegments,
  18724. heightSegments: heightSegments,
  18725. phiStart: phiStart,
  18726. phiLength: phiLength,
  18727. thetaStart: thetaStart,
  18728. thetaLength: thetaLength
  18729. };
  18730. this.fromBufferGeometry(new SphereBufferGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength));
  18731. this.mergeVertices();
  18732. }
  18733. SphereGeometry.prototype = Object.create(Geometry.prototype);
  18734. SphereGeometry.prototype.constructor = SphereGeometry; // SphereBufferGeometry
  18735. function SphereBufferGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
  18736. BufferGeometry.call(this);
  18737. this.type = 'SphereBufferGeometry';
  18738. this.parameters = {
  18739. radius: radius,
  18740. widthSegments: widthSegments,
  18741. heightSegments: heightSegments,
  18742. phiStart: phiStart,
  18743. phiLength: phiLength,
  18744. thetaStart: thetaStart,
  18745. thetaLength: thetaLength
  18746. };
  18747. radius = radius || 1;
  18748. widthSegments = Math.max(3, Math.floor(widthSegments) || 8);
  18749. heightSegments = Math.max(2, Math.floor(heightSegments) || 6);
  18750. phiStart = phiStart !== undefined ? phiStart : 0;
  18751. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  18752. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18753. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  18754. var thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  18755. var ix, iy;
  18756. var index = 0;
  18757. var grid = [];
  18758. var vertex = new Vector3();
  18759. var normal = new Vector3(); // buffers
  18760. var indices = [];
  18761. var vertices = [];
  18762. var normals = [];
  18763. var uvs = []; // generate vertices, normals and uvs
  18764. for (iy = 0; iy <= heightSegments; iy++) {
  18765. var verticesRow = [];
  18766. var v = iy / heightSegments; // special case for the poles
  18767. var uOffset = 0;
  18768. if (iy == 0 && thetaStart == 0) {
  18769. uOffset = 0.5 / widthSegments;
  18770. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  18771. uOffset = -0.5 / widthSegments;
  18772. }
  18773. for (ix = 0; ix <= widthSegments; ix++) {
  18774. var u = ix / widthSegments; // vertex
  18775. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  18776. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  18777. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  18778. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  18779. normal.copy(vertex).normalize();
  18780. normals.push(normal.x, normal.y, normal.z); // uv
  18781. uvs.push(u + uOffset, 1 - v);
  18782. verticesRow.push(index++);
  18783. }
  18784. grid.push(verticesRow);
  18785. } // indices
  18786. for (iy = 0; iy < heightSegments; iy++) {
  18787. for (ix = 0; ix < widthSegments; ix++) {
  18788. var a = grid[iy][ix + 1];
  18789. var b = grid[iy][ix];
  18790. var c = grid[iy + 1][ix];
  18791. var d = grid[iy + 1][ix + 1];
  18792. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  18793. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  18794. }
  18795. } // build geometry
  18796. this.setIndex(indices);
  18797. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18798. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  18799. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18800. }
  18801. SphereBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18802. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  18803. /**
  18804. * @author Kaleb Murphy
  18805. * @author Mugen87 / https://github.com/Mugen87
  18806. */
  18807. // RingGeometry
  18808. function RingGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
  18809. Geometry.call(this);
  18810. this.type = 'RingGeometry';
  18811. this.parameters = {
  18812. innerRadius: innerRadius,
  18813. outerRadius: outerRadius,
  18814. thetaSegments: thetaSegments,
  18815. phiSegments: phiSegments,
  18816. thetaStart: thetaStart,
  18817. thetaLength: thetaLength
  18818. };
  18819. this.fromBufferGeometry(new RingBufferGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength));
  18820. this.mergeVertices();
  18821. }
  18822. RingGeometry.prototype = Object.create(Geometry.prototype);
  18823. RingGeometry.prototype.constructor = RingGeometry; // RingBufferGeometry
  18824. function RingBufferGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
  18825. BufferGeometry.call(this);
  18826. this.type = 'RingBufferGeometry';
  18827. this.parameters = {
  18828. innerRadius: innerRadius,
  18829. outerRadius: outerRadius,
  18830. thetaSegments: thetaSegments,
  18831. phiSegments: phiSegments,
  18832. thetaStart: thetaStart,
  18833. thetaLength: thetaLength
  18834. };
  18835. innerRadius = innerRadius || 0.5;
  18836. outerRadius = outerRadius || 1;
  18837. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18838. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18839. thetaSegments = thetaSegments !== undefined ? Math.max(3, thetaSegments) : 8;
  18840. phiSegments = phiSegments !== undefined ? Math.max(1, phiSegments) : 1; // buffers
  18841. var indices = [];
  18842. var vertices = [];
  18843. var normals = [];
  18844. var uvs = []; // some helper variables
  18845. var segment;
  18846. var radius = innerRadius;
  18847. var radiusStep = (outerRadius - innerRadius) / phiSegments;
  18848. var vertex = new Vector3();
  18849. var uv = new Vector2();
  18850. var j, i; // generate vertices, normals and uvs
  18851. for (j = 0; j <= phiSegments; j++) {
  18852. for (i = 0; i <= thetaSegments; i++) {
  18853. // values are generate from the inside of the ring to the outside
  18854. segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  18855. vertex.x = radius * Math.cos(segment);
  18856. vertex.y = radius * Math.sin(segment);
  18857. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  18858. normals.push(0, 0, 1); // uv
  18859. uv.x = (vertex.x / outerRadius + 1) / 2;
  18860. uv.y = (vertex.y / outerRadius + 1) / 2;
  18861. uvs.push(uv.x, uv.y);
  18862. } // increase the radius for next row of vertices
  18863. radius += radiusStep;
  18864. } // indices
  18865. for (j = 0; j < phiSegments; j++) {
  18866. var thetaSegmentLevel = j * (thetaSegments + 1);
  18867. for (i = 0; i < thetaSegments; i++) {
  18868. segment = i + thetaSegmentLevel;
  18869. var a = segment;
  18870. var b = segment + thetaSegments + 1;
  18871. var c = segment + thetaSegments + 2;
  18872. var d = segment + 1; // faces
  18873. indices.push(a, b, d);
  18874. indices.push(b, c, d);
  18875. }
  18876. } // build geometry
  18877. this.setIndex(indices);
  18878. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18879. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  18880. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18881. }
  18882. RingBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18883. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  18884. /**
  18885. * @author zz85 / https://github.com/zz85
  18886. * @author bhouston / http://clara.io
  18887. * @author Mugen87 / https://github.com/Mugen87
  18888. */
  18889. // LatheGeometry
  18890. function LatheGeometry(points, segments, phiStart, phiLength) {
  18891. Geometry.call(this);
  18892. this.type = 'LatheGeometry';
  18893. this.parameters = {
  18894. points: points,
  18895. segments: segments,
  18896. phiStart: phiStart,
  18897. phiLength: phiLength
  18898. };
  18899. this.fromBufferGeometry(new LatheBufferGeometry(points, segments, phiStart, phiLength));
  18900. this.mergeVertices();
  18901. }
  18902. LatheGeometry.prototype = Object.create(Geometry.prototype);
  18903. LatheGeometry.prototype.constructor = LatheGeometry; // LatheBufferGeometry
  18904. function LatheBufferGeometry(points, segments, phiStart, phiLength) {
  18905. BufferGeometry.call(this);
  18906. this.type = 'LatheBufferGeometry';
  18907. this.parameters = {
  18908. points: points,
  18909. segments: segments,
  18910. phiStart: phiStart,
  18911. phiLength: phiLength
  18912. };
  18913. segments = Math.floor(segments) || 12;
  18914. phiStart = phiStart || 0;
  18915. phiLength = phiLength || Math.PI * 2; // clamp phiLength so it's in range of [ 0, 2PI ]
  18916. phiLength = _Math.clamp(phiLength, 0, Math.PI * 2); // buffers
  18917. var indices = [];
  18918. var vertices = [];
  18919. var uvs = []; // helper variables
  18920. var base;
  18921. var inverseSegments = 1.0 / segments;
  18922. var vertex = new Vector3();
  18923. var uv = new Vector2();
  18924. var i, j; // generate vertices and uvs
  18925. for (i = 0; i <= segments; i++) {
  18926. var phi = phiStart + i * inverseSegments * phiLength;
  18927. var sin = Math.sin(phi);
  18928. var cos = Math.cos(phi);
  18929. for (j = 0; j <= points.length - 1; j++) {
  18930. // vertex
  18931. vertex.x = points[j].x * sin;
  18932. vertex.y = points[j].y;
  18933. vertex.z = points[j].x * cos;
  18934. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  18935. uv.x = i / segments;
  18936. uv.y = j / (points.length - 1);
  18937. uvs.push(uv.x, uv.y);
  18938. }
  18939. } // indices
  18940. for (i = 0; i < segments; i++) {
  18941. for (j = 0; j < points.length - 1; j++) {
  18942. base = j + i * points.length;
  18943. var a = base;
  18944. var b = base + points.length;
  18945. var c = base + points.length + 1;
  18946. var d = base + 1; // faces
  18947. indices.push(a, b, d);
  18948. indices.push(b, c, d);
  18949. }
  18950. } // build geometry
  18951. this.setIndex(indices);
  18952. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18953. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // generate normals
  18954. this.computeVertexNormals(); // if the geometry is closed, we need to average the normals along the seam.
  18955. // because the corresponding vertices are identical (but still have different UVs).
  18956. if (phiLength === Math.PI * 2) {
  18957. var normals = this.attributes.normal.array;
  18958. var n1 = new Vector3();
  18959. var n2 = new Vector3();
  18960. var n = new Vector3(); // this is the buffer offset for the last line of vertices
  18961. base = segments * points.length * 3;
  18962. for (i = 0, j = 0; i < points.length; i++, j += 3) {
  18963. // select the normal of the vertex in the first line
  18964. n1.x = normals[j + 0];
  18965. n1.y = normals[j + 1];
  18966. n1.z = normals[j + 2]; // select the normal of the vertex in the last line
  18967. n2.x = normals[base + j + 0];
  18968. n2.y = normals[base + j + 1];
  18969. n2.z = normals[base + j + 2]; // average normals
  18970. n.addVectors(n1, n2).normalize(); // assign the new values to both normals
  18971. normals[j + 0] = normals[base + j + 0] = n.x;
  18972. normals[j + 1] = normals[base + j + 1] = n.y;
  18973. normals[j + 2] = normals[base + j + 2] = n.z;
  18974. }
  18975. }
  18976. }
  18977. LatheBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18978. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  18979. /**
  18980. * @author jonobr1 / http://jonobr1.com
  18981. * @author Mugen87 / https://github.com/Mugen87
  18982. */
  18983. // ShapeGeometry
  18984. function ShapeGeometry(shapes, curveSegments) {
  18985. Geometry.call(this);
  18986. this.type = 'ShapeGeometry';
  18987. if (typeof curveSegments === 'object') {
  18988. console.warn('THREE.ShapeGeometry: Options parameter has been removed.');
  18989. curveSegments = curveSegments.curveSegments;
  18990. }
  18991. this.parameters = {
  18992. shapes: shapes,
  18993. curveSegments: curveSegments
  18994. };
  18995. this.fromBufferGeometry(new ShapeBufferGeometry(shapes, curveSegments));
  18996. this.mergeVertices();
  18997. }
  18998. ShapeGeometry.prototype = Object.create(Geometry.prototype);
  18999. ShapeGeometry.prototype.constructor = ShapeGeometry;
  19000. ShapeGeometry.prototype.toJSON = function () {
  19001. var data = Geometry.prototype.toJSON.call(this);
  19002. var shapes = this.parameters.shapes;
  19003. return toJSON$1(shapes, data);
  19004. }; // ShapeBufferGeometry
  19005. function ShapeBufferGeometry(shapes, curveSegments) {
  19006. BufferGeometry.call(this);
  19007. this.type = 'ShapeBufferGeometry';
  19008. this.parameters = {
  19009. shapes: shapes,
  19010. curveSegments: curveSegments
  19011. };
  19012. curveSegments = curveSegments || 12; // buffers
  19013. var indices = [];
  19014. var vertices = [];
  19015. var normals = [];
  19016. var uvs = []; // helper variables
  19017. var groupStart = 0;
  19018. var groupCount = 0; // allow single and array values for "shapes" parameter
  19019. if (Array.isArray(shapes) === false) {
  19020. addShape(shapes);
  19021. } else {
  19022. for (var i = 0; i < shapes.length; i++) {
  19023. addShape(shapes[i]);
  19024. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  19025. groupStart += groupCount;
  19026. groupCount = 0;
  19027. }
  19028. } // build geometry
  19029. this.setIndex(indices);
  19030. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  19031. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  19032. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  19033. function addShape(shape) {
  19034. var i, l, shapeHole;
  19035. var indexOffset = vertices.length / 3;
  19036. var points = shape.extractPoints(curveSegments);
  19037. var shapeVertices = points.shape;
  19038. var shapeHoles = points.holes; // check direction of vertices
  19039. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  19040. shapeVertices = shapeVertices.reverse();
  19041. }
  19042. for (i = 0, l = shapeHoles.length; i < l; i++) {
  19043. shapeHole = shapeHoles[i];
  19044. if (ShapeUtils.isClockWise(shapeHole) === true) {
  19045. shapeHoles[i] = shapeHole.reverse();
  19046. }
  19047. }
  19048. var faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  19049. for (i = 0, l = shapeHoles.length; i < l; i++) {
  19050. shapeHole = shapeHoles[i];
  19051. shapeVertices = shapeVertices.concat(shapeHole);
  19052. } // vertices, normals, uvs
  19053. for (i = 0, l = shapeVertices.length; i < l; i++) {
  19054. var vertex = shapeVertices[i];
  19055. vertices.push(vertex.x, vertex.y, 0);
  19056. normals.push(0, 0, 1);
  19057. uvs.push(vertex.x, vertex.y); // world uvs
  19058. } // incides
  19059. for (i = 0, l = faces.length; i < l; i++) {
  19060. var face = faces[i];
  19061. var a = face[0] + indexOffset;
  19062. var b = face[1] + indexOffset;
  19063. var c = face[2] + indexOffset;
  19064. indices.push(a, b, c);
  19065. groupCount += 3;
  19066. }
  19067. }
  19068. }
  19069. ShapeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19070. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  19071. ShapeBufferGeometry.prototype.toJSON = function () {
  19072. var data = BufferGeometry.prototype.toJSON.call(this);
  19073. var shapes = this.parameters.shapes;
  19074. return toJSON$1(shapes, data);
  19075. }; //
  19076. function toJSON$1(shapes, data) {
  19077. data.shapes = [];
  19078. if (Array.isArray(shapes)) {
  19079. for (var i = 0, l = shapes.length; i < l; i++) {
  19080. var shape = shapes[i];
  19081. data.shapes.push(shape.uuid);
  19082. }
  19083. } else {
  19084. data.shapes.push(shapes.uuid);
  19085. }
  19086. return data;
  19087. }
  19088. /**
  19089. * @author WestLangley / http://github.com/WestLangley
  19090. * @author Mugen87 / https://github.com/Mugen87
  19091. */
  19092. function EdgesGeometry(geometry, thresholdAngle) {
  19093. BufferGeometry.call(this);
  19094. this.type = 'EdgesGeometry';
  19095. this.parameters = {
  19096. thresholdAngle: thresholdAngle
  19097. };
  19098. thresholdAngle = thresholdAngle !== undefined ? thresholdAngle : 1; // buffer
  19099. var vertices = []; // helper variables
  19100. var thresholdDot = Math.cos(_Math.DEG2RAD * thresholdAngle);
  19101. var edge = [0, 0],
  19102. edges = {},
  19103. edge1,
  19104. edge2;
  19105. var key,
  19106. keys = ['a', 'b', 'c']; // prepare source geometry
  19107. var geometry2;
  19108. if (geometry.isBufferGeometry) {
  19109. geometry2 = new Geometry();
  19110. geometry2.fromBufferGeometry(geometry);
  19111. } else {
  19112. geometry2 = geometry.clone();
  19113. }
  19114. geometry2.mergeVertices();
  19115. geometry2.computeFaceNormals();
  19116. var sourceVertices = geometry2.vertices;
  19117. var faces = geometry2.faces; // now create a data structure where each entry represents an edge with its adjoining faces
  19118. for (var i = 0, l = faces.length; i < l; i++) {
  19119. var face = faces[i];
  19120. for (var j = 0; j < 3; j++) {
  19121. edge1 = face[keys[j]];
  19122. edge2 = face[keys[(j + 1) % 3]];
  19123. edge[0] = Math.min(edge1, edge2);
  19124. edge[1] = Math.max(edge1, edge2);
  19125. key = edge[0] + ',' + edge[1];
  19126. if (edges[key] === undefined) {
  19127. edges[key] = {
  19128. index1: edge[0],
  19129. index2: edge[1],
  19130. face1: i,
  19131. face2: undefined
  19132. };
  19133. } else {
  19134. edges[key].face2 = i;
  19135. }
  19136. }
  19137. } // generate vertices
  19138. for (key in edges) {
  19139. 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.
  19140. if (e.face2 === undefined || faces[e.face1].normal.dot(faces[e.face2].normal) <= thresholdDot) {
  19141. var vertex = sourceVertices[e.index1];
  19142. vertices.push(vertex.x, vertex.y, vertex.z);
  19143. vertex = sourceVertices[e.index2];
  19144. vertices.push(vertex.x, vertex.y, vertex.z);
  19145. }
  19146. } // build geometry
  19147. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  19148. }
  19149. EdgesGeometry.prototype = Object.create(BufferGeometry.prototype);
  19150. EdgesGeometry.prototype.constructor = EdgesGeometry;
  19151. /**
  19152. * @author mrdoob / http://mrdoob.com/
  19153. * @author Mugen87 / https://github.com/Mugen87
  19154. */
  19155. // CylinderGeometry
  19156. function CylinderGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  19157. Geometry.call(this);
  19158. this.type = 'CylinderGeometry';
  19159. this.parameters = {
  19160. radiusTop: radiusTop,
  19161. radiusBottom: radiusBottom,
  19162. height: height,
  19163. radialSegments: radialSegments,
  19164. heightSegments: heightSegments,
  19165. openEnded: openEnded,
  19166. thetaStart: thetaStart,
  19167. thetaLength: thetaLength
  19168. };
  19169. this.fromBufferGeometry(new CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength));
  19170. this.mergeVertices();
  19171. }
  19172. CylinderGeometry.prototype = Object.create(Geometry.prototype);
  19173. CylinderGeometry.prototype.constructor = CylinderGeometry; // CylinderBufferGeometry
  19174. function CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  19175. BufferGeometry.call(this);
  19176. this.type = 'CylinderBufferGeometry';
  19177. this.parameters = {
  19178. radiusTop: radiusTop,
  19179. radiusBottom: radiusBottom,
  19180. height: height,
  19181. radialSegments: radialSegments,
  19182. heightSegments: heightSegments,
  19183. openEnded: openEnded,
  19184. thetaStart: thetaStart,
  19185. thetaLength: thetaLength
  19186. };
  19187. var scope = this;
  19188. radiusTop = radiusTop !== undefined ? radiusTop : 1;
  19189. radiusBottom = radiusBottom !== undefined ? radiusBottom : 1;
  19190. height = height || 1;
  19191. radialSegments = Math.floor(radialSegments) || 8;
  19192. heightSegments = Math.floor(heightSegments) || 1;
  19193. openEnded = openEnded !== undefined ? openEnded : false;
  19194. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  19195. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; // buffers
  19196. var indices = [];
  19197. var vertices = [];
  19198. var normals = [];
  19199. var uvs = []; // helper variables
  19200. var index = 0;
  19201. var indexArray = [];
  19202. var halfHeight = height / 2;
  19203. var groupStart = 0; // generate geometry
  19204. generateTorso();
  19205. if (openEnded === false) {
  19206. if (radiusTop > 0) generateCap(true);
  19207. if (radiusBottom > 0) generateCap(false);
  19208. } // build geometry
  19209. this.setIndex(indices);
  19210. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  19211. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  19212. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19213. function generateTorso() {
  19214. var x, y;
  19215. var normal = new Vector3();
  19216. var vertex = new Vector3();
  19217. var groupCount = 0; // this will be used to calculate the normal
  19218. var slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  19219. for (y = 0; y <= heightSegments; y++) {
  19220. var indexRow = [];
  19221. var v = y / heightSegments; // calculate the radius of the current row
  19222. var radius = v * (radiusBottom - radiusTop) + radiusTop;
  19223. for (x = 0; x <= radialSegments; x++) {
  19224. var u = x / radialSegments;
  19225. var theta = u * thetaLength + thetaStart;
  19226. var sinTheta = Math.sin(theta);
  19227. var cosTheta = Math.cos(theta); // vertex
  19228. vertex.x = radius * sinTheta;
  19229. vertex.y = -v * height + halfHeight;
  19230. vertex.z = radius * cosTheta;
  19231. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19232. normal.set(sinTheta, slope, cosTheta).normalize();
  19233. normals.push(normal.x, normal.y, normal.z); // uv
  19234. uvs.push(u, 1 - v); // save index of vertex in respective row
  19235. indexRow.push(index++);
  19236. } // now save vertices of the row in our index array
  19237. indexArray.push(indexRow);
  19238. } // generate indices
  19239. for (x = 0; x < radialSegments; x++) {
  19240. for (y = 0; y < heightSegments; y++) {
  19241. // we use the index array to access the correct indices
  19242. var a = indexArray[y][x];
  19243. var b = indexArray[y + 1][x];
  19244. var c = indexArray[y + 1][x + 1];
  19245. var d = indexArray[y][x + 1]; // faces
  19246. indices.push(a, b, d);
  19247. indices.push(b, c, d); // update group counter
  19248. groupCount += 6;
  19249. }
  19250. } // add a group to the geometry. this will ensure multi material support
  19251. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  19252. groupStart += groupCount;
  19253. }
  19254. function generateCap(top) {
  19255. var x, centerIndexStart, centerIndexEnd;
  19256. var uv = new Vector2();
  19257. var vertex = new Vector3();
  19258. var groupCount = 0;
  19259. var radius = top === true ? radiusTop : radiusBottom;
  19260. var sign = top === true ? 1 : -1; // save the index of the first center vertex
  19261. centerIndexStart = index; // first we generate the center vertex data of the cap.
  19262. // because the geometry needs one set of uvs per face,
  19263. // we must generate a center vertex per face/segment
  19264. for (x = 1; x <= radialSegments; x++) {
  19265. // vertex
  19266. vertices.push(0, halfHeight * sign, 0); // normal
  19267. normals.push(0, sign, 0); // uv
  19268. uvs.push(0.5, 0.5); // increase index
  19269. index++;
  19270. } // save the index of the last center vertex
  19271. centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  19272. for (x = 0; x <= radialSegments; x++) {
  19273. var u = x / radialSegments;
  19274. var theta = u * thetaLength + thetaStart;
  19275. var cosTheta = Math.cos(theta);
  19276. var sinTheta = Math.sin(theta); // vertex
  19277. vertex.x = radius * sinTheta;
  19278. vertex.y = halfHeight * sign;
  19279. vertex.z = radius * cosTheta;
  19280. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19281. normals.push(0, sign, 0); // uv
  19282. uv.x = cosTheta * 0.5 + 0.5;
  19283. uv.y = sinTheta * 0.5 * sign + 0.5;
  19284. uvs.push(uv.x, uv.y); // increase index
  19285. index++;
  19286. } // generate indices
  19287. for (x = 0; x < radialSegments; x++) {
  19288. var c = centerIndexStart + x;
  19289. var i = centerIndexEnd + x;
  19290. if (top === true) {
  19291. // face top
  19292. indices.push(i, i + 1, c);
  19293. } else {
  19294. // face bottom
  19295. indices.push(i + 1, i, c);
  19296. }
  19297. groupCount += 3;
  19298. } // add a group to the geometry. this will ensure multi material support
  19299. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  19300. groupStart += groupCount;
  19301. }
  19302. }
  19303. CylinderBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19304. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  19305. /**
  19306. * @author abelnation / http://github.com/abelnation
  19307. */
  19308. // ConeGeometry
  19309. function ConeGeometry(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  19310. CylinderGeometry.call(this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  19311. this.type = 'ConeGeometry';
  19312. this.parameters = {
  19313. radius: radius,
  19314. height: height,
  19315. radialSegments: radialSegments,
  19316. heightSegments: heightSegments,
  19317. openEnded: openEnded,
  19318. thetaStart: thetaStart,
  19319. thetaLength: thetaLength
  19320. };
  19321. }
  19322. ConeGeometry.prototype = Object.create(CylinderGeometry.prototype);
  19323. ConeGeometry.prototype.constructor = ConeGeometry; // ConeBufferGeometry
  19324. function ConeBufferGeometry(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  19325. CylinderBufferGeometry.call(this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  19326. this.type = 'ConeBufferGeometry';
  19327. this.parameters = {
  19328. radius: radius,
  19329. height: height,
  19330. radialSegments: radialSegments,
  19331. heightSegments: heightSegments,
  19332. openEnded: openEnded,
  19333. thetaStart: thetaStart,
  19334. thetaLength: thetaLength
  19335. };
  19336. }
  19337. ConeBufferGeometry.prototype = Object.create(CylinderBufferGeometry.prototype);
  19338. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  19339. /**
  19340. * @author benaadams / https://twitter.com/ben_a_adams
  19341. * @author Mugen87 / https://github.com/Mugen87
  19342. * @author hughes
  19343. */
  19344. // CircleGeometry
  19345. function CircleGeometry(radius, segments, thetaStart, thetaLength) {
  19346. Geometry.call(this);
  19347. this.type = 'CircleGeometry';
  19348. this.parameters = {
  19349. radius: radius,
  19350. segments: segments,
  19351. thetaStart: thetaStart,
  19352. thetaLength: thetaLength
  19353. };
  19354. this.fromBufferGeometry(new CircleBufferGeometry(radius, segments, thetaStart, thetaLength));
  19355. this.mergeVertices();
  19356. }
  19357. CircleGeometry.prototype = Object.create(Geometry.prototype);
  19358. CircleGeometry.prototype.constructor = CircleGeometry; // CircleBufferGeometry
  19359. function CircleBufferGeometry(radius, segments, thetaStart, thetaLength) {
  19360. BufferGeometry.call(this);
  19361. this.type = 'CircleBufferGeometry';
  19362. this.parameters = {
  19363. radius: radius,
  19364. segments: segments,
  19365. thetaStart: thetaStart,
  19366. thetaLength: thetaLength
  19367. };
  19368. radius = radius || 1;
  19369. segments = segments !== undefined ? Math.max(3, segments) : 8;
  19370. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19371. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; // buffers
  19372. var indices = [];
  19373. var vertices = [];
  19374. var normals = [];
  19375. var uvs = []; // helper variables
  19376. var i, s;
  19377. var vertex = new Vector3();
  19378. var uv = new Vector2(); // center point
  19379. vertices.push(0, 0, 0);
  19380. normals.push(0, 0, 1);
  19381. uvs.push(0.5, 0.5);
  19382. for (s = 0, i = 3; s <= segments; s++, i += 3) {
  19383. var segment = thetaStart + s / segments * thetaLength; // vertex
  19384. vertex.x = radius * Math.cos(segment);
  19385. vertex.y = radius * Math.sin(segment);
  19386. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19387. normals.push(0, 0, 1); // uvs
  19388. uv.x = (vertices[i] / radius + 1) / 2;
  19389. uv.y = (vertices[i + 1] / radius + 1) / 2;
  19390. uvs.push(uv.x, uv.y);
  19391. } // indices
  19392. for (i = 1; i <= segments; i++) {
  19393. indices.push(i, i + 1, 0);
  19394. } // build geometry
  19395. this.setIndex(indices);
  19396. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  19397. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  19398. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19399. }
  19400. CircleBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19401. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  19402. var Geometries =
  19403. /*#__PURE__*/
  19404. Object.freeze({
  19405. WireframeGeometry: WireframeGeometry,
  19406. ParametricGeometry: ParametricGeometry,
  19407. ParametricBufferGeometry: ParametricBufferGeometry,
  19408. TetrahedronGeometry: TetrahedronGeometry,
  19409. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  19410. OctahedronGeometry: OctahedronGeometry,
  19411. OctahedronBufferGeometry: OctahedronBufferGeometry,
  19412. IcosahedronGeometry: IcosahedronGeometry,
  19413. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  19414. DodecahedronGeometry: DodecahedronGeometry,
  19415. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  19416. PolyhedronGeometry: PolyhedronGeometry,
  19417. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  19418. TubeGeometry: TubeGeometry,
  19419. TubeBufferGeometry: TubeBufferGeometry,
  19420. TorusKnotGeometry: TorusKnotGeometry,
  19421. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  19422. TorusGeometry: TorusGeometry,
  19423. TorusBufferGeometry: TorusBufferGeometry,
  19424. TextGeometry: TextGeometry,
  19425. TextBufferGeometry: TextBufferGeometry,
  19426. SphereGeometry: SphereGeometry,
  19427. SphereBufferGeometry: SphereBufferGeometry,
  19428. RingGeometry: RingGeometry,
  19429. RingBufferGeometry: RingBufferGeometry,
  19430. PlaneGeometry: PlaneGeometry,
  19431. PlaneBufferGeometry: PlaneBufferGeometry,
  19432. LatheGeometry: LatheGeometry,
  19433. LatheBufferGeometry: LatheBufferGeometry,
  19434. ShapeGeometry: ShapeGeometry,
  19435. ShapeBufferGeometry: ShapeBufferGeometry,
  19436. ExtrudeGeometry: ExtrudeGeometry,
  19437. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  19438. EdgesGeometry: EdgesGeometry,
  19439. ConeGeometry: ConeGeometry,
  19440. ConeBufferGeometry: ConeBufferGeometry,
  19441. CylinderGeometry: CylinderGeometry,
  19442. CylinderBufferGeometry: CylinderBufferGeometry,
  19443. CircleGeometry: CircleGeometry,
  19444. CircleBufferGeometry: CircleBufferGeometry,
  19445. BoxGeometry: BoxGeometry,
  19446. BoxBufferGeometry: BoxBufferGeometry
  19447. });
  19448. /**
  19449. * @author mrdoob / http://mrdoob.com/
  19450. *
  19451. * parameters = {
  19452. * color: <THREE.Color>
  19453. * }
  19454. */
  19455. function ShadowMaterial(parameters) {
  19456. Material.call(this);
  19457. this.type = 'ShadowMaterial';
  19458. this.color = new Color(0x000000);
  19459. this.transparent = true;
  19460. this.setValues(parameters);
  19461. }
  19462. ShadowMaterial.prototype = Object.create(Material.prototype);
  19463. ShadowMaterial.prototype.constructor = ShadowMaterial;
  19464. ShadowMaterial.prototype.isShadowMaterial = true;
  19465. ShadowMaterial.prototype.copy = function (source) {
  19466. Material.prototype.copy.call(this, source);
  19467. this.color.copy(source.color);
  19468. return this;
  19469. };
  19470. /**
  19471. * @author mrdoob / http://mrdoob.com/
  19472. */
  19473. function RawShaderMaterial(parameters) {
  19474. ShaderMaterial.call(this, parameters);
  19475. this.type = 'RawShaderMaterial';
  19476. }
  19477. RawShaderMaterial.prototype = Object.create(ShaderMaterial.prototype);
  19478. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  19479. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  19480. /**
  19481. * @author WestLangley / http://github.com/WestLangley
  19482. *
  19483. * parameters = {
  19484. * color: <hex>,
  19485. * roughness: <float>,
  19486. * metalness: <float>,
  19487. * opacity: <float>,
  19488. *
  19489. * map: new THREE.Texture( <Image> ),
  19490. *
  19491. * lightMap: new THREE.Texture( <Image> ),
  19492. * lightMapIntensity: <float>
  19493. *
  19494. * aoMap: new THREE.Texture( <Image> ),
  19495. * aoMapIntensity: <float>
  19496. *
  19497. * emissive: <hex>,
  19498. * emissiveIntensity: <float>
  19499. * emissiveMap: new THREE.Texture( <Image> ),
  19500. *
  19501. * bumpMap: new THREE.Texture( <Image> ),
  19502. * bumpScale: <float>,
  19503. *
  19504. * normalMap: new THREE.Texture( <Image> ),
  19505. * normalMapType: THREE.TangentSpaceNormalMap,
  19506. * normalScale: <Vector2>,
  19507. *
  19508. * displacementMap: new THREE.Texture( <Image> ),
  19509. * displacementScale: <float>,
  19510. * displacementBias: <float>,
  19511. *
  19512. * roughnessMap: new THREE.Texture( <Image> ),
  19513. *
  19514. * metalnessMap: new THREE.Texture( <Image> ),
  19515. *
  19516. * alphaMap: new THREE.Texture( <Image> ),
  19517. *
  19518. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  19519. * envMapIntensity: <float>
  19520. *
  19521. * refractionRatio: <float>,
  19522. *
  19523. * wireframe: <boolean>,
  19524. * wireframeLinewidth: <float>,
  19525. *
  19526. * skinning: <bool>,
  19527. * morphTargets: <bool>,
  19528. * morphNormals: <bool>
  19529. * }
  19530. */
  19531. function MeshStandardMaterial(parameters) {
  19532. Material.call(this);
  19533. this.defines = {
  19534. 'STANDARD': ''
  19535. };
  19536. this.type = 'MeshStandardMaterial';
  19537. this.color = new Color(0xffffff); // diffuse
  19538. this.roughness = 0.5;
  19539. this.metalness = 0.5;
  19540. this.map = null;
  19541. this.lightMap = null;
  19542. this.lightMapIntensity = 1.0;
  19543. this.aoMap = null;
  19544. this.aoMapIntensity = 1.0;
  19545. this.emissive = new Color(0x000000);
  19546. this.emissiveIntensity = 1.0;
  19547. this.emissiveMap = null;
  19548. this.bumpMap = null;
  19549. this.bumpScale = 1;
  19550. this.normalMap = null;
  19551. this.normalMapType = TangentSpaceNormalMap;
  19552. this.normalScale = new Vector2(1, 1);
  19553. this.displacementMap = null;
  19554. this.displacementScale = 1;
  19555. this.displacementBias = 0;
  19556. this.roughnessMap = null;
  19557. this.metalnessMap = null;
  19558. this.alphaMap = null;
  19559. this.envMap = null;
  19560. this.envMapIntensity = 1.0;
  19561. this.refractionRatio = 0.98;
  19562. this.wireframe = false;
  19563. this.wireframeLinewidth = 1;
  19564. this.wireframeLinecap = 'round';
  19565. this.wireframeLinejoin = 'round';
  19566. this.skinning = false;
  19567. this.morphTargets = false;
  19568. this.morphNormals = false;
  19569. this.setValues(parameters);
  19570. }
  19571. MeshStandardMaterial.prototype = Object.create(Material.prototype);
  19572. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  19573. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  19574. MeshStandardMaterial.prototype.copy = function (source) {
  19575. Material.prototype.copy.call(this, source);
  19576. this.defines = {
  19577. 'STANDARD': ''
  19578. };
  19579. this.color.copy(source.color);
  19580. this.roughness = source.roughness;
  19581. this.metalness = source.metalness;
  19582. this.map = source.map;
  19583. this.lightMap = source.lightMap;
  19584. this.lightMapIntensity = source.lightMapIntensity;
  19585. this.aoMap = source.aoMap;
  19586. this.aoMapIntensity = source.aoMapIntensity;
  19587. this.emissive.copy(source.emissive);
  19588. this.emissiveMap = source.emissiveMap;
  19589. this.emissiveIntensity = source.emissiveIntensity;
  19590. this.bumpMap = source.bumpMap;
  19591. this.bumpScale = source.bumpScale;
  19592. this.normalMap = source.normalMap;
  19593. this.normalMapType = source.normalMapType;
  19594. this.normalScale.copy(source.normalScale);
  19595. this.displacementMap = source.displacementMap;
  19596. this.displacementScale = source.displacementScale;
  19597. this.displacementBias = source.displacementBias;
  19598. this.roughnessMap = source.roughnessMap;
  19599. this.metalnessMap = source.metalnessMap;
  19600. this.alphaMap = source.alphaMap;
  19601. this.envMap = source.envMap;
  19602. this.envMapIntensity = source.envMapIntensity;
  19603. this.refractionRatio = source.refractionRatio;
  19604. this.wireframe = source.wireframe;
  19605. this.wireframeLinewidth = source.wireframeLinewidth;
  19606. this.wireframeLinecap = source.wireframeLinecap;
  19607. this.wireframeLinejoin = source.wireframeLinejoin;
  19608. this.skinning = source.skinning;
  19609. this.morphTargets = source.morphTargets;
  19610. this.morphNormals = source.morphNormals;
  19611. return this;
  19612. };
  19613. /**
  19614. * @author WestLangley / http://github.com/WestLangley
  19615. *
  19616. * parameters = {
  19617. * reflectivity: <float>
  19618. * clearcoat: <float>
  19619. * clearcoatRoughness: <float>
  19620. *
  19621. * sheen: <Color>
  19622. *
  19623. * clearcoatNormalScale: <Vector2>,
  19624. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  19625. * }
  19626. */
  19627. function MeshPhysicalMaterial(parameters) {
  19628. MeshStandardMaterial.call(this);
  19629. this.defines = {
  19630. 'STANDARD': '',
  19631. 'PHYSICAL': ''
  19632. };
  19633. this.type = 'MeshPhysicalMaterial';
  19634. this.reflectivity = 0.5; // maps to F0 = 0.04
  19635. this.clearcoat = 0.0;
  19636. this.clearcoatRoughness = 0.0;
  19637. this.sheen = null; // null will disable sheen bsdf
  19638. this.clearcoatNormalScale = new Vector2(1, 1);
  19639. this.clearcoatNormalMap = null;
  19640. this.transparency = 0.0;
  19641. this.setValues(parameters);
  19642. }
  19643. MeshPhysicalMaterial.prototype = Object.create(MeshStandardMaterial.prototype);
  19644. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  19645. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  19646. MeshPhysicalMaterial.prototype.copy = function (source) {
  19647. MeshStandardMaterial.prototype.copy.call(this, source);
  19648. this.defines = {
  19649. 'STANDARD': '',
  19650. 'PHYSICAL': ''
  19651. };
  19652. this.reflectivity = source.reflectivity;
  19653. this.clearcoat = source.clearcoat;
  19654. this.clearcoatRoughness = source.clearcoatRoughness;
  19655. if (source.sheen) this.sheen = (this.sheen || new Color()).copy(source.sheen);else this.sheen = null;
  19656. this.clearcoatNormalMap = source.clearcoatNormalMap;
  19657. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  19658. this.transparency = source.transparency;
  19659. return this;
  19660. };
  19661. /**
  19662. * @author mrdoob / http://mrdoob.com/
  19663. * @author alteredq / http://alteredqualia.com/
  19664. *
  19665. * parameters = {
  19666. * color: <hex>,
  19667. * specular: <hex>,
  19668. * shininess: <float>,
  19669. * opacity: <float>,
  19670. *
  19671. * map: new THREE.Texture( <Image> ),
  19672. *
  19673. * lightMap: new THREE.Texture( <Image> ),
  19674. * lightMapIntensity: <float>
  19675. *
  19676. * aoMap: new THREE.Texture( <Image> ),
  19677. * aoMapIntensity: <float>
  19678. *
  19679. * emissive: <hex>,
  19680. * emissiveIntensity: <float>
  19681. * emissiveMap: new THREE.Texture( <Image> ),
  19682. *
  19683. * bumpMap: new THREE.Texture( <Image> ),
  19684. * bumpScale: <float>,
  19685. *
  19686. * normalMap: new THREE.Texture( <Image> ),
  19687. * normalMapType: THREE.TangentSpaceNormalMap,
  19688. * normalScale: <Vector2>,
  19689. *
  19690. * displacementMap: new THREE.Texture( <Image> ),
  19691. * displacementScale: <float>,
  19692. * displacementBias: <float>,
  19693. *
  19694. * specularMap: new THREE.Texture( <Image> ),
  19695. *
  19696. * alphaMap: new THREE.Texture( <Image> ),
  19697. *
  19698. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  19699. * combine: THREE.Multiply,
  19700. * reflectivity: <float>,
  19701. * refractionRatio: <float>,
  19702. *
  19703. * wireframe: <boolean>,
  19704. * wireframeLinewidth: <float>,
  19705. *
  19706. * skinning: <bool>,
  19707. * morphTargets: <bool>,
  19708. * morphNormals: <bool>
  19709. * }
  19710. */
  19711. function MeshPhongMaterial(parameters) {
  19712. Material.call(this);
  19713. this.type = 'MeshPhongMaterial';
  19714. this.color = new Color(0xffffff); // diffuse
  19715. this.specular = new Color(0x111111);
  19716. this.shininess = 30;
  19717. this.map = null;
  19718. this.lightMap = null;
  19719. this.lightMapIntensity = 1.0;
  19720. this.aoMap = null;
  19721. this.aoMapIntensity = 1.0;
  19722. this.emissive = new Color(0x000000);
  19723. this.emissiveIntensity = 1.0;
  19724. this.emissiveMap = null;
  19725. this.bumpMap = null;
  19726. this.bumpScale = 1;
  19727. this.normalMap = null;
  19728. this.normalMapType = TangentSpaceNormalMap;
  19729. this.normalScale = new Vector2(1, 1);
  19730. this.displacementMap = null;
  19731. this.displacementScale = 1;
  19732. this.displacementBias = 0;
  19733. this.specularMap = null;
  19734. this.alphaMap = null;
  19735. this.envMap = null;
  19736. this.combine = MultiplyOperation;
  19737. this.reflectivity = 1;
  19738. this.refractionRatio = 0.98;
  19739. this.wireframe = false;
  19740. this.wireframeLinewidth = 1;
  19741. this.wireframeLinecap = 'round';
  19742. this.wireframeLinejoin = 'round';
  19743. this.skinning = false;
  19744. this.morphTargets = false;
  19745. this.morphNormals = false;
  19746. this.setValues(parameters);
  19747. }
  19748. MeshPhongMaterial.prototype = Object.create(Material.prototype);
  19749. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  19750. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  19751. MeshPhongMaterial.prototype.copy = function (source) {
  19752. Material.prototype.copy.call(this, source);
  19753. this.color.copy(source.color);
  19754. this.specular.copy(source.specular);
  19755. this.shininess = source.shininess;
  19756. this.map = source.map;
  19757. this.lightMap = source.lightMap;
  19758. this.lightMapIntensity = source.lightMapIntensity;
  19759. this.aoMap = source.aoMap;
  19760. this.aoMapIntensity = source.aoMapIntensity;
  19761. this.emissive.copy(source.emissive);
  19762. this.emissiveMap = source.emissiveMap;
  19763. this.emissiveIntensity = source.emissiveIntensity;
  19764. this.bumpMap = source.bumpMap;
  19765. this.bumpScale = source.bumpScale;
  19766. this.normalMap = source.normalMap;
  19767. this.normalMapType = source.normalMapType;
  19768. this.normalScale.copy(source.normalScale);
  19769. this.displacementMap = source.displacementMap;
  19770. this.displacementScale = source.displacementScale;
  19771. this.displacementBias = source.displacementBias;
  19772. this.specularMap = source.specularMap;
  19773. this.alphaMap = source.alphaMap;
  19774. this.envMap = source.envMap;
  19775. this.combine = source.combine;
  19776. this.reflectivity = source.reflectivity;
  19777. this.refractionRatio = source.refractionRatio;
  19778. this.wireframe = source.wireframe;
  19779. this.wireframeLinewidth = source.wireframeLinewidth;
  19780. this.wireframeLinecap = source.wireframeLinecap;
  19781. this.wireframeLinejoin = source.wireframeLinejoin;
  19782. this.skinning = source.skinning;
  19783. this.morphTargets = source.morphTargets;
  19784. this.morphNormals = source.morphNormals;
  19785. return this;
  19786. };
  19787. /**
  19788. * @author takahirox / http://github.com/takahirox
  19789. *
  19790. * parameters = {
  19791. * gradientMap: new THREE.Texture( <Image> )
  19792. * }
  19793. */
  19794. function MeshToonMaterial(parameters) {
  19795. MeshPhongMaterial.call(this);
  19796. this.defines = {
  19797. 'TOON': ''
  19798. };
  19799. this.type = 'MeshToonMaterial';
  19800. this.gradientMap = null;
  19801. this.setValues(parameters);
  19802. }
  19803. MeshToonMaterial.prototype = Object.create(MeshPhongMaterial.prototype);
  19804. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  19805. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  19806. MeshToonMaterial.prototype.copy = function (source) {
  19807. MeshPhongMaterial.prototype.copy.call(this, source);
  19808. this.gradientMap = source.gradientMap;
  19809. return this;
  19810. };
  19811. /**
  19812. * @author mrdoob / http://mrdoob.com/
  19813. * @author WestLangley / http://github.com/WestLangley
  19814. *
  19815. * parameters = {
  19816. * opacity: <float>,
  19817. *
  19818. * bumpMap: new THREE.Texture( <Image> ),
  19819. * bumpScale: <float>,
  19820. *
  19821. * normalMap: new THREE.Texture( <Image> ),
  19822. * normalMapType: THREE.TangentSpaceNormalMap,
  19823. * normalScale: <Vector2>,
  19824. *
  19825. * displacementMap: new THREE.Texture( <Image> ),
  19826. * displacementScale: <float>,
  19827. * displacementBias: <float>,
  19828. *
  19829. * wireframe: <boolean>,
  19830. * wireframeLinewidth: <float>
  19831. *
  19832. * skinning: <bool>,
  19833. * morphTargets: <bool>,
  19834. * morphNormals: <bool>
  19835. * }
  19836. */
  19837. function MeshNormalMaterial(parameters) {
  19838. Material.call(this);
  19839. this.type = 'MeshNormalMaterial';
  19840. this.bumpMap = null;
  19841. this.bumpScale = 1;
  19842. this.normalMap = null;
  19843. this.normalMapType = TangentSpaceNormalMap;
  19844. this.normalScale = new Vector2(1, 1);
  19845. this.displacementMap = null;
  19846. this.displacementScale = 1;
  19847. this.displacementBias = 0;
  19848. this.wireframe = false;
  19849. this.wireframeLinewidth = 1;
  19850. this.fog = false;
  19851. this.skinning = false;
  19852. this.morphTargets = false;
  19853. this.morphNormals = false;
  19854. this.setValues(parameters);
  19855. }
  19856. MeshNormalMaterial.prototype = Object.create(Material.prototype);
  19857. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  19858. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  19859. MeshNormalMaterial.prototype.copy = function (source) {
  19860. Material.prototype.copy.call(this, source);
  19861. this.bumpMap = source.bumpMap;
  19862. this.bumpScale = source.bumpScale;
  19863. this.normalMap = source.normalMap;
  19864. this.normalMapType = source.normalMapType;
  19865. this.normalScale.copy(source.normalScale);
  19866. this.displacementMap = source.displacementMap;
  19867. this.displacementScale = source.displacementScale;
  19868. this.displacementBias = source.displacementBias;
  19869. this.wireframe = source.wireframe;
  19870. this.wireframeLinewidth = source.wireframeLinewidth;
  19871. this.skinning = source.skinning;
  19872. this.morphTargets = source.morphTargets;
  19873. this.morphNormals = source.morphNormals;
  19874. return this;
  19875. };
  19876. /**
  19877. * @author mrdoob / http://mrdoob.com/
  19878. * @author alteredq / http://alteredqualia.com/
  19879. *
  19880. * parameters = {
  19881. * color: <hex>,
  19882. * opacity: <float>,
  19883. *
  19884. * map: new THREE.Texture( <Image> ),
  19885. *
  19886. * lightMap: new THREE.Texture( <Image> ),
  19887. * lightMapIntensity: <float>
  19888. *
  19889. * aoMap: new THREE.Texture( <Image> ),
  19890. * aoMapIntensity: <float>
  19891. *
  19892. * emissive: <hex>,
  19893. * emissiveIntensity: <float>
  19894. * emissiveMap: new THREE.Texture( <Image> ),
  19895. *
  19896. * specularMap: new THREE.Texture( <Image> ),
  19897. *
  19898. * alphaMap: new THREE.Texture( <Image> ),
  19899. *
  19900. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  19901. * combine: THREE.Multiply,
  19902. * reflectivity: <float>,
  19903. * refractionRatio: <float>,
  19904. *
  19905. * wireframe: <boolean>,
  19906. * wireframeLinewidth: <float>,
  19907. *
  19908. * skinning: <bool>,
  19909. * morphTargets: <bool>,
  19910. * morphNormals: <bool>
  19911. * }
  19912. */
  19913. function MeshLambertMaterial(parameters) {
  19914. Material.call(this);
  19915. this.type = 'MeshLambertMaterial';
  19916. this.color = new Color(0xffffff); // diffuse
  19917. this.map = null;
  19918. this.lightMap = null;
  19919. this.lightMapIntensity = 1.0;
  19920. this.aoMap = null;
  19921. this.aoMapIntensity = 1.0;
  19922. this.emissive = new Color(0x000000);
  19923. this.emissiveIntensity = 1.0;
  19924. this.emissiveMap = null;
  19925. this.specularMap = null;
  19926. this.alphaMap = null;
  19927. this.envMap = null;
  19928. this.combine = MultiplyOperation;
  19929. this.reflectivity = 1;
  19930. this.refractionRatio = 0.98;
  19931. this.wireframe = false;
  19932. this.wireframeLinewidth = 1;
  19933. this.wireframeLinecap = 'round';
  19934. this.wireframeLinejoin = 'round';
  19935. this.skinning = false;
  19936. this.morphTargets = false;
  19937. this.morphNormals = false;
  19938. this.setValues(parameters);
  19939. }
  19940. MeshLambertMaterial.prototype = Object.create(Material.prototype);
  19941. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  19942. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  19943. MeshLambertMaterial.prototype.copy = function (source) {
  19944. Material.prototype.copy.call(this, source);
  19945. this.color.copy(source.color);
  19946. this.map = source.map;
  19947. this.lightMap = source.lightMap;
  19948. this.lightMapIntensity = source.lightMapIntensity;
  19949. this.aoMap = source.aoMap;
  19950. this.aoMapIntensity = source.aoMapIntensity;
  19951. this.emissive.copy(source.emissive);
  19952. this.emissiveMap = source.emissiveMap;
  19953. this.emissiveIntensity = source.emissiveIntensity;
  19954. this.specularMap = source.specularMap;
  19955. this.alphaMap = source.alphaMap;
  19956. this.envMap = source.envMap;
  19957. this.combine = source.combine;
  19958. this.reflectivity = source.reflectivity;
  19959. this.refractionRatio = source.refractionRatio;
  19960. this.wireframe = source.wireframe;
  19961. this.wireframeLinewidth = source.wireframeLinewidth;
  19962. this.wireframeLinecap = source.wireframeLinecap;
  19963. this.wireframeLinejoin = source.wireframeLinejoin;
  19964. this.skinning = source.skinning;
  19965. this.morphTargets = source.morphTargets;
  19966. this.morphNormals = source.morphNormals;
  19967. return this;
  19968. };
  19969. /**
  19970. * @author WestLangley / http://github.com/WestLangley
  19971. *
  19972. * parameters = {
  19973. * color: <hex>,
  19974. * opacity: <float>,
  19975. *
  19976. * matcap: new THREE.Texture( <Image> ),
  19977. *
  19978. * map: new THREE.Texture( <Image> ),
  19979. *
  19980. * bumpMap: new THREE.Texture( <Image> ),
  19981. * bumpScale: <float>,
  19982. *
  19983. * normalMap: new THREE.Texture( <Image> ),
  19984. * normalMapType: THREE.TangentSpaceNormalMap,
  19985. * normalScale: <Vector2>,
  19986. *
  19987. * displacementMap: new THREE.Texture( <Image> ),
  19988. * displacementScale: <float>,
  19989. * displacementBias: <float>,
  19990. *
  19991. * alphaMap: new THREE.Texture( <Image> ),
  19992. *
  19993. * skinning: <bool>,
  19994. * morphTargets: <bool>,
  19995. * morphNormals: <bool>
  19996. * }
  19997. */
  19998. function MeshMatcapMaterial(parameters) {
  19999. Material.call(this);
  20000. this.defines = {
  20001. 'MATCAP': ''
  20002. };
  20003. this.type = 'MeshMatcapMaterial';
  20004. this.color = new Color(0xffffff); // diffuse
  20005. this.matcap = null;
  20006. this.map = null;
  20007. this.bumpMap = null;
  20008. this.bumpScale = 1;
  20009. this.normalMap = null;
  20010. this.normalMapType = TangentSpaceNormalMap;
  20011. this.normalScale = new Vector2(1, 1);
  20012. this.displacementMap = null;
  20013. this.displacementScale = 1;
  20014. this.displacementBias = 0;
  20015. this.alphaMap = null;
  20016. this.skinning = false;
  20017. this.morphTargets = false;
  20018. this.morphNormals = false;
  20019. this.setValues(parameters);
  20020. }
  20021. MeshMatcapMaterial.prototype = Object.create(Material.prototype);
  20022. MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial;
  20023. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  20024. MeshMatcapMaterial.prototype.copy = function (source) {
  20025. Material.prototype.copy.call(this, source);
  20026. this.defines = {
  20027. 'MATCAP': ''
  20028. };
  20029. this.color.copy(source.color);
  20030. this.matcap = source.matcap;
  20031. this.map = source.map;
  20032. this.bumpMap = source.bumpMap;
  20033. this.bumpScale = source.bumpScale;
  20034. this.normalMap = source.normalMap;
  20035. this.normalMapType = source.normalMapType;
  20036. this.normalScale.copy(source.normalScale);
  20037. this.displacementMap = source.displacementMap;
  20038. this.displacementScale = source.displacementScale;
  20039. this.displacementBias = source.displacementBias;
  20040. this.alphaMap = source.alphaMap;
  20041. this.skinning = source.skinning;
  20042. this.morphTargets = source.morphTargets;
  20043. this.morphNormals = source.morphNormals;
  20044. return this;
  20045. };
  20046. /**
  20047. * @author alteredq / http://alteredqualia.com/
  20048. *
  20049. * parameters = {
  20050. * color: <hex>,
  20051. * opacity: <float>,
  20052. *
  20053. * linewidth: <float>,
  20054. *
  20055. * scale: <float>,
  20056. * dashSize: <float>,
  20057. * gapSize: <float>
  20058. * }
  20059. */
  20060. function LineDashedMaterial(parameters) {
  20061. LineBasicMaterial.call(this);
  20062. this.type = 'LineDashedMaterial';
  20063. this.scale = 1;
  20064. this.dashSize = 3;
  20065. this.gapSize = 1;
  20066. this.setValues(parameters);
  20067. }
  20068. LineDashedMaterial.prototype = Object.create(LineBasicMaterial.prototype);
  20069. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  20070. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  20071. LineDashedMaterial.prototype.copy = function (source) {
  20072. LineBasicMaterial.prototype.copy.call(this, source);
  20073. this.scale = source.scale;
  20074. this.dashSize = source.dashSize;
  20075. this.gapSize = source.gapSize;
  20076. return this;
  20077. };
  20078. var Materials =
  20079. /*#__PURE__*/
  20080. Object.freeze({
  20081. ShadowMaterial: ShadowMaterial,
  20082. SpriteMaterial: SpriteMaterial,
  20083. RawShaderMaterial: RawShaderMaterial,
  20084. ShaderMaterial: ShaderMaterial,
  20085. PointsMaterial: PointsMaterial,
  20086. MeshPhysicalMaterial: MeshPhysicalMaterial,
  20087. MeshStandardMaterial: MeshStandardMaterial,
  20088. MeshPhongMaterial: MeshPhongMaterial,
  20089. MeshToonMaterial: MeshToonMaterial,
  20090. MeshNormalMaterial: MeshNormalMaterial,
  20091. MeshLambertMaterial: MeshLambertMaterial,
  20092. MeshDepthMaterial: MeshDepthMaterial,
  20093. MeshDistanceMaterial: MeshDistanceMaterial,
  20094. MeshBasicMaterial: MeshBasicMaterial,
  20095. MeshMatcapMaterial: MeshMatcapMaterial,
  20096. LineDashedMaterial: LineDashedMaterial,
  20097. LineBasicMaterial: LineBasicMaterial,
  20098. Material: Material
  20099. });
  20100. /**
  20101. * @author tschw
  20102. * @author Ben Houston / http://clara.io/
  20103. * @author David Sarno / http://lighthaus.us/
  20104. */
  20105. var AnimationUtils = {
  20106. // same as Array.prototype.slice, but also works on typed arrays
  20107. arraySlice: function (array, from, to) {
  20108. if (AnimationUtils.isTypedArray(array)) {
  20109. // in ios9 array.subarray(from, undefined) will return empty array
  20110. // but array.subarray(from) or array.subarray(from, len) is correct
  20111. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  20112. }
  20113. return array.slice(from, to);
  20114. },
  20115. // converts an array to a specific type
  20116. convertArray: function (array, type, forceClone) {
  20117. if (!array || // let 'undefined' and 'null' pass
  20118. !forceClone && array.constructor === type) return array;
  20119. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  20120. return new type(array); // create typed array
  20121. }
  20122. return Array.prototype.slice.call(array); // create Array
  20123. },
  20124. isTypedArray: function (object) {
  20125. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  20126. },
  20127. // returns an array by which times and values can be sorted
  20128. getKeyframeOrder: function (times) {
  20129. function compareTime(i, j) {
  20130. return times[i] - times[j];
  20131. }
  20132. var n = times.length;
  20133. var result = new Array(n);
  20134. for (var i = 0; i !== n; ++i) result[i] = i;
  20135. result.sort(compareTime);
  20136. return result;
  20137. },
  20138. // uses the array previously returned by 'getKeyframeOrder' to sort data
  20139. sortedArray: function (values, stride, order) {
  20140. var nValues = values.length;
  20141. var result = new values.constructor(nValues);
  20142. for (var i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  20143. var srcOffset = order[i] * stride;
  20144. for (var j = 0; j !== stride; ++j) {
  20145. result[dstOffset++] = values[srcOffset + j];
  20146. }
  20147. }
  20148. return result;
  20149. },
  20150. // function for parsing AOS keyframe formats
  20151. flattenJSON: function (jsonKeys, times, values, valuePropertyName) {
  20152. var i = 1,
  20153. key = jsonKeys[0];
  20154. while (key !== undefined && key[valuePropertyName] === undefined) {
  20155. key = jsonKeys[i++];
  20156. }
  20157. if (key === undefined) return; // no data
  20158. var value = key[valuePropertyName];
  20159. if (value === undefined) return; // no data
  20160. if (Array.isArray(value)) {
  20161. do {
  20162. value = key[valuePropertyName];
  20163. if (value !== undefined) {
  20164. times.push(key.time);
  20165. values.push.apply(values, value); // push all elements
  20166. }
  20167. key = jsonKeys[i++];
  20168. } while (key !== undefined);
  20169. } else if (value.toArray !== undefined) {
  20170. // ...assume THREE.Math-ish
  20171. do {
  20172. value = key[valuePropertyName];
  20173. if (value !== undefined) {
  20174. times.push(key.time);
  20175. value.toArray(values, values.length);
  20176. }
  20177. key = jsonKeys[i++];
  20178. } while (key !== undefined);
  20179. } else {
  20180. // otherwise push as-is
  20181. do {
  20182. value = key[valuePropertyName];
  20183. if (value !== undefined) {
  20184. times.push(key.time);
  20185. values.push(value);
  20186. }
  20187. key = jsonKeys[i++];
  20188. } while (key !== undefined);
  20189. }
  20190. }
  20191. };
  20192. /**
  20193. * Abstract base class of interpolants over parametric samples.
  20194. *
  20195. * The parameter domain is one dimensional, typically the time or a path
  20196. * along a curve defined by the data.
  20197. *
  20198. * The sample values can have any dimensionality and derived classes may
  20199. * apply special interpretations to the data.
  20200. *
  20201. * This class provides the interval seek in a Template Method, deferring
  20202. * the actual interpolation to derived classes.
  20203. *
  20204. * Time complexity is O(1) for linear access crossing at most two points
  20205. * and O(log N) for random access, where N is the number of positions.
  20206. *
  20207. * References:
  20208. *
  20209. * http://www.oodesign.com/template-method-pattern.html
  20210. *
  20211. * @author tschw
  20212. */
  20213. exports.AnimationUtils = AnimationUtils;
  20214. function Interpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20215. this.parameterPositions = parameterPositions;
  20216. this._cachedIndex = 0;
  20217. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  20218. this.sampleValues = sampleValues;
  20219. this.valueSize = sampleSize;
  20220. }
  20221. Object.assign(Interpolant.prototype, {
  20222. evaluate: function (t) {
  20223. var pp = this.parameterPositions,
  20224. i1 = this._cachedIndex,
  20225. t1 = pp[i1],
  20226. t0 = pp[i1 - 1];
  20227. validate_interval: {
  20228. seek: {
  20229. var right;
  20230. linear_scan: {
  20231. //- See http://jsperf.com/comparison-to-undefined/3
  20232. //- slower code:
  20233. //-
  20234. //- if ( t >= t1 || t1 === undefined ) {
  20235. forward_scan: if (!(t < t1)) {
  20236. for (var giveUpAt = i1 + 2;;) {
  20237. if (t1 === undefined) {
  20238. if (t < t0) break forward_scan; // after end
  20239. i1 = pp.length;
  20240. this._cachedIndex = i1;
  20241. return this.afterEnd_(i1 - 1, t, t0);
  20242. }
  20243. if (i1 === giveUpAt) break; // this loop
  20244. t0 = t1;
  20245. t1 = pp[++i1];
  20246. if (t < t1) {
  20247. // we have arrived at the sought interval
  20248. break seek;
  20249. }
  20250. } // prepare binary search on the right side of the index
  20251. right = pp.length;
  20252. break linear_scan;
  20253. } //- slower code:
  20254. //- if ( t < t0 || t0 === undefined ) {
  20255. if (!(t >= t0)) {
  20256. // looping?
  20257. var t1global = pp[1];
  20258. if (t < t1global) {
  20259. i1 = 2; // + 1, using the scan for the details
  20260. t0 = t1global;
  20261. } // linear reverse scan
  20262. for (var giveUpAt = i1 - 2;;) {
  20263. if (t0 === undefined) {
  20264. // before start
  20265. this._cachedIndex = 0;
  20266. return this.beforeStart_(0, t, t1);
  20267. }
  20268. if (i1 === giveUpAt) break; // this loop
  20269. t1 = t0;
  20270. t0 = pp[--i1 - 1];
  20271. if (t >= t0) {
  20272. // we have arrived at the sought interval
  20273. break seek;
  20274. }
  20275. } // prepare binary search on the left side of the index
  20276. right = i1;
  20277. i1 = 0;
  20278. break linear_scan;
  20279. } // the interval is valid
  20280. break validate_interval;
  20281. } // linear scan
  20282. // binary search
  20283. while (i1 < right) {
  20284. var mid = i1 + right >>> 1;
  20285. if (t < pp[mid]) {
  20286. right = mid;
  20287. } else {
  20288. i1 = mid + 1;
  20289. }
  20290. }
  20291. t1 = pp[i1];
  20292. t0 = pp[i1 - 1]; // check boundary cases, again
  20293. if (t0 === undefined) {
  20294. this._cachedIndex = 0;
  20295. return this.beforeStart_(0, t, t1);
  20296. }
  20297. if (t1 === undefined) {
  20298. i1 = pp.length;
  20299. this._cachedIndex = i1;
  20300. return this.afterEnd_(i1 - 1, t0, t);
  20301. }
  20302. } // seek
  20303. this._cachedIndex = i1;
  20304. this.intervalChanged_(i1, t0, t1);
  20305. } // validate_interval
  20306. return this.interpolate_(i1, t0, t, t1);
  20307. },
  20308. settings: null,
  20309. // optional, subclass-specific settings structure
  20310. // Note: The indirection allows central control of many interpolants.
  20311. // --- Protected interface
  20312. DefaultSettings_: {},
  20313. getSettings_: function () {
  20314. return this.settings || this.DefaultSettings_;
  20315. },
  20316. copySampleValue_: function (index) {
  20317. // copies a sample value to the result buffer
  20318. var result = this.resultBuffer,
  20319. values = this.sampleValues,
  20320. stride = this.valueSize,
  20321. offset = index * stride;
  20322. for (var i = 0; i !== stride; ++i) {
  20323. result[i] = values[offset + i];
  20324. }
  20325. return result;
  20326. },
  20327. // Template methods for derived classes:
  20328. interpolate_: function ()
  20329. /* i1, t0, t, t1 */
  20330. {
  20331. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  20332. },
  20333. intervalChanged_: function ()
  20334. /* i1, t0, t1 */
  20335. {// empty
  20336. }
  20337. }); //!\ DECLARE ALIAS AFTER assign prototype !
  20338. Object.assign(Interpolant.prototype, {
  20339. //( 0, t, t0 ), returns this.resultBuffer
  20340. beforeStart_: Interpolant.prototype.copySampleValue_,
  20341. //( N-1, tN-1, t ), returns this.resultBuffer
  20342. afterEnd_: Interpolant.prototype.copySampleValue_
  20343. });
  20344. /**
  20345. * Fast and simple cubic spline interpolant.
  20346. *
  20347. * It was derived from a Hermitian construction setting the first derivative
  20348. * at each sample position to the linear slope between neighboring positions
  20349. * over their parameter interval.
  20350. *
  20351. * @author tschw
  20352. */
  20353. function CubicInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20354. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  20355. this._weightPrev = -0;
  20356. this._offsetPrev = -0;
  20357. this._weightNext = -0;
  20358. this._offsetNext = -0;
  20359. }
  20360. CubicInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  20361. constructor: CubicInterpolant,
  20362. DefaultSettings_: {
  20363. endingStart: ZeroCurvatureEnding,
  20364. endingEnd: ZeroCurvatureEnding
  20365. },
  20366. intervalChanged_: function (i1, t0, t1) {
  20367. var pp = this.parameterPositions,
  20368. iPrev = i1 - 2,
  20369. iNext = i1 + 1,
  20370. tPrev = pp[iPrev],
  20371. tNext = pp[iNext];
  20372. if (tPrev === undefined) {
  20373. switch (this.getSettings_().endingStart) {
  20374. case ZeroSlopeEnding:
  20375. // f'(t0) = 0
  20376. iPrev = i1;
  20377. tPrev = 2 * t0 - t1;
  20378. break;
  20379. case WrapAroundEnding:
  20380. // use the other end of the curve
  20381. iPrev = pp.length - 2;
  20382. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  20383. break;
  20384. default:
  20385. // ZeroCurvatureEnding
  20386. // f''(t0) = 0 a.k.a. Natural Spline
  20387. iPrev = i1;
  20388. tPrev = t1;
  20389. }
  20390. }
  20391. if (tNext === undefined) {
  20392. switch (this.getSettings_().endingEnd) {
  20393. case ZeroSlopeEnding:
  20394. // f'(tN) = 0
  20395. iNext = i1;
  20396. tNext = 2 * t1 - t0;
  20397. break;
  20398. case WrapAroundEnding:
  20399. // use the other end of the curve
  20400. iNext = 1;
  20401. tNext = t1 + pp[1] - pp[0];
  20402. break;
  20403. default:
  20404. // ZeroCurvatureEnding
  20405. // f''(tN) = 0, a.k.a. Natural Spline
  20406. iNext = i1 - 1;
  20407. tNext = t0;
  20408. }
  20409. }
  20410. var halfDt = (t1 - t0) * 0.5,
  20411. stride = this.valueSize;
  20412. this._weightPrev = halfDt / (t0 - tPrev);
  20413. this._weightNext = halfDt / (tNext - t1);
  20414. this._offsetPrev = iPrev * stride;
  20415. this._offsetNext = iNext * stride;
  20416. },
  20417. interpolate_: function (i1, t0, t, t1) {
  20418. var result = this.resultBuffer,
  20419. values = this.sampleValues,
  20420. stride = this.valueSize,
  20421. o1 = i1 * stride,
  20422. o0 = o1 - stride,
  20423. oP = this._offsetPrev,
  20424. oN = this._offsetNext,
  20425. wP = this._weightPrev,
  20426. wN = this._weightNext,
  20427. p = (t - t0) / (t1 - t0),
  20428. pp = p * p,
  20429. ppp = pp * p; // evaluate polynomials
  20430. var sP = -wP * ppp + 2 * wP * pp - wP * p;
  20431. var s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  20432. var s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  20433. var sN = wN * ppp - wN * pp; // combine data linearly
  20434. for (var i = 0; i !== stride; ++i) {
  20435. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  20436. }
  20437. return result;
  20438. }
  20439. });
  20440. /**
  20441. * @author tschw
  20442. */
  20443. function LinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20444. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  20445. }
  20446. LinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  20447. constructor: LinearInterpolant,
  20448. interpolate_: function (i1, t0, t, t1) {
  20449. var result = this.resultBuffer,
  20450. values = this.sampleValues,
  20451. stride = this.valueSize,
  20452. offset1 = i1 * stride,
  20453. offset0 = offset1 - stride,
  20454. weight1 = (t - t0) / (t1 - t0),
  20455. weight0 = 1 - weight1;
  20456. for (var i = 0; i !== stride; ++i) {
  20457. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  20458. }
  20459. return result;
  20460. }
  20461. });
  20462. /**
  20463. *
  20464. * Interpolant that evaluates to the sample value at the position preceeding
  20465. * the parameter.
  20466. *
  20467. * @author tschw
  20468. */
  20469. function DiscreteInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20470. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  20471. }
  20472. DiscreteInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  20473. constructor: DiscreteInterpolant,
  20474. interpolate_: function (i1
  20475. /*, t0, t, t1 */
  20476. ) {
  20477. return this.copySampleValue_(i1 - 1);
  20478. }
  20479. });
  20480. /**
  20481. *
  20482. * A timed sequence of keyframes for a specific property.
  20483. *
  20484. *
  20485. * @author Ben Houston / http://clara.io/
  20486. * @author David Sarno / http://lighthaus.us/
  20487. * @author tschw
  20488. */
  20489. function KeyframeTrack(name, times, values, interpolation) {
  20490. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  20491. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  20492. this.name = name;
  20493. this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
  20494. this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
  20495. this.setInterpolation(interpolation || this.DefaultInterpolation);
  20496. } // Static methods
  20497. Object.assign(KeyframeTrack, {
  20498. // Serialization (in static context, because of constructor invocation
  20499. // and automatic invocation of .toJSON):
  20500. toJSON: function (track) {
  20501. var trackType = track.constructor;
  20502. var json; // derived classes can define a static toJSON method
  20503. if (trackType.toJSON !== undefined) {
  20504. json = trackType.toJSON(track);
  20505. } else {
  20506. // by default, we assume the data can be serialized as-is
  20507. json = {
  20508. 'name': track.name,
  20509. 'times': AnimationUtils.convertArray(track.times, Array),
  20510. 'values': AnimationUtils.convertArray(track.values, Array)
  20511. };
  20512. var interpolation = track.getInterpolation();
  20513. if (interpolation !== track.DefaultInterpolation) {
  20514. json.interpolation = interpolation;
  20515. }
  20516. }
  20517. json.type = track.ValueTypeName; // mandatory
  20518. return json;
  20519. }
  20520. });
  20521. Object.assign(KeyframeTrack.prototype, {
  20522. constructor: KeyframeTrack,
  20523. TimeBufferType: Float32Array,
  20524. ValueBufferType: Float32Array,
  20525. DefaultInterpolation: InterpolateLinear,
  20526. InterpolantFactoryMethodDiscrete: function (result) {
  20527. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  20528. },
  20529. InterpolantFactoryMethodLinear: function (result) {
  20530. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  20531. },
  20532. InterpolantFactoryMethodSmooth: function (result) {
  20533. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  20534. },
  20535. setInterpolation: function (interpolation) {
  20536. var factoryMethod;
  20537. switch (interpolation) {
  20538. case InterpolateDiscrete:
  20539. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  20540. break;
  20541. case InterpolateLinear:
  20542. factoryMethod = this.InterpolantFactoryMethodLinear;
  20543. break;
  20544. case InterpolateSmooth:
  20545. factoryMethod = this.InterpolantFactoryMethodSmooth;
  20546. break;
  20547. }
  20548. if (factoryMethod === undefined) {
  20549. var message = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name;
  20550. if (this.createInterpolant === undefined) {
  20551. // fall back to default, unless the default itself is messed up
  20552. if (interpolation !== this.DefaultInterpolation) {
  20553. this.setInterpolation(this.DefaultInterpolation);
  20554. } else {
  20555. throw new Error(message); // fatal, in this case
  20556. }
  20557. }
  20558. console.warn('THREE.KeyframeTrack:', message);
  20559. return this;
  20560. }
  20561. this.createInterpolant = factoryMethod;
  20562. return this;
  20563. },
  20564. getInterpolation: function () {
  20565. switch (this.createInterpolant) {
  20566. case this.InterpolantFactoryMethodDiscrete:
  20567. return InterpolateDiscrete;
  20568. case this.InterpolantFactoryMethodLinear:
  20569. return InterpolateLinear;
  20570. case this.InterpolantFactoryMethodSmooth:
  20571. return InterpolateSmooth;
  20572. }
  20573. },
  20574. getValueSize: function () {
  20575. return this.values.length / this.times.length;
  20576. },
  20577. // move all keyframes either forwards or backwards in time
  20578. shift: function (timeOffset) {
  20579. if (timeOffset !== 0.0) {
  20580. var times = this.times;
  20581. for (var i = 0, n = times.length; i !== n; ++i) {
  20582. times[i] += timeOffset;
  20583. }
  20584. }
  20585. return this;
  20586. },
  20587. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  20588. scale: function (timeScale) {
  20589. if (timeScale !== 1.0) {
  20590. var times = this.times;
  20591. for (var i = 0, n = times.length; i !== n; ++i) {
  20592. times[i] *= timeScale;
  20593. }
  20594. }
  20595. return this;
  20596. },
  20597. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  20598. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  20599. trim: function (startTime, endTime) {
  20600. var times = this.times,
  20601. nKeys = times.length,
  20602. from = 0,
  20603. to = nKeys - 1;
  20604. while (from !== nKeys && times[from] < startTime) {
  20605. ++from;
  20606. }
  20607. while (to !== -1 && times[to] > endTime) {
  20608. --to;
  20609. }
  20610. ++to; // inclusive -> exclusive bound
  20611. if (from !== 0 || to !== nKeys) {
  20612. // empty tracks are forbidden, so keep at least one keyframe
  20613. if (from >= to) to = Math.max(to, 1), from = to - 1;
  20614. var stride = this.getValueSize();
  20615. this.times = AnimationUtils.arraySlice(times, from, to);
  20616. this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
  20617. }
  20618. return this;
  20619. },
  20620. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  20621. validate: function () {
  20622. var valid = true;
  20623. var valueSize = this.getValueSize();
  20624. if (valueSize - Math.floor(valueSize) !== 0) {
  20625. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  20626. valid = false;
  20627. }
  20628. var times = this.times,
  20629. values = this.values,
  20630. nKeys = times.length;
  20631. if (nKeys === 0) {
  20632. console.error('THREE.KeyframeTrack: Track is empty.', this);
  20633. valid = false;
  20634. }
  20635. var prevTime = null;
  20636. for (var i = 0; i !== nKeys; i++) {
  20637. var currTime = times[i];
  20638. if (typeof currTime === 'number' && isNaN(currTime)) {
  20639. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  20640. valid = false;
  20641. break;
  20642. }
  20643. if (prevTime !== null && prevTime > currTime) {
  20644. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  20645. valid = false;
  20646. break;
  20647. }
  20648. prevTime = currTime;
  20649. }
  20650. if (values !== undefined) {
  20651. if (AnimationUtils.isTypedArray(values)) {
  20652. for (var i = 0, n = values.length; i !== n; ++i) {
  20653. var value = values[i];
  20654. if (isNaN(value)) {
  20655. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  20656. valid = false;
  20657. break;
  20658. }
  20659. }
  20660. }
  20661. }
  20662. return valid;
  20663. },
  20664. // removes equivalent sequential keys as common in morph target sequences
  20665. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  20666. optimize: function () {
  20667. var times = this.times,
  20668. values = this.values,
  20669. stride = this.getValueSize(),
  20670. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  20671. writeIndex = 1,
  20672. lastIndex = times.length - 1;
  20673. for (var i = 1; i < lastIndex; ++i) {
  20674. var keep = false;
  20675. var time = times[i];
  20676. var timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  20677. if (time !== timeNext && (i !== 1 || time !== time[0])) {
  20678. if (!smoothInterpolation) {
  20679. // remove unnecessary keyframes same as their neighbors
  20680. var offset = i * stride,
  20681. offsetP = offset - stride,
  20682. offsetN = offset + stride;
  20683. for (var j = 0; j !== stride; ++j) {
  20684. var value = values[offset + j];
  20685. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  20686. keep = true;
  20687. break;
  20688. }
  20689. }
  20690. } else {
  20691. keep = true;
  20692. }
  20693. } // in-place compaction
  20694. if (keep) {
  20695. if (i !== writeIndex) {
  20696. times[writeIndex] = times[i];
  20697. var readOffset = i * stride,
  20698. writeOffset = writeIndex * stride;
  20699. for (var j = 0; j !== stride; ++j) {
  20700. values[writeOffset + j] = values[readOffset + j];
  20701. }
  20702. }
  20703. ++writeIndex;
  20704. }
  20705. } // flush last keyframe (compaction looks ahead)
  20706. if (lastIndex > 0) {
  20707. times[writeIndex] = times[lastIndex];
  20708. for (var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  20709. values[writeOffset + j] = values[readOffset + j];
  20710. }
  20711. ++writeIndex;
  20712. }
  20713. if (writeIndex !== times.length) {
  20714. this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
  20715. this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
  20716. }
  20717. return this;
  20718. },
  20719. clone: function () {
  20720. var times = AnimationUtils.arraySlice(this.times, 0);
  20721. var values = AnimationUtils.arraySlice(this.values, 0);
  20722. var TypedKeyframeTrack = this.constructor;
  20723. var track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  20724. track.createInterpolant = this.createInterpolant;
  20725. return track;
  20726. }
  20727. });
  20728. /**
  20729. *
  20730. * A Track of Boolean keyframe values.
  20731. *
  20732. *
  20733. * @author Ben Houston / http://clara.io/
  20734. * @author David Sarno / http://lighthaus.us/
  20735. * @author tschw
  20736. */
  20737. function BooleanKeyframeTrack(name, times, values) {
  20738. KeyframeTrack.call(this, name, times, values);
  20739. }
  20740. BooleanKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  20741. constructor: BooleanKeyframeTrack,
  20742. ValueTypeName: 'bool',
  20743. ValueBufferType: Array,
  20744. DefaultInterpolation: InterpolateDiscrete,
  20745. InterpolantFactoryMethodLinear: undefined,
  20746. InterpolantFactoryMethodSmooth: undefined // Note: Actually this track could have a optimized / compressed
  20747. // representation of a single value and a custom interpolant that
  20748. // computes "firstValue ^ isOdd( index )".
  20749. });
  20750. /**
  20751. *
  20752. * A Track of keyframe values that represent color.
  20753. *
  20754. *
  20755. * @author Ben Houston / http://clara.io/
  20756. * @author David Sarno / http://lighthaus.us/
  20757. * @author tschw
  20758. */
  20759. function ColorKeyframeTrack(name, times, values, interpolation) {
  20760. KeyframeTrack.call(this, name, times, values, interpolation);
  20761. }
  20762. ColorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  20763. constructor: ColorKeyframeTrack,
  20764. ValueTypeName: 'color' // ValueBufferType is inherited
  20765. // DefaultInterpolation is inherited
  20766. // Note: Very basic implementation and nothing special yet.
  20767. // However, this is the place for color space parameterization.
  20768. });
  20769. /**
  20770. *
  20771. * A Track of numeric keyframe values.
  20772. *
  20773. * @author Ben Houston / http://clara.io/
  20774. * @author David Sarno / http://lighthaus.us/
  20775. * @author tschw
  20776. */
  20777. function NumberKeyframeTrack(name, times, values, interpolation) {
  20778. KeyframeTrack.call(this, name, times, values, interpolation);
  20779. }
  20780. NumberKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  20781. constructor: NumberKeyframeTrack,
  20782. ValueTypeName: 'number' // ValueBufferType is inherited
  20783. // DefaultInterpolation is inherited
  20784. });
  20785. /**
  20786. * Spherical linear unit quaternion interpolant.
  20787. *
  20788. * @author tschw
  20789. */
  20790. function QuaternionLinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20791. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  20792. }
  20793. QuaternionLinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  20794. constructor: QuaternionLinearInterpolant,
  20795. interpolate_: function (i1, t0, t, t1) {
  20796. var result = this.resultBuffer,
  20797. values = this.sampleValues,
  20798. stride = this.valueSize,
  20799. offset = i1 * stride,
  20800. alpha = (t - t0) / (t1 - t0);
  20801. for (var end = offset + stride; offset !== end; offset += 4) {
  20802. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  20803. }
  20804. return result;
  20805. }
  20806. });
  20807. /**
  20808. *
  20809. * A Track of quaternion keyframe values.
  20810. *
  20811. * @author Ben Houston / http://clara.io/
  20812. * @author David Sarno / http://lighthaus.us/
  20813. * @author tschw
  20814. */
  20815. function QuaternionKeyframeTrack(name, times, values, interpolation) {
  20816. KeyframeTrack.call(this, name, times, values, interpolation);
  20817. }
  20818. QuaternionKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  20819. constructor: QuaternionKeyframeTrack,
  20820. ValueTypeName: 'quaternion',
  20821. // ValueBufferType is inherited
  20822. DefaultInterpolation: InterpolateLinear,
  20823. InterpolantFactoryMethodLinear: function (result) {
  20824. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  20825. },
  20826. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  20827. });
  20828. /**
  20829. *
  20830. * A Track that interpolates Strings
  20831. *
  20832. *
  20833. * @author Ben Houston / http://clara.io/
  20834. * @author David Sarno / http://lighthaus.us/
  20835. * @author tschw
  20836. */
  20837. function StringKeyframeTrack(name, times, values, interpolation) {
  20838. KeyframeTrack.call(this, name, times, values, interpolation);
  20839. }
  20840. StringKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  20841. constructor: StringKeyframeTrack,
  20842. ValueTypeName: 'string',
  20843. ValueBufferType: Array,
  20844. DefaultInterpolation: InterpolateDiscrete,
  20845. InterpolantFactoryMethodLinear: undefined,
  20846. InterpolantFactoryMethodSmooth: undefined
  20847. });
  20848. /**
  20849. *
  20850. * A Track of vectored keyframe values.
  20851. *
  20852. *
  20853. * @author Ben Houston / http://clara.io/
  20854. * @author David Sarno / http://lighthaus.us/
  20855. * @author tschw
  20856. */
  20857. function VectorKeyframeTrack(name, times, values, interpolation) {
  20858. KeyframeTrack.call(this, name, times, values, interpolation);
  20859. }
  20860. VectorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  20861. constructor: VectorKeyframeTrack,
  20862. ValueTypeName: 'vector' // ValueBufferType is inherited
  20863. // DefaultInterpolation is inherited
  20864. });
  20865. /**
  20866. *
  20867. * Reusable set of Tracks that represent an animation.
  20868. *
  20869. * @author Ben Houston / http://clara.io/
  20870. * @author David Sarno / http://lighthaus.us/
  20871. */
  20872. function AnimationClip(name, duration, tracks) {
  20873. this.name = name;
  20874. this.tracks = tracks;
  20875. this.duration = duration !== undefined ? duration : -1;
  20876. this.uuid = _Math.generateUUID(); // this means it should figure out its duration by scanning the tracks
  20877. if (this.duration < 0) {
  20878. this.resetDuration();
  20879. }
  20880. }
  20881. function getTrackTypeForValueTypeName(typeName) {
  20882. switch (typeName.toLowerCase()) {
  20883. case 'scalar':
  20884. case 'double':
  20885. case 'float':
  20886. case 'number':
  20887. case 'integer':
  20888. return NumberKeyframeTrack;
  20889. case 'vector':
  20890. case 'vector2':
  20891. case 'vector3':
  20892. case 'vector4':
  20893. return VectorKeyframeTrack;
  20894. case 'color':
  20895. return ColorKeyframeTrack;
  20896. case 'quaternion':
  20897. return QuaternionKeyframeTrack;
  20898. case 'bool':
  20899. case 'boolean':
  20900. return BooleanKeyframeTrack;
  20901. case 'string':
  20902. return StringKeyframeTrack;
  20903. }
  20904. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  20905. }
  20906. function parseKeyframeTrack(json) {
  20907. if (json.type === undefined) {
  20908. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  20909. }
  20910. var trackType = getTrackTypeForValueTypeName(json.type);
  20911. if (json.times === undefined) {
  20912. var times = [],
  20913. values = [];
  20914. AnimationUtils.flattenJSON(json.keys, times, values, 'value');
  20915. json.times = times;
  20916. json.values = values;
  20917. } // derived classes can define a static parse method
  20918. if (trackType.parse !== undefined) {
  20919. return trackType.parse(json);
  20920. } else {
  20921. // by default, we assume a constructor compatible with the base
  20922. return new trackType(json.name, json.times, json.values, json.interpolation);
  20923. }
  20924. }
  20925. Object.assign(AnimationClip, {
  20926. parse: function (json) {
  20927. var tracks = [],
  20928. jsonTracks = json.tracks,
  20929. frameTime = 1.0 / (json.fps || 1.0);
  20930. for (var i = 0, n = jsonTracks.length; i !== n; ++i) {
  20931. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  20932. }
  20933. return new AnimationClip(json.name, json.duration, tracks);
  20934. },
  20935. toJSON: function (clip) {
  20936. var tracks = [],
  20937. clipTracks = clip.tracks;
  20938. var json = {
  20939. 'name': clip.name,
  20940. 'duration': clip.duration,
  20941. 'tracks': tracks,
  20942. 'uuid': clip.uuid
  20943. };
  20944. for (var i = 0, n = clipTracks.length; i !== n; ++i) {
  20945. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  20946. }
  20947. return json;
  20948. },
  20949. CreateFromMorphTargetSequence: function (name, morphTargetSequence, fps, noLoop) {
  20950. var numMorphTargets = morphTargetSequence.length;
  20951. var tracks = [];
  20952. for (var i = 0; i < numMorphTargets; i++) {
  20953. var times = [];
  20954. var values = [];
  20955. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  20956. values.push(0, 1, 0);
  20957. var order = AnimationUtils.getKeyframeOrder(times);
  20958. times = AnimationUtils.sortedArray(times, 1, order);
  20959. values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  20960. // last frame as well for perfect loop.
  20961. if (!noLoop && times[0] === 0) {
  20962. times.push(numMorphTargets);
  20963. values.push(values[0]);
  20964. }
  20965. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  20966. }
  20967. return new AnimationClip(name, -1, tracks);
  20968. },
  20969. findByName: function (objectOrClipArray, name) {
  20970. var clipArray = objectOrClipArray;
  20971. if (!Array.isArray(objectOrClipArray)) {
  20972. var o = objectOrClipArray;
  20973. clipArray = o.geometry && o.geometry.animations || o.animations;
  20974. }
  20975. for (var i = 0; i < clipArray.length; i++) {
  20976. if (clipArray[i].name === name) {
  20977. return clipArray[i];
  20978. }
  20979. }
  20980. return null;
  20981. },
  20982. CreateClipsFromMorphTargetSequences: function (morphTargets, fps, noLoop) {
  20983. var animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  20984. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  20985. var pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  20986. // patterns like Walk_001, Walk_002, Run_001, Run_002
  20987. for (var i = 0, il = morphTargets.length; i < il; i++) {
  20988. var morphTarget = morphTargets[i];
  20989. var parts = morphTarget.name.match(pattern);
  20990. if (parts && parts.length > 1) {
  20991. var name = parts[1];
  20992. var animationMorphTargets = animationToMorphTargets[name];
  20993. if (!animationMorphTargets) {
  20994. animationToMorphTargets[name] = animationMorphTargets = [];
  20995. }
  20996. animationMorphTargets.push(morphTarget);
  20997. }
  20998. }
  20999. var clips = [];
  21000. for (var name in animationToMorphTargets) {
  21001. clips.push(AnimationClip.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  21002. }
  21003. return clips;
  21004. },
  21005. // parse the animation.hierarchy format
  21006. parseAnimation: function (animation, bones) {
  21007. if (!animation) {
  21008. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  21009. return null;
  21010. }
  21011. var addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  21012. // only return track if there are actually keys.
  21013. if (animationKeys.length !== 0) {
  21014. var times = [];
  21015. var values = [];
  21016. AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  21017. if (times.length !== 0) {
  21018. destTracks.push(new trackType(trackName, times, values));
  21019. }
  21020. }
  21021. };
  21022. var tracks = [];
  21023. var clipName = animation.name || 'default'; // automatic length determination in AnimationClip.
  21024. var duration = animation.length || -1;
  21025. var fps = animation.fps || 30;
  21026. var hierarchyTracks = animation.hierarchy || [];
  21027. for (var h = 0; h < hierarchyTracks.length; h++) {
  21028. var animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  21029. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  21030. if (animationKeys[0].morphTargets) {
  21031. // figure out all morph targets used in this track
  21032. var morphTargetNames = {};
  21033. for (var k = 0; k < animationKeys.length; k++) {
  21034. if (animationKeys[k].morphTargets) {
  21035. for (var m = 0; m < animationKeys[k].morphTargets.length; m++) {
  21036. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  21037. }
  21038. }
  21039. } // create a track for each morph target with all zero
  21040. // morphTargetInfluences except for the keys in which
  21041. // the morphTarget is named.
  21042. for (var morphTargetName in morphTargetNames) {
  21043. var times = [];
  21044. var values = [];
  21045. for (var m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  21046. var animationKey = animationKeys[k];
  21047. times.push(animationKey.time);
  21048. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  21049. }
  21050. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  21051. }
  21052. duration = morphTargetNames.length * (fps || 1.0);
  21053. } else {
  21054. // ...assume skeletal animation
  21055. var boneName = '.bones[' + bones[h].name + ']';
  21056. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  21057. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  21058. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  21059. }
  21060. }
  21061. if (tracks.length === 0) {
  21062. return null;
  21063. }
  21064. var clip = new AnimationClip(clipName, duration, tracks);
  21065. return clip;
  21066. }
  21067. });
  21068. Object.assign(AnimationClip.prototype, {
  21069. resetDuration: function () {
  21070. var tracks = this.tracks,
  21071. duration = 0;
  21072. for (var i = 0, n = tracks.length; i !== n; ++i) {
  21073. var track = this.tracks[i];
  21074. duration = Math.max(duration, track.times[track.times.length - 1]);
  21075. }
  21076. this.duration = duration;
  21077. return this;
  21078. },
  21079. trim: function () {
  21080. for (var i = 0; i < this.tracks.length; i++) {
  21081. this.tracks[i].trim(0, this.duration);
  21082. }
  21083. return this;
  21084. },
  21085. validate: function () {
  21086. var valid = true;
  21087. for (var i = 0; i < this.tracks.length; i++) {
  21088. valid = valid && this.tracks[i].validate();
  21089. }
  21090. return valid;
  21091. },
  21092. optimize: function () {
  21093. for (var i = 0; i < this.tracks.length; i++) {
  21094. this.tracks[i].optimize();
  21095. }
  21096. return this;
  21097. },
  21098. clone: function () {
  21099. var tracks = [];
  21100. for (var i = 0; i < this.tracks.length; i++) {
  21101. tracks.push(this.tracks[i].clone());
  21102. }
  21103. return new AnimationClip(this.name, this.duration, tracks);
  21104. }
  21105. });
  21106. /**
  21107. * @author mrdoob / http://mrdoob.com/
  21108. */
  21109. var Cache = {
  21110. enabled: false,
  21111. files: {},
  21112. add: function (key, file) {
  21113. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  21114. this.files[key] = file;
  21115. },
  21116. get: function (key) {
  21117. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  21118. return this.files[key];
  21119. },
  21120. remove: function (key) {
  21121. delete this.files[key];
  21122. },
  21123. clear: function () {
  21124. this.files = {};
  21125. }
  21126. };
  21127. /**
  21128. * @author mrdoob / http://mrdoob.com/
  21129. */
  21130. exports.Cache = Cache;
  21131. function LoadingManager(onLoad, onProgress, onError) {
  21132. var scope = this;
  21133. var isLoading = false;
  21134. var itemsLoaded = 0;
  21135. var itemsTotal = 0;
  21136. var urlModifier = undefined;
  21137. var handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  21138. // in the constructor
  21139. this.onStart = undefined;
  21140. this.onLoad = onLoad;
  21141. this.onProgress = onProgress;
  21142. this.onError = onError;
  21143. this.itemStart = function (url) {
  21144. itemsTotal++;
  21145. if (isLoading === false) {
  21146. if (scope.onStart !== undefined) {
  21147. scope.onStart(url, itemsLoaded, itemsTotal);
  21148. }
  21149. }
  21150. isLoading = true;
  21151. };
  21152. this.itemEnd = function (url) {
  21153. itemsLoaded++;
  21154. if (scope.onProgress !== undefined) {
  21155. scope.onProgress(url, itemsLoaded, itemsTotal);
  21156. }
  21157. if (itemsLoaded === itemsTotal) {
  21158. isLoading = false;
  21159. if (scope.onLoad !== undefined) {
  21160. scope.onLoad();
  21161. }
  21162. }
  21163. };
  21164. this.itemError = function (url) {
  21165. if (scope.onError !== undefined) {
  21166. scope.onError(url);
  21167. }
  21168. };
  21169. this.resolveURL = function (url) {
  21170. if (urlModifier) {
  21171. return urlModifier(url);
  21172. }
  21173. return url;
  21174. };
  21175. this.setURLModifier = function (transform) {
  21176. urlModifier = transform;
  21177. return this;
  21178. };
  21179. this.addHandler = function (regex, loader) {
  21180. handlers.push(regex, loader);
  21181. return this;
  21182. };
  21183. this.removeHandler = function (regex) {
  21184. var index = handlers.indexOf(regex);
  21185. if (index !== -1) {
  21186. handlers.splice(index, 2);
  21187. }
  21188. return this;
  21189. };
  21190. this.getHandler = function (file) {
  21191. for (var i = 0, l = handlers.length; i < l; i += 2) {
  21192. var regex = handlers[i];
  21193. var loader = handlers[i + 1];
  21194. if (regex.test(file)) {
  21195. return loader;
  21196. }
  21197. }
  21198. return null;
  21199. };
  21200. }
  21201. var DefaultLoadingManager = new LoadingManager();
  21202. /**
  21203. * @author alteredq / http://alteredqualia.com/
  21204. */
  21205. exports.DefaultLoadingManager = DefaultLoadingManager;
  21206. function Loader(manager) {
  21207. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  21208. this.crossOrigin = 'anonymous';
  21209. this.path = '';
  21210. this.resourcePath = '';
  21211. }
  21212. Object.assign(Loader.prototype, {
  21213. load: function ()
  21214. /* url, onLoad, onProgress, onError */
  21215. {},
  21216. parse: function ()
  21217. /* data */
  21218. {},
  21219. setCrossOrigin: function (crossOrigin) {
  21220. this.crossOrigin = crossOrigin;
  21221. return this;
  21222. },
  21223. setPath: function (path) {
  21224. this.path = path;
  21225. return this;
  21226. },
  21227. setResourcePath: function (resourcePath) {
  21228. this.resourcePath = resourcePath;
  21229. return this;
  21230. }
  21231. });
  21232. /**
  21233. * @author mrdoob / http://mrdoob.com/
  21234. */
  21235. var loading = {};
  21236. function FileLoader(manager) {
  21237. Loader.call(this, manager);
  21238. }
  21239. FileLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21240. constructor: FileLoader,
  21241. load: function (url, onLoad, onProgress, onError) {
  21242. if (url === undefined) url = '';
  21243. if (this.path !== undefined) url = this.path + url;
  21244. url = this.manager.resolveURL(url);
  21245. var scope = this;
  21246. var cached = Cache.get(url);
  21247. if (cached !== undefined) {
  21248. scope.manager.itemStart(url);
  21249. setTimeout(function () {
  21250. if (onLoad) onLoad(cached);
  21251. scope.manager.itemEnd(url);
  21252. }, 0);
  21253. return cached;
  21254. } // Check if request is duplicate
  21255. if (loading[url] !== undefined) {
  21256. loading[url].push({
  21257. onLoad: onLoad,
  21258. onProgress: onProgress,
  21259. onError: onError
  21260. });
  21261. return;
  21262. } // Check for data: URI
  21263. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  21264. var dataUriRegexResult = url.match(dataUriRegex); // Safari can not handle Data URIs through XMLHttpRequest so process manually
  21265. if (dataUriRegexResult) {
  21266. var mimeType = dataUriRegexResult[1];
  21267. var isBase64 = !!dataUriRegexResult[2];
  21268. var data = dataUriRegexResult[3];
  21269. data = decodeURIComponent(data);
  21270. if (isBase64) data = atob(data);
  21271. try {
  21272. var response;
  21273. var responseType = (this.responseType || '').toLowerCase();
  21274. switch (responseType) {
  21275. case 'arraybuffer':
  21276. case 'blob':
  21277. var view = new Uint8Array(data.length);
  21278. for (var i = 0; i < data.length; i++) {
  21279. view[i] = data.charCodeAt(i);
  21280. }
  21281. if (responseType === 'blob') {
  21282. response = new Blob([view.buffer], {
  21283. type: mimeType
  21284. });
  21285. } else {
  21286. response = view.buffer;
  21287. }
  21288. break;
  21289. case 'document':
  21290. var parser = new DOMParser();
  21291. response = parser.parseFromString(data, mimeType);
  21292. break;
  21293. case 'json':
  21294. response = JSON.parse(data);
  21295. break;
  21296. default:
  21297. // 'text' or other
  21298. response = data;
  21299. break;
  21300. } // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  21301. setTimeout(function () {
  21302. if (onLoad) onLoad(response);
  21303. scope.manager.itemEnd(url);
  21304. }, 0);
  21305. } catch (error) {
  21306. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  21307. setTimeout(function () {
  21308. if (onError) onError(error);
  21309. scope.manager.itemError(url);
  21310. scope.manager.itemEnd(url);
  21311. }, 0);
  21312. }
  21313. } else {
  21314. // Initialise array for duplicate requests
  21315. loading[url] = [];
  21316. loading[url].push({
  21317. onLoad: onLoad,
  21318. onProgress: onProgress,
  21319. onError: onError
  21320. });
  21321. var request = new XMLHttpRequest();
  21322. request.open('GET', url, true);
  21323. request.addEventListener('load', function (event) {
  21324. var response = this.response;
  21325. Cache.add(url, response);
  21326. var callbacks = loading[url];
  21327. delete loading[url];
  21328. if (this.status === 200 || this.status === 0) {
  21329. // Some browsers return HTTP Status 0 when using non-http protocol
  21330. // e.g. 'file://' or 'data://'. Handle as success.
  21331. if (this.status === 0) console.warn('THREE.FileLoader: HTTP Status 0 received.');
  21332. for (var i = 0, il = callbacks.length; i < il; i++) {
  21333. var callback = callbacks[i];
  21334. if (callback.onLoad) callback.onLoad(response);
  21335. }
  21336. scope.manager.itemEnd(url);
  21337. } else {
  21338. for (var i = 0, il = callbacks.length; i < il; i++) {
  21339. var callback = callbacks[i];
  21340. if (callback.onError) callback.onError(event);
  21341. }
  21342. scope.manager.itemError(url);
  21343. scope.manager.itemEnd(url);
  21344. }
  21345. }, false);
  21346. request.addEventListener('progress', function (event) {
  21347. var callbacks = loading[url];
  21348. for (var i = 0, il = callbacks.length; i < il; i++) {
  21349. var callback = callbacks[i];
  21350. if (callback.onProgress) callback.onProgress(event);
  21351. }
  21352. }, false);
  21353. request.addEventListener('error', function (event) {
  21354. var callbacks = loading[url];
  21355. delete loading[url];
  21356. for (var i = 0, il = callbacks.length; i < il; i++) {
  21357. var callback = callbacks[i];
  21358. if (callback.onError) callback.onError(event);
  21359. }
  21360. scope.manager.itemError(url);
  21361. scope.manager.itemEnd(url);
  21362. }, false);
  21363. request.addEventListener('abort', function (event) {
  21364. var callbacks = loading[url];
  21365. delete loading[url];
  21366. for (var i = 0, il = callbacks.length; i < il; i++) {
  21367. var callback = callbacks[i];
  21368. if (callback.onError) callback.onError(event);
  21369. }
  21370. scope.manager.itemError(url);
  21371. scope.manager.itemEnd(url);
  21372. }, false);
  21373. if (this.responseType !== undefined) request.responseType = this.responseType;
  21374. if (this.withCredentials !== undefined) request.withCredentials = this.withCredentials;
  21375. if (request.overrideMimeType) request.overrideMimeType(this.mimeType !== undefined ? this.mimeType : 'text/plain');
  21376. for (var header in this.requestHeader) {
  21377. request.setRequestHeader(header, this.requestHeader[header]);
  21378. }
  21379. request.send(null);
  21380. }
  21381. scope.manager.itemStart(url);
  21382. return request;
  21383. },
  21384. setResponseType: function (value) {
  21385. this.responseType = value;
  21386. return this;
  21387. },
  21388. setWithCredentials: function (value) {
  21389. this.withCredentials = value;
  21390. return this;
  21391. },
  21392. setMimeType: function (value) {
  21393. this.mimeType = value;
  21394. return this;
  21395. },
  21396. setRequestHeader: function (value) {
  21397. this.requestHeader = value;
  21398. return this;
  21399. }
  21400. });
  21401. /**
  21402. * @author bhouston / http://clara.io/
  21403. */
  21404. function AnimationLoader(manager) {
  21405. Loader.call(this, manager);
  21406. }
  21407. AnimationLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21408. constructor: AnimationLoader,
  21409. load: function (url, onLoad, onProgress, onError) {
  21410. var scope = this;
  21411. var loader = new FileLoader(scope.manager);
  21412. loader.setPath(scope.path);
  21413. loader.load(url, function (text) {
  21414. onLoad(scope.parse(JSON.parse(text)));
  21415. }, onProgress, onError);
  21416. },
  21417. parse: function (json) {
  21418. var animations = [];
  21419. for (var i = 0; i < json.length; i++) {
  21420. var clip = AnimationClip.parse(json[i]);
  21421. animations.push(clip);
  21422. }
  21423. return animations;
  21424. }
  21425. });
  21426. /**
  21427. * @author mrdoob / http://mrdoob.com/
  21428. *
  21429. * Abstract Base class to block based textures loader (dds, pvr, ...)
  21430. *
  21431. * Sub classes have to implement the parse() method which will be used in load().
  21432. */
  21433. function CompressedTextureLoader(manager) {
  21434. Loader.call(this, manager);
  21435. }
  21436. CompressedTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21437. constructor: CompressedTextureLoader,
  21438. load: function (url, onLoad, onProgress, onError) {
  21439. var scope = this;
  21440. var images = [];
  21441. var texture = new CompressedTexture();
  21442. texture.image = images;
  21443. var loader = new FileLoader(this.manager);
  21444. loader.setPath(this.path);
  21445. loader.setResponseType('arraybuffer');
  21446. function loadTexture(i) {
  21447. loader.load(url[i], function (buffer) {
  21448. var texDatas = scope.parse(buffer, true);
  21449. images[i] = {
  21450. width: texDatas.width,
  21451. height: texDatas.height,
  21452. format: texDatas.format,
  21453. mipmaps: texDatas.mipmaps
  21454. };
  21455. loaded += 1;
  21456. if (loaded === 6) {
  21457. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  21458. texture.format = texDatas.format;
  21459. texture.needsUpdate = true;
  21460. if (onLoad) onLoad(texture);
  21461. }
  21462. }, onProgress, onError);
  21463. }
  21464. if (Array.isArray(url)) {
  21465. var loaded = 0;
  21466. for (var i = 0, il = url.length; i < il; ++i) {
  21467. loadTexture(i);
  21468. }
  21469. } else {
  21470. // compressed cubemap texture stored in a single DDS file
  21471. loader.load(url, function (buffer) {
  21472. var texDatas = scope.parse(buffer, true);
  21473. if (texDatas.isCubemap) {
  21474. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  21475. for (var f = 0; f < faces; f++) {
  21476. images[f] = {
  21477. mipmaps: []
  21478. };
  21479. for (var i = 0; i < texDatas.mipmapCount; i++) {
  21480. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  21481. images[f].format = texDatas.format;
  21482. images[f].width = texDatas.width;
  21483. images[f].height = texDatas.height;
  21484. }
  21485. }
  21486. } else {
  21487. texture.image.width = texDatas.width;
  21488. texture.image.height = texDatas.height;
  21489. texture.mipmaps = texDatas.mipmaps;
  21490. }
  21491. if (texDatas.mipmapCount === 1) {
  21492. texture.minFilter = LinearFilter;
  21493. }
  21494. texture.format = texDatas.format;
  21495. texture.needsUpdate = true;
  21496. if (onLoad) onLoad(texture);
  21497. }, onProgress, onError);
  21498. }
  21499. return texture;
  21500. }
  21501. });
  21502. /**
  21503. * @author Nikos M. / https://github.com/foo123/
  21504. *
  21505. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  21506. *
  21507. * Sub classes have to implement the parse() method which will be used in load().
  21508. */
  21509. function DataTextureLoader(manager) {
  21510. Loader.call(this, manager);
  21511. }
  21512. DataTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21513. constructor: DataTextureLoader,
  21514. load: function (url, onLoad, onProgress, onError) {
  21515. var scope = this;
  21516. var texture = new DataTexture();
  21517. var loader = new FileLoader(this.manager);
  21518. loader.setResponseType('arraybuffer');
  21519. loader.setPath(this.path);
  21520. loader.load(url, function (buffer) {
  21521. var texData = scope.parse(buffer);
  21522. if (!texData) return;
  21523. if (texData.image !== undefined) {
  21524. texture.image = texData.image;
  21525. } else if (texData.data !== undefined) {
  21526. texture.image.width = texData.width;
  21527. texture.image.height = texData.height;
  21528. texture.image.data = texData.data;
  21529. }
  21530. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  21531. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  21532. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  21533. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearMipmapLinearFilter;
  21534. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  21535. if (texData.format !== undefined) {
  21536. texture.format = texData.format;
  21537. }
  21538. if (texData.type !== undefined) {
  21539. texture.type = texData.type;
  21540. }
  21541. if (texData.mipmaps !== undefined) {
  21542. texture.mipmaps = texData.mipmaps;
  21543. }
  21544. if (texData.mipmapCount === 1) {
  21545. texture.minFilter = LinearFilter;
  21546. }
  21547. texture.needsUpdate = true;
  21548. if (onLoad) onLoad(texture, texData);
  21549. }, onProgress, onError);
  21550. return texture;
  21551. }
  21552. });
  21553. /**
  21554. * @author mrdoob / http://mrdoob.com/
  21555. */
  21556. function ImageLoader(manager) {
  21557. Loader.call(this, manager);
  21558. }
  21559. ImageLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21560. constructor: ImageLoader,
  21561. load: function (url, onLoad, onProgress, onError) {
  21562. if (this.path !== undefined) url = this.path + url;
  21563. url = this.manager.resolveURL(url);
  21564. var scope = this;
  21565. var cached = Cache.get(url);
  21566. if (cached !== undefined) {
  21567. scope.manager.itemStart(url);
  21568. setTimeout(function () {
  21569. if (onLoad) onLoad(cached);
  21570. scope.manager.itemEnd(url);
  21571. }, 0);
  21572. return cached;
  21573. }
  21574. var image = document.createElementNS('http://www.w3.org/1999/xhtml', 'img');
  21575. function onImageLoad() {
  21576. image.removeEventListener('load', onImageLoad, false);
  21577. image.removeEventListener('error', onImageError, false);
  21578. Cache.add(url, this);
  21579. if (onLoad) onLoad(this);
  21580. scope.manager.itemEnd(url);
  21581. }
  21582. function onImageError(event) {
  21583. image.removeEventListener('load', onImageLoad, false);
  21584. image.removeEventListener('error', onImageError, false);
  21585. if (onError) onError(event);
  21586. scope.manager.itemError(url);
  21587. scope.manager.itemEnd(url);
  21588. }
  21589. image.addEventListener('load', onImageLoad, false);
  21590. image.addEventListener('error', onImageError, false);
  21591. if (url.substr(0, 5) !== 'data:') {
  21592. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  21593. }
  21594. scope.manager.itemStart(url);
  21595. image.src = url;
  21596. return image;
  21597. }
  21598. });
  21599. /**
  21600. * @author mrdoob / http://mrdoob.com/
  21601. */
  21602. function CubeTextureLoader(manager) {
  21603. Loader.call(this, manager);
  21604. }
  21605. CubeTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21606. constructor: CubeTextureLoader,
  21607. load: function (urls, onLoad, onProgress, onError) {
  21608. var texture = new CubeTexture();
  21609. var loader = new ImageLoader(this.manager);
  21610. loader.setCrossOrigin(this.crossOrigin);
  21611. loader.setPath(this.path);
  21612. var loaded = 0;
  21613. function loadTexture(i) {
  21614. loader.load(urls[i], function (image) {
  21615. texture.images[i] = image;
  21616. loaded++;
  21617. if (loaded === 6) {
  21618. texture.needsUpdate = true;
  21619. if (onLoad) onLoad(texture);
  21620. }
  21621. }, undefined, onError);
  21622. }
  21623. for (var i = 0; i < urls.length; ++i) {
  21624. loadTexture(i);
  21625. }
  21626. return texture;
  21627. }
  21628. });
  21629. /**
  21630. * @author mrdoob / http://mrdoob.com/
  21631. */
  21632. function TextureLoader(manager) {
  21633. Loader.call(this, manager);
  21634. }
  21635. TextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21636. constructor: TextureLoader,
  21637. load: function (url, onLoad, onProgress, onError) {
  21638. var texture = new Texture();
  21639. var loader = new ImageLoader(this.manager);
  21640. loader.setCrossOrigin(this.crossOrigin);
  21641. loader.setPath(this.path);
  21642. loader.load(url, function (image) {
  21643. texture.image = image; // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  21644. var isJPEG = url.search(/\.jpe?g($|\?)/i) > 0 || url.search(/^data\:image\/jpeg/) === 0;
  21645. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  21646. texture.needsUpdate = true;
  21647. if (onLoad !== undefined) {
  21648. onLoad(texture);
  21649. }
  21650. }, onProgress, onError);
  21651. return texture;
  21652. }
  21653. });
  21654. /**
  21655. * @author zz85 / http://www.lab4games.net/zz85/blog
  21656. * Extensible curve object
  21657. *
  21658. * Some common of curve methods:
  21659. * .getPoint( t, optionalTarget ), .getTangent( t )
  21660. * .getPointAt( u, optionalTarget ), .getTangentAt( u )
  21661. * .getPoints(), .getSpacedPoints()
  21662. * .getLength()
  21663. * .updateArcLengths()
  21664. *
  21665. * This following curves inherit from THREE.Curve:
  21666. *
  21667. * -- 2D curves --
  21668. * THREE.ArcCurve
  21669. * THREE.CubicBezierCurve
  21670. * THREE.EllipseCurve
  21671. * THREE.LineCurve
  21672. * THREE.QuadraticBezierCurve
  21673. * THREE.SplineCurve
  21674. *
  21675. * -- 3D curves --
  21676. * THREE.CatmullRomCurve3
  21677. * THREE.CubicBezierCurve3
  21678. * THREE.LineCurve3
  21679. * THREE.QuadraticBezierCurve3
  21680. *
  21681. * A series of curves can be represented as a THREE.CurvePath.
  21682. *
  21683. **/
  21684. /**************************************************************
  21685. * Abstract Curve base class
  21686. **************************************************************/
  21687. function Curve() {
  21688. this.type = 'Curve';
  21689. this.arcLengthDivisions = 200;
  21690. }
  21691. Object.assign(Curve.prototype, {
  21692. // Virtual base class method to overwrite and implement in subclasses
  21693. // - t [0 .. 1]
  21694. getPoint: function ()
  21695. /* t, optionalTarget */
  21696. {
  21697. console.warn('THREE.Curve: .getPoint() not implemented.');
  21698. return null;
  21699. },
  21700. // Get point at relative position in curve according to arc length
  21701. // - u [0 .. 1]
  21702. getPointAt: function (u, optionalTarget) {
  21703. var t = this.getUtoTmapping(u);
  21704. return this.getPoint(t, optionalTarget);
  21705. },
  21706. // Get sequence of points using getPoint( t )
  21707. getPoints: function (divisions) {
  21708. if (divisions === undefined) divisions = 5;
  21709. var points = [];
  21710. for (var d = 0; d <= divisions; d++) {
  21711. points.push(this.getPoint(d / divisions));
  21712. }
  21713. return points;
  21714. },
  21715. // Get sequence of points using getPointAt( u )
  21716. getSpacedPoints: function (divisions) {
  21717. if (divisions === undefined) divisions = 5;
  21718. var points = [];
  21719. for (var d = 0; d <= divisions; d++) {
  21720. points.push(this.getPointAt(d / divisions));
  21721. }
  21722. return points;
  21723. },
  21724. // Get total curve arc length
  21725. getLength: function () {
  21726. var lengths = this.getLengths();
  21727. return lengths[lengths.length - 1];
  21728. },
  21729. // Get list of cumulative segment lengths
  21730. getLengths: function (divisions) {
  21731. if (divisions === undefined) divisions = this.arcLengthDivisions;
  21732. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  21733. return this.cacheArcLengths;
  21734. }
  21735. this.needsUpdate = false;
  21736. var cache = [];
  21737. var current,
  21738. last = this.getPoint(0);
  21739. var p,
  21740. sum = 0;
  21741. cache.push(0);
  21742. for (p = 1; p <= divisions; p++) {
  21743. current = this.getPoint(p / divisions);
  21744. sum += current.distanceTo(last);
  21745. cache.push(sum);
  21746. last = current;
  21747. }
  21748. this.cacheArcLengths = cache;
  21749. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  21750. },
  21751. updateArcLengths: function () {
  21752. this.needsUpdate = true;
  21753. this.getLengths();
  21754. },
  21755. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  21756. getUtoTmapping: function (u, distance) {
  21757. var arcLengths = this.getLengths();
  21758. var i = 0,
  21759. il = arcLengths.length;
  21760. var targetArcLength; // The targeted u distance value to get
  21761. if (distance) {
  21762. targetArcLength = distance;
  21763. } else {
  21764. targetArcLength = u * arcLengths[il - 1];
  21765. } // binary search for the index with largest value smaller than target u distance
  21766. var low = 0,
  21767. high = il - 1,
  21768. comparison;
  21769. while (low <= high) {
  21770. 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
  21771. comparison = arcLengths[i] - targetArcLength;
  21772. if (comparison < 0) {
  21773. low = i + 1;
  21774. } else if (comparison > 0) {
  21775. high = i - 1;
  21776. } else {
  21777. high = i;
  21778. break; // DONE
  21779. }
  21780. }
  21781. i = high;
  21782. if (arcLengths[i] === targetArcLength) {
  21783. return i / (il - 1);
  21784. } // we could get finer grain at lengths, or use simple interpolation between two points
  21785. var lengthBefore = arcLengths[i];
  21786. var lengthAfter = arcLengths[i + 1];
  21787. var segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  21788. var segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  21789. var t = (i + segmentFraction) / (il - 1);
  21790. return t;
  21791. },
  21792. // Returns a unit vector tangent at t
  21793. // In case any sub curve does not implement its tangent derivation,
  21794. // 2 points a small delta apart will be used to find its gradient
  21795. // which seems to give a reasonable approximation
  21796. getTangent: function (t) {
  21797. var delta = 0.0001;
  21798. var t1 = t - delta;
  21799. var t2 = t + delta; // Capping in case of danger
  21800. if (t1 < 0) t1 = 0;
  21801. if (t2 > 1) t2 = 1;
  21802. var pt1 = this.getPoint(t1);
  21803. var pt2 = this.getPoint(t2);
  21804. var vec = pt2.clone().sub(pt1);
  21805. return vec.normalize();
  21806. },
  21807. getTangentAt: function (u) {
  21808. var t = this.getUtoTmapping(u);
  21809. return this.getTangent(t);
  21810. },
  21811. computeFrenetFrames: function (segments, closed) {
  21812. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  21813. var normal = new Vector3();
  21814. var tangents = [];
  21815. var normals = [];
  21816. var binormals = [];
  21817. var vec = new Vector3();
  21818. var mat = new Matrix4();
  21819. var i, u, theta; // compute the tangent vectors for each segment on the curve
  21820. for (i = 0; i <= segments; i++) {
  21821. u = i / segments;
  21822. tangents[i] = this.getTangentAt(u);
  21823. tangents[i].normalize();
  21824. } // select an initial normal vector perpendicular to the first tangent vector,
  21825. // and in the direction of the minimum tangent xyz component
  21826. normals[0] = new Vector3();
  21827. binormals[0] = new Vector3();
  21828. var min = Number.MAX_VALUE;
  21829. var tx = Math.abs(tangents[0].x);
  21830. var ty = Math.abs(tangents[0].y);
  21831. var tz = Math.abs(tangents[0].z);
  21832. if (tx <= min) {
  21833. min = tx;
  21834. normal.set(1, 0, 0);
  21835. }
  21836. if (ty <= min) {
  21837. min = ty;
  21838. normal.set(0, 1, 0);
  21839. }
  21840. if (tz <= min) {
  21841. normal.set(0, 0, 1);
  21842. }
  21843. vec.crossVectors(tangents[0], normal).normalize();
  21844. normals[0].crossVectors(tangents[0], vec);
  21845. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  21846. for (i = 1; i <= segments; i++) {
  21847. normals[i] = normals[i - 1].clone();
  21848. binormals[i] = binormals[i - 1].clone();
  21849. vec.crossVectors(tangents[i - 1], tangents[i]);
  21850. if (vec.length() > Number.EPSILON) {
  21851. vec.normalize();
  21852. theta = Math.acos(_Math.clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  21853. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  21854. }
  21855. binormals[i].crossVectors(tangents[i], normals[i]);
  21856. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  21857. if (closed === true) {
  21858. theta = Math.acos(_Math.clamp(normals[0].dot(normals[segments]), -1, 1));
  21859. theta /= segments;
  21860. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  21861. theta = -theta;
  21862. }
  21863. for (i = 1; i <= segments; i++) {
  21864. // twist a little...
  21865. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  21866. binormals[i].crossVectors(tangents[i], normals[i]);
  21867. }
  21868. }
  21869. return {
  21870. tangents: tangents,
  21871. normals: normals,
  21872. binormals: binormals
  21873. };
  21874. },
  21875. clone: function () {
  21876. return new this.constructor().copy(this);
  21877. },
  21878. copy: function (source) {
  21879. this.arcLengthDivisions = source.arcLengthDivisions;
  21880. return this;
  21881. },
  21882. toJSON: function () {
  21883. var data = {
  21884. metadata: {
  21885. version: 4.5,
  21886. type: 'Curve',
  21887. generator: 'Curve.toJSON'
  21888. }
  21889. };
  21890. data.arcLengthDivisions = this.arcLengthDivisions;
  21891. data.type = this.type;
  21892. return data;
  21893. },
  21894. fromJSON: function (json) {
  21895. this.arcLengthDivisions = json.arcLengthDivisions;
  21896. return this;
  21897. }
  21898. });
  21899. function EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  21900. Curve.call(this);
  21901. this.type = 'EllipseCurve';
  21902. this.aX = aX || 0;
  21903. this.aY = aY || 0;
  21904. this.xRadius = xRadius || 1;
  21905. this.yRadius = yRadius || 1;
  21906. this.aStartAngle = aStartAngle || 0;
  21907. this.aEndAngle = aEndAngle || 2 * Math.PI;
  21908. this.aClockwise = aClockwise || false;
  21909. this.aRotation = aRotation || 0;
  21910. }
  21911. EllipseCurve.prototype = Object.create(Curve.prototype);
  21912. EllipseCurve.prototype.constructor = EllipseCurve;
  21913. EllipseCurve.prototype.isEllipseCurve = true;
  21914. EllipseCurve.prototype.getPoint = function (t, optionalTarget) {
  21915. var point = optionalTarget || new Vector2();
  21916. var twoPi = Math.PI * 2;
  21917. var deltaAngle = this.aEndAngle - this.aStartAngle;
  21918. var samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  21919. while (deltaAngle < 0) deltaAngle += twoPi;
  21920. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  21921. if (deltaAngle < Number.EPSILON) {
  21922. if (samePoints) {
  21923. deltaAngle = 0;
  21924. } else {
  21925. deltaAngle = twoPi;
  21926. }
  21927. }
  21928. if (this.aClockwise === true && !samePoints) {
  21929. if (deltaAngle === twoPi) {
  21930. deltaAngle = -twoPi;
  21931. } else {
  21932. deltaAngle = deltaAngle - twoPi;
  21933. }
  21934. }
  21935. var angle = this.aStartAngle + t * deltaAngle;
  21936. var x = this.aX + this.xRadius * Math.cos(angle);
  21937. var y = this.aY + this.yRadius * Math.sin(angle);
  21938. if (this.aRotation !== 0) {
  21939. var cos = Math.cos(this.aRotation);
  21940. var sin = Math.sin(this.aRotation);
  21941. var tx = x - this.aX;
  21942. var ty = y - this.aY; // Rotate the point about the center of the ellipse.
  21943. x = tx * cos - ty * sin + this.aX;
  21944. y = tx * sin + ty * cos + this.aY;
  21945. }
  21946. return point.set(x, y);
  21947. };
  21948. EllipseCurve.prototype.copy = function (source) {
  21949. Curve.prototype.copy.call(this, source);
  21950. this.aX = source.aX;
  21951. this.aY = source.aY;
  21952. this.xRadius = source.xRadius;
  21953. this.yRadius = source.yRadius;
  21954. this.aStartAngle = source.aStartAngle;
  21955. this.aEndAngle = source.aEndAngle;
  21956. this.aClockwise = source.aClockwise;
  21957. this.aRotation = source.aRotation;
  21958. return this;
  21959. };
  21960. EllipseCurve.prototype.toJSON = function () {
  21961. var data = Curve.prototype.toJSON.call(this);
  21962. data.aX = this.aX;
  21963. data.aY = this.aY;
  21964. data.xRadius = this.xRadius;
  21965. data.yRadius = this.yRadius;
  21966. data.aStartAngle = this.aStartAngle;
  21967. data.aEndAngle = this.aEndAngle;
  21968. data.aClockwise = this.aClockwise;
  21969. data.aRotation = this.aRotation;
  21970. return data;
  21971. };
  21972. EllipseCurve.prototype.fromJSON = function (json) {
  21973. Curve.prototype.fromJSON.call(this, json);
  21974. this.aX = json.aX;
  21975. this.aY = json.aY;
  21976. this.xRadius = json.xRadius;
  21977. this.yRadius = json.yRadius;
  21978. this.aStartAngle = json.aStartAngle;
  21979. this.aEndAngle = json.aEndAngle;
  21980. this.aClockwise = json.aClockwise;
  21981. this.aRotation = json.aRotation;
  21982. return this;
  21983. };
  21984. function ArcCurve(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  21985. EllipseCurve.call(this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  21986. this.type = 'ArcCurve';
  21987. }
  21988. ArcCurve.prototype = Object.create(EllipseCurve.prototype);
  21989. ArcCurve.prototype.constructor = ArcCurve;
  21990. ArcCurve.prototype.isArcCurve = true;
  21991. /**
  21992. * @author zz85 https://github.com/zz85
  21993. *
  21994. * Centripetal CatmullRom Curve - which is useful for avoiding
  21995. * cusps and self-intersections in non-uniform catmull rom curves.
  21996. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  21997. *
  21998. * curve.type accepts centripetal(default), chordal and catmullrom
  21999. * curve.tension is used for catmullrom which defaults to 0.5
  22000. */
  22001. /*
  22002. Based on an optimized c++ solution in
  22003. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  22004. - http://ideone.com/NoEbVM
  22005. This CubicPoly class could be used for reusing some variables and calculations,
  22006. but for three.js curve use, it could be possible inlined and flatten into a single function call
  22007. which can be placed in CurveUtils.
  22008. */
  22009. function CubicPoly() {
  22010. var c0 = 0,
  22011. c1 = 0,
  22012. c2 = 0,
  22013. c3 = 0;
  22014. /*
  22015. * Compute coefficients for a cubic polynomial
  22016. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  22017. * such that
  22018. * p(0) = x0, p(1) = x1
  22019. * and
  22020. * p'(0) = t0, p'(1) = t1.
  22021. */
  22022. function init(x0, x1, t0, t1) {
  22023. c0 = x0;
  22024. c1 = t0;
  22025. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  22026. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  22027. }
  22028. return {
  22029. initCatmullRom: function (x0, x1, x2, x3, tension) {
  22030. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  22031. },
  22032. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  22033. // compute tangents when parameterized in [t1,t2]
  22034. var t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  22035. var t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  22036. t1 *= dt1;
  22037. t2 *= dt1;
  22038. init(x1, x2, t1, t2);
  22039. },
  22040. calc: function (t) {
  22041. var t2 = t * t;
  22042. var t3 = t2 * t;
  22043. return c0 + c1 * t + c2 * t2 + c3 * t3;
  22044. }
  22045. };
  22046. } //
  22047. var tmp = new Vector3();
  22048. var px = new CubicPoly(),
  22049. py = new CubicPoly(),
  22050. pz = new CubicPoly();
  22051. function CatmullRomCurve3(points, closed, curveType, tension) {
  22052. Curve.call(this);
  22053. this.type = 'CatmullRomCurve3';
  22054. this.points = points || [];
  22055. this.closed = closed || false;
  22056. this.curveType = curveType || 'centripetal';
  22057. this.tension = tension || 0.5;
  22058. }
  22059. CatmullRomCurve3.prototype = Object.create(Curve.prototype);
  22060. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  22061. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  22062. CatmullRomCurve3.prototype.getPoint = function (t, optionalTarget) {
  22063. var point = optionalTarget || new Vector3();
  22064. var points = this.points;
  22065. var l = points.length;
  22066. var p = (l - (this.closed ? 0 : 1)) * t;
  22067. var intPoint = Math.floor(p);
  22068. var weight = p - intPoint;
  22069. if (this.closed) {
  22070. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  22071. } else if (weight === 0 && intPoint === l - 1) {
  22072. intPoint = l - 2;
  22073. weight = 1;
  22074. }
  22075. var p0, p1, p2, p3; // 4 points
  22076. if (this.closed || intPoint > 0) {
  22077. p0 = points[(intPoint - 1) % l];
  22078. } else {
  22079. // extrapolate first point
  22080. tmp.subVectors(points[0], points[1]).add(points[0]);
  22081. p0 = tmp;
  22082. }
  22083. p1 = points[intPoint % l];
  22084. p2 = points[(intPoint + 1) % l];
  22085. if (this.closed || intPoint + 2 < l) {
  22086. p3 = points[(intPoint + 2) % l];
  22087. } else {
  22088. // extrapolate last point
  22089. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  22090. p3 = tmp;
  22091. }
  22092. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  22093. // init Centripetal / Chordal Catmull-Rom
  22094. var pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  22095. var dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  22096. var dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  22097. var dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  22098. if (dt1 < 1e-4) dt1 = 1.0;
  22099. if (dt0 < 1e-4) dt0 = dt1;
  22100. if (dt2 < 1e-4) dt2 = dt1;
  22101. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  22102. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  22103. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  22104. } else if (this.curveType === 'catmullrom') {
  22105. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  22106. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  22107. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  22108. }
  22109. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  22110. return point;
  22111. };
  22112. CatmullRomCurve3.prototype.copy = function (source) {
  22113. Curve.prototype.copy.call(this, source);
  22114. this.points = [];
  22115. for (var i = 0, l = source.points.length; i < l; i++) {
  22116. var point = source.points[i];
  22117. this.points.push(point.clone());
  22118. }
  22119. this.closed = source.closed;
  22120. this.curveType = source.curveType;
  22121. this.tension = source.tension;
  22122. return this;
  22123. };
  22124. CatmullRomCurve3.prototype.toJSON = function () {
  22125. var data = Curve.prototype.toJSON.call(this);
  22126. data.points = [];
  22127. for (var i = 0, l = this.points.length; i < l; i++) {
  22128. var point = this.points[i];
  22129. data.points.push(point.toArray());
  22130. }
  22131. data.closed = this.closed;
  22132. data.curveType = this.curveType;
  22133. data.tension = this.tension;
  22134. return data;
  22135. };
  22136. CatmullRomCurve3.prototype.fromJSON = function (json) {
  22137. Curve.prototype.fromJSON.call(this, json);
  22138. this.points = [];
  22139. for (var i = 0, l = json.points.length; i < l; i++) {
  22140. var point = json.points[i];
  22141. this.points.push(new Vector3().fromArray(point));
  22142. }
  22143. this.closed = json.closed;
  22144. this.curveType = json.curveType;
  22145. this.tension = json.tension;
  22146. return this;
  22147. };
  22148. /**
  22149. * @author zz85 / http://www.lab4games.net/zz85/blog
  22150. *
  22151. * Bezier Curves formulas obtained from
  22152. * http://en.wikipedia.org/wiki/Bézier_curve
  22153. */
  22154. function CatmullRom(t, p0, p1, p2, p3) {
  22155. var v0 = (p2 - p0) * 0.5;
  22156. var v1 = (p3 - p1) * 0.5;
  22157. var t2 = t * t;
  22158. var t3 = t * t2;
  22159. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  22160. } //
  22161. function QuadraticBezierP0(t, p) {
  22162. var k = 1 - t;
  22163. return k * k * p;
  22164. }
  22165. function QuadraticBezierP1(t, p) {
  22166. return 2 * (1 - t) * t * p;
  22167. }
  22168. function QuadraticBezierP2(t, p) {
  22169. return t * t * p;
  22170. }
  22171. function QuadraticBezier(t, p0, p1, p2) {
  22172. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  22173. } //
  22174. function CubicBezierP0(t, p) {
  22175. var k = 1 - t;
  22176. return k * k * k * p;
  22177. }
  22178. function CubicBezierP1(t, p) {
  22179. var k = 1 - t;
  22180. return 3 * k * k * t * p;
  22181. }
  22182. function CubicBezierP2(t, p) {
  22183. return 3 * (1 - t) * t * t * p;
  22184. }
  22185. function CubicBezierP3(t, p) {
  22186. return t * t * t * p;
  22187. }
  22188. function CubicBezier(t, p0, p1, p2, p3) {
  22189. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  22190. }
  22191. function CubicBezierCurve(v0, v1, v2, v3) {
  22192. Curve.call(this);
  22193. this.type = 'CubicBezierCurve';
  22194. this.v0 = v0 || new Vector2();
  22195. this.v1 = v1 || new Vector2();
  22196. this.v2 = v2 || new Vector2();
  22197. this.v3 = v3 || new Vector2();
  22198. }
  22199. CubicBezierCurve.prototype = Object.create(Curve.prototype);
  22200. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  22201. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  22202. CubicBezierCurve.prototype.getPoint = function (t, optionalTarget) {
  22203. var point = optionalTarget || new Vector2();
  22204. var v0 = this.v0,
  22205. v1 = this.v1,
  22206. v2 = this.v2,
  22207. v3 = this.v3;
  22208. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  22209. return point;
  22210. };
  22211. CubicBezierCurve.prototype.copy = function (source) {
  22212. Curve.prototype.copy.call(this, source);
  22213. this.v0.copy(source.v0);
  22214. this.v1.copy(source.v1);
  22215. this.v2.copy(source.v2);
  22216. this.v3.copy(source.v3);
  22217. return this;
  22218. };
  22219. CubicBezierCurve.prototype.toJSON = function () {
  22220. var data = Curve.prototype.toJSON.call(this);
  22221. data.v0 = this.v0.toArray();
  22222. data.v1 = this.v1.toArray();
  22223. data.v2 = this.v2.toArray();
  22224. data.v3 = this.v3.toArray();
  22225. return data;
  22226. };
  22227. CubicBezierCurve.prototype.fromJSON = function (json) {
  22228. Curve.prototype.fromJSON.call(this, json);
  22229. this.v0.fromArray(json.v0);
  22230. this.v1.fromArray(json.v1);
  22231. this.v2.fromArray(json.v2);
  22232. this.v3.fromArray(json.v3);
  22233. return this;
  22234. };
  22235. function CubicBezierCurve3(v0, v1, v2, v3) {
  22236. Curve.call(this);
  22237. this.type = 'CubicBezierCurve3';
  22238. this.v0 = v0 || new Vector3();
  22239. this.v1 = v1 || new Vector3();
  22240. this.v2 = v2 || new Vector3();
  22241. this.v3 = v3 || new Vector3();
  22242. }
  22243. CubicBezierCurve3.prototype = Object.create(Curve.prototype);
  22244. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  22245. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  22246. CubicBezierCurve3.prototype.getPoint = function (t, optionalTarget) {
  22247. var point = optionalTarget || new Vector3();
  22248. var v0 = this.v0,
  22249. v1 = this.v1,
  22250. v2 = this.v2,
  22251. v3 = this.v3;
  22252. 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));
  22253. return point;
  22254. };
  22255. CubicBezierCurve3.prototype.copy = function (source) {
  22256. Curve.prototype.copy.call(this, source);
  22257. this.v0.copy(source.v0);
  22258. this.v1.copy(source.v1);
  22259. this.v2.copy(source.v2);
  22260. this.v3.copy(source.v3);
  22261. return this;
  22262. };
  22263. CubicBezierCurve3.prototype.toJSON = function () {
  22264. var data = Curve.prototype.toJSON.call(this);
  22265. data.v0 = this.v0.toArray();
  22266. data.v1 = this.v1.toArray();
  22267. data.v2 = this.v2.toArray();
  22268. data.v3 = this.v3.toArray();
  22269. return data;
  22270. };
  22271. CubicBezierCurve3.prototype.fromJSON = function (json) {
  22272. Curve.prototype.fromJSON.call(this, json);
  22273. this.v0.fromArray(json.v0);
  22274. this.v1.fromArray(json.v1);
  22275. this.v2.fromArray(json.v2);
  22276. this.v3.fromArray(json.v3);
  22277. return this;
  22278. };
  22279. function LineCurve(v1, v2) {
  22280. Curve.call(this);
  22281. this.type = 'LineCurve';
  22282. this.v1 = v1 || new Vector2();
  22283. this.v2 = v2 || new Vector2();
  22284. }
  22285. LineCurve.prototype = Object.create(Curve.prototype);
  22286. LineCurve.prototype.constructor = LineCurve;
  22287. LineCurve.prototype.isLineCurve = true;
  22288. LineCurve.prototype.getPoint = function (t, optionalTarget) {
  22289. var point = optionalTarget || new Vector2();
  22290. if (t === 1) {
  22291. point.copy(this.v2);
  22292. } else {
  22293. point.copy(this.v2).sub(this.v1);
  22294. point.multiplyScalar(t).add(this.v1);
  22295. }
  22296. return point;
  22297. }; // Line curve is linear, so we can overwrite default getPointAt
  22298. LineCurve.prototype.getPointAt = function (u, optionalTarget) {
  22299. return this.getPoint(u, optionalTarget);
  22300. };
  22301. LineCurve.prototype.getTangent = function ()
  22302. /* t */
  22303. {
  22304. var tangent = this.v2.clone().sub(this.v1);
  22305. return tangent.normalize();
  22306. };
  22307. LineCurve.prototype.copy = function (source) {
  22308. Curve.prototype.copy.call(this, source);
  22309. this.v1.copy(source.v1);
  22310. this.v2.copy(source.v2);
  22311. return this;
  22312. };
  22313. LineCurve.prototype.toJSON = function () {
  22314. var data = Curve.prototype.toJSON.call(this);
  22315. data.v1 = this.v1.toArray();
  22316. data.v2 = this.v2.toArray();
  22317. return data;
  22318. };
  22319. LineCurve.prototype.fromJSON = function (json) {
  22320. Curve.prototype.fromJSON.call(this, json);
  22321. this.v1.fromArray(json.v1);
  22322. this.v2.fromArray(json.v2);
  22323. return this;
  22324. };
  22325. function LineCurve3(v1, v2) {
  22326. Curve.call(this);
  22327. this.type = 'LineCurve3';
  22328. this.v1 = v1 || new Vector3();
  22329. this.v2 = v2 || new Vector3();
  22330. }
  22331. LineCurve3.prototype = Object.create(Curve.prototype);
  22332. LineCurve3.prototype.constructor = LineCurve3;
  22333. LineCurve3.prototype.isLineCurve3 = true;
  22334. LineCurve3.prototype.getPoint = function (t, optionalTarget) {
  22335. var point = optionalTarget || new Vector3();
  22336. if (t === 1) {
  22337. point.copy(this.v2);
  22338. } else {
  22339. point.copy(this.v2).sub(this.v1);
  22340. point.multiplyScalar(t).add(this.v1);
  22341. }
  22342. return point;
  22343. }; // Line curve is linear, so we can overwrite default getPointAt
  22344. LineCurve3.prototype.getPointAt = function (u, optionalTarget) {
  22345. return this.getPoint(u, optionalTarget);
  22346. };
  22347. LineCurve3.prototype.copy = function (source) {
  22348. Curve.prototype.copy.call(this, source);
  22349. this.v1.copy(source.v1);
  22350. this.v2.copy(source.v2);
  22351. return this;
  22352. };
  22353. LineCurve3.prototype.toJSON = function () {
  22354. var data = Curve.prototype.toJSON.call(this);
  22355. data.v1 = this.v1.toArray();
  22356. data.v2 = this.v2.toArray();
  22357. return data;
  22358. };
  22359. LineCurve3.prototype.fromJSON = function (json) {
  22360. Curve.prototype.fromJSON.call(this, json);
  22361. this.v1.fromArray(json.v1);
  22362. this.v2.fromArray(json.v2);
  22363. return this;
  22364. };
  22365. function QuadraticBezierCurve(v0, v1, v2) {
  22366. Curve.call(this);
  22367. this.type = 'QuadraticBezierCurve';
  22368. this.v0 = v0 || new Vector2();
  22369. this.v1 = v1 || new Vector2();
  22370. this.v2 = v2 || new Vector2();
  22371. }
  22372. QuadraticBezierCurve.prototype = Object.create(Curve.prototype);
  22373. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  22374. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  22375. QuadraticBezierCurve.prototype.getPoint = function (t, optionalTarget) {
  22376. var point = optionalTarget || new Vector2();
  22377. var v0 = this.v0,
  22378. v1 = this.v1,
  22379. v2 = this.v2;
  22380. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  22381. return point;
  22382. };
  22383. QuadraticBezierCurve.prototype.copy = function (source) {
  22384. Curve.prototype.copy.call(this, source);
  22385. this.v0.copy(source.v0);
  22386. this.v1.copy(source.v1);
  22387. this.v2.copy(source.v2);
  22388. return this;
  22389. };
  22390. QuadraticBezierCurve.prototype.toJSON = function () {
  22391. var data = Curve.prototype.toJSON.call(this);
  22392. data.v0 = this.v0.toArray();
  22393. data.v1 = this.v1.toArray();
  22394. data.v2 = this.v2.toArray();
  22395. return data;
  22396. };
  22397. QuadraticBezierCurve.prototype.fromJSON = function (json) {
  22398. Curve.prototype.fromJSON.call(this, json);
  22399. this.v0.fromArray(json.v0);
  22400. this.v1.fromArray(json.v1);
  22401. this.v2.fromArray(json.v2);
  22402. return this;
  22403. };
  22404. function QuadraticBezierCurve3(v0, v1, v2) {
  22405. Curve.call(this);
  22406. this.type = 'QuadraticBezierCurve3';
  22407. this.v0 = v0 || new Vector3();
  22408. this.v1 = v1 || new Vector3();
  22409. this.v2 = v2 || new Vector3();
  22410. }
  22411. QuadraticBezierCurve3.prototype = Object.create(Curve.prototype);
  22412. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  22413. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  22414. QuadraticBezierCurve3.prototype.getPoint = function (t, optionalTarget) {
  22415. var point = optionalTarget || new Vector3();
  22416. var v0 = this.v0,
  22417. v1 = this.v1,
  22418. v2 = this.v2;
  22419. 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));
  22420. return point;
  22421. };
  22422. QuadraticBezierCurve3.prototype.copy = function (source) {
  22423. Curve.prototype.copy.call(this, source);
  22424. this.v0.copy(source.v0);
  22425. this.v1.copy(source.v1);
  22426. this.v2.copy(source.v2);
  22427. return this;
  22428. };
  22429. QuadraticBezierCurve3.prototype.toJSON = function () {
  22430. var data = Curve.prototype.toJSON.call(this);
  22431. data.v0 = this.v0.toArray();
  22432. data.v1 = this.v1.toArray();
  22433. data.v2 = this.v2.toArray();
  22434. return data;
  22435. };
  22436. QuadraticBezierCurve3.prototype.fromJSON = function (json) {
  22437. Curve.prototype.fromJSON.call(this, json);
  22438. this.v0.fromArray(json.v0);
  22439. this.v1.fromArray(json.v1);
  22440. this.v2.fromArray(json.v2);
  22441. return this;
  22442. };
  22443. function SplineCurve(points
  22444. /* array of Vector2 */
  22445. ) {
  22446. Curve.call(this);
  22447. this.type = 'SplineCurve';
  22448. this.points = points || [];
  22449. }
  22450. SplineCurve.prototype = Object.create(Curve.prototype);
  22451. SplineCurve.prototype.constructor = SplineCurve;
  22452. SplineCurve.prototype.isSplineCurve = true;
  22453. SplineCurve.prototype.getPoint = function (t, optionalTarget) {
  22454. var point = optionalTarget || new Vector2();
  22455. var points = this.points;
  22456. var p = (points.length - 1) * t;
  22457. var intPoint = Math.floor(p);
  22458. var weight = p - intPoint;
  22459. var p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  22460. var p1 = points[intPoint];
  22461. var p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  22462. var p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  22463. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  22464. return point;
  22465. };
  22466. SplineCurve.prototype.copy = function (source) {
  22467. Curve.prototype.copy.call(this, source);
  22468. this.points = [];
  22469. for (var i = 0, l = source.points.length; i < l; i++) {
  22470. var point = source.points[i];
  22471. this.points.push(point.clone());
  22472. }
  22473. return this;
  22474. };
  22475. SplineCurve.prototype.toJSON = function () {
  22476. var data = Curve.prototype.toJSON.call(this);
  22477. data.points = [];
  22478. for (var i = 0, l = this.points.length; i < l; i++) {
  22479. var point = this.points[i];
  22480. data.points.push(point.toArray());
  22481. }
  22482. return data;
  22483. };
  22484. SplineCurve.prototype.fromJSON = function (json) {
  22485. Curve.prototype.fromJSON.call(this, json);
  22486. this.points = [];
  22487. for (var i = 0, l = json.points.length; i < l; i++) {
  22488. var point = json.points[i];
  22489. this.points.push(new Vector2().fromArray(point));
  22490. }
  22491. return this;
  22492. };
  22493. var Curves =
  22494. /*#__PURE__*/
  22495. Object.freeze({
  22496. ArcCurve: ArcCurve,
  22497. CatmullRomCurve3: CatmullRomCurve3,
  22498. CubicBezierCurve: CubicBezierCurve,
  22499. CubicBezierCurve3: CubicBezierCurve3,
  22500. EllipseCurve: EllipseCurve,
  22501. LineCurve: LineCurve,
  22502. LineCurve3: LineCurve3,
  22503. QuadraticBezierCurve: QuadraticBezierCurve,
  22504. QuadraticBezierCurve3: QuadraticBezierCurve3,
  22505. SplineCurve: SplineCurve
  22506. });
  22507. /**
  22508. * @author zz85 / http://www.lab4games.net/zz85/blog
  22509. *
  22510. **/
  22511. /**************************************************************
  22512. * Curved Path - a curve path is simply a array of connected
  22513. * curves, but retains the api of a curve
  22514. **************************************************************/
  22515. function CurvePath() {
  22516. Curve.call(this);
  22517. this.type = 'CurvePath';
  22518. this.curves = [];
  22519. this.autoClose = false; // Automatically closes the path
  22520. }
  22521. CurvePath.prototype = Object.assign(Object.create(Curve.prototype), {
  22522. constructor: CurvePath,
  22523. add: function (curve) {
  22524. this.curves.push(curve);
  22525. },
  22526. closePath: function () {
  22527. // Add a line curve if start and end of lines are not connected
  22528. var startPoint = this.curves[0].getPoint(0);
  22529. var endPoint = this.curves[this.curves.length - 1].getPoint(1);
  22530. if (!startPoint.equals(endPoint)) {
  22531. this.curves.push(new LineCurve(endPoint, startPoint));
  22532. }
  22533. },
  22534. // To get accurate point with reference to
  22535. // entire path distance at time t,
  22536. // following has to be done:
  22537. // 1. Length of each sub path have to be known
  22538. // 2. Locate and identify type of curve
  22539. // 3. Get t for the curve
  22540. // 4. Return curve.getPointAt(t')
  22541. getPoint: function (t) {
  22542. var d = t * this.getLength();
  22543. var curveLengths = this.getCurveLengths();
  22544. var i = 0; // To think about boundaries points.
  22545. while (i < curveLengths.length) {
  22546. if (curveLengths[i] >= d) {
  22547. var diff = curveLengths[i] - d;
  22548. var curve = this.curves[i];
  22549. var segmentLength = curve.getLength();
  22550. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  22551. return curve.getPointAt(u);
  22552. }
  22553. i++;
  22554. }
  22555. return null; // loop where sum != 0, sum > d , sum+1 <d
  22556. },
  22557. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  22558. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  22559. // getPoint() depends on getLength
  22560. getLength: function () {
  22561. var lens = this.getCurveLengths();
  22562. return lens[lens.length - 1];
  22563. },
  22564. // cacheLengths must be recalculated.
  22565. updateArcLengths: function () {
  22566. this.needsUpdate = true;
  22567. this.cacheLengths = null;
  22568. this.getCurveLengths();
  22569. },
  22570. // Compute lengths and cache them
  22571. // We cannot overwrite getLengths() because UtoT mapping uses it.
  22572. getCurveLengths: function () {
  22573. // We use cache values if curves and cache array are same length
  22574. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  22575. return this.cacheLengths;
  22576. } // Get length of sub-curve
  22577. // Push sums into cached array
  22578. var lengths = [],
  22579. sums = 0;
  22580. for (var i = 0, l = this.curves.length; i < l; i++) {
  22581. sums += this.curves[i].getLength();
  22582. lengths.push(sums);
  22583. }
  22584. this.cacheLengths = lengths;
  22585. return lengths;
  22586. },
  22587. getSpacedPoints: function (divisions) {
  22588. if (divisions === undefined) divisions = 40;
  22589. var points = [];
  22590. for (var i = 0; i <= divisions; i++) {
  22591. points.push(this.getPoint(i / divisions));
  22592. }
  22593. if (this.autoClose) {
  22594. points.push(points[0]);
  22595. }
  22596. return points;
  22597. },
  22598. getPoints: function (divisions) {
  22599. divisions = divisions || 12;
  22600. var points = [],
  22601. last;
  22602. for (var i = 0, curves = this.curves; i < curves.length; i++) {
  22603. var curve = curves[i];
  22604. var resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
  22605. var pts = curve.getPoints(resolution);
  22606. for (var j = 0; j < pts.length; j++) {
  22607. var point = pts[j];
  22608. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  22609. points.push(point);
  22610. last = point;
  22611. }
  22612. }
  22613. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  22614. points.push(points[0]);
  22615. }
  22616. return points;
  22617. },
  22618. copy: function (source) {
  22619. Curve.prototype.copy.call(this, source);
  22620. this.curves = [];
  22621. for (var i = 0, l = source.curves.length; i < l; i++) {
  22622. var curve = source.curves[i];
  22623. this.curves.push(curve.clone());
  22624. }
  22625. this.autoClose = source.autoClose;
  22626. return this;
  22627. },
  22628. toJSON: function () {
  22629. var data = Curve.prototype.toJSON.call(this);
  22630. data.autoClose = this.autoClose;
  22631. data.curves = [];
  22632. for (var i = 0, l = this.curves.length; i < l; i++) {
  22633. var curve = this.curves[i];
  22634. data.curves.push(curve.toJSON());
  22635. }
  22636. return data;
  22637. },
  22638. fromJSON: function (json) {
  22639. Curve.prototype.fromJSON.call(this, json);
  22640. this.autoClose = json.autoClose;
  22641. this.curves = [];
  22642. for (var i = 0, l = json.curves.length; i < l; i++) {
  22643. var curve = json.curves[i];
  22644. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  22645. }
  22646. return this;
  22647. }
  22648. });
  22649. /**
  22650. * @author zz85 / http://www.lab4games.net/zz85/blog
  22651. * Creates free form 2d path using series of points, lines or curves.
  22652. **/
  22653. function Path(points) {
  22654. CurvePath.call(this);
  22655. this.type = 'Path';
  22656. this.currentPoint = new Vector2();
  22657. if (points) {
  22658. this.setFromPoints(points);
  22659. }
  22660. }
  22661. Path.prototype = Object.assign(Object.create(CurvePath.prototype), {
  22662. constructor: Path,
  22663. setFromPoints: function (points) {
  22664. this.moveTo(points[0].x, points[0].y);
  22665. for (var i = 1, l = points.length; i < l; i++) {
  22666. this.lineTo(points[i].x, points[i].y);
  22667. }
  22668. },
  22669. moveTo: function (x, y) {
  22670. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  22671. },
  22672. lineTo: function (x, y) {
  22673. var curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  22674. this.curves.push(curve);
  22675. this.currentPoint.set(x, y);
  22676. },
  22677. quadraticCurveTo: function (aCPx, aCPy, aX, aY) {
  22678. var curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  22679. this.curves.push(curve);
  22680. this.currentPoint.set(aX, aY);
  22681. },
  22682. bezierCurveTo: function (aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  22683. var curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  22684. this.curves.push(curve);
  22685. this.currentPoint.set(aX, aY);
  22686. },
  22687. splineThru: function (pts
  22688. /*Array of Vector*/
  22689. ) {
  22690. var npts = [this.currentPoint.clone()].concat(pts);
  22691. var curve = new SplineCurve(npts);
  22692. this.curves.push(curve);
  22693. this.currentPoint.copy(pts[pts.length - 1]);
  22694. },
  22695. arc: function (aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  22696. var x0 = this.currentPoint.x;
  22697. var y0 = this.currentPoint.y;
  22698. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  22699. },
  22700. absarc: function (aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  22701. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  22702. },
  22703. ellipse: function (aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  22704. var x0 = this.currentPoint.x;
  22705. var y0 = this.currentPoint.y;
  22706. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  22707. },
  22708. absellipse: function (aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  22709. var curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  22710. if (this.curves.length > 0) {
  22711. // if a previous curve is present, attempt to join
  22712. var firstPoint = curve.getPoint(0);
  22713. if (!firstPoint.equals(this.currentPoint)) {
  22714. this.lineTo(firstPoint.x, firstPoint.y);
  22715. }
  22716. }
  22717. this.curves.push(curve);
  22718. var lastPoint = curve.getPoint(1);
  22719. this.currentPoint.copy(lastPoint);
  22720. },
  22721. copy: function (source) {
  22722. CurvePath.prototype.copy.call(this, source);
  22723. this.currentPoint.copy(source.currentPoint);
  22724. return this;
  22725. },
  22726. toJSON: function () {
  22727. var data = CurvePath.prototype.toJSON.call(this);
  22728. data.currentPoint = this.currentPoint.toArray();
  22729. return data;
  22730. },
  22731. fromJSON: function (json) {
  22732. CurvePath.prototype.fromJSON.call(this, json);
  22733. this.currentPoint.fromArray(json.currentPoint);
  22734. return this;
  22735. }
  22736. });
  22737. /**
  22738. * @author zz85 / http://www.lab4games.net/zz85/blog
  22739. * Defines a 2d shape plane using paths.
  22740. **/
  22741. // STEP 1 Create a path.
  22742. // STEP 2 Turn path into shape.
  22743. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  22744. // STEP 3a - Extract points from each shape, turn to vertices
  22745. // STEP 3b - Triangulate each shape, add faces.
  22746. function Shape(points) {
  22747. Path.call(this, points);
  22748. this.uuid = _Math.generateUUID();
  22749. this.type = 'Shape';
  22750. this.holes = [];
  22751. }
  22752. Shape.prototype = Object.assign(Object.create(Path.prototype), {
  22753. constructor: Shape,
  22754. getPointsHoles: function (divisions) {
  22755. var holesPts = [];
  22756. for (var i = 0, l = this.holes.length; i < l; i++) {
  22757. holesPts[i] = this.holes[i].getPoints(divisions);
  22758. }
  22759. return holesPts;
  22760. },
  22761. // get points of shape and holes (keypoints based on segments parameter)
  22762. extractPoints: function (divisions) {
  22763. return {
  22764. shape: this.getPoints(divisions),
  22765. holes: this.getPointsHoles(divisions)
  22766. };
  22767. },
  22768. copy: function (source) {
  22769. Path.prototype.copy.call(this, source);
  22770. this.holes = [];
  22771. for (var i = 0, l = source.holes.length; i < l; i++) {
  22772. var hole = source.holes[i];
  22773. this.holes.push(hole.clone());
  22774. }
  22775. return this;
  22776. },
  22777. toJSON: function () {
  22778. var data = Path.prototype.toJSON.call(this);
  22779. data.uuid = this.uuid;
  22780. data.holes = [];
  22781. for (var i = 0, l = this.holes.length; i < l; i++) {
  22782. var hole = this.holes[i];
  22783. data.holes.push(hole.toJSON());
  22784. }
  22785. return data;
  22786. },
  22787. fromJSON: function (json) {
  22788. Path.prototype.fromJSON.call(this, json);
  22789. this.uuid = json.uuid;
  22790. this.holes = [];
  22791. for (var i = 0, l = json.holes.length; i < l; i++) {
  22792. var hole = json.holes[i];
  22793. this.holes.push(new Path().fromJSON(hole));
  22794. }
  22795. return this;
  22796. }
  22797. });
  22798. /**
  22799. * @author mrdoob / http://mrdoob.com/
  22800. * @author alteredq / http://alteredqualia.com/
  22801. */
  22802. function Light(color, intensity) {
  22803. Object3D.call(this);
  22804. this.type = 'Light';
  22805. this.color = new Color(color);
  22806. this.intensity = intensity !== undefined ? intensity : 1;
  22807. this.receiveShadow = undefined;
  22808. }
  22809. Light.prototype = Object.assign(Object.create(Object3D.prototype), {
  22810. constructor: Light,
  22811. isLight: true,
  22812. copy: function (source) {
  22813. Object3D.prototype.copy.call(this, source);
  22814. this.color.copy(source.color);
  22815. this.intensity = source.intensity;
  22816. return this;
  22817. },
  22818. toJSON: function (meta) {
  22819. var data = Object3D.prototype.toJSON.call(this, meta);
  22820. data.object.color = this.color.getHex();
  22821. data.object.intensity = this.intensity;
  22822. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  22823. if (this.distance !== undefined) data.object.distance = this.distance;
  22824. if (this.angle !== undefined) data.object.angle = this.angle;
  22825. if (this.decay !== undefined) data.object.decay = this.decay;
  22826. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  22827. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  22828. return data;
  22829. }
  22830. });
  22831. /**
  22832. * @author alteredq / http://alteredqualia.com/
  22833. */
  22834. function HemisphereLight(skyColor, groundColor, intensity) {
  22835. Light.call(this, skyColor, intensity);
  22836. this.type = 'HemisphereLight';
  22837. this.castShadow = undefined;
  22838. this.position.copy(Object3D.DefaultUp);
  22839. this.updateMatrix();
  22840. this.groundColor = new Color(groundColor);
  22841. }
  22842. HemisphereLight.prototype = Object.assign(Object.create(Light.prototype), {
  22843. constructor: HemisphereLight,
  22844. isHemisphereLight: true,
  22845. copy: function (source) {
  22846. Light.prototype.copy.call(this, source);
  22847. this.groundColor.copy(source.groundColor);
  22848. return this;
  22849. }
  22850. });
  22851. /**
  22852. * @author mrdoob / http://mrdoob.com/
  22853. */
  22854. function LightShadow(camera) {
  22855. this.camera = camera;
  22856. this.bias = 0;
  22857. this.radius = 1;
  22858. this.mapSize = new Vector2(512, 512);
  22859. this.map = null;
  22860. this.mapPass = null;
  22861. this.matrix = new Matrix4();
  22862. this._frustum = new Frustum();
  22863. this._frameExtents = new Vector2(1, 1);
  22864. this._viewportCount = 1;
  22865. this._viewports = [new Vector4(0, 0, 1, 1)];
  22866. }
  22867. Object.assign(LightShadow.prototype, {
  22868. _projScreenMatrix: new Matrix4(),
  22869. _lightPositionWorld: new Vector3(),
  22870. _lookTarget: new Vector3(),
  22871. getViewportCount: function () {
  22872. return this._viewportCount;
  22873. },
  22874. getFrustum: function () {
  22875. return this._frustum;
  22876. },
  22877. updateMatrices: function (light) {
  22878. var shadowCamera = this.camera,
  22879. shadowMatrix = this.matrix,
  22880. projScreenMatrix = this._projScreenMatrix,
  22881. lookTarget = this._lookTarget,
  22882. lightPositionWorld = this._lightPositionWorld;
  22883. lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  22884. shadowCamera.position.copy(lightPositionWorld);
  22885. lookTarget.setFromMatrixPosition(light.target.matrixWorld);
  22886. shadowCamera.lookAt(lookTarget);
  22887. shadowCamera.updateMatrixWorld();
  22888. projScreenMatrix.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  22889. this._frustum.setFromMatrix(projScreenMatrix);
  22890. 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);
  22891. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  22892. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  22893. },
  22894. getViewport: function (viewportIndex) {
  22895. return this._viewports[viewportIndex];
  22896. },
  22897. getFrameExtents: function () {
  22898. return this._frameExtents;
  22899. },
  22900. copy: function (source) {
  22901. this.camera = source.camera.clone();
  22902. this.bias = source.bias;
  22903. this.radius = source.radius;
  22904. this.mapSize.copy(source.mapSize);
  22905. return this;
  22906. },
  22907. clone: function () {
  22908. return new this.constructor().copy(this);
  22909. },
  22910. toJSON: function () {
  22911. var object = {};
  22912. if (this.bias !== 0) object.bias = this.bias;
  22913. if (this.radius !== 1) object.radius = this.radius;
  22914. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  22915. object.camera = this.camera.toJSON(false).object;
  22916. delete object.camera.matrix;
  22917. return object;
  22918. }
  22919. });
  22920. /**
  22921. * @author mrdoob / http://mrdoob.com/
  22922. */
  22923. function SpotLightShadow() {
  22924. LightShadow.call(this, new PerspectiveCamera(50, 1, 0.5, 500));
  22925. }
  22926. SpotLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  22927. constructor: SpotLightShadow,
  22928. isSpotLightShadow: true,
  22929. updateMatrices: function (light, viewCamera, viewportIndex) {
  22930. var camera = this.camera;
  22931. var fov = _Math.RAD2DEG * 2 * light.angle;
  22932. var aspect = this.mapSize.width / this.mapSize.height;
  22933. var far = light.distance || camera.far;
  22934. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  22935. camera.fov = fov;
  22936. camera.aspect = aspect;
  22937. camera.far = far;
  22938. camera.updateProjectionMatrix();
  22939. }
  22940. LightShadow.prototype.updateMatrices.call(this, light, viewCamera, viewportIndex);
  22941. }
  22942. });
  22943. /**
  22944. * @author alteredq / http://alteredqualia.com/
  22945. */
  22946. function SpotLight(color, intensity, distance, angle, penumbra, decay) {
  22947. Light.call(this, color, intensity);
  22948. this.type = 'SpotLight';
  22949. this.position.copy(Object3D.DefaultUp);
  22950. this.updateMatrix();
  22951. this.target = new Object3D();
  22952. Object.defineProperty(this, 'power', {
  22953. get: function () {
  22954. // intensity = power per solid angle.
  22955. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22956. return this.intensity * Math.PI;
  22957. },
  22958. set: function (power) {
  22959. // intensity = power per solid angle.
  22960. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22961. this.intensity = power / Math.PI;
  22962. }
  22963. });
  22964. this.distance = distance !== undefined ? distance : 0;
  22965. this.angle = angle !== undefined ? angle : Math.PI / 3;
  22966. this.penumbra = penumbra !== undefined ? penumbra : 0;
  22967. this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
  22968. this.shadow = new SpotLightShadow();
  22969. }
  22970. SpotLight.prototype = Object.assign(Object.create(Light.prototype), {
  22971. constructor: SpotLight,
  22972. isSpotLight: true,
  22973. copy: function (source) {
  22974. Light.prototype.copy.call(this, source);
  22975. this.distance = source.distance;
  22976. this.angle = source.angle;
  22977. this.penumbra = source.penumbra;
  22978. this.decay = source.decay;
  22979. this.target = source.target.clone();
  22980. this.shadow = source.shadow.clone();
  22981. return this;
  22982. }
  22983. });
  22984. function PointLightShadow() {
  22985. LightShadow.call(this, new PerspectiveCamera(90, 1, 0.5, 500));
  22986. this._frameExtents = new Vector2(4, 2);
  22987. this._viewportCount = 6;
  22988. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  22989. // following orientation:
  22990. //
  22991. // xzXZ
  22992. // y Y
  22993. //
  22994. // X - Positive x direction
  22995. // x - Negative x direction
  22996. // Y - Positive y direction
  22997. // y - Negative y direction
  22998. // Z - Positive z direction
  22999. // z - Negative z direction
  23000. // positive X
  23001. new Vector4(2, 1, 1, 1), // negative X
  23002. new Vector4(0, 1, 1, 1), // positive Z
  23003. new Vector4(3, 1, 1, 1), // negative Z
  23004. new Vector4(1, 1, 1, 1), // positive Y
  23005. new Vector4(3, 0, 1, 1), // negative Y
  23006. new Vector4(1, 0, 1, 1)];
  23007. 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)];
  23008. 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)];
  23009. }
  23010. PointLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  23011. constructor: PointLightShadow,
  23012. isPointLightShadow: true,
  23013. updateMatrices: function (light, viewCamera, viewportIndex) {
  23014. var camera = this.camera,
  23015. shadowMatrix = this.matrix,
  23016. lightPositionWorld = this._lightPositionWorld,
  23017. lookTarget = this._lookTarget,
  23018. projScreenMatrix = this._projScreenMatrix;
  23019. lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  23020. camera.position.copy(lightPositionWorld);
  23021. lookTarget.copy(camera.position);
  23022. lookTarget.add(this._cubeDirections[viewportIndex]);
  23023. camera.up.copy(this._cubeUps[viewportIndex]);
  23024. camera.lookAt(lookTarget);
  23025. camera.updateMatrixWorld();
  23026. shadowMatrix.makeTranslation(-lightPositionWorld.x, -lightPositionWorld.y, -lightPositionWorld.z);
  23027. projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  23028. this._frustum.setFromMatrix(projScreenMatrix);
  23029. }
  23030. });
  23031. /**
  23032. * @author mrdoob / http://mrdoob.com/
  23033. */
  23034. function PointLight(color, intensity, distance, decay) {
  23035. Light.call(this, color, intensity);
  23036. this.type = 'PointLight';
  23037. Object.defineProperty(this, 'power', {
  23038. get: function () {
  23039. // intensity = power per solid angle.
  23040. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23041. return this.intensity * 4 * Math.PI;
  23042. },
  23043. set: function (power) {
  23044. // intensity = power per solid angle.
  23045. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23046. this.intensity = power / (4 * Math.PI);
  23047. }
  23048. });
  23049. this.distance = distance !== undefined ? distance : 0;
  23050. this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
  23051. this.shadow = new PointLightShadow();
  23052. }
  23053. PointLight.prototype = Object.assign(Object.create(Light.prototype), {
  23054. constructor: PointLight,
  23055. isPointLight: true,
  23056. copy: function (source) {
  23057. Light.prototype.copy.call(this, source);
  23058. this.distance = source.distance;
  23059. this.decay = source.decay;
  23060. this.shadow = source.shadow.clone();
  23061. return this;
  23062. }
  23063. });
  23064. /**
  23065. * @author alteredq / http://alteredqualia.com/
  23066. * @author arose / http://github.com/arose
  23067. */
  23068. function OrthographicCamera(left, right, top, bottom, near, far) {
  23069. Camera.call(this);
  23070. this.type = 'OrthographicCamera';
  23071. this.zoom = 1;
  23072. this.view = null;
  23073. this.left = left !== undefined ? left : -1;
  23074. this.right = right !== undefined ? right : 1;
  23075. this.top = top !== undefined ? top : 1;
  23076. this.bottom = bottom !== undefined ? bottom : -1;
  23077. this.near = near !== undefined ? near : 0.1;
  23078. this.far = far !== undefined ? far : 2000;
  23079. this.updateProjectionMatrix();
  23080. }
  23081. OrthographicCamera.prototype = Object.assign(Object.create(Camera.prototype), {
  23082. constructor: OrthographicCamera,
  23083. isOrthographicCamera: true,
  23084. copy: function (source, recursive) {
  23085. Camera.prototype.copy.call(this, source, recursive);
  23086. this.left = source.left;
  23087. this.right = source.right;
  23088. this.top = source.top;
  23089. this.bottom = source.bottom;
  23090. this.near = source.near;
  23091. this.far = source.far;
  23092. this.zoom = source.zoom;
  23093. this.view = source.view === null ? null : Object.assign({}, source.view);
  23094. return this;
  23095. },
  23096. setViewOffset: function (fullWidth, fullHeight, x, y, width, height) {
  23097. if (this.view === null) {
  23098. this.view = {
  23099. enabled: true,
  23100. fullWidth: 1,
  23101. fullHeight: 1,
  23102. offsetX: 0,
  23103. offsetY: 0,
  23104. width: 1,
  23105. height: 1
  23106. };
  23107. }
  23108. this.view.enabled = true;
  23109. this.view.fullWidth = fullWidth;
  23110. this.view.fullHeight = fullHeight;
  23111. this.view.offsetX = x;
  23112. this.view.offsetY = y;
  23113. this.view.width = width;
  23114. this.view.height = height;
  23115. this.updateProjectionMatrix();
  23116. },
  23117. clearViewOffset: function () {
  23118. if (this.view !== null) {
  23119. this.view.enabled = false;
  23120. }
  23121. this.updateProjectionMatrix();
  23122. },
  23123. updateProjectionMatrix: function () {
  23124. var dx = (this.right - this.left) / (2 * this.zoom);
  23125. var dy = (this.top - this.bottom) / (2 * this.zoom);
  23126. var cx = (this.right + this.left) / 2;
  23127. var cy = (this.top + this.bottom) / 2;
  23128. var left = cx - dx;
  23129. var right = cx + dx;
  23130. var top = cy + dy;
  23131. var bottom = cy - dy;
  23132. if (this.view !== null && this.view.enabled) {
  23133. var zoomW = this.zoom / (this.view.width / this.view.fullWidth);
  23134. var zoomH = this.zoom / (this.view.height / this.view.fullHeight);
  23135. var scaleW = (this.right - this.left) / this.view.width;
  23136. var scaleH = (this.top - this.bottom) / this.view.height;
  23137. left += scaleW * (this.view.offsetX / zoomW);
  23138. right = left + scaleW * (this.view.width / zoomW);
  23139. top -= scaleH * (this.view.offsetY / zoomH);
  23140. bottom = top - scaleH * (this.view.height / zoomH);
  23141. }
  23142. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  23143. this.projectionMatrixInverse.getInverse(this.projectionMatrix);
  23144. },
  23145. toJSON: function (meta) {
  23146. var data = Object3D.prototype.toJSON.call(this, meta);
  23147. data.object.zoom = this.zoom;
  23148. data.object.left = this.left;
  23149. data.object.right = this.right;
  23150. data.object.top = this.top;
  23151. data.object.bottom = this.bottom;
  23152. data.object.near = this.near;
  23153. data.object.far = this.far;
  23154. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  23155. return data;
  23156. }
  23157. });
  23158. /**
  23159. * @author mrdoob / http://mrdoob.com/
  23160. */
  23161. function DirectionalLightShadow() {
  23162. LightShadow.call(this, new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  23163. }
  23164. DirectionalLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  23165. constructor: DirectionalLightShadow,
  23166. isDirectionalLightShadow: true,
  23167. updateMatrices: function (light, viewCamera, viewportIndex) {
  23168. LightShadow.prototype.updateMatrices.call(this, light, viewCamera, viewportIndex);
  23169. }
  23170. });
  23171. /**
  23172. * @author mrdoob / http://mrdoob.com/
  23173. * @author alteredq / http://alteredqualia.com/
  23174. */
  23175. function DirectionalLight(color, intensity) {
  23176. Light.call(this, color, intensity);
  23177. this.type = 'DirectionalLight';
  23178. this.position.copy(Object3D.DefaultUp);
  23179. this.updateMatrix();
  23180. this.target = new Object3D();
  23181. this.shadow = new DirectionalLightShadow();
  23182. }
  23183. DirectionalLight.prototype = Object.assign(Object.create(Light.prototype), {
  23184. constructor: DirectionalLight,
  23185. isDirectionalLight: true,
  23186. copy: function (source) {
  23187. Light.prototype.copy.call(this, source);
  23188. this.target = source.target.clone();
  23189. this.shadow = source.shadow.clone();
  23190. return this;
  23191. }
  23192. });
  23193. /**
  23194. * @author mrdoob / http://mrdoob.com/
  23195. */
  23196. function AmbientLight(color, intensity) {
  23197. Light.call(this, color, intensity);
  23198. this.type = 'AmbientLight';
  23199. this.castShadow = undefined;
  23200. }
  23201. AmbientLight.prototype = Object.assign(Object.create(Light.prototype), {
  23202. constructor: AmbientLight,
  23203. isAmbientLight: true
  23204. });
  23205. /**
  23206. * @author abelnation / http://github.com/abelnation
  23207. */
  23208. function RectAreaLight(color, intensity, width, height) {
  23209. Light.call(this, color, intensity);
  23210. this.type = 'RectAreaLight';
  23211. this.width = width !== undefined ? width : 10;
  23212. this.height = height !== undefined ? height : 10;
  23213. }
  23214. RectAreaLight.prototype = Object.assign(Object.create(Light.prototype), {
  23215. constructor: RectAreaLight,
  23216. isRectAreaLight: true,
  23217. copy: function (source) {
  23218. Light.prototype.copy.call(this, source);
  23219. this.width = source.width;
  23220. this.height = source.height;
  23221. return this;
  23222. },
  23223. toJSON: function (meta) {
  23224. var data = Light.prototype.toJSON.call(this, meta);
  23225. data.object.width = this.width;
  23226. data.object.height = this.height;
  23227. return data;
  23228. }
  23229. });
  23230. /**
  23231. * @author mrdoob / http://mrdoob.com/
  23232. */
  23233. function MaterialLoader(manager) {
  23234. Loader.call(this, manager);
  23235. this.textures = {};
  23236. }
  23237. MaterialLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  23238. constructor: MaterialLoader,
  23239. load: function (url, onLoad, onProgress, onError) {
  23240. var scope = this;
  23241. var loader = new FileLoader(scope.manager);
  23242. loader.setPath(scope.path);
  23243. loader.load(url, function (text) {
  23244. onLoad(scope.parse(JSON.parse(text)));
  23245. }, onProgress, onError);
  23246. },
  23247. parse: function (json) {
  23248. var textures = this.textures;
  23249. function getTexture(name) {
  23250. if (textures[name] === undefined) {
  23251. console.warn('THREE.MaterialLoader: Undefined texture', name);
  23252. }
  23253. return textures[name];
  23254. }
  23255. var material = new Materials[json.type]();
  23256. if (json.uuid !== undefined) material.uuid = json.uuid;
  23257. if (json.name !== undefined) material.name = json.name;
  23258. if (json.color !== undefined) material.color.setHex(json.color);
  23259. if (json.roughness !== undefined) material.roughness = json.roughness;
  23260. if (json.metalness !== undefined) material.metalness = json.metalness;
  23261. if (json.sheen !== undefined) material.sheen = new Color().setHex(json.sheen);
  23262. if (json.emissive !== undefined) material.emissive.setHex(json.emissive);
  23263. if (json.specular !== undefined) material.specular.setHex(json.specular);
  23264. if (json.shininess !== undefined) material.shininess = json.shininess;
  23265. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  23266. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  23267. if (json.vertexColors !== undefined) material.vertexColors = json.vertexColors;
  23268. if (json.fog !== undefined) material.fog = json.fog;
  23269. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  23270. if (json.blending !== undefined) material.blending = json.blending;
  23271. if (json.combine !== undefined) material.combine = json.combine;
  23272. if (json.side !== undefined) material.side = json.side;
  23273. if (json.opacity !== undefined) material.opacity = json.opacity;
  23274. if (json.transparent !== undefined) material.transparent = json.transparent;
  23275. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  23276. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  23277. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  23278. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  23279. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  23280. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  23281. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  23282. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  23283. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  23284. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  23285. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  23286. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  23287. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  23288. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  23289. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  23290. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  23291. if (json.rotation !== undefined) material.rotation = json.rotation;
  23292. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  23293. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  23294. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  23295. if (json.scale !== undefined) material.scale = json.scale;
  23296. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  23297. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  23298. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  23299. if (json.skinning !== undefined) material.skinning = json.skinning;
  23300. if (json.morphTargets !== undefined) material.morphTargets = json.morphTargets;
  23301. if (json.morphNormals !== undefined) material.morphNormals = json.morphNormals;
  23302. if (json.dithering !== undefined) material.dithering = json.dithering;
  23303. if (json.visible !== undefined) material.visible = json.visible;
  23304. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  23305. if (json.userData !== undefined) material.userData = json.userData; // Shader Material
  23306. if (json.uniforms !== undefined) {
  23307. for (var name in json.uniforms) {
  23308. var uniform = json.uniforms[name];
  23309. material.uniforms[name] = {};
  23310. switch (uniform.type) {
  23311. case 't':
  23312. material.uniforms[name].value = getTexture(uniform.value);
  23313. break;
  23314. case 'c':
  23315. material.uniforms[name].value = new Color().setHex(uniform.value);
  23316. break;
  23317. case 'v2':
  23318. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  23319. break;
  23320. case 'v3':
  23321. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  23322. break;
  23323. case 'v4':
  23324. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  23325. break;
  23326. case 'm3':
  23327. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  23328. case 'm4':
  23329. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  23330. break;
  23331. default:
  23332. material.uniforms[name].value = uniform.value;
  23333. }
  23334. }
  23335. }
  23336. if (json.defines !== undefined) material.defines = json.defines;
  23337. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  23338. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  23339. if (json.extensions !== undefined) {
  23340. for (var key in json.extensions) {
  23341. material.extensions[key] = json.extensions[key];
  23342. }
  23343. } // Deprecated
  23344. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  23345. // for PointsMaterial
  23346. if (json.size !== undefined) material.size = json.size;
  23347. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  23348. if (json.map !== undefined) material.map = getTexture(json.map);
  23349. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  23350. if (json.alphaMap !== undefined) {
  23351. material.alphaMap = getTexture(json.alphaMap);
  23352. material.transparent = true;
  23353. }
  23354. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  23355. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  23356. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  23357. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  23358. if (json.normalScale !== undefined) {
  23359. var normalScale = json.normalScale;
  23360. if (Array.isArray(normalScale) === false) {
  23361. // Blender exporter used to export a scalar. See #7459
  23362. normalScale = [normalScale, normalScale];
  23363. }
  23364. material.normalScale = new Vector2().fromArray(normalScale);
  23365. }
  23366. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  23367. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  23368. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  23369. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  23370. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  23371. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  23372. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  23373. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  23374. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  23375. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  23376. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  23377. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  23378. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  23379. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  23380. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  23381. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  23382. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  23383. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  23384. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  23385. return material;
  23386. },
  23387. setTextures: function (value) {
  23388. this.textures = value;
  23389. return this;
  23390. }
  23391. });
  23392. /**
  23393. * @author Don McCurdy / https://www.donmccurdy.com
  23394. */
  23395. var LoaderUtils = {
  23396. decodeText: function (array) {
  23397. if (typeof TextDecoder !== 'undefined') {
  23398. return new TextDecoder().decode(array);
  23399. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  23400. // throws a "maximum call stack size exceeded" error for large arrays.
  23401. var s = '';
  23402. for (var i = 0, il = array.length; i < il; i++) {
  23403. // Implicitly assumes little-endian.
  23404. s += String.fromCharCode(array[i]);
  23405. }
  23406. try {
  23407. // merges multi-byte utf-8 characters.
  23408. return decodeURIComponent(escape(s));
  23409. } catch (e) {
  23410. // see #16358
  23411. return s;
  23412. }
  23413. },
  23414. extractUrlBase: function (url) {
  23415. var index = url.lastIndexOf('/');
  23416. if (index === -1) return './';
  23417. return url.substr(0, index + 1);
  23418. }
  23419. };
  23420. /**
  23421. * @author benaadams / https://twitter.com/ben_a_adams
  23422. */
  23423. exports.LoaderUtils = LoaderUtils;
  23424. function InstancedBufferGeometry() {
  23425. BufferGeometry.call(this);
  23426. this.type = 'InstancedBufferGeometry';
  23427. this.maxInstancedCount = undefined;
  23428. }
  23429. InstancedBufferGeometry.prototype = Object.assign(Object.create(BufferGeometry.prototype), {
  23430. constructor: InstancedBufferGeometry,
  23431. isInstancedBufferGeometry: true,
  23432. copy: function (source) {
  23433. BufferGeometry.prototype.copy.call(this, source);
  23434. this.maxInstancedCount = source.maxInstancedCount;
  23435. return this;
  23436. },
  23437. clone: function () {
  23438. return new this.constructor().copy(this);
  23439. },
  23440. toJSON: function () {
  23441. var data = BufferGeometry.prototype.toJSON.call(this);
  23442. data.maxInstancedCount = this.maxInstancedCount;
  23443. data.isInstancedBufferGeometry = true;
  23444. return data;
  23445. }
  23446. });
  23447. /**
  23448. * @author benaadams / https://twitter.com/ben_a_adams
  23449. */
  23450. function InstancedBufferAttribute(array, itemSize, normalized, meshPerAttribute) {
  23451. if (typeof normalized === 'number') {
  23452. meshPerAttribute = normalized;
  23453. normalized = false;
  23454. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  23455. }
  23456. BufferAttribute.call(this, array, itemSize, normalized);
  23457. this.meshPerAttribute = meshPerAttribute || 1;
  23458. }
  23459. InstancedBufferAttribute.prototype = Object.assign(Object.create(BufferAttribute.prototype), {
  23460. constructor: InstancedBufferAttribute,
  23461. isInstancedBufferAttribute: true,
  23462. copy: function (source) {
  23463. BufferAttribute.prototype.copy.call(this, source);
  23464. this.meshPerAttribute = source.meshPerAttribute;
  23465. return this;
  23466. },
  23467. toJSON: function () {
  23468. var data = BufferAttribute.prototype.toJSON.call(this);
  23469. data.meshPerAttribute = this.meshPerAttribute;
  23470. data.isInstancedBufferAttribute = true;
  23471. return data;
  23472. }
  23473. });
  23474. /**
  23475. * @author mrdoob / http://mrdoob.com/
  23476. */
  23477. function BufferGeometryLoader(manager) {
  23478. Loader.call(this, manager);
  23479. }
  23480. BufferGeometryLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  23481. constructor: BufferGeometryLoader,
  23482. load: function (url, onLoad, onProgress, onError) {
  23483. var scope = this;
  23484. var loader = new FileLoader(scope.manager);
  23485. loader.setPath(scope.path);
  23486. loader.load(url, function (text) {
  23487. onLoad(scope.parse(JSON.parse(text)));
  23488. }, onProgress, onError);
  23489. },
  23490. parse: function (json) {
  23491. var geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  23492. var index = json.data.index;
  23493. if (index !== undefined) {
  23494. var typedArray = new TYPED_ARRAYS[index.type](index.array);
  23495. geometry.setIndex(new BufferAttribute(typedArray, 1));
  23496. }
  23497. var attributes = json.data.attributes;
  23498. for (var key in attributes) {
  23499. var attribute = attributes[key];
  23500. var typedArray = new TYPED_ARRAYS[attribute.type](attribute.array);
  23501. var bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  23502. var bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  23503. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  23504. geometry.addAttribute(key, bufferAttribute);
  23505. }
  23506. var morphAttributes = json.data.morphAttributes;
  23507. if (morphAttributes) {
  23508. for (var key in morphAttributes) {
  23509. var attributeArray = morphAttributes[key];
  23510. var array = [];
  23511. for (var i = 0, il = attributeArray.length; i < il; i++) {
  23512. var attribute = attributeArray[i];
  23513. var typedArray = new TYPED_ARRAYS[attribute.type](attribute.array);
  23514. var bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  23515. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  23516. array.push(bufferAttribute);
  23517. }
  23518. geometry.morphAttributes[key] = array;
  23519. }
  23520. }
  23521. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  23522. if (groups !== undefined) {
  23523. for (var i = 0, n = groups.length; i !== n; ++i) {
  23524. var group = groups[i];
  23525. geometry.addGroup(group.start, group.count, group.materialIndex);
  23526. }
  23527. }
  23528. var boundingSphere = json.data.boundingSphere;
  23529. if (boundingSphere !== undefined) {
  23530. var center = new Vector3();
  23531. if (boundingSphere.center !== undefined) {
  23532. center.fromArray(boundingSphere.center);
  23533. }
  23534. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  23535. }
  23536. if (json.name) geometry.name = json.name;
  23537. if (json.userData) geometry.userData = json.userData;
  23538. return geometry;
  23539. }
  23540. });
  23541. var TYPED_ARRAYS = {
  23542. Int8Array: Int8Array,
  23543. Uint8Array: Uint8Array,
  23544. // Workaround for IE11 pre KB2929437. See #11440
  23545. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  23546. Int16Array: Int16Array,
  23547. Uint16Array: Uint16Array,
  23548. Int32Array: Int32Array,
  23549. Uint32Array: Uint32Array,
  23550. Float32Array: Float32Array,
  23551. Float64Array: Float64Array
  23552. };
  23553. /**
  23554. * @author mrdoob / http://mrdoob.com/
  23555. */
  23556. function ObjectLoader(manager) {
  23557. Loader.call(this, manager);
  23558. }
  23559. ObjectLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  23560. constructor: ObjectLoader,
  23561. load: function (url, onLoad, onProgress, onError) {
  23562. var scope = this;
  23563. var path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  23564. this.resourcePath = this.resourcePath || path;
  23565. var loader = new FileLoader(scope.manager);
  23566. loader.setPath(this.path);
  23567. loader.load(url, function (text) {
  23568. var json = null;
  23569. try {
  23570. json = JSON.parse(text);
  23571. } catch (error) {
  23572. if (onError !== undefined) onError(error);
  23573. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  23574. return;
  23575. }
  23576. var metadata = json.metadata;
  23577. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  23578. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  23579. return;
  23580. }
  23581. scope.parse(json, onLoad);
  23582. }, onProgress, onError);
  23583. },
  23584. parse: function (json, onLoad) {
  23585. var shapes = this.parseShape(json.shapes);
  23586. var geometries = this.parseGeometries(json.geometries, shapes);
  23587. var images = this.parseImages(json.images, function () {
  23588. if (onLoad !== undefined) onLoad(object);
  23589. });
  23590. var textures = this.parseTextures(json.textures, images);
  23591. var materials = this.parseMaterials(json.materials, textures);
  23592. var object = this.parseObject(json.object, geometries, materials);
  23593. if (json.animations) {
  23594. object.animations = this.parseAnimations(json.animations);
  23595. }
  23596. if (json.images === undefined || json.images.length === 0) {
  23597. if (onLoad !== undefined) onLoad(object);
  23598. }
  23599. return object;
  23600. },
  23601. parseShape: function (json) {
  23602. var shapes = {};
  23603. if (json !== undefined) {
  23604. for (var i = 0, l = json.length; i < l; i++) {
  23605. var shape = new Shape().fromJSON(json[i]);
  23606. shapes[shape.uuid] = shape;
  23607. }
  23608. }
  23609. return shapes;
  23610. },
  23611. parseGeometries: function (json, shapes) {
  23612. var geometries = {};
  23613. if (json !== undefined) {
  23614. var bufferGeometryLoader = new BufferGeometryLoader();
  23615. for (var i = 0, l = json.length; i < l; i++) {
  23616. var geometry;
  23617. var data = json[i];
  23618. switch (data.type) {
  23619. case 'PlaneGeometry':
  23620. case 'PlaneBufferGeometry':
  23621. geometry = new Geometries[data.type](data.width, data.height, data.widthSegments, data.heightSegments);
  23622. break;
  23623. case 'BoxGeometry':
  23624. case 'BoxBufferGeometry':
  23625. case 'CubeGeometry':
  23626. // backwards compatible
  23627. geometry = new Geometries[data.type](data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  23628. break;
  23629. case 'CircleGeometry':
  23630. case 'CircleBufferGeometry':
  23631. geometry = new Geometries[data.type](data.radius, data.segments, data.thetaStart, data.thetaLength);
  23632. break;
  23633. case 'CylinderGeometry':
  23634. case 'CylinderBufferGeometry':
  23635. geometry = new Geometries[data.type](data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  23636. break;
  23637. case 'ConeGeometry':
  23638. case 'ConeBufferGeometry':
  23639. geometry = new Geometries[data.type](data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  23640. break;
  23641. case 'SphereGeometry':
  23642. case 'SphereBufferGeometry':
  23643. geometry = new Geometries[data.type](data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  23644. break;
  23645. case 'DodecahedronGeometry':
  23646. case 'DodecahedronBufferGeometry':
  23647. case 'IcosahedronGeometry':
  23648. case 'IcosahedronBufferGeometry':
  23649. case 'OctahedronGeometry':
  23650. case 'OctahedronBufferGeometry':
  23651. case 'TetrahedronGeometry':
  23652. case 'TetrahedronBufferGeometry':
  23653. geometry = new Geometries[data.type](data.radius, data.detail);
  23654. break;
  23655. case 'RingGeometry':
  23656. case 'RingBufferGeometry':
  23657. geometry = new Geometries[data.type](data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  23658. break;
  23659. case 'TorusGeometry':
  23660. case 'TorusBufferGeometry':
  23661. geometry = new Geometries[data.type](data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  23662. break;
  23663. case 'TorusKnotGeometry':
  23664. case 'TorusKnotBufferGeometry':
  23665. geometry = new Geometries[data.type](data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  23666. break;
  23667. case 'TubeGeometry':
  23668. case 'TubeBufferGeometry':
  23669. // This only works for built-in curves (e.g. CatmullRomCurve3).
  23670. // User defined curves or instances of CurvePath will not be deserialized.
  23671. geometry = new Geometries[data.type](new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  23672. break;
  23673. case 'LatheGeometry':
  23674. case 'LatheBufferGeometry':
  23675. geometry = new Geometries[data.type](data.points, data.segments, data.phiStart, data.phiLength);
  23676. break;
  23677. case 'PolyhedronGeometry':
  23678. case 'PolyhedronBufferGeometry':
  23679. geometry = new Geometries[data.type](data.vertices, data.indices, data.radius, data.details);
  23680. break;
  23681. case 'ShapeGeometry':
  23682. case 'ShapeBufferGeometry':
  23683. var geometryShapes = [];
  23684. for (var j = 0, jl = data.shapes.length; j < jl; j++) {
  23685. var shape = shapes[data.shapes[j]];
  23686. geometryShapes.push(shape);
  23687. }
  23688. geometry = new Geometries[data.type](geometryShapes, data.curveSegments);
  23689. break;
  23690. case 'ExtrudeGeometry':
  23691. case 'ExtrudeBufferGeometry':
  23692. var geometryShapes = [];
  23693. for (var j = 0, jl = data.shapes.length; j < jl; j++) {
  23694. var shape = shapes[data.shapes[j]];
  23695. geometryShapes.push(shape);
  23696. }
  23697. var extrudePath = data.options.extrudePath;
  23698. if (extrudePath !== undefined) {
  23699. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  23700. }
  23701. geometry = new Geometries[data.type](geometryShapes, data.options);
  23702. break;
  23703. case 'BufferGeometry':
  23704. case 'InstancedBufferGeometry':
  23705. geometry = bufferGeometryLoader.parse(data);
  23706. break;
  23707. case 'Geometry':
  23708. if ('THREE' in window && 'LegacyJSONLoader' in THREE) {
  23709. var geometryLoader = new THREE.LegacyJSONLoader();
  23710. geometry = geometryLoader.parse(data, this.resourcePath).geometry;
  23711. } else {
  23712. console.error('THREE.ObjectLoader: You have to import LegacyJSONLoader in order load geometry data of type "Geometry".');
  23713. }
  23714. break;
  23715. default:
  23716. console.warn('THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"');
  23717. continue;
  23718. }
  23719. geometry.uuid = data.uuid;
  23720. if (data.name !== undefined) geometry.name = data.name;
  23721. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  23722. geometries[data.uuid] = geometry;
  23723. }
  23724. }
  23725. return geometries;
  23726. },
  23727. parseMaterials: function (json, textures) {
  23728. var cache = {}; // MultiMaterial
  23729. var materials = {};
  23730. if (json !== undefined) {
  23731. var loader = new MaterialLoader();
  23732. loader.setTextures(textures);
  23733. for (var i = 0, l = json.length; i < l; i++) {
  23734. var data = json[i];
  23735. if (data.type === 'MultiMaterial') {
  23736. // Deprecated
  23737. var array = [];
  23738. for (var j = 0; j < data.materials.length; j++) {
  23739. var material = data.materials[j];
  23740. if (cache[material.uuid] === undefined) {
  23741. cache[material.uuid] = loader.parse(material);
  23742. }
  23743. array.push(cache[material.uuid]);
  23744. }
  23745. materials[data.uuid] = array;
  23746. } else {
  23747. if (cache[data.uuid] === undefined) {
  23748. cache[data.uuid] = loader.parse(data);
  23749. }
  23750. materials[data.uuid] = cache[data.uuid];
  23751. }
  23752. }
  23753. }
  23754. return materials;
  23755. },
  23756. parseAnimations: function (json) {
  23757. var animations = [];
  23758. for (var i = 0; i < json.length; i++) {
  23759. var data = json[i];
  23760. var clip = AnimationClip.parse(data);
  23761. if (data.uuid !== undefined) clip.uuid = data.uuid;
  23762. animations.push(clip);
  23763. }
  23764. return animations;
  23765. },
  23766. parseImages: function (json, onLoad) {
  23767. var scope = this;
  23768. var images = {};
  23769. function loadImage(url) {
  23770. scope.manager.itemStart(url);
  23771. return loader.load(url, function () {
  23772. scope.manager.itemEnd(url);
  23773. }, undefined, function () {
  23774. scope.manager.itemError(url);
  23775. scope.manager.itemEnd(url);
  23776. });
  23777. }
  23778. if (json !== undefined && json.length > 0) {
  23779. var manager = new LoadingManager(onLoad);
  23780. var loader = new ImageLoader(manager);
  23781. loader.setCrossOrigin(this.crossOrigin);
  23782. for (var i = 0, il = json.length; i < il; i++) {
  23783. var image = json[i];
  23784. var url = image.url;
  23785. if (Array.isArray(url)) {
  23786. // load array of images e.g CubeTexture
  23787. images[image.uuid] = [];
  23788. for (var j = 0, jl = url.length; j < jl; j++) {
  23789. var currentUrl = url[j];
  23790. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(currentUrl) ? currentUrl : scope.resourcePath + currentUrl;
  23791. images[image.uuid].push(loadImage(path));
  23792. }
  23793. } else {
  23794. // load single image
  23795. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(image.url) ? image.url : scope.resourcePath + image.url;
  23796. images[image.uuid] = loadImage(path);
  23797. }
  23798. }
  23799. }
  23800. return images;
  23801. },
  23802. parseTextures: function (json, images) {
  23803. function parseConstant(value, type) {
  23804. if (typeof value === 'number') return value;
  23805. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  23806. return type[value];
  23807. }
  23808. var textures = {};
  23809. if (json !== undefined) {
  23810. for (var i = 0, l = json.length; i < l; i++) {
  23811. var data = json[i];
  23812. if (data.image === undefined) {
  23813. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  23814. }
  23815. if (images[data.image] === undefined) {
  23816. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  23817. }
  23818. var texture;
  23819. if (Array.isArray(images[data.image])) {
  23820. texture = new CubeTexture(images[data.image]);
  23821. } else {
  23822. texture = new Texture(images[data.image]);
  23823. }
  23824. texture.needsUpdate = true;
  23825. texture.uuid = data.uuid;
  23826. if (data.name !== undefined) texture.name = data.name;
  23827. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  23828. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  23829. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  23830. if (data.center !== undefined) texture.center.fromArray(data.center);
  23831. if (data.rotation !== undefined) texture.rotation = data.rotation;
  23832. if (data.wrap !== undefined) {
  23833. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  23834. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  23835. }
  23836. if (data.format !== undefined) texture.format = data.format;
  23837. if (data.type !== undefined) texture.type = data.type;
  23838. if (data.encoding !== undefined) texture.encoding = data.encoding;
  23839. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  23840. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  23841. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  23842. if (data.flipY !== undefined) texture.flipY = data.flipY;
  23843. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  23844. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  23845. textures[data.uuid] = texture;
  23846. }
  23847. }
  23848. return textures;
  23849. },
  23850. parseObject: function (data, geometries, materials) {
  23851. var object;
  23852. function getGeometry(name) {
  23853. if (geometries[name] === undefined) {
  23854. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  23855. }
  23856. return geometries[name];
  23857. }
  23858. function getMaterial(name) {
  23859. if (name === undefined) return undefined;
  23860. if (Array.isArray(name)) {
  23861. var array = [];
  23862. for (var i = 0, l = name.length; i < l; i++) {
  23863. var uuid = name[i];
  23864. if (materials[uuid] === undefined) {
  23865. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  23866. }
  23867. array.push(materials[uuid]);
  23868. }
  23869. return array;
  23870. }
  23871. if (materials[name] === undefined) {
  23872. console.warn('THREE.ObjectLoader: Undefined material', name);
  23873. }
  23874. return materials[name];
  23875. }
  23876. switch (data.type) {
  23877. case 'Scene':
  23878. object = new Scene();
  23879. if (data.background !== undefined) {
  23880. if (Number.isInteger(data.background)) {
  23881. object.background = new Color(data.background);
  23882. }
  23883. }
  23884. if (data.fog !== undefined) {
  23885. if (data.fog.type === 'Fog') {
  23886. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  23887. } else if (data.fog.type === 'FogExp2') {
  23888. object.fog = new FogExp2(data.fog.color, data.fog.density);
  23889. }
  23890. }
  23891. break;
  23892. case 'PerspectiveCamera':
  23893. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  23894. if (data.focus !== undefined) object.focus = data.focus;
  23895. if (data.zoom !== undefined) object.zoom = data.zoom;
  23896. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  23897. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  23898. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  23899. break;
  23900. case 'OrthographicCamera':
  23901. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  23902. if (data.zoom !== undefined) object.zoom = data.zoom;
  23903. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  23904. break;
  23905. case 'AmbientLight':
  23906. object = new AmbientLight(data.color, data.intensity);
  23907. break;
  23908. case 'DirectionalLight':
  23909. object = new DirectionalLight(data.color, data.intensity);
  23910. break;
  23911. case 'PointLight':
  23912. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  23913. break;
  23914. case 'RectAreaLight':
  23915. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  23916. break;
  23917. case 'SpotLight':
  23918. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  23919. break;
  23920. case 'HemisphereLight':
  23921. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  23922. break;
  23923. case 'SkinnedMesh':
  23924. console.warn('THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.');
  23925. case 'Mesh':
  23926. var geometry = getGeometry(data.geometry);
  23927. var material = getMaterial(data.material);
  23928. if (geometry.bones && geometry.bones.length > 0) {
  23929. object = new SkinnedMesh(geometry, material);
  23930. } else {
  23931. object = new Mesh(geometry, material);
  23932. }
  23933. if (data.drawMode !== undefined) object.setDrawMode(data.drawMode);
  23934. break;
  23935. case 'LOD':
  23936. object = new LOD();
  23937. break;
  23938. case 'Line':
  23939. object = new Line(getGeometry(data.geometry), getMaterial(data.material), data.mode);
  23940. break;
  23941. case 'LineLoop':
  23942. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  23943. break;
  23944. case 'LineSegments':
  23945. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  23946. break;
  23947. case 'PointCloud':
  23948. case 'Points':
  23949. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  23950. break;
  23951. case 'Sprite':
  23952. object = new Sprite(getMaterial(data.material));
  23953. break;
  23954. case 'Group':
  23955. object = new Group();
  23956. break;
  23957. default:
  23958. object = new Object3D();
  23959. }
  23960. object.uuid = data.uuid;
  23961. if (data.name !== undefined) object.name = data.name;
  23962. if (data.matrix !== undefined) {
  23963. object.matrix.fromArray(data.matrix);
  23964. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  23965. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  23966. } else {
  23967. if (data.position !== undefined) object.position.fromArray(data.position);
  23968. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  23969. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  23970. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  23971. }
  23972. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  23973. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  23974. if (data.shadow) {
  23975. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  23976. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  23977. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  23978. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  23979. }
  23980. if (data.visible !== undefined) object.visible = data.visible;
  23981. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  23982. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  23983. if (data.userData !== undefined) object.userData = data.userData;
  23984. if (data.layers !== undefined) object.layers.mask = data.layers;
  23985. if (data.children !== undefined) {
  23986. var children = data.children;
  23987. for (var i = 0; i < children.length; i++) {
  23988. object.add(this.parseObject(children[i], geometries, materials));
  23989. }
  23990. }
  23991. if (data.type === 'LOD') {
  23992. var levels = data.levels;
  23993. for (var l = 0; l < levels.length; l++) {
  23994. var level = levels[l];
  23995. var child = object.getObjectByProperty('uuid', level.object);
  23996. if (child !== undefined) {
  23997. object.addLevel(child, level.distance);
  23998. }
  23999. }
  24000. }
  24001. return object;
  24002. }
  24003. });
  24004. var TEXTURE_MAPPING = {
  24005. UVMapping: UVMapping,
  24006. CubeReflectionMapping: CubeReflectionMapping,
  24007. CubeRefractionMapping: CubeRefractionMapping,
  24008. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  24009. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  24010. SphericalReflectionMapping: SphericalReflectionMapping,
  24011. CubeUVReflectionMapping: CubeUVReflectionMapping,
  24012. CubeUVRefractionMapping: CubeUVRefractionMapping
  24013. };
  24014. var TEXTURE_WRAPPING = {
  24015. RepeatWrapping: RepeatWrapping,
  24016. ClampToEdgeWrapping: ClampToEdgeWrapping,
  24017. MirroredRepeatWrapping: MirroredRepeatWrapping
  24018. };
  24019. var TEXTURE_FILTER = {
  24020. NearestFilter: NearestFilter,
  24021. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  24022. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  24023. LinearFilter: LinearFilter,
  24024. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  24025. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  24026. };
  24027. /**
  24028. * @author thespite / http://clicktorelease.com/
  24029. */
  24030. function ImageBitmapLoader(manager) {
  24031. if (typeof createImageBitmap === 'undefined') {
  24032. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  24033. }
  24034. if (typeof fetch === 'undefined') {
  24035. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  24036. }
  24037. Loader.call(this, manager);
  24038. this.options = undefined;
  24039. }
  24040. ImageBitmapLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24041. constructor: ImageBitmapLoader,
  24042. setOptions: function setOptions(options) {
  24043. this.options = options;
  24044. return this;
  24045. },
  24046. load: function (url, onLoad, onProgress, onError) {
  24047. if (url === undefined) url = '';
  24048. if (this.path !== undefined) url = this.path + url;
  24049. url = this.manager.resolveURL(url);
  24050. var scope = this;
  24051. var cached = Cache.get(url);
  24052. if (cached !== undefined) {
  24053. scope.manager.itemStart(url);
  24054. setTimeout(function () {
  24055. if (onLoad) onLoad(cached);
  24056. scope.manager.itemEnd(url);
  24057. }, 0);
  24058. return cached;
  24059. }
  24060. fetch(url).then(function (res) {
  24061. return res.blob();
  24062. }).then(function (blob) {
  24063. if (scope.options === undefined) {
  24064. // Workaround for FireFox. It causes an error if you pass options.
  24065. return createImageBitmap(blob);
  24066. } else {
  24067. return createImageBitmap(blob, scope.options);
  24068. }
  24069. }).then(function (imageBitmap) {
  24070. Cache.add(url, imageBitmap);
  24071. if (onLoad) onLoad(imageBitmap);
  24072. scope.manager.itemEnd(url);
  24073. }).catch(function (e) {
  24074. if (onError) onError(e);
  24075. scope.manager.itemError(url);
  24076. scope.manager.itemEnd(url);
  24077. });
  24078. scope.manager.itemStart(url);
  24079. }
  24080. });
  24081. /**
  24082. * @author zz85 / http://www.lab4games.net/zz85/blog
  24083. * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  24084. **/
  24085. function ShapePath() {
  24086. this.type = 'ShapePath';
  24087. this.color = new Color();
  24088. this.subPaths = [];
  24089. this.currentPath = null;
  24090. }
  24091. Object.assign(ShapePath.prototype, {
  24092. moveTo: function (x, y) {
  24093. this.currentPath = new Path();
  24094. this.subPaths.push(this.currentPath);
  24095. this.currentPath.moveTo(x, y);
  24096. },
  24097. lineTo: function (x, y) {
  24098. this.currentPath.lineTo(x, y);
  24099. },
  24100. quadraticCurveTo: function (aCPx, aCPy, aX, aY) {
  24101. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  24102. },
  24103. bezierCurveTo: function (aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  24104. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  24105. },
  24106. splineThru: function (pts) {
  24107. this.currentPath.splineThru(pts);
  24108. },
  24109. toShapes: function (isCCW, noHoles) {
  24110. function toShapesNoHoles(inSubpaths) {
  24111. var shapes = [];
  24112. for (var i = 0, l = inSubpaths.length; i < l; i++) {
  24113. var tmpPath = inSubpaths[i];
  24114. var tmpShape = new Shape();
  24115. tmpShape.curves = tmpPath.curves;
  24116. shapes.push(tmpShape);
  24117. }
  24118. return shapes;
  24119. }
  24120. function isPointInsidePolygon(inPt, inPolygon) {
  24121. var polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  24122. // toggling of inside/outside at every single! intersection point of an edge
  24123. // with the horizontal line through inPt, left of inPt
  24124. // not counting lowerY endpoints of edges and whole edges on that line
  24125. var inside = false;
  24126. for (var p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  24127. var edgeLowPt = inPolygon[p];
  24128. var edgeHighPt = inPolygon[q];
  24129. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  24130. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  24131. if (Math.abs(edgeDy) > Number.EPSILON) {
  24132. // not parallel
  24133. if (edgeDy < 0) {
  24134. edgeLowPt = inPolygon[q];
  24135. edgeDx = -edgeDx;
  24136. edgeHighPt = inPolygon[p];
  24137. edgeDy = -edgeDy;
  24138. }
  24139. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  24140. if (inPt.y === edgeLowPt.y) {
  24141. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  24142. // continue; // no intersection or edgeLowPt => doesn't count !!!
  24143. } else {
  24144. var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  24145. if (perpEdge === 0) return true; // inPt is on contour ?
  24146. if (perpEdge < 0) continue;
  24147. inside = !inside; // true intersection left of inPt
  24148. }
  24149. } else {
  24150. // parallel or collinear
  24151. if (inPt.y !== edgeLowPt.y) continue; // parallel
  24152. // edge lies on the same horizontal line as inPt
  24153. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  24154. // continue;
  24155. }
  24156. }
  24157. return inside;
  24158. }
  24159. var isClockWise = ShapeUtils.isClockWise;
  24160. var subPaths = this.subPaths;
  24161. if (subPaths.length === 0) return [];
  24162. if (noHoles === true) return toShapesNoHoles(subPaths);
  24163. var solid,
  24164. tmpPath,
  24165. tmpShape,
  24166. shapes = [];
  24167. if (subPaths.length === 1) {
  24168. tmpPath = subPaths[0];
  24169. tmpShape = new Shape();
  24170. tmpShape.curves = tmpPath.curves;
  24171. shapes.push(tmpShape);
  24172. return shapes;
  24173. }
  24174. var holesFirst = !isClockWise(subPaths[0].getPoints());
  24175. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  24176. var betterShapeHoles = [];
  24177. var newShapes = [];
  24178. var newShapeHoles = [];
  24179. var mainIdx = 0;
  24180. var tmpPoints;
  24181. newShapes[mainIdx] = undefined;
  24182. newShapeHoles[mainIdx] = [];
  24183. for (var i = 0, l = subPaths.length; i < l; i++) {
  24184. tmpPath = subPaths[i];
  24185. tmpPoints = tmpPath.getPoints();
  24186. solid = isClockWise(tmpPoints);
  24187. solid = isCCW ? !solid : solid;
  24188. if (solid) {
  24189. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  24190. newShapes[mainIdx] = {
  24191. s: new Shape(),
  24192. p: tmpPoints
  24193. };
  24194. newShapes[mainIdx].s.curves = tmpPath.curves;
  24195. if (holesFirst) mainIdx++;
  24196. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  24197. } else {
  24198. newShapeHoles[mainIdx].push({
  24199. h: tmpPath,
  24200. p: tmpPoints[0]
  24201. }); //console.log('ccw', i);
  24202. }
  24203. } // only Holes? -> probably all Shapes with wrong orientation
  24204. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  24205. if (newShapes.length > 1) {
  24206. var ambiguous = false;
  24207. var toChange = [];
  24208. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  24209. betterShapeHoles[sIdx] = [];
  24210. }
  24211. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  24212. var sho = newShapeHoles[sIdx];
  24213. for (var hIdx = 0; hIdx < sho.length; hIdx++) {
  24214. var ho = sho[hIdx];
  24215. var hole_unassigned = true;
  24216. for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  24217. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  24218. if (sIdx !== s2Idx) toChange.push({
  24219. froms: sIdx,
  24220. tos: s2Idx,
  24221. hole: hIdx
  24222. });
  24223. if (hole_unassigned) {
  24224. hole_unassigned = false;
  24225. betterShapeHoles[s2Idx].push(ho);
  24226. } else {
  24227. ambiguous = true;
  24228. }
  24229. }
  24230. }
  24231. if (hole_unassigned) {
  24232. betterShapeHoles[sIdx].push(ho);
  24233. }
  24234. }
  24235. } // console.log("ambiguous: ", ambiguous);
  24236. if (toChange.length > 0) {
  24237. // console.log("to change: ", toChange);
  24238. if (!ambiguous) newShapeHoles = betterShapeHoles;
  24239. }
  24240. }
  24241. var tmpHoles;
  24242. for (var i = 0, il = newShapes.length; i < il; i++) {
  24243. tmpShape = newShapes[i].s;
  24244. shapes.push(tmpShape);
  24245. tmpHoles = newShapeHoles[i];
  24246. for (var j = 0, jl = tmpHoles.length; j < jl; j++) {
  24247. tmpShape.holes.push(tmpHoles[j].h);
  24248. }
  24249. } //console.log("shape", shapes);
  24250. return shapes;
  24251. }
  24252. });
  24253. /**
  24254. * @author zz85 / http://www.lab4games.net/zz85/blog
  24255. * @author mrdoob / http://mrdoob.com/
  24256. */
  24257. function Font(data) {
  24258. this.type = 'Font';
  24259. this.data = data;
  24260. }
  24261. Object.assign(Font.prototype, {
  24262. isFont: true,
  24263. generateShapes: function (text, size) {
  24264. if (size === undefined) size = 100;
  24265. var shapes = [];
  24266. var paths = createPaths(text, size, this.data);
  24267. for (var p = 0, pl = paths.length; p < pl; p++) {
  24268. Array.prototype.push.apply(shapes, paths[p].toShapes());
  24269. }
  24270. return shapes;
  24271. }
  24272. });
  24273. function createPaths(text, size, data) {
  24274. var chars = Array.from ? Array.from(text) : String(text).split(''); // see #13988
  24275. var scale = size / data.resolution;
  24276. var line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale;
  24277. var paths = [];
  24278. var offsetX = 0,
  24279. offsetY = 0;
  24280. for (var i = 0; i < chars.length; i++) {
  24281. var char = chars[i];
  24282. if (char === '\n') {
  24283. offsetX = 0;
  24284. offsetY -= line_height;
  24285. } else {
  24286. var ret = createPath(char, scale, offsetX, offsetY, data);
  24287. offsetX += ret.offsetX;
  24288. paths.push(ret.path);
  24289. }
  24290. }
  24291. return paths;
  24292. }
  24293. function createPath(char, scale, offsetX, offsetY, data) {
  24294. var glyph = data.glyphs[char] || data.glyphs['?'];
  24295. if (!glyph) {
  24296. console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.');
  24297. return;
  24298. }
  24299. var path = new ShapePath();
  24300. var x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  24301. if (glyph.o) {
  24302. var outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(' '));
  24303. for (var i = 0, l = outline.length; i < l;) {
  24304. var action = outline[i++];
  24305. switch (action) {
  24306. case 'm':
  24307. // moveTo
  24308. x = outline[i++] * scale + offsetX;
  24309. y = outline[i++] * scale + offsetY;
  24310. path.moveTo(x, y);
  24311. break;
  24312. case 'l':
  24313. // lineTo
  24314. x = outline[i++] * scale + offsetX;
  24315. y = outline[i++] * scale + offsetY;
  24316. path.lineTo(x, y);
  24317. break;
  24318. case 'q':
  24319. // quadraticCurveTo
  24320. cpx = outline[i++] * scale + offsetX;
  24321. cpy = outline[i++] * scale + offsetY;
  24322. cpx1 = outline[i++] * scale + offsetX;
  24323. cpy1 = outline[i++] * scale + offsetY;
  24324. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  24325. break;
  24326. case 'b':
  24327. // bezierCurveTo
  24328. cpx = outline[i++] * scale + offsetX;
  24329. cpy = outline[i++] * scale + offsetY;
  24330. cpx1 = outline[i++] * scale + offsetX;
  24331. cpy1 = outline[i++] * scale + offsetY;
  24332. cpx2 = outline[i++] * scale + offsetX;
  24333. cpy2 = outline[i++] * scale + offsetY;
  24334. path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);
  24335. break;
  24336. }
  24337. }
  24338. }
  24339. return {
  24340. offsetX: glyph.ha * scale,
  24341. path: path
  24342. };
  24343. }
  24344. /**
  24345. * @author mrdoob / http://mrdoob.com/
  24346. */
  24347. function FontLoader(manager) {
  24348. Loader.call(this, manager);
  24349. }
  24350. FontLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24351. constructor: FontLoader,
  24352. load: function (url, onLoad, onProgress, onError) {
  24353. var scope = this;
  24354. var loader = new FileLoader(this.manager);
  24355. loader.setPath(this.path);
  24356. loader.load(url, function (text) {
  24357. var json;
  24358. try {
  24359. json = JSON.parse(text);
  24360. } catch (e) {
  24361. console.warn('THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.');
  24362. json = JSON.parse(text.substring(65, text.length - 2));
  24363. }
  24364. var font = scope.parse(json);
  24365. if (onLoad) onLoad(font);
  24366. }, onProgress, onError);
  24367. },
  24368. parse: function (json) {
  24369. return new Font(json);
  24370. }
  24371. });
  24372. /**
  24373. * @author mrdoob / http://mrdoob.com/
  24374. */
  24375. var _context;
  24376. var AudioContext = {
  24377. getContext: function () {
  24378. if (_context === undefined) {
  24379. _context = new (window.AudioContext || window.webkitAudioContext)();
  24380. }
  24381. return _context;
  24382. },
  24383. setContext: function (value) {
  24384. _context = value;
  24385. }
  24386. };
  24387. /**
  24388. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  24389. */
  24390. exports.AudioContext = AudioContext;
  24391. function AudioLoader(manager) {
  24392. Loader.call(this, manager);
  24393. }
  24394. AudioLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24395. constructor: AudioLoader,
  24396. load: function (url, onLoad, onProgress, onError) {
  24397. var loader = new FileLoader(this.manager);
  24398. loader.setResponseType('arraybuffer');
  24399. loader.setPath(this.path);
  24400. loader.load(url, function (buffer) {
  24401. // Create a copy of the buffer. The `decodeAudioData` method
  24402. // detaches the buffer when complete, preventing reuse.
  24403. var bufferCopy = buffer.slice(0);
  24404. var context = AudioContext.getContext();
  24405. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  24406. onLoad(audioBuffer);
  24407. });
  24408. }, onProgress, onError);
  24409. }
  24410. });
  24411. /**
  24412. * @author bhouston / http://clara.io
  24413. * @author WestLangley / http://github.com/WestLangley
  24414. *
  24415. * Primary reference:
  24416. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24417. *
  24418. * Secondary reference:
  24419. * https://www.ppsloan.org/publications/StupidSH36.pdf
  24420. */
  24421. // 3-band SH defined by 9 coefficients
  24422. function SphericalHarmonics3() {
  24423. this.coefficients = [];
  24424. for (var i = 0; i < 9; i++) {
  24425. this.coefficients.push(new Vector3());
  24426. }
  24427. }
  24428. Object.assign(SphericalHarmonics3.prototype, {
  24429. isSphericalHarmonics3: true,
  24430. set: function (coefficients) {
  24431. for (var i = 0; i < 9; i++) {
  24432. this.coefficients[i].copy(coefficients[i]);
  24433. }
  24434. return this;
  24435. },
  24436. zero: function () {
  24437. for (var i = 0; i < 9; i++) {
  24438. this.coefficients[i].set(0, 0, 0);
  24439. }
  24440. return this;
  24441. },
  24442. // get the radiance in the direction of the normal
  24443. // target is a Vector3
  24444. getAt: function (normal, target) {
  24445. // normal is assumed to be unit length
  24446. var x = normal.x,
  24447. y = normal.y,
  24448. z = normal.z;
  24449. var coeff = this.coefficients; // band 0
  24450. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  24451. target.addScale(coeff[1], 0.488603 * y);
  24452. target.addScale(coeff[2], 0.488603 * z);
  24453. target.addScale(coeff[3], 0.488603 * x); // band 2
  24454. target.addScale(coeff[4], 1.092548 * (x * y));
  24455. target.addScale(coeff[5], 1.092548 * (y * z));
  24456. target.addScale(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  24457. target.addScale(coeff[7], 1.092548 * (x * z));
  24458. target.addScale(coeff[8], 0.546274 * (x * x - y * y));
  24459. return target;
  24460. },
  24461. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  24462. // target is a Vector3
  24463. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24464. getIrradianceAt: function (normal, target) {
  24465. // normal is assumed to be unit length
  24466. var x = normal.x,
  24467. y = normal.y,
  24468. z = normal.z;
  24469. var coeff = this.coefficients; // band 0
  24470. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  24471. // band 1
  24472. target.addScale(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  24473. target.addScale(coeff[2], 2.0 * 0.511664 * z);
  24474. target.addScale(coeff[3], 2.0 * 0.511664 * x); // band 2
  24475. target.addScale(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  24476. target.addScale(coeff[5], 2.0 * 0.429043 * y * z);
  24477. target.addScale(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  24478. target.addScale(coeff[7], 2.0 * 0.429043 * x * z);
  24479. target.addScale(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  24480. return target;
  24481. },
  24482. add: function (sh) {
  24483. for (var i = 0; i < 9; i++) {
  24484. this.coefficients[i].add(sh.coefficients[i]);
  24485. }
  24486. return this;
  24487. },
  24488. scale: function (s) {
  24489. for (var i = 0; i < 9; i++) {
  24490. this.coefficients[i].multiplyScalar(s);
  24491. }
  24492. return this;
  24493. },
  24494. lerp: function (sh, alpha) {
  24495. for (var i = 0; i < 9; i++) {
  24496. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  24497. }
  24498. return this;
  24499. },
  24500. equals: function (sh) {
  24501. for (var i = 0; i < 9; i++) {
  24502. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  24503. return false;
  24504. }
  24505. }
  24506. return true;
  24507. },
  24508. copy: function (sh) {
  24509. return this.set(sh.coefficients);
  24510. },
  24511. clone: function () {
  24512. return new this.constructor().copy(this);
  24513. },
  24514. fromArray: function (array, offset) {
  24515. if (offset === undefined) offset = 0;
  24516. var coefficients = this.coefficients;
  24517. for (var i = 0; i < 9; i++) {
  24518. coefficients[i].fromArray(array, offset + i * 3);
  24519. }
  24520. return this;
  24521. },
  24522. toArray: function (array, offset) {
  24523. if (array === undefined) array = [];
  24524. if (offset === undefined) offset = 0;
  24525. var coefficients = this.coefficients;
  24526. for (var i = 0; i < 9; i++) {
  24527. coefficients[i].toArray(array, offset + i * 3);
  24528. }
  24529. return array;
  24530. }
  24531. });
  24532. Object.assign(SphericalHarmonics3, {
  24533. // evaluate the basis functions
  24534. // shBasis is an Array[ 9 ]
  24535. getBasisAt: function (normal, shBasis) {
  24536. // normal is assumed to be unit length
  24537. var x = normal.x,
  24538. y = normal.y,
  24539. z = normal.z; // band 0
  24540. shBasis[0] = 0.282095; // band 1
  24541. shBasis[1] = 0.488603 * y;
  24542. shBasis[2] = 0.488603 * z;
  24543. shBasis[3] = 0.488603 * x; // band 2
  24544. shBasis[4] = 1.092548 * x * y;
  24545. shBasis[5] = 1.092548 * y * z;
  24546. shBasis[6] = 0.315392 * (3 * z * z - 1);
  24547. shBasis[7] = 1.092548 * x * z;
  24548. shBasis[8] = 0.546274 * (x * x - y * y);
  24549. }
  24550. });
  24551. /**
  24552. * @author WestLangley / http://github.com/WestLangley
  24553. *
  24554. * A LightProbe is a source of indirect-diffuse light
  24555. */
  24556. function LightProbe(sh, intensity) {
  24557. Light.call(this, undefined, intensity);
  24558. this.sh = sh !== undefined ? sh : new SphericalHarmonics3();
  24559. }
  24560. LightProbe.prototype = Object.assign(Object.create(Light.prototype), {
  24561. constructor: LightProbe,
  24562. isLightProbe: true,
  24563. copy: function (source) {
  24564. Light.prototype.copy.call(this, source);
  24565. this.sh.copy(source.sh);
  24566. this.intensity = source.intensity;
  24567. return this;
  24568. },
  24569. toJSON: function (meta) {
  24570. var data = Light.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  24571. return data;
  24572. }
  24573. });
  24574. /**
  24575. * @author WestLangley / http://github.com/WestLangley
  24576. */
  24577. function HemisphereLightProbe(skyColor, groundColor, intensity) {
  24578. LightProbe.call(this, undefined, intensity);
  24579. var color1 = new Color().set(skyColor);
  24580. var color2 = new Color().set(groundColor);
  24581. var sky = new Vector3(color1.r, color1.g, color1.b);
  24582. var ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  24583. var c0 = Math.sqrt(Math.PI);
  24584. var c1 = c0 * Math.sqrt(0.75);
  24585. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  24586. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  24587. }
  24588. HemisphereLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
  24589. constructor: HemisphereLightProbe,
  24590. isHemisphereLightProbe: true,
  24591. copy: function (source) {
  24592. // modifying colors not currently supported
  24593. LightProbe.prototype.copy.call(this, source);
  24594. return this;
  24595. },
  24596. toJSON: function (meta) {
  24597. var data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  24598. return data;
  24599. }
  24600. });
  24601. /**
  24602. * @author WestLangley / http://github.com/WestLangley
  24603. */
  24604. function AmbientLightProbe(color, intensity) {
  24605. LightProbe.call(this, undefined, intensity);
  24606. var color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  24607. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  24608. }
  24609. AmbientLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
  24610. constructor: AmbientLightProbe,
  24611. isAmbientLightProbe: true,
  24612. copy: function (source) {
  24613. // modifying color not currently supported
  24614. LightProbe.prototype.copy.call(this, source);
  24615. return this;
  24616. },
  24617. toJSON: function (meta) {
  24618. var data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  24619. return data;
  24620. }
  24621. });
  24622. var _eyeRight = new Matrix4();
  24623. var _eyeLeft = new Matrix4();
  24624. /**
  24625. * @author mrdoob / http://mrdoob.com/
  24626. */
  24627. function StereoCamera() {
  24628. this.type = 'StereoCamera';
  24629. this.aspect = 1;
  24630. this.eyeSep = 0.064;
  24631. this.cameraL = new PerspectiveCamera();
  24632. this.cameraL.layers.enable(1);
  24633. this.cameraL.matrixAutoUpdate = false;
  24634. this.cameraR = new PerspectiveCamera();
  24635. this.cameraR.layers.enable(2);
  24636. this.cameraR.matrixAutoUpdate = false;
  24637. this._cache = {
  24638. focus: null,
  24639. fov: null,
  24640. aspect: null,
  24641. near: null,
  24642. far: null,
  24643. zoom: null,
  24644. eyeSep: null
  24645. };
  24646. }
  24647. Object.assign(StereoCamera.prototype, {
  24648. update: function (camera) {
  24649. var cache = this._cache;
  24650. 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;
  24651. if (needsUpdate) {
  24652. cache.focus = camera.focus;
  24653. cache.fov = camera.fov;
  24654. cache.aspect = camera.aspect * this.aspect;
  24655. cache.near = camera.near;
  24656. cache.far = camera.far;
  24657. cache.zoom = camera.zoom;
  24658. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  24659. // http://paulbourke.net/stereographics/stereorender/
  24660. var projectionMatrix = camera.projectionMatrix.clone();
  24661. var eyeSepHalf = cache.eyeSep / 2;
  24662. var eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  24663. var ymax = cache.near * Math.tan(_Math.DEG2RAD * cache.fov * 0.5) / cache.zoom;
  24664. var xmin, xmax; // translate xOffset
  24665. _eyeLeft.elements[12] = -eyeSepHalf;
  24666. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  24667. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  24668. xmax = ymax * cache.aspect + eyeSepOnProjection;
  24669. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  24670. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  24671. this.cameraL.projectionMatrix.copy(projectionMatrix); // for right eye
  24672. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  24673. xmax = ymax * cache.aspect - eyeSepOnProjection;
  24674. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  24675. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  24676. this.cameraR.projectionMatrix.copy(projectionMatrix);
  24677. }
  24678. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  24679. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  24680. }
  24681. });
  24682. /**
  24683. * @author alteredq / http://alteredqualia.com/
  24684. */
  24685. function Clock(autoStart) {
  24686. this.autoStart = autoStart !== undefined ? autoStart : true;
  24687. this.startTime = 0;
  24688. this.oldTime = 0;
  24689. this.elapsedTime = 0;
  24690. this.running = false;
  24691. }
  24692. Object.assign(Clock.prototype, {
  24693. start: function () {
  24694. this.startTime = (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  24695. this.oldTime = this.startTime;
  24696. this.elapsedTime = 0;
  24697. this.running = true;
  24698. },
  24699. stop: function () {
  24700. this.getElapsedTime();
  24701. this.running = false;
  24702. this.autoStart = false;
  24703. },
  24704. getElapsedTime: function () {
  24705. this.getDelta();
  24706. return this.elapsedTime;
  24707. },
  24708. getDelta: function () {
  24709. var diff = 0;
  24710. if (this.autoStart && !this.running) {
  24711. this.start();
  24712. return 0;
  24713. }
  24714. if (this.running) {
  24715. var newTime = (typeof performance === 'undefined' ? Date : performance).now();
  24716. diff = (newTime - this.oldTime) / 1000;
  24717. this.oldTime = newTime;
  24718. this.elapsedTime += diff;
  24719. }
  24720. return diff;
  24721. }
  24722. });
  24723. /**
  24724. * @author mrdoob / http://mrdoob.com/
  24725. */
  24726. var _position$2 = new Vector3();
  24727. var _quaternion$3 = new Quaternion();
  24728. var _scale$1 = new Vector3();
  24729. var _orientation = new Vector3();
  24730. function AudioListener() {
  24731. Object3D.call(this);
  24732. this.type = 'AudioListener';
  24733. this.context = AudioContext.getContext();
  24734. this.gain = this.context.createGain();
  24735. this.gain.connect(this.context.destination);
  24736. this.filter = null;
  24737. this.timeDelta = 0; // private
  24738. this._clock = new Clock();
  24739. }
  24740. AudioListener.prototype = Object.assign(Object.create(Object3D.prototype), {
  24741. constructor: AudioListener,
  24742. getInput: function () {
  24743. return this.gain;
  24744. },
  24745. removeFilter: function () {
  24746. if (this.filter !== null) {
  24747. this.gain.disconnect(this.filter);
  24748. this.filter.disconnect(this.context.destination);
  24749. this.gain.connect(this.context.destination);
  24750. this.filter = null;
  24751. }
  24752. return this;
  24753. },
  24754. getFilter: function () {
  24755. return this.filter;
  24756. },
  24757. setFilter: function (value) {
  24758. if (this.filter !== null) {
  24759. this.gain.disconnect(this.filter);
  24760. this.filter.disconnect(this.context.destination);
  24761. } else {
  24762. this.gain.disconnect(this.context.destination);
  24763. }
  24764. this.filter = value;
  24765. this.gain.connect(this.filter);
  24766. this.filter.connect(this.context.destination);
  24767. return this;
  24768. },
  24769. getMasterVolume: function () {
  24770. return this.gain.gain.value;
  24771. },
  24772. setMasterVolume: function (value) {
  24773. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  24774. return this;
  24775. },
  24776. updateMatrixWorld: function (force) {
  24777. Object3D.prototype.updateMatrixWorld.call(this, force);
  24778. var listener = this.context.listener;
  24779. var up = this.up;
  24780. this.timeDelta = this._clock.getDelta();
  24781. this.matrixWorld.decompose(_position$2, _quaternion$3, _scale$1);
  24782. _orientation.set(0, 0, -1).applyQuaternion(_quaternion$3);
  24783. if (listener.positionX) {
  24784. // code path for Chrome (see #14393)
  24785. var endTime = this.context.currentTime + this.timeDelta;
  24786. listener.positionX.linearRampToValueAtTime(_position$2.x, endTime);
  24787. listener.positionY.linearRampToValueAtTime(_position$2.y, endTime);
  24788. listener.positionZ.linearRampToValueAtTime(_position$2.z, endTime);
  24789. listener.forwardX.linearRampToValueAtTime(_orientation.x, endTime);
  24790. listener.forwardY.linearRampToValueAtTime(_orientation.y, endTime);
  24791. listener.forwardZ.linearRampToValueAtTime(_orientation.z, endTime);
  24792. listener.upX.linearRampToValueAtTime(up.x, endTime);
  24793. listener.upY.linearRampToValueAtTime(up.y, endTime);
  24794. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  24795. } else {
  24796. listener.setPosition(_position$2.x, _position$2.y, _position$2.z);
  24797. listener.setOrientation(_orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z);
  24798. }
  24799. }
  24800. });
  24801. /**
  24802. * @author mrdoob / http://mrdoob.com/
  24803. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  24804. */
  24805. function Audio(listener) {
  24806. Object3D.call(this);
  24807. this.type = 'Audio';
  24808. this.listener = listener;
  24809. this.context = listener.context;
  24810. this.gain = this.context.createGain();
  24811. this.gain.connect(listener.getInput());
  24812. this.autoplay = false;
  24813. this.buffer = null;
  24814. this.detune = 0;
  24815. this.loop = false;
  24816. this.startTime = 0;
  24817. this.offset = 0;
  24818. this.duration = undefined;
  24819. this.playbackRate = 1;
  24820. this.isPlaying = false;
  24821. this.hasPlaybackControl = true;
  24822. this.sourceType = 'empty';
  24823. this.filters = [];
  24824. }
  24825. Audio.prototype = Object.assign(Object.create(Object3D.prototype), {
  24826. constructor: Audio,
  24827. getOutput: function () {
  24828. return this.gain;
  24829. },
  24830. setNodeSource: function (audioNode) {
  24831. this.hasPlaybackControl = false;
  24832. this.sourceType = 'audioNode';
  24833. this.source = audioNode;
  24834. this.connect();
  24835. return this;
  24836. },
  24837. setMediaElementSource: function (mediaElement) {
  24838. this.hasPlaybackControl = false;
  24839. this.sourceType = 'mediaNode';
  24840. this.source = this.context.createMediaElementSource(mediaElement);
  24841. this.connect();
  24842. return this;
  24843. },
  24844. setMediaStreamSource: function (mediaStream) {
  24845. this.hasPlaybackControl = false;
  24846. this.sourceType = 'mediaStreamNode';
  24847. this.source = this.context.createMediaStreamSource(mediaStream);
  24848. this.connect();
  24849. return this;
  24850. },
  24851. setBuffer: function (audioBuffer) {
  24852. this.buffer = audioBuffer;
  24853. this.sourceType = 'buffer';
  24854. if (this.autoplay) this.play();
  24855. return this;
  24856. },
  24857. play: function () {
  24858. if (this.isPlaying === true) {
  24859. console.warn('THREE.Audio: Audio is already playing.');
  24860. return;
  24861. }
  24862. if (this.hasPlaybackControl === false) {
  24863. console.warn('THREE.Audio: this Audio has no playback control.');
  24864. return;
  24865. }
  24866. var source = this.context.createBufferSource();
  24867. source.buffer = this.buffer;
  24868. source.loop = this.loop;
  24869. source.onended = this.onEnded.bind(this);
  24870. this.startTime = this.context.currentTime;
  24871. source.start(this.startTime, this.offset, this.duration);
  24872. this.isPlaying = true;
  24873. this.source = source;
  24874. this.setDetune(this.detune);
  24875. this.setPlaybackRate(this.playbackRate);
  24876. return this.connect();
  24877. },
  24878. pause: function () {
  24879. if (this.hasPlaybackControl === false) {
  24880. console.warn('THREE.Audio: this Audio has no playback control.');
  24881. return;
  24882. }
  24883. if (this.isPlaying === true) {
  24884. this.source.stop();
  24885. this.source.onended = null;
  24886. this.offset += (this.context.currentTime - this.startTime) * this.playbackRate;
  24887. this.isPlaying = false;
  24888. }
  24889. return this;
  24890. },
  24891. stop: function () {
  24892. if (this.hasPlaybackControl === false) {
  24893. console.warn('THREE.Audio: this Audio has no playback control.');
  24894. return;
  24895. }
  24896. this.source.stop();
  24897. this.source.onended = null;
  24898. this.offset = 0;
  24899. this.isPlaying = false;
  24900. return this;
  24901. },
  24902. connect: function () {
  24903. if (this.filters.length > 0) {
  24904. this.source.connect(this.filters[0]);
  24905. for (var i = 1, l = this.filters.length; i < l; i++) {
  24906. this.filters[i - 1].connect(this.filters[i]);
  24907. }
  24908. this.filters[this.filters.length - 1].connect(this.getOutput());
  24909. } else {
  24910. this.source.connect(this.getOutput());
  24911. }
  24912. return this;
  24913. },
  24914. disconnect: function () {
  24915. if (this.filters.length > 0) {
  24916. this.source.disconnect(this.filters[0]);
  24917. for (var i = 1, l = this.filters.length; i < l; i++) {
  24918. this.filters[i - 1].disconnect(this.filters[i]);
  24919. }
  24920. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  24921. } else {
  24922. this.source.disconnect(this.getOutput());
  24923. }
  24924. return this;
  24925. },
  24926. getFilters: function () {
  24927. return this.filters;
  24928. },
  24929. setFilters: function (value) {
  24930. if (!value) value = [];
  24931. if (this.isPlaying === true) {
  24932. this.disconnect();
  24933. this.filters = value;
  24934. this.connect();
  24935. } else {
  24936. this.filters = value;
  24937. }
  24938. return this;
  24939. },
  24940. setDetune: function (value) {
  24941. this.detune = value;
  24942. if (this.source.detune === undefined) return; // only set detune when available
  24943. if (this.isPlaying === true) {
  24944. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  24945. }
  24946. return this;
  24947. },
  24948. getDetune: function () {
  24949. return this.detune;
  24950. },
  24951. getFilter: function () {
  24952. return this.getFilters()[0];
  24953. },
  24954. setFilter: function (filter) {
  24955. return this.setFilters(filter ? [filter] : []);
  24956. },
  24957. setPlaybackRate: function (value) {
  24958. if (this.hasPlaybackControl === false) {
  24959. console.warn('THREE.Audio: this Audio has no playback control.');
  24960. return;
  24961. }
  24962. this.playbackRate = value;
  24963. if (this.isPlaying === true) {
  24964. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  24965. }
  24966. return this;
  24967. },
  24968. getPlaybackRate: function () {
  24969. return this.playbackRate;
  24970. },
  24971. onEnded: function () {
  24972. this.isPlaying = false;
  24973. },
  24974. getLoop: function () {
  24975. if (this.hasPlaybackControl === false) {
  24976. console.warn('THREE.Audio: this Audio has no playback control.');
  24977. return false;
  24978. }
  24979. return this.loop;
  24980. },
  24981. setLoop: function (value) {
  24982. if (this.hasPlaybackControl === false) {
  24983. console.warn('THREE.Audio: this Audio has no playback control.');
  24984. return;
  24985. }
  24986. this.loop = value;
  24987. if (this.isPlaying === true) {
  24988. this.source.loop = this.loop;
  24989. }
  24990. return this;
  24991. },
  24992. getVolume: function () {
  24993. return this.gain.gain.value;
  24994. },
  24995. setVolume: function (value) {
  24996. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  24997. return this;
  24998. }
  24999. });
  25000. /**
  25001. * @author mrdoob / http://mrdoob.com/
  25002. */
  25003. var _position$3 = new Vector3();
  25004. var _quaternion$4 = new Quaternion();
  25005. var _scale$2 = new Vector3();
  25006. var _orientation$1 = new Vector3();
  25007. function PositionalAudio(listener) {
  25008. Audio.call(this, listener);
  25009. this.panner = this.context.createPanner();
  25010. this.panner.panningModel = 'HRTF';
  25011. this.panner.connect(this.gain);
  25012. }
  25013. PositionalAudio.prototype = Object.assign(Object.create(Audio.prototype), {
  25014. constructor: PositionalAudio,
  25015. getOutput: function () {
  25016. return this.panner;
  25017. },
  25018. getRefDistance: function () {
  25019. return this.panner.refDistance;
  25020. },
  25021. setRefDistance: function (value) {
  25022. this.panner.refDistance = value;
  25023. return this;
  25024. },
  25025. getRolloffFactor: function () {
  25026. return this.panner.rolloffFactor;
  25027. },
  25028. setRolloffFactor: function (value) {
  25029. this.panner.rolloffFactor = value;
  25030. return this;
  25031. },
  25032. getDistanceModel: function () {
  25033. return this.panner.distanceModel;
  25034. },
  25035. setDistanceModel: function (value) {
  25036. this.panner.distanceModel = value;
  25037. return this;
  25038. },
  25039. getMaxDistance: function () {
  25040. return this.panner.maxDistance;
  25041. },
  25042. setMaxDistance: function (value) {
  25043. this.panner.maxDistance = value;
  25044. return this;
  25045. },
  25046. setDirectionalCone: function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  25047. this.panner.coneInnerAngle = coneInnerAngle;
  25048. this.panner.coneOuterAngle = coneOuterAngle;
  25049. this.panner.coneOuterGain = coneOuterGain;
  25050. return this;
  25051. },
  25052. updateMatrixWorld: function (force) {
  25053. Object3D.prototype.updateMatrixWorld.call(this, force);
  25054. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  25055. this.matrixWorld.decompose(_position$3, _quaternion$4, _scale$2);
  25056. _orientation$1.set(0, 0, 1).applyQuaternion(_quaternion$4);
  25057. var panner = this.panner;
  25058. if (panner.positionX) {
  25059. // code path for Chrome and Firefox (see #14393)
  25060. var endTime = this.context.currentTime + this.listener.timeDelta;
  25061. panner.positionX.linearRampToValueAtTime(_position$3.x, endTime);
  25062. panner.positionY.linearRampToValueAtTime(_position$3.y, endTime);
  25063. panner.positionZ.linearRampToValueAtTime(_position$3.z, endTime);
  25064. panner.orientationX.linearRampToValueAtTime(_orientation$1.x, endTime);
  25065. panner.orientationY.linearRampToValueAtTime(_orientation$1.y, endTime);
  25066. panner.orientationZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  25067. } else {
  25068. panner.setPosition(_position$3.x, _position$3.y, _position$3.z);
  25069. panner.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z);
  25070. }
  25071. }
  25072. });
  25073. /**
  25074. * @author mrdoob / http://mrdoob.com/
  25075. */
  25076. function AudioAnalyser(audio, fftSize) {
  25077. this.analyser = audio.context.createAnalyser();
  25078. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  25079. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  25080. audio.getOutput().connect(this.analyser);
  25081. }
  25082. Object.assign(AudioAnalyser.prototype, {
  25083. getFrequencyData: function () {
  25084. this.analyser.getByteFrequencyData(this.data);
  25085. return this.data;
  25086. },
  25087. getAverageFrequency: function () {
  25088. var value = 0,
  25089. data = this.getFrequencyData();
  25090. for (var i = 0; i < data.length; i++) {
  25091. value += data[i];
  25092. }
  25093. return value / data.length;
  25094. }
  25095. });
  25096. /**
  25097. *
  25098. * Buffered scene graph property that allows weighted accumulation.
  25099. *
  25100. *
  25101. * @author Ben Houston / http://clara.io/
  25102. * @author David Sarno / http://lighthaus.us/
  25103. * @author tschw
  25104. */
  25105. function PropertyMixer(binding, typeName, valueSize) {
  25106. this.binding = binding;
  25107. this.valueSize = valueSize;
  25108. var bufferType = Float64Array,
  25109. mixFunction;
  25110. switch (typeName) {
  25111. case 'quaternion':
  25112. mixFunction = this._slerp;
  25113. break;
  25114. case 'string':
  25115. case 'bool':
  25116. bufferType = Array;
  25117. mixFunction = this._select;
  25118. break;
  25119. default:
  25120. mixFunction = this._lerp;
  25121. }
  25122. this.buffer = new bufferType(valueSize * 4); // layout: [ incoming | accu0 | accu1 | orig ]
  25123. //
  25124. // interpolators can use .buffer as their .result
  25125. // the data then goes to 'incoming'
  25126. //
  25127. // 'accu0' and 'accu1' are used frame-interleaved for
  25128. // the cumulative result and are compared to detect
  25129. // changes
  25130. //
  25131. // 'orig' stores the original state of the property
  25132. this._mixBufferRegion = mixFunction;
  25133. this.cumulativeWeight = 0;
  25134. this.useCount = 0;
  25135. this.referenceCount = 0;
  25136. }
  25137. Object.assign(PropertyMixer.prototype, {
  25138. // accumulate data in the 'incoming' region into 'accu<i>'
  25139. accumulate: function (accuIndex, weight) {
  25140. // note: happily accumulating nothing when weight = 0, the caller knows
  25141. // the weight and shouldn't have made the call in the first place
  25142. var buffer = this.buffer,
  25143. stride = this.valueSize,
  25144. offset = accuIndex * stride + stride,
  25145. currentWeight = this.cumulativeWeight;
  25146. if (currentWeight === 0) {
  25147. // accuN := incoming * weight
  25148. for (var i = 0; i !== stride; ++i) {
  25149. buffer[offset + i] = buffer[i];
  25150. }
  25151. currentWeight = weight;
  25152. } else {
  25153. // accuN := accuN + incoming * weight
  25154. currentWeight += weight;
  25155. var mix = weight / currentWeight;
  25156. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  25157. }
  25158. this.cumulativeWeight = currentWeight;
  25159. },
  25160. // apply the state of 'accu<i>' to the binding when accus differ
  25161. apply: function (accuIndex) {
  25162. var stride = this.valueSize,
  25163. buffer = this.buffer,
  25164. offset = accuIndex * stride + stride,
  25165. weight = this.cumulativeWeight,
  25166. binding = this.binding;
  25167. this.cumulativeWeight = 0;
  25168. if (weight < 1) {
  25169. // accuN := accuN + original * ( 1 - cumulativeWeight )
  25170. var originalValueOffset = stride * 3;
  25171. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  25172. }
  25173. for (var i = stride, e = stride + stride; i !== e; ++i) {
  25174. if (buffer[i] !== buffer[i + stride]) {
  25175. // value has changed -> update scene graph
  25176. binding.setValue(buffer, offset);
  25177. break;
  25178. }
  25179. }
  25180. },
  25181. // remember the state of the bound property and copy it to both accus
  25182. saveOriginalState: function () {
  25183. var binding = this.binding;
  25184. var buffer = this.buffer,
  25185. stride = this.valueSize,
  25186. originalValueOffset = stride * 3;
  25187. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  25188. for (var i = stride, e = originalValueOffset; i !== e; ++i) {
  25189. buffer[i] = buffer[originalValueOffset + i % stride];
  25190. }
  25191. this.cumulativeWeight = 0;
  25192. },
  25193. // apply the state previously taken via 'saveOriginalState' to the binding
  25194. restoreOriginalState: function () {
  25195. var originalValueOffset = this.valueSize * 3;
  25196. this.binding.setValue(this.buffer, originalValueOffset);
  25197. },
  25198. // mix functions
  25199. _select: function (buffer, dstOffset, srcOffset, t, stride) {
  25200. if (t >= 0.5) {
  25201. for (var i = 0; i !== stride; ++i) {
  25202. buffer[dstOffset + i] = buffer[srcOffset + i];
  25203. }
  25204. }
  25205. },
  25206. _slerp: function (buffer, dstOffset, srcOffset, t) {
  25207. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  25208. },
  25209. _lerp: function (buffer, dstOffset, srcOffset, t, stride) {
  25210. var s = 1 - t;
  25211. for (var i = 0; i !== stride; ++i) {
  25212. var j = dstOffset + i;
  25213. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  25214. }
  25215. }
  25216. });
  25217. /**
  25218. *
  25219. * A reference to a real property in the scene graph.
  25220. *
  25221. *
  25222. * @author Ben Houston / http://clara.io/
  25223. * @author David Sarno / http://lighthaus.us/
  25224. * @author tschw
  25225. */
  25226. // Characters [].:/ are reserved for track binding syntax.
  25227. var _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  25228. var _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  25229. // only latin characters, and the unicode \p{L} is not yet supported. So
  25230. // instead, we exclude reserved characters and match everything else.
  25231. var _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  25232. var _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  25233. // be matched to parse the rest of the track name.
  25234. var _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  25235. var _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  25236. // characters. Accessor may contain any character except closing bracket.
  25237. var _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  25238. // contain any non-bracket characters.
  25239. var _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  25240. var _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  25241. var _supportedObjectNames = ['material', 'materials', 'bones'];
  25242. function Composite(targetGroup, path, optionalParsedPath) {
  25243. var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  25244. this._targetGroup = targetGroup;
  25245. this._bindings = targetGroup.subscribe_(path, parsedPath);
  25246. }
  25247. Object.assign(Composite.prototype, {
  25248. getValue: function (array, offset) {
  25249. this.bind(); // bind all binding
  25250. var firstValidIndex = this._targetGroup.nCachedObjects_,
  25251. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  25252. if (binding !== undefined) binding.getValue(array, offset);
  25253. },
  25254. setValue: function (array, offset) {
  25255. var bindings = this._bindings;
  25256. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25257. bindings[i].setValue(array, offset);
  25258. }
  25259. },
  25260. bind: function () {
  25261. var bindings = this._bindings;
  25262. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25263. bindings[i].bind();
  25264. }
  25265. },
  25266. unbind: function () {
  25267. var bindings = this._bindings;
  25268. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25269. bindings[i].unbind();
  25270. }
  25271. }
  25272. });
  25273. function PropertyBinding(rootNode, path, parsedPath) {
  25274. this.path = path;
  25275. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  25276. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  25277. this.rootNode = rootNode;
  25278. }
  25279. Object.assign(PropertyBinding, {
  25280. Composite: Composite,
  25281. create: function (root, path, parsedPath) {
  25282. if (!(root && root.isAnimationObjectGroup)) {
  25283. return new PropertyBinding(root, path, parsedPath);
  25284. } else {
  25285. return new PropertyBinding.Composite(root, path, parsedPath);
  25286. }
  25287. },
  25288. /**
  25289. * Replaces spaces with underscores and removes unsupported characters from
  25290. * node names, to ensure compatibility with parseTrackName().
  25291. *
  25292. * @param {string} name Node name to be sanitized.
  25293. * @return {string}
  25294. */
  25295. sanitizeNodeName: function (name) {
  25296. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  25297. },
  25298. parseTrackName: function (trackName) {
  25299. var matches = _trackRe.exec(trackName);
  25300. if (!matches) {
  25301. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  25302. }
  25303. var results = {
  25304. // directoryName: matches[ 1 ], // (tschw) currently unused
  25305. nodeName: matches[2],
  25306. objectName: matches[3],
  25307. objectIndex: matches[4],
  25308. propertyName: matches[5],
  25309. // required
  25310. propertyIndex: matches[6]
  25311. };
  25312. var lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  25313. if (lastDot !== undefined && lastDot !== -1) {
  25314. var objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against a whitelist. Otherwise, there
  25315. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  25316. // 'bar' could be the objectName, or part of a nodeName (which can
  25317. // include '.' characters).
  25318. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  25319. results.nodeName = results.nodeName.substring(0, lastDot);
  25320. results.objectName = objectName;
  25321. }
  25322. }
  25323. if (results.propertyName === null || results.propertyName.length === 0) {
  25324. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  25325. }
  25326. return results;
  25327. },
  25328. findNode: function (root, nodeName) {
  25329. if (!nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  25330. return root;
  25331. } // search into skeleton bones.
  25332. if (root.skeleton) {
  25333. var bone = root.skeleton.getBoneByName(nodeName);
  25334. if (bone !== undefined) {
  25335. return bone;
  25336. }
  25337. } // search into node subtree.
  25338. if (root.children) {
  25339. var searchNodeSubtree = function (children) {
  25340. for (var i = 0; i < children.length; i++) {
  25341. var childNode = children[i];
  25342. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  25343. return childNode;
  25344. }
  25345. var result = searchNodeSubtree(childNode.children);
  25346. if (result) return result;
  25347. }
  25348. return null;
  25349. };
  25350. var subTreeNode = searchNodeSubtree(root.children);
  25351. if (subTreeNode) {
  25352. return subTreeNode;
  25353. }
  25354. }
  25355. return null;
  25356. }
  25357. });
  25358. Object.assign(PropertyBinding.prototype, {
  25359. // prototype, continued
  25360. // these are used to "bind" a nonexistent property
  25361. _getValue_unavailable: function () {},
  25362. _setValue_unavailable: function () {},
  25363. BindingType: {
  25364. Direct: 0,
  25365. EntireArray: 1,
  25366. ArrayElement: 2,
  25367. HasFromToArray: 3
  25368. },
  25369. Versioning: {
  25370. None: 0,
  25371. NeedsUpdate: 1,
  25372. MatrixWorldNeedsUpdate: 2
  25373. },
  25374. GetterByBindingType: [function getValue_direct(buffer, offset) {
  25375. buffer[offset] = this.node[this.propertyName];
  25376. }, function getValue_array(buffer, offset) {
  25377. var source = this.resolvedProperty;
  25378. for (var i = 0, n = source.length; i !== n; ++i) {
  25379. buffer[offset++] = source[i];
  25380. }
  25381. }, function getValue_arrayElement(buffer, offset) {
  25382. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  25383. }, function getValue_toArray(buffer, offset) {
  25384. this.resolvedProperty.toArray(buffer, offset);
  25385. }],
  25386. SetterByBindingTypeAndVersioning: [[// Direct
  25387. function setValue_direct(buffer, offset) {
  25388. this.targetObject[this.propertyName] = buffer[offset];
  25389. }, function setValue_direct_setNeedsUpdate(buffer, offset) {
  25390. this.targetObject[this.propertyName] = buffer[offset];
  25391. this.targetObject.needsUpdate = true;
  25392. }, function setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  25393. this.targetObject[this.propertyName] = buffer[offset];
  25394. this.targetObject.matrixWorldNeedsUpdate = true;
  25395. }], [// EntireArray
  25396. function setValue_array(buffer, offset) {
  25397. var dest = this.resolvedProperty;
  25398. for (var i = 0, n = dest.length; i !== n; ++i) {
  25399. dest[i] = buffer[offset++];
  25400. }
  25401. }, function setValue_array_setNeedsUpdate(buffer, offset) {
  25402. var dest = this.resolvedProperty;
  25403. for (var i = 0, n = dest.length; i !== n; ++i) {
  25404. dest[i] = buffer[offset++];
  25405. }
  25406. this.targetObject.needsUpdate = true;
  25407. }, function setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  25408. var dest = this.resolvedProperty;
  25409. for (var i = 0, n = dest.length; i !== n; ++i) {
  25410. dest[i] = buffer[offset++];
  25411. }
  25412. this.targetObject.matrixWorldNeedsUpdate = true;
  25413. }], [// ArrayElement
  25414. function setValue_arrayElement(buffer, offset) {
  25415. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25416. }, function setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  25417. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25418. this.targetObject.needsUpdate = true;
  25419. }, function setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  25420. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25421. this.targetObject.matrixWorldNeedsUpdate = true;
  25422. }], [// HasToFromArray
  25423. function setValue_fromArray(buffer, offset) {
  25424. this.resolvedProperty.fromArray(buffer, offset);
  25425. }, function setValue_fromArray_setNeedsUpdate(buffer, offset) {
  25426. this.resolvedProperty.fromArray(buffer, offset);
  25427. this.targetObject.needsUpdate = true;
  25428. }, function setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  25429. this.resolvedProperty.fromArray(buffer, offset);
  25430. this.targetObject.matrixWorldNeedsUpdate = true;
  25431. }]],
  25432. getValue: function getValue_unbound(targetArray, offset) {
  25433. this.bind();
  25434. this.getValue(targetArray, offset); // Note: This class uses a State pattern on a per-method basis:
  25435. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  25436. // prototype version of these methods with one that represents
  25437. // the bound state. When the property is not found, the methods
  25438. // become no-ops.
  25439. },
  25440. setValue: function getValue_unbound(sourceArray, offset) {
  25441. this.bind();
  25442. this.setValue(sourceArray, offset);
  25443. },
  25444. // create getter / setter pair for a property in the scene graph
  25445. bind: function () {
  25446. var targetObject = this.node,
  25447. parsedPath = this.parsedPath,
  25448. objectName = parsedPath.objectName,
  25449. propertyName = parsedPath.propertyName,
  25450. propertyIndex = parsedPath.propertyIndex;
  25451. if (!targetObject) {
  25452. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  25453. this.node = targetObject;
  25454. } // set fail state so we can just 'return' on error
  25455. this.getValue = this._getValue_unavailable;
  25456. this.setValue = this._setValue_unavailable; // ensure there is a value node
  25457. if (!targetObject) {
  25458. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  25459. return;
  25460. }
  25461. if (objectName) {
  25462. var objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  25463. switch (objectName) {
  25464. case 'materials':
  25465. if (!targetObject.material) {
  25466. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  25467. return;
  25468. }
  25469. if (!targetObject.material.materials) {
  25470. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  25471. return;
  25472. }
  25473. targetObject = targetObject.material.materials;
  25474. break;
  25475. case 'bones':
  25476. if (!targetObject.skeleton) {
  25477. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  25478. return;
  25479. } // potential future optimization: skip this if propertyIndex is already an integer
  25480. // and convert the integer string to a true integer.
  25481. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  25482. for (var i = 0; i < targetObject.length; i++) {
  25483. if (targetObject[i].name === objectIndex) {
  25484. objectIndex = i;
  25485. break;
  25486. }
  25487. }
  25488. break;
  25489. default:
  25490. if (targetObject[objectName] === undefined) {
  25491. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  25492. return;
  25493. }
  25494. targetObject = targetObject[objectName];
  25495. }
  25496. if (objectIndex !== undefined) {
  25497. if (targetObject[objectIndex] === undefined) {
  25498. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  25499. return;
  25500. }
  25501. targetObject = targetObject[objectIndex];
  25502. }
  25503. } // resolve property
  25504. var nodeProperty = targetObject[propertyName];
  25505. if (nodeProperty === undefined) {
  25506. var nodeName = parsedPath.nodeName;
  25507. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  25508. return;
  25509. } // determine versioning scheme
  25510. var versioning = this.Versioning.None;
  25511. this.targetObject = targetObject;
  25512. if (targetObject.needsUpdate !== undefined) {
  25513. // material
  25514. versioning = this.Versioning.NeedsUpdate;
  25515. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  25516. // node transform
  25517. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  25518. } // determine how the property gets bound
  25519. var bindingType = this.BindingType.Direct;
  25520. if (propertyIndex !== undefined) {
  25521. // access a sub element of the property array (only primitives are supported right now)
  25522. if (propertyName === "morphTargetInfluences") {
  25523. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  25524. // support resolving morphTarget names into indices.
  25525. if (!targetObject.geometry) {
  25526. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  25527. return;
  25528. }
  25529. if (targetObject.geometry.isBufferGeometry) {
  25530. if (!targetObject.geometry.morphAttributes) {
  25531. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  25532. return;
  25533. }
  25534. for (var i = 0; i < this.node.geometry.morphAttributes.position.length; i++) {
  25535. if (targetObject.geometry.morphAttributes.position[i].name === propertyIndex) {
  25536. propertyIndex = i;
  25537. break;
  25538. }
  25539. }
  25540. } else {
  25541. if (!targetObject.geometry.morphTargets) {
  25542. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.', this);
  25543. return;
  25544. }
  25545. for (var i = 0; i < this.node.geometry.morphTargets.length; i++) {
  25546. if (targetObject.geometry.morphTargets[i].name === propertyIndex) {
  25547. propertyIndex = i;
  25548. break;
  25549. }
  25550. }
  25551. }
  25552. }
  25553. bindingType = this.BindingType.ArrayElement;
  25554. this.resolvedProperty = nodeProperty;
  25555. this.propertyIndex = propertyIndex;
  25556. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  25557. // must use copy for Object3D.Euler/Quaternion
  25558. bindingType = this.BindingType.HasFromToArray;
  25559. this.resolvedProperty = nodeProperty;
  25560. } else if (Array.isArray(nodeProperty)) {
  25561. bindingType = this.BindingType.EntireArray;
  25562. this.resolvedProperty = nodeProperty;
  25563. } else {
  25564. this.propertyName = propertyName;
  25565. } // select getter / setter
  25566. this.getValue = this.GetterByBindingType[bindingType];
  25567. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  25568. },
  25569. unbind: function () {
  25570. this.node = null; // back to the prototype version of getValue / setValue
  25571. // note: avoiding to mutate the shape of 'this' via 'delete'
  25572. this.getValue = this._getValue_unbound;
  25573. this.setValue = this._setValue_unbound;
  25574. }
  25575. }); //!\ DECLARE ALIAS AFTER assign prototype !
  25576. Object.assign(PropertyBinding.prototype, {
  25577. // initial state of these methods that calls 'bind'
  25578. _getValue_unbound: PropertyBinding.prototype.getValue,
  25579. _setValue_unbound: PropertyBinding.prototype.setValue
  25580. });
  25581. /**
  25582. *
  25583. * A group of objects that receives a shared animation state.
  25584. *
  25585. * Usage:
  25586. *
  25587. * - Add objects you would otherwise pass as 'root' to the
  25588. * constructor or the .clipAction method of AnimationMixer.
  25589. *
  25590. * - Instead pass this object as 'root'.
  25591. *
  25592. * - You can also add and remove objects later when the mixer
  25593. * is running.
  25594. *
  25595. * Note:
  25596. *
  25597. * Objects of this class appear as one object to the mixer,
  25598. * so cache control of the individual objects must be done
  25599. * on the group.
  25600. *
  25601. * Limitation:
  25602. *
  25603. * - The animated properties must be compatible among the
  25604. * all objects in the group.
  25605. *
  25606. * - A single property can either be controlled through a
  25607. * target group or directly, but not both.
  25608. *
  25609. * @author tschw
  25610. */
  25611. function AnimationObjectGroup() {
  25612. this.uuid = _Math.generateUUID(); // cached objects followed by the active ones
  25613. this._objects = Array.prototype.slice.call(arguments);
  25614. this.nCachedObjects_ = 0; // threshold
  25615. // note: read by PropertyBinding.Composite
  25616. var indices = {};
  25617. this._indicesByUUID = indices; // for bookkeeping
  25618. for (var i = 0, n = arguments.length; i !== n; ++i) {
  25619. indices[arguments[i].uuid] = i;
  25620. }
  25621. this._paths = []; // inside: string
  25622. this._parsedPaths = []; // inside: { we don't care, here }
  25623. this._bindings = []; // inside: Array< PropertyBinding >
  25624. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  25625. var scope = this;
  25626. this.stats = {
  25627. objects: {
  25628. get total() {
  25629. return scope._objects.length;
  25630. },
  25631. get inUse() {
  25632. return this.total - scope.nCachedObjects_;
  25633. }
  25634. },
  25635. get bindingsPerObject() {
  25636. return scope._bindings.length;
  25637. }
  25638. };
  25639. }
  25640. Object.assign(AnimationObjectGroup.prototype, {
  25641. isAnimationObjectGroup: true,
  25642. add: function () {
  25643. var objects = this._objects,
  25644. nObjects = objects.length,
  25645. nCachedObjects = this.nCachedObjects_,
  25646. indicesByUUID = this._indicesByUUID,
  25647. paths = this._paths,
  25648. parsedPaths = this._parsedPaths,
  25649. bindings = this._bindings,
  25650. nBindings = bindings.length,
  25651. knownObject = undefined;
  25652. for (var i = 0, n = arguments.length; i !== n; ++i) {
  25653. var object = arguments[i],
  25654. uuid = object.uuid,
  25655. index = indicesByUUID[uuid];
  25656. if (index === undefined) {
  25657. // unknown object -> add it to the ACTIVE region
  25658. index = nObjects++;
  25659. indicesByUUID[uuid] = index;
  25660. objects.push(object); // accounting is done, now do the same for all bindings
  25661. for (var j = 0, m = nBindings; j !== m; ++j) {
  25662. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  25663. }
  25664. } else if (index < nCachedObjects) {
  25665. knownObject = objects[index]; // move existing object to the ACTIVE region
  25666. var firstActiveIndex = --nCachedObjects,
  25667. lastCachedObject = objects[firstActiveIndex];
  25668. indicesByUUID[lastCachedObject.uuid] = index;
  25669. objects[index] = lastCachedObject;
  25670. indicesByUUID[uuid] = firstActiveIndex;
  25671. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  25672. for (var j = 0, m = nBindings; j !== m; ++j) {
  25673. var bindingsForPath = bindings[j],
  25674. lastCached = bindingsForPath[firstActiveIndex],
  25675. binding = bindingsForPath[index];
  25676. bindingsForPath[index] = lastCached;
  25677. if (binding === undefined) {
  25678. // since we do not bother to create new bindings
  25679. // for objects that are cached, the binding may
  25680. // or may not exist
  25681. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  25682. }
  25683. bindingsForPath[firstActiveIndex] = binding;
  25684. }
  25685. } else if (objects[index] !== knownObject) {
  25686. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  25687. } // else the object is already where we want it to be
  25688. } // for arguments
  25689. this.nCachedObjects_ = nCachedObjects;
  25690. },
  25691. remove: function () {
  25692. var objects = this._objects,
  25693. nCachedObjects = this.nCachedObjects_,
  25694. indicesByUUID = this._indicesByUUID,
  25695. bindings = this._bindings,
  25696. nBindings = bindings.length;
  25697. for (var i = 0, n = arguments.length; i !== n; ++i) {
  25698. var object = arguments[i],
  25699. uuid = object.uuid,
  25700. index = indicesByUUID[uuid];
  25701. if (index !== undefined && index >= nCachedObjects) {
  25702. // move existing object into the CACHED region
  25703. var lastCachedIndex = nCachedObjects++,
  25704. firstActiveObject = objects[lastCachedIndex];
  25705. indicesByUUID[firstActiveObject.uuid] = index;
  25706. objects[index] = firstActiveObject;
  25707. indicesByUUID[uuid] = lastCachedIndex;
  25708. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  25709. for (var j = 0, m = nBindings; j !== m; ++j) {
  25710. var bindingsForPath = bindings[j],
  25711. firstActive = bindingsForPath[lastCachedIndex],
  25712. binding = bindingsForPath[index];
  25713. bindingsForPath[index] = firstActive;
  25714. bindingsForPath[lastCachedIndex] = binding;
  25715. }
  25716. }
  25717. } // for arguments
  25718. this.nCachedObjects_ = nCachedObjects;
  25719. },
  25720. // remove & forget
  25721. uncache: function () {
  25722. var objects = this._objects,
  25723. nObjects = objects.length,
  25724. nCachedObjects = this.nCachedObjects_,
  25725. indicesByUUID = this._indicesByUUID,
  25726. bindings = this._bindings,
  25727. nBindings = bindings.length;
  25728. for (var i = 0, n = arguments.length; i !== n; ++i) {
  25729. var object = arguments[i],
  25730. uuid = object.uuid,
  25731. index = indicesByUUID[uuid];
  25732. if (index !== undefined) {
  25733. delete indicesByUUID[uuid];
  25734. if (index < nCachedObjects) {
  25735. // object is cached, shrink the CACHED region
  25736. var firstActiveIndex = --nCachedObjects,
  25737. lastCachedObject = objects[firstActiveIndex],
  25738. lastIndex = --nObjects,
  25739. lastObject = objects[lastIndex]; // last cached object takes this object's place
  25740. indicesByUUID[lastCachedObject.uuid] = index;
  25741. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  25742. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  25743. objects[firstActiveIndex] = lastObject;
  25744. objects.pop(); // accounting is done, now do the same for all bindings
  25745. for (var j = 0, m = nBindings; j !== m; ++j) {
  25746. var bindingsForPath = bindings[j],
  25747. lastCached = bindingsForPath[firstActiveIndex],
  25748. last = bindingsForPath[lastIndex];
  25749. bindingsForPath[index] = lastCached;
  25750. bindingsForPath[firstActiveIndex] = last;
  25751. bindingsForPath.pop();
  25752. }
  25753. } else {
  25754. // object is active, just swap with the last and pop
  25755. var lastIndex = --nObjects,
  25756. lastObject = objects[lastIndex];
  25757. indicesByUUID[lastObject.uuid] = index;
  25758. objects[index] = lastObject;
  25759. objects.pop(); // accounting is done, now do the same for all bindings
  25760. for (var j = 0, m = nBindings; j !== m; ++j) {
  25761. var bindingsForPath = bindings[j];
  25762. bindingsForPath[index] = bindingsForPath[lastIndex];
  25763. bindingsForPath.pop();
  25764. }
  25765. } // cached or active
  25766. } // if object is known
  25767. } // for arguments
  25768. this.nCachedObjects_ = nCachedObjects;
  25769. },
  25770. // Internal interface used by befriended PropertyBinding.Composite:
  25771. subscribe_: function (path, parsedPath) {
  25772. // returns an array of bindings for the given path that is changed
  25773. // according to the contained objects in the group
  25774. var indicesByPath = this._bindingsIndicesByPath,
  25775. index = indicesByPath[path],
  25776. bindings = this._bindings;
  25777. if (index !== undefined) return bindings[index];
  25778. var paths = this._paths,
  25779. parsedPaths = this._parsedPaths,
  25780. objects = this._objects,
  25781. nObjects = objects.length,
  25782. nCachedObjects = this.nCachedObjects_,
  25783. bindingsForPath = new Array(nObjects);
  25784. index = bindings.length;
  25785. indicesByPath[path] = index;
  25786. paths.push(path);
  25787. parsedPaths.push(parsedPath);
  25788. bindings.push(bindingsForPath);
  25789. for (var i = nCachedObjects, n = objects.length; i !== n; ++i) {
  25790. var object = objects[i];
  25791. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  25792. }
  25793. return bindingsForPath;
  25794. },
  25795. unsubscribe_: function (path) {
  25796. // tells the group to forget about a property path and no longer
  25797. // update the array previously obtained with 'subscribe_'
  25798. var indicesByPath = this._bindingsIndicesByPath,
  25799. index = indicesByPath[path];
  25800. if (index !== undefined) {
  25801. var paths = this._paths,
  25802. parsedPaths = this._parsedPaths,
  25803. bindings = this._bindings,
  25804. lastBindingsIndex = bindings.length - 1,
  25805. lastBindings = bindings[lastBindingsIndex],
  25806. lastBindingsPath = path[lastBindingsIndex];
  25807. indicesByPath[lastBindingsPath] = index;
  25808. bindings[index] = lastBindings;
  25809. bindings.pop();
  25810. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  25811. parsedPaths.pop();
  25812. paths[index] = paths[lastBindingsIndex];
  25813. paths.pop();
  25814. }
  25815. }
  25816. });
  25817. /**
  25818. *
  25819. * Action provided by AnimationMixer for scheduling clip playback on specific
  25820. * objects.
  25821. *
  25822. * @author Ben Houston / http://clara.io/
  25823. * @author David Sarno / http://lighthaus.us/
  25824. * @author tschw
  25825. *
  25826. */
  25827. function AnimationAction(mixer, clip, localRoot) {
  25828. this._mixer = mixer;
  25829. this._clip = clip;
  25830. this._localRoot = localRoot || null;
  25831. var tracks = clip.tracks,
  25832. nTracks = tracks.length,
  25833. interpolants = new Array(nTracks);
  25834. var interpolantSettings = {
  25835. endingStart: ZeroCurvatureEnding,
  25836. endingEnd: ZeroCurvatureEnding
  25837. };
  25838. for (var i = 0; i !== nTracks; ++i) {
  25839. var interpolant = tracks[i].createInterpolant(null);
  25840. interpolants[i] = interpolant;
  25841. interpolant.settings = interpolantSettings;
  25842. }
  25843. this._interpolantSettings = interpolantSettings;
  25844. this._interpolants = interpolants; // bound by the mixer
  25845. // inside: PropertyMixer (managed by the mixer)
  25846. this._propertyBindings = new Array(nTracks);
  25847. this._cacheIndex = null; // for the memory manager
  25848. this._byClipCacheIndex = null; // for the memory manager
  25849. this._timeScaleInterpolant = null;
  25850. this._weightInterpolant = null;
  25851. this.loop = LoopRepeat;
  25852. this._loopCount = -1; // global mixer time when the action is to be started
  25853. // it's set back to 'null' upon start of the action
  25854. this._startTime = null; // scaled local time of the action
  25855. // gets clamped or wrapped to 0..clip.duration according to loop
  25856. this.time = 0;
  25857. this.timeScale = 1;
  25858. this._effectiveTimeScale = 1;
  25859. this.weight = 1;
  25860. this._effectiveWeight = 1;
  25861. this.repetitions = Infinity; // no. of repetitions when looping
  25862. this.paused = false; // true -> zero effective time scale
  25863. this.enabled = true; // false -> zero effective weight
  25864. this.clampWhenFinished = false; // keep feeding the last frame?
  25865. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  25866. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  25867. }
  25868. Object.assign(AnimationAction.prototype, {
  25869. // State & Scheduling
  25870. play: function () {
  25871. this._mixer._activateAction(this);
  25872. return this;
  25873. },
  25874. stop: function () {
  25875. this._mixer._deactivateAction(this);
  25876. return this.reset();
  25877. },
  25878. reset: function () {
  25879. this.paused = false;
  25880. this.enabled = true;
  25881. this.time = 0; // restart clip
  25882. this._loopCount = -1; // forget previous loops
  25883. this._startTime = null; // forget scheduling
  25884. return this.stopFading().stopWarping();
  25885. },
  25886. isRunning: function () {
  25887. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  25888. },
  25889. // return true when play has been called
  25890. isScheduled: function () {
  25891. return this._mixer._isActiveAction(this);
  25892. },
  25893. startAt: function (time) {
  25894. this._startTime = time;
  25895. return this;
  25896. },
  25897. setLoop: function (mode, repetitions) {
  25898. this.loop = mode;
  25899. this.repetitions = repetitions;
  25900. return this;
  25901. },
  25902. // Weight
  25903. // set the weight stopping any scheduled fading
  25904. // although .enabled = false yields an effective weight of zero, this
  25905. // method does *not* change .enabled, because it would be confusing
  25906. setEffectiveWeight: function (weight) {
  25907. this.weight = weight; // note: same logic as when updated at runtime
  25908. this._effectiveWeight = this.enabled ? weight : 0;
  25909. return this.stopFading();
  25910. },
  25911. // return the weight considering fading and .enabled
  25912. getEffectiveWeight: function () {
  25913. return this._effectiveWeight;
  25914. },
  25915. fadeIn: function (duration) {
  25916. return this._scheduleFading(duration, 0, 1);
  25917. },
  25918. fadeOut: function (duration) {
  25919. return this._scheduleFading(duration, 1, 0);
  25920. },
  25921. crossFadeFrom: function (fadeOutAction, duration, warp) {
  25922. fadeOutAction.fadeOut(duration);
  25923. this.fadeIn(duration);
  25924. if (warp) {
  25925. var fadeInDuration = this._clip.duration,
  25926. fadeOutDuration = fadeOutAction._clip.duration,
  25927. startEndRatio = fadeOutDuration / fadeInDuration,
  25928. endStartRatio = fadeInDuration / fadeOutDuration;
  25929. fadeOutAction.warp(1.0, startEndRatio, duration);
  25930. this.warp(endStartRatio, 1.0, duration);
  25931. }
  25932. return this;
  25933. },
  25934. crossFadeTo: function (fadeInAction, duration, warp) {
  25935. return fadeInAction.crossFadeFrom(this, duration, warp);
  25936. },
  25937. stopFading: function () {
  25938. var weightInterpolant = this._weightInterpolant;
  25939. if (weightInterpolant !== null) {
  25940. this._weightInterpolant = null;
  25941. this._mixer._takeBackControlInterpolant(weightInterpolant);
  25942. }
  25943. return this;
  25944. },
  25945. // Time Scale Control
  25946. // set the time scale stopping any scheduled warping
  25947. // although .paused = true yields an effective time scale of zero, this
  25948. // method does *not* change .paused, because it would be confusing
  25949. setEffectiveTimeScale: function (timeScale) {
  25950. this.timeScale = timeScale;
  25951. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  25952. return this.stopWarping();
  25953. },
  25954. // return the time scale considering warping and .paused
  25955. getEffectiveTimeScale: function () {
  25956. return this._effectiveTimeScale;
  25957. },
  25958. setDuration: function (duration) {
  25959. this.timeScale = this._clip.duration / duration;
  25960. return this.stopWarping();
  25961. },
  25962. syncWith: function (action) {
  25963. this.time = action.time;
  25964. this.timeScale = action.timeScale;
  25965. return this.stopWarping();
  25966. },
  25967. halt: function (duration) {
  25968. return this.warp(this._effectiveTimeScale, 0, duration);
  25969. },
  25970. warp: function (startTimeScale, endTimeScale, duration) {
  25971. var mixer = this._mixer,
  25972. now = mixer.time,
  25973. interpolant = this._timeScaleInterpolant,
  25974. timeScale = this.timeScale;
  25975. if (interpolant === null) {
  25976. interpolant = mixer._lendControlInterpolant();
  25977. this._timeScaleInterpolant = interpolant;
  25978. }
  25979. var times = interpolant.parameterPositions,
  25980. values = interpolant.sampleValues;
  25981. times[0] = now;
  25982. times[1] = now + duration;
  25983. values[0] = startTimeScale / timeScale;
  25984. values[1] = endTimeScale / timeScale;
  25985. return this;
  25986. },
  25987. stopWarping: function () {
  25988. var timeScaleInterpolant = this._timeScaleInterpolant;
  25989. if (timeScaleInterpolant !== null) {
  25990. this._timeScaleInterpolant = null;
  25991. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  25992. }
  25993. return this;
  25994. },
  25995. // Object Accessors
  25996. getMixer: function () {
  25997. return this._mixer;
  25998. },
  25999. getClip: function () {
  26000. return this._clip;
  26001. },
  26002. getRoot: function () {
  26003. return this._localRoot || this._mixer._root;
  26004. },
  26005. // Interna
  26006. _update: function (time, deltaTime, timeDirection, accuIndex) {
  26007. // called by the mixer
  26008. if (!this.enabled) {
  26009. // call ._updateWeight() to update ._effectiveWeight
  26010. this._updateWeight(time);
  26011. return;
  26012. }
  26013. var startTime = this._startTime;
  26014. if (startTime !== null) {
  26015. // check for scheduled start of action
  26016. var timeRunning = (time - startTime) * timeDirection;
  26017. if (timeRunning < 0 || timeDirection === 0) {
  26018. return; // yet to come / don't decide when delta = 0
  26019. } // start
  26020. this._startTime = null; // unschedule
  26021. deltaTime = timeDirection * timeRunning;
  26022. } // apply time scale and advance time
  26023. deltaTime *= this._updateTimeScale(time);
  26024. var clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  26025. // an effective weight of 0
  26026. var weight = this._updateWeight(time);
  26027. if (weight > 0) {
  26028. var interpolants = this._interpolants;
  26029. var propertyMixers = this._propertyBindings;
  26030. for (var j = 0, m = interpolants.length; j !== m; ++j) {
  26031. interpolants[j].evaluate(clipTime);
  26032. propertyMixers[j].accumulate(accuIndex, weight);
  26033. }
  26034. }
  26035. },
  26036. _updateWeight: function (time) {
  26037. var weight = 0;
  26038. if (this.enabled) {
  26039. weight = this.weight;
  26040. var interpolant = this._weightInterpolant;
  26041. if (interpolant !== null) {
  26042. var interpolantValue = interpolant.evaluate(time)[0];
  26043. weight *= interpolantValue;
  26044. if (time > interpolant.parameterPositions[1]) {
  26045. this.stopFading();
  26046. if (interpolantValue === 0) {
  26047. // faded out, disable
  26048. this.enabled = false;
  26049. }
  26050. }
  26051. }
  26052. }
  26053. this._effectiveWeight = weight;
  26054. return weight;
  26055. },
  26056. _updateTimeScale: function (time) {
  26057. var timeScale = 0;
  26058. if (!this.paused) {
  26059. timeScale = this.timeScale;
  26060. var interpolant = this._timeScaleInterpolant;
  26061. if (interpolant !== null) {
  26062. var interpolantValue = interpolant.evaluate(time)[0];
  26063. timeScale *= interpolantValue;
  26064. if (time > interpolant.parameterPositions[1]) {
  26065. this.stopWarping();
  26066. if (timeScale === 0) {
  26067. // motion has halted, pause
  26068. this.paused = true;
  26069. } else {
  26070. // warp done - apply final time scale
  26071. this.timeScale = timeScale;
  26072. }
  26073. }
  26074. }
  26075. }
  26076. this._effectiveTimeScale = timeScale;
  26077. return timeScale;
  26078. },
  26079. _updateTime: function (deltaTime) {
  26080. var time = this.time + deltaTime;
  26081. var duration = this._clip.duration;
  26082. var loop = this.loop;
  26083. var loopCount = this._loopCount;
  26084. var pingPong = loop === LoopPingPong;
  26085. if (deltaTime === 0) {
  26086. if (loopCount === -1) return time;
  26087. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  26088. }
  26089. if (loop === LoopOnce) {
  26090. if (loopCount === -1) {
  26091. // just started
  26092. this._loopCount = 0;
  26093. this._setEndings(true, true, false);
  26094. }
  26095. handle_stop: {
  26096. if (time >= duration) {
  26097. time = duration;
  26098. } else if (time < 0) {
  26099. time = 0;
  26100. } else {
  26101. this.time = time;
  26102. break handle_stop;
  26103. }
  26104. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26105. this.time = time;
  26106. this._mixer.dispatchEvent({
  26107. type: 'finished',
  26108. action: this,
  26109. direction: deltaTime < 0 ? -1 : 1
  26110. });
  26111. }
  26112. } else {
  26113. // repetitive Repeat or PingPong
  26114. if (loopCount === -1) {
  26115. // just started
  26116. if (deltaTime >= 0) {
  26117. loopCount = 0;
  26118. this._setEndings(true, this.repetitions === 0, pingPong);
  26119. } else {
  26120. // when looping in reverse direction, the initial
  26121. // transition through zero counts as a repetition,
  26122. // so leave loopCount at -1
  26123. this._setEndings(this.repetitions === 0, true, pingPong);
  26124. }
  26125. }
  26126. if (time >= duration || time < 0) {
  26127. // wrap around
  26128. var loopDelta = Math.floor(time / duration); // signed
  26129. time -= duration * loopDelta;
  26130. loopCount += Math.abs(loopDelta);
  26131. var pending = this.repetitions - loopCount;
  26132. if (pending <= 0) {
  26133. // have to stop (switch state, clamp time, fire event)
  26134. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26135. time = deltaTime > 0 ? duration : 0;
  26136. this.time = time;
  26137. this._mixer.dispatchEvent({
  26138. type: 'finished',
  26139. action: this,
  26140. direction: deltaTime > 0 ? 1 : -1
  26141. });
  26142. } else {
  26143. // keep running
  26144. if (pending === 1) {
  26145. // entering the last round
  26146. var atStart = deltaTime < 0;
  26147. this._setEndings(atStart, !atStart, pingPong);
  26148. } else {
  26149. this._setEndings(false, false, pingPong);
  26150. }
  26151. this._loopCount = loopCount;
  26152. this.time = time;
  26153. this._mixer.dispatchEvent({
  26154. type: 'loop',
  26155. action: this,
  26156. loopDelta: loopDelta
  26157. });
  26158. }
  26159. } else {
  26160. this.time = time;
  26161. }
  26162. if (pingPong && (loopCount & 1) === 1) {
  26163. // invert time for the "pong round"
  26164. return duration - time;
  26165. }
  26166. }
  26167. return time;
  26168. },
  26169. _setEndings: function (atStart, atEnd, pingPong) {
  26170. var settings = this._interpolantSettings;
  26171. if (pingPong) {
  26172. settings.endingStart = ZeroSlopeEnding;
  26173. settings.endingEnd = ZeroSlopeEnding;
  26174. } else {
  26175. // assuming for LoopOnce atStart == atEnd == true
  26176. if (atStart) {
  26177. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26178. } else {
  26179. settings.endingStart = WrapAroundEnding;
  26180. }
  26181. if (atEnd) {
  26182. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26183. } else {
  26184. settings.endingEnd = WrapAroundEnding;
  26185. }
  26186. }
  26187. },
  26188. _scheduleFading: function (duration, weightNow, weightThen) {
  26189. var mixer = this._mixer,
  26190. now = mixer.time,
  26191. interpolant = this._weightInterpolant;
  26192. if (interpolant === null) {
  26193. interpolant = mixer._lendControlInterpolant();
  26194. this._weightInterpolant = interpolant;
  26195. }
  26196. var times = interpolant.parameterPositions,
  26197. values = interpolant.sampleValues;
  26198. times[0] = now;
  26199. values[0] = weightNow;
  26200. times[1] = now + duration;
  26201. values[1] = weightThen;
  26202. return this;
  26203. }
  26204. });
  26205. /**
  26206. *
  26207. * Player for AnimationClips.
  26208. *
  26209. *
  26210. * @author Ben Houston / http://clara.io/
  26211. * @author David Sarno / http://lighthaus.us/
  26212. * @author tschw
  26213. */
  26214. function AnimationMixer(root) {
  26215. this._root = root;
  26216. this._initMemoryManager();
  26217. this._accuIndex = 0;
  26218. this.time = 0;
  26219. this.timeScale = 1.0;
  26220. }
  26221. AnimationMixer.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  26222. constructor: AnimationMixer,
  26223. _bindAction: function (action, prototypeAction) {
  26224. var root = action._localRoot || this._root,
  26225. tracks = action._clip.tracks,
  26226. nTracks = tracks.length,
  26227. bindings = action._propertyBindings,
  26228. interpolants = action._interpolants,
  26229. rootUuid = root.uuid,
  26230. bindingsByRoot = this._bindingsByRootAndName,
  26231. bindingsByName = bindingsByRoot[rootUuid];
  26232. if (bindingsByName === undefined) {
  26233. bindingsByName = {};
  26234. bindingsByRoot[rootUuid] = bindingsByName;
  26235. }
  26236. for (var i = 0; i !== nTracks; ++i) {
  26237. var track = tracks[i],
  26238. trackName = track.name,
  26239. binding = bindingsByName[trackName];
  26240. if (binding !== undefined) {
  26241. bindings[i] = binding;
  26242. } else {
  26243. binding = bindings[i];
  26244. if (binding !== undefined) {
  26245. // existing binding, make sure the cache knows
  26246. if (binding._cacheIndex === null) {
  26247. ++binding.referenceCount;
  26248. this._addInactiveBinding(binding, rootUuid, trackName);
  26249. }
  26250. continue;
  26251. }
  26252. var path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  26253. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  26254. ++binding.referenceCount;
  26255. this._addInactiveBinding(binding, rootUuid, trackName);
  26256. bindings[i] = binding;
  26257. }
  26258. interpolants[i].resultBuffer = binding.buffer;
  26259. }
  26260. },
  26261. _activateAction: function (action) {
  26262. if (!this._isActiveAction(action)) {
  26263. if (action._cacheIndex === null) {
  26264. // this action has been forgotten by the cache, but the user
  26265. // appears to be still using it -> rebind
  26266. var rootUuid = (action._localRoot || this._root).uuid,
  26267. clipUuid = action._clip.uuid,
  26268. actionsForClip = this._actionsByClip[clipUuid];
  26269. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  26270. this._addInactiveAction(action, clipUuid, rootUuid);
  26271. }
  26272. var bindings = action._propertyBindings; // increment reference counts / sort out state
  26273. for (var i = 0, n = bindings.length; i !== n; ++i) {
  26274. var binding = bindings[i];
  26275. if (binding.useCount++ === 0) {
  26276. this._lendBinding(binding);
  26277. binding.saveOriginalState();
  26278. }
  26279. }
  26280. this._lendAction(action);
  26281. }
  26282. },
  26283. _deactivateAction: function (action) {
  26284. if (this._isActiveAction(action)) {
  26285. var bindings = action._propertyBindings; // decrement reference counts / sort out state
  26286. for (var i = 0, n = bindings.length; i !== n; ++i) {
  26287. var binding = bindings[i];
  26288. if (--binding.useCount === 0) {
  26289. binding.restoreOriginalState();
  26290. this._takeBackBinding(binding);
  26291. }
  26292. }
  26293. this._takeBackAction(action);
  26294. }
  26295. },
  26296. // Memory manager
  26297. _initMemoryManager: function () {
  26298. this._actions = []; // 'nActiveActions' followed by inactive ones
  26299. this._nActiveActions = 0;
  26300. this._actionsByClip = {}; // inside:
  26301. // {
  26302. // knownActions: Array< AnimationAction > - used as prototypes
  26303. // actionByRoot: AnimationAction - lookup
  26304. // }
  26305. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  26306. this._nActiveBindings = 0;
  26307. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  26308. this._controlInterpolants = []; // same game as above
  26309. this._nActiveControlInterpolants = 0;
  26310. var scope = this;
  26311. this.stats = {
  26312. actions: {
  26313. get total() {
  26314. return scope._actions.length;
  26315. },
  26316. get inUse() {
  26317. return scope._nActiveActions;
  26318. }
  26319. },
  26320. bindings: {
  26321. get total() {
  26322. return scope._bindings.length;
  26323. },
  26324. get inUse() {
  26325. return scope._nActiveBindings;
  26326. }
  26327. },
  26328. controlInterpolants: {
  26329. get total() {
  26330. return scope._controlInterpolants.length;
  26331. },
  26332. get inUse() {
  26333. return scope._nActiveControlInterpolants;
  26334. }
  26335. }
  26336. };
  26337. },
  26338. // Memory management for AnimationAction objects
  26339. _isActiveAction: function (action) {
  26340. var index = action._cacheIndex;
  26341. return index !== null && index < this._nActiveActions;
  26342. },
  26343. _addInactiveAction: function (action, clipUuid, rootUuid) {
  26344. var actions = this._actions,
  26345. actionsByClip = this._actionsByClip,
  26346. actionsForClip = actionsByClip[clipUuid];
  26347. if (actionsForClip === undefined) {
  26348. actionsForClip = {
  26349. knownActions: [action],
  26350. actionByRoot: {}
  26351. };
  26352. action._byClipCacheIndex = 0;
  26353. actionsByClip[clipUuid] = actionsForClip;
  26354. } else {
  26355. var knownActions = actionsForClip.knownActions;
  26356. action._byClipCacheIndex = knownActions.length;
  26357. knownActions.push(action);
  26358. }
  26359. action._cacheIndex = actions.length;
  26360. actions.push(action);
  26361. actionsForClip.actionByRoot[rootUuid] = action;
  26362. },
  26363. _removeInactiveAction: function (action) {
  26364. var actions = this._actions,
  26365. lastInactiveAction = actions[actions.length - 1],
  26366. cacheIndex = action._cacheIndex;
  26367. lastInactiveAction._cacheIndex = cacheIndex;
  26368. actions[cacheIndex] = lastInactiveAction;
  26369. actions.pop();
  26370. action._cacheIndex = null;
  26371. var clipUuid = action._clip.uuid,
  26372. actionsByClip = this._actionsByClip,
  26373. actionsForClip = actionsByClip[clipUuid],
  26374. knownActionsForClip = actionsForClip.knownActions,
  26375. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  26376. byClipCacheIndex = action._byClipCacheIndex;
  26377. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  26378. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  26379. knownActionsForClip.pop();
  26380. action._byClipCacheIndex = null;
  26381. var actionByRoot = actionsForClip.actionByRoot,
  26382. rootUuid = (action._localRoot || this._root).uuid;
  26383. delete actionByRoot[rootUuid];
  26384. if (knownActionsForClip.length === 0) {
  26385. delete actionsByClip[clipUuid];
  26386. }
  26387. this._removeInactiveBindingsForAction(action);
  26388. },
  26389. _removeInactiveBindingsForAction: function (action) {
  26390. var bindings = action._propertyBindings;
  26391. for (var i = 0, n = bindings.length; i !== n; ++i) {
  26392. var binding = bindings[i];
  26393. if (--binding.referenceCount === 0) {
  26394. this._removeInactiveBinding(binding);
  26395. }
  26396. }
  26397. },
  26398. _lendAction: function (action) {
  26399. // [ active actions | inactive actions ]
  26400. // [ active actions >| inactive actions ]
  26401. // s a
  26402. // <-swap->
  26403. // a s
  26404. var actions = this._actions,
  26405. prevIndex = action._cacheIndex,
  26406. lastActiveIndex = this._nActiveActions++,
  26407. firstInactiveAction = actions[lastActiveIndex];
  26408. action._cacheIndex = lastActiveIndex;
  26409. actions[lastActiveIndex] = action;
  26410. firstInactiveAction._cacheIndex = prevIndex;
  26411. actions[prevIndex] = firstInactiveAction;
  26412. },
  26413. _takeBackAction: function (action) {
  26414. // [ active actions | inactive actions ]
  26415. // [ active actions |< inactive actions ]
  26416. // a s
  26417. // <-swap->
  26418. // s a
  26419. var actions = this._actions,
  26420. prevIndex = action._cacheIndex,
  26421. firstInactiveIndex = --this._nActiveActions,
  26422. lastActiveAction = actions[firstInactiveIndex];
  26423. action._cacheIndex = firstInactiveIndex;
  26424. actions[firstInactiveIndex] = action;
  26425. lastActiveAction._cacheIndex = prevIndex;
  26426. actions[prevIndex] = lastActiveAction;
  26427. },
  26428. // Memory management for PropertyMixer objects
  26429. _addInactiveBinding: function (binding, rootUuid, trackName) {
  26430. var bindingsByRoot = this._bindingsByRootAndName,
  26431. bindingByName = bindingsByRoot[rootUuid],
  26432. bindings = this._bindings;
  26433. if (bindingByName === undefined) {
  26434. bindingByName = {};
  26435. bindingsByRoot[rootUuid] = bindingByName;
  26436. }
  26437. bindingByName[trackName] = binding;
  26438. binding._cacheIndex = bindings.length;
  26439. bindings.push(binding);
  26440. },
  26441. _removeInactiveBinding: function (binding) {
  26442. var bindings = this._bindings,
  26443. propBinding = binding.binding,
  26444. rootUuid = propBinding.rootNode.uuid,
  26445. trackName = propBinding.path,
  26446. bindingsByRoot = this._bindingsByRootAndName,
  26447. bindingByName = bindingsByRoot[rootUuid],
  26448. lastInactiveBinding = bindings[bindings.length - 1],
  26449. cacheIndex = binding._cacheIndex;
  26450. lastInactiveBinding._cacheIndex = cacheIndex;
  26451. bindings[cacheIndex] = lastInactiveBinding;
  26452. bindings.pop();
  26453. delete bindingByName[trackName];
  26454. if (Object.keys(bindingByName).length === 0) {
  26455. delete bindingsByRoot[rootUuid];
  26456. }
  26457. },
  26458. _lendBinding: function (binding) {
  26459. var bindings = this._bindings,
  26460. prevIndex = binding._cacheIndex,
  26461. lastActiveIndex = this._nActiveBindings++,
  26462. firstInactiveBinding = bindings[lastActiveIndex];
  26463. binding._cacheIndex = lastActiveIndex;
  26464. bindings[lastActiveIndex] = binding;
  26465. firstInactiveBinding._cacheIndex = prevIndex;
  26466. bindings[prevIndex] = firstInactiveBinding;
  26467. },
  26468. _takeBackBinding: function (binding) {
  26469. var bindings = this._bindings,
  26470. prevIndex = binding._cacheIndex,
  26471. firstInactiveIndex = --this._nActiveBindings,
  26472. lastActiveBinding = bindings[firstInactiveIndex];
  26473. binding._cacheIndex = firstInactiveIndex;
  26474. bindings[firstInactiveIndex] = binding;
  26475. lastActiveBinding._cacheIndex = prevIndex;
  26476. bindings[prevIndex] = lastActiveBinding;
  26477. },
  26478. // Memory management of Interpolants for weight and time scale
  26479. _lendControlInterpolant: function () {
  26480. var interpolants = this._controlInterpolants,
  26481. lastActiveIndex = this._nActiveControlInterpolants++,
  26482. interpolant = interpolants[lastActiveIndex];
  26483. if (interpolant === undefined) {
  26484. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
  26485. interpolant.__cacheIndex = lastActiveIndex;
  26486. interpolants[lastActiveIndex] = interpolant;
  26487. }
  26488. return interpolant;
  26489. },
  26490. _takeBackControlInterpolant: function (interpolant) {
  26491. var interpolants = this._controlInterpolants,
  26492. prevIndex = interpolant.__cacheIndex,
  26493. firstInactiveIndex = --this._nActiveControlInterpolants,
  26494. lastActiveInterpolant = interpolants[firstInactiveIndex];
  26495. interpolant.__cacheIndex = firstInactiveIndex;
  26496. interpolants[firstInactiveIndex] = interpolant;
  26497. lastActiveInterpolant.__cacheIndex = prevIndex;
  26498. interpolants[prevIndex] = lastActiveInterpolant;
  26499. },
  26500. _controlInterpolantsResultBuffer: new Float32Array(1),
  26501. // return an action for a clip optionally using a custom root target
  26502. // object (this method allocates a lot of dynamic memory in case a
  26503. // previously unknown clip/root combination is specified)
  26504. clipAction: function (clip, optionalRoot) {
  26505. var root = optionalRoot || this._root,
  26506. rootUuid = root.uuid,
  26507. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  26508. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  26509. actionsForClip = this._actionsByClip[clipUuid],
  26510. prototypeAction = null;
  26511. if (actionsForClip !== undefined) {
  26512. var existingAction = actionsForClip.actionByRoot[rootUuid];
  26513. if (existingAction !== undefined) {
  26514. return existingAction;
  26515. } // we know the clip, so we don't have to parse all
  26516. // the bindings again but can just copy
  26517. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  26518. if (clipObject === null) clipObject = prototypeAction._clip;
  26519. } // clip must be known when specified via string
  26520. if (clipObject === null) return null; // allocate all resources required to run it
  26521. var newAction = new AnimationAction(this, clipObject, optionalRoot);
  26522. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  26523. this._addInactiveAction(newAction, clipUuid, rootUuid);
  26524. return newAction;
  26525. },
  26526. // get an existing action
  26527. existingAction: function (clip, optionalRoot) {
  26528. var root = optionalRoot || this._root,
  26529. rootUuid = root.uuid,
  26530. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  26531. clipUuid = clipObject ? clipObject.uuid : clip,
  26532. actionsForClip = this._actionsByClip[clipUuid];
  26533. if (actionsForClip !== undefined) {
  26534. return actionsForClip.actionByRoot[rootUuid] || null;
  26535. }
  26536. return null;
  26537. },
  26538. // deactivates all previously scheduled actions
  26539. stopAllAction: function () {
  26540. var actions = this._actions,
  26541. nActions = this._nActiveActions,
  26542. bindings = this._bindings,
  26543. nBindings = this._nActiveBindings;
  26544. this._nActiveActions = 0;
  26545. this._nActiveBindings = 0;
  26546. for (var i = 0; i !== nActions; ++i) {
  26547. actions[i].reset();
  26548. }
  26549. for (var i = 0; i !== nBindings; ++i) {
  26550. bindings[i].useCount = 0;
  26551. }
  26552. return this;
  26553. },
  26554. // advance the time and update apply the animation
  26555. update: function (deltaTime) {
  26556. deltaTime *= this.timeScale;
  26557. var actions = this._actions,
  26558. nActions = this._nActiveActions,
  26559. time = this.time += deltaTime,
  26560. timeDirection = Math.sign(deltaTime),
  26561. accuIndex = this._accuIndex ^= 1; // run active actions
  26562. for (var i = 0; i !== nActions; ++i) {
  26563. var action = actions[i];
  26564. action._update(time, deltaTime, timeDirection, accuIndex);
  26565. } // update scene graph
  26566. var bindings = this._bindings,
  26567. nBindings = this._nActiveBindings;
  26568. for (var i = 0; i !== nBindings; ++i) {
  26569. bindings[i].apply(accuIndex);
  26570. }
  26571. return this;
  26572. },
  26573. // Allows you to seek to a specific time in an animation.
  26574. setTime: function (timeInSeconds) {
  26575. this.time = 0; // Zero out time attribute for AnimationMixer object;
  26576. for (var i = 0; i < this._actions.length; i++) {
  26577. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  26578. }
  26579. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  26580. },
  26581. // return this mixer's root target object
  26582. getRoot: function () {
  26583. return this._root;
  26584. },
  26585. // free all resources specific to a particular clip
  26586. uncacheClip: function (clip) {
  26587. var actions = this._actions,
  26588. clipUuid = clip.uuid,
  26589. actionsByClip = this._actionsByClip,
  26590. actionsForClip = actionsByClip[clipUuid];
  26591. if (actionsForClip !== undefined) {
  26592. // note: just calling _removeInactiveAction would mess up the
  26593. // iteration state and also require updating the state we can
  26594. // just throw away
  26595. var actionsToRemove = actionsForClip.knownActions;
  26596. for (var i = 0, n = actionsToRemove.length; i !== n; ++i) {
  26597. var action = actionsToRemove[i];
  26598. this._deactivateAction(action);
  26599. var cacheIndex = action._cacheIndex,
  26600. lastInactiveAction = actions[actions.length - 1];
  26601. action._cacheIndex = null;
  26602. action._byClipCacheIndex = null;
  26603. lastInactiveAction._cacheIndex = cacheIndex;
  26604. actions[cacheIndex] = lastInactiveAction;
  26605. actions.pop();
  26606. this._removeInactiveBindingsForAction(action);
  26607. }
  26608. delete actionsByClip[clipUuid];
  26609. }
  26610. },
  26611. // free all resources specific to a particular root target object
  26612. uncacheRoot: function (root) {
  26613. var rootUuid = root.uuid,
  26614. actionsByClip = this._actionsByClip;
  26615. for (var clipUuid in actionsByClip) {
  26616. var actionByRoot = actionsByClip[clipUuid].actionByRoot,
  26617. action = actionByRoot[rootUuid];
  26618. if (action !== undefined) {
  26619. this._deactivateAction(action);
  26620. this._removeInactiveAction(action);
  26621. }
  26622. }
  26623. var bindingsByRoot = this._bindingsByRootAndName,
  26624. bindingByName = bindingsByRoot[rootUuid];
  26625. if (bindingByName !== undefined) {
  26626. for (var trackName in bindingByName) {
  26627. var binding = bindingByName[trackName];
  26628. binding.restoreOriginalState();
  26629. this._removeInactiveBinding(binding);
  26630. }
  26631. }
  26632. },
  26633. // remove a targeted clip from the cache
  26634. uncacheAction: function (clip, optionalRoot) {
  26635. var action = this.existingAction(clip, optionalRoot);
  26636. if (action !== null) {
  26637. this._deactivateAction(action);
  26638. this._removeInactiveAction(action);
  26639. }
  26640. }
  26641. });
  26642. /**
  26643. * @author mrdoob / http://mrdoob.com/
  26644. */
  26645. function Uniform(value) {
  26646. if (typeof value === 'string') {
  26647. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  26648. value = arguments[1];
  26649. }
  26650. this.value = value;
  26651. }
  26652. Uniform.prototype.clone = function () {
  26653. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  26654. };
  26655. /**
  26656. * @author benaadams / https://twitter.com/ben_a_adams
  26657. */
  26658. function InstancedInterleavedBuffer(array, stride, meshPerAttribute) {
  26659. InterleavedBuffer.call(this, array, stride);
  26660. this.meshPerAttribute = meshPerAttribute || 1;
  26661. }
  26662. InstancedInterleavedBuffer.prototype = Object.assign(Object.create(InterleavedBuffer.prototype), {
  26663. constructor: InstancedInterleavedBuffer,
  26664. isInstancedInterleavedBuffer: true,
  26665. copy: function (source) {
  26666. InterleavedBuffer.prototype.copy.call(this, source);
  26667. this.meshPerAttribute = source.meshPerAttribute;
  26668. return this;
  26669. }
  26670. });
  26671. /**
  26672. * @author mrdoob / http://mrdoob.com/
  26673. * @author bhouston / http://clara.io/
  26674. * @author stephomi / http://stephaneginier.com/
  26675. */
  26676. function Raycaster(origin, direction, near, far) {
  26677. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  26678. this.near = near || 0;
  26679. this.far = far || Infinity;
  26680. this.camera = null;
  26681. this.params = {
  26682. Mesh: {},
  26683. Line: {},
  26684. LOD: {},
  26685. Points: {
  26686. threshold: 1
  26687. },
  26688. Sprite: {}
  26689. };
  26690. Object.defineProperties(this.params, {
  26691. PointCloud: {
  26692. get: function () {
  26693. console.warn('THREE.Raycaster: params.PointCloud has been renamed to params.Points.');
  26694. return this.Points;
  26695. }
  26696. }
  26697. });
  26698. }
  26699. function ascSort(a, b) {
  26700. return a.distance - b.distance;
  26701. }
  26702. function intersectObject(object, raycaster, intersects, recursive) {
  26703. if (object.visible === false) return;
  26704. object.raycast(raycaster, intersects);
  26705. if (recursive === true) {
  26706. var children = object.children;
  26707. for (var i = 0, l = children.length; i < l; i++) {
  26708. intersectObject(children[i], raycaster, intersects, true);
  26709. }
  26710. }
  26711. }
  26712. Object.assign(Raycaster.prototype, {
  26713. linePrecision: 1,
  26714. set: function (origin, direction) {
  26715. // direction is assumed to be normalized (for accurate distance calculations)
  26716. this.ray.set(origin, direction);
  26717. },
  26718. setFromCamera: function (coords, camera) {
  26719. if (camera && camera.isPerspectiveCamera) {
  26720. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  26721. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  26722. this.camera = camera;
  26723. } else if (camera && camera.isOrthographicCamera) {
  26724. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  26725. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  26726. this.camera = camera;
  26727. } else {
  26728. console.error('THREE.Raycaster: Unsupported camera type.');
  26729. }
  26730. },
  26731. intersectObject: function (object, recursive, optionalTarget) {
  26732. var intersects = optionalTarget || [];
  26733. intersectObject(object, this, intersects, recursive);
  26734. intersects.sort(ascSort);
  26735. return intersects;
  26736. },
  26737. intersectObjects: function (objects, recursive, optionalTarget) {
  26738. var intersects = optionalTarget || [];
  26739. if (Array.isArray(objects) === false) {
  26740. console.warn('THREE.Raycaster.intersectObjects: objects is not an Array.');
  26741. return intersects;
  26742. }
  26743. for (var i = 0, l = objects.length; i < l; i++) {
  26744. intersectObject(objects[i], this, intersects, recursive);
  26745. }
  26746. intersects.sort(ascSort);
  26747. return intersects;
  26748. }
  26749. });
  26750. /**
  26751. * @author bhouston / http://clara.io
  26752. * @author WestLangley / http://github.com/WestLangley
  26753. *
  26754. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  26755. *
  26756. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  26757. * The azimuthal angle (theta) is measured from the positive z-axiz.
  26758. */
  26759. function Spherical(radius, phi, theta) {
  26760. this.radius = radius !== undefined ? radius : 1.0;
  26761. this.phi = phi !== undefined ? phi : 0; // polar angle
  26762. this.theta = theta !== undefined ? theta : 0; // azimuthal angle
  26763. return this;
  26764. }
  26765. Object.assign(Spherical.prototype, {
  26766. set: function (radius, phi, theta) {
  26767. this.radius = radius;
  26768. this.phi = phi;
  26769. this.theta = theta;
  26770. return this;
  26771. },
  26772. clone: function () {
  26773. return new this.constructor().copy(this);
  26774. },
  26775. copy: function (other) {
  26776. this.radius = other.radius;
  26777. this.phi = other.phi;
  26778. this.theta = other.theta;
  26779. return this;
  26780. },
  26781. // restrict phi to be betwee EPS and PI-EPS
  26782. makeSafe: function () {
  26783. var EPS = 0.000001;
  26784. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  26785. return this;
  26786. },
  26787. setFromVector3: function (v) {
  26788. return this.setFromCartesianCoords(v.x, v.y, v.z);
  26789. },
  26790. setFromCartesianCoords: function (x, y, z) {
  26791. this.radius = Math.sqrt(x * x + y * y + z * z);
  26792. if (this.radius === 0) {
  26793. this.theta = 0;
  26794. this.phi = 0;
  26795. } else {
  26796. this.theta = Math.atan2(x, z);
  26797. this.phi = Math.acos(_Math.clamp(y / this.radius, -1, 1));
  26798. }
  26799. return this;
  26800. }
  26801. });
  26802. /**
  26803. * @author Mugen87 / https://github.com/Mugen87
  26804. *
  26805. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  26806. *
  26807. */
  26808. function Cylindrical(radius, theta, y) {
  26809. this.radius = radius !== undefined ? radius : 1.0; // distance from the origin to a point in the x-z plane
  26810. this.theta = theta !== undefined ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  26811. this.y = y !== undefined ? y : 0; // height above the x-z plane
  26812. return this;
  26813. }
  26814. Object.assign(Cylindrical.prototype, {
  26815. set: function (radius, theta, y) {
  26816. this.radius = radius;
  26817. this.theta = theta;
  26818. this.y = y;
  26819. return this;
  26820. },
  26821. clone: function () {
  26822. return new this.constructor().copy(this);
  26823. },
  26824. copy: function (other) {
  26825. this.radius = other.radius;
  26826. this.theta = other.theta;
  26827. this.y = other.y;
  26828. return this;
  26829. },
  26830. setFromVector3: function (v) {
  26831. return this.setFromCartesianCoords(v.x, v.y, v.z);
  26832. },
  26833. setFromCartesianCoords: function (x, y, z) {
  26834. this.radius = Math.sqrt(x * x + z * z);
  26835. this.theta = Math.atan2(x, z);
  26836. this.y = y;
  26837. return this;
  26838. }
  26839. });
  26840. /**
  26841. * @author bhouston / http://clara.io
  26842. */
  26843. var _vector$6 = new Vector2();
  26844. function Box2(min, max) {
  26845. this.min = min !== undefined ? min : new Vector2(+Infinity, +Infinity);
  26846. this.max = max !== undefined ? max : new Vector2(-Infinity, -Infinity);
  26847. }
  26848. Object.assign(Box2.prototype, {
  26849. set: function (min, max) {
  26850. this.min.copy(min);
  26851. this.max.copy(max);
  26852. return this;
  26853. },
  26854. setFromPoints: function (points) {
  26855. this.makeEmpty();
  26856. for (var i = 0, il = points.length; i < il; i++) {
  26857. this.expandByPoint(points[i]);
  26858. }
  26859. return this;
  26860. },
  26861. setFromCenterAndSize: function (center, size) {
  26862. var halfSize = _vector$6.copy(size).multiplyScalar(0.5);
  26863. this.min.copy(center).sub(halfSize);
  26864. this.max.copy(center).add(halfSize);
  26865. return this;
  26866. },
  26867. clone: function () {
  26868. return new this.constructor().copy(this);
  26869. },
  26870. copy: function (box) {
  26871. this.min.copy(box.min);
  26872. this.max.copy(box.max);
  26873. return this;
  26874. },
  26875. makeEmpty: function () {
  26876. this.min.x = this.min.y = +Infinity;
  26877. this.max.x = this.max.y = -Infinity;
  26878. return this;
  26879. },
  26880. isEmpty: function () {
  26881. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  26882. return this.max.x < this.min.x || this.max.y < this.min.y;
  26883. },
  26884. getCenter: function (target) {
  26885. if (target === undefined) {
  26886. console.warn('THREE.Box2: .getCenter() target is now required');
  26887. target = new Vector2();
  26888. }
  26889. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  26890. },
  26891. getSize: function (target) {
  26892. if (target === undefined) {
  26893. console.warn('THREE.Box2: .getSize() target is now required');
  26894. target = new Vector2();
  26895. }
  26896. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  26897. },
  26898. expandByPoint: function (point) {
  26899. this.min.min(point);
  26900. this.max.max(point);
  26901. return this;
  26902. },
  26903. expandByVector: function (vector) {
  26904. this.min.sub(vector);
  26905. this.max.add(vector);
  26906. return this;
  26907. },
  26908. expandByScalar: function (scalar) {
  26909. this.min.addScalar(-scalar);
  26910. this.max.addScalar(scalar);
  26911. return this;
  26912. },
  26913. containsPoint: function (point) {
  26914. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  26915. },
  26916. containsBox: function (box) {
  26917. 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;
  26918. },
  26919. getParameter: function (point, target) {
  26920. // This can potentially have a divide by zero if the box
  26921. // has a size dimension of 0.
  26922. if (target === undefined) {
  26923. console.warn('THREE.Box2: .getParameter() target is now required');
  26924. target = new Vector2();
  26925. }
  26926. 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));
  26927. },
  26928. intersectsBox: function (box) {
  26929. // using 4 splitting planes to rule out intersections
  26930. 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;
  26931. },
  26932. clampPoint: function (point, target) {
  26933. if (target === undefined) {
  26934. console.warn('THREE.Box2: .clampPoint() target is now required');
  26935. target = new Vector2();
  26936. }
  26937. return target.copy(point).clamp(this.min, this.max);
  26938. },
  26939. distanceToPoint: function (point) {
  26940. var clampedPoint = _vector$6.copy(point).clamp(this.min, this.max);
  26941. return clampedPoint.sub(point).length();
  26942. },
  26943. intersect: function (box) {
  26944. this.min.max(box.min);
  26945. this.max.min(box.max);
  26946. return this;
  26947. },
  26948. union: function (box) {
  26949. this.min.min(box.min);
  26950. this.max.max(box.max);
  26951. return this;
  26952. },
  26953. translate: function (offset) {
  26954. this.min.add(offset);
  26955. this.max.add(offset);
  26956. return this;
  26957. },
  26958. equals: function (box) {
  26959. return box.min.equals(this.min) && box.max.equals(this.max);
  26960. }
  26961. });
  26962. /**
  26963. * @author bhouston / http://clara.io
  26964. */
  26965. var _startP = new Vector3();
  26966. var _startEnd = new Vector3();
  26967. function Line3(start, end) {
  26968. this.start = start !== undefined ? start : new Vector3();
  26969. this.end = end !== undefined ? end : new Vector3();
  26970. }
  26971. Object.assign(Line3.prototype, {
  26972. set: function (start, end) {
  26973. this.start.copy(start);
  26974. this.end.copy(end);
  26975. return this;
  26976. },
  26977. clone: function () {
  26978. return new this.constructor().copy(this);
  26979. },
  26980. copy: function (line) {
  26981. this.start.copy(line.start);
  26982. this.end.copy(line.end);
  26983. return this;
  26984. },
  26985. getCenter: function (target) {
  26986. if (target === undefined) {
  26987. console.warn('THREE.Line3: .getCenter() target is now required');
  26988. target = new Vector3();
  26989. }
  26990. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  26991. },
  26992. delta: function (target) {
  26993. if (target === undefined) {
  26994. console.warn('THREE.Line3: .delta() target is now required');
  26995. target = new Vector3();
  26996. }
  26997. return target.subVectors(this.end, this.start);
  26998. },
  26999. distanceSq: function () {
  27000. return this.start.distanceToSquared(this.end);
  27001. },
  27002. distance: function () {
  27003. return this.start.distanceTo(this.end);
  27004. },
  27005. at: function (t, target) {
  27006. if (target === undefined) {
  27007. console.warn('THREE.Line3: .at() target is now required');
  27008. target = new Vector3();
  27009. }
  27010. return this.delta(target).multiplyScalar(t).add(this.start);
  27011. },
  27012. closestPointToPointParameter: function (point, clampToLine) {
  27013. _startP.subVectors(point, this.start);
  27014. _startEnd.subVectors(this.end, this.start);
  27015. var startEnd2 = _startEnd.dot(_startEnd);
  27016. var startEnd_startP = _startEnd.dot(_startP);
  27017. var t = startEnd_startP / startEnd2;
  27018. if (clampToLine) {
  27019. t = _Math.clamp(t, 0, 1);
  27020. }
  27021. return t;
  27022. },
  27023. closestPointToPoint: function (point, clampToLine, target) {
  27024. var t = this.closestPointToPointParameter(point, clampToLine);
  27025. if (target === undefined) {
  27026. console.warn('THREE.Line3: .closestPointToPoint() target is now required');
  27027. target = new Vector3();
  27028. }
  27029. return this.delta(target).multiplyScalar(t).add(this.start);
  27030. },
  27031. applyMatrix4: function (matrix) {
  27032. this.start.applyMatrix4(matrix);
  27033. this.end.applyMatrix4(matrix);
  27034. return this;
  27035. },
  27036. equals: function (line) {
  27037. return line.start.equals(this.start) && line.end.equals(this.end);
  27038. }
  27039. });
  27040. /**
  27041. * @author alteredq / http://alteredqualia.com/
  27042. */
  27043. function ImmediateRenderObject(material) {
  27044. Object3D.call(this);
  27045. this.material = material;
  27046. this.render = function ()
  27047. /* renderCallback */
  27048. {};
  27049. }
  27050. ImmediateRenderObject.prototype = Object.create(Object3D.prototype);
  27051. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  27052. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  27053. /**
  27054. * @author mrdoob / http://mrdoob.com/
  27055. * @author WestLangley / http://github.com/WestLangley
  27056. */
  27057. var _v1$5 = new Vector3();
  27058. var _v2$3 = new Vector3();
  27059. var _normalMatrix$1 = new Matrix3();
  27060. var _keys = ['a', 'b', 'c'];
  27061. function VertexNormalsHelper(object, size, hex, linewidth) {
  27062. this.object = object;
  27063. this.size = size !== undefined ? size : 1;
  27064. var color = hex !== undefined ? hex : 0xff0000;
  27065. var width = linewidth !== undefined ? linewidth : 1; //
  27066. var nNormals = 0;
  27067. var objGeometry = this.object.geometry;
  27068. if (objGeometry && objGeometry.isGeometry) {
  27069. nNormals = objGeometry.faces.length * 3;
  27070. } else if (objGeometry && objGeometry.isBufferGeometry) {
  27071. nNormals = objGeometry.attributes.normal.count;
  27072. } //
  27073. var geometry = new BufferGeometry();
  27074. var positions = new Float32BufferAttribute(nNormals * 2 * 3, 3);
  27075. geometry.addAttribute('position', positions);
  27076. LineSegments.call(this, geometry, new LineBasicMaterial({
  27077. color: color,
  27078. linewidth: width
  27079. })); //
  27080. this.matrixAutoUpdate = false;
  27081. this.update();
  27082. }
  27083. VertexNormalsHelper.prototype = Object.create(LineSegments.prototype);
  27084. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  27085. VertexNormalsHelper.prototype.update = function () {
  27086. this.object.updateMatrixWorld(true);
  27087. _normalMatrix$1.getNormalMatrix(this.object.matrixWorld);
  27088. var matrixWorld = this.object.matrixWorld;
  27089. var position = this.geometry.attributes.position; //
  27090. var objGeometry = this.object.geometry;
  27091. if (objGeometry && objGeometry.isGeometry) {
  27092. var vertices = objGeometry.vertices;
  27093. var faces = objGeometry.faces;
  27094. var idx = 0;
  27095. for (var i = 0, l = faces.length; i < l; i++) {
  27096. var face = faces[i];
  27097. for (var j = 0, jl = face.vertexNormals.length; j < jl; j++) {
  27098. var vertex = vertices[face[_keys[j]]];
  27099. var normal = face.vertexNormals[j];
  27100. _v1$5.copy(vertex).applyMatrix4(matrixWorld);
  27101. _v2$3.copy(normal).applyMatrix3(_normalMatrix$1).normalize().multiplyScalar(this.size).add(_v1$5);
  27102. position.setXYZ(idx, _v1$5.x, _v1$5.y, _v1$5.z);
  27103. idx = idx + 1;
  27104. position.setXYZ(idx, _v2$3.x, _v2$3.y, _v2$3.z);
  27105. idx = idx + 1;
  27106. }
  27107. }
  27108. } else if (objGeometry && objGeometry.isBufferGeometry) {
  27109. var objPos = objGeometry.attributes.position;
  27110. var objNorm = objGeometry.attributes.normal;
  27111. var idx = 0; // for simplicity, ignore index and drawcalls, and render every normal
  27112. for (var j = 0, jl = objPos.count; j < jl; j++) {
  27113. _v1$5.set(objPos.getX(j), objPos.getY(j), objPos.getZ(j)).applyMatrix4(matrixWorld);
  27114. _v2$3.set(objNorm.getX(j), objNorm.getY(j), objNorm.getZ(j));
  27115. _v2$3.applyMatrix3(_normalMatrix$1).normalize().multiplyScalar(this.size).add(_v1$5);
  27116. position.setXYZ(idx, _v1$5.x, _v1$5.y, _v1$5.z);
  27117. idx = idx + 1;
  27118. position.setXYZ(idx, _v2$3.x, _v2$3.y, _v2$3.z);
  27119. idx = idx + 1;
  27120. }
  27121. }
  27122. position.needsUpdate = true;
  27123. };
  27124. /**
  27125. * @author alteredq / http://alteredqualia.com/
  27126. * @author mrdoob / http://mrdoob.com/
  27127. * @author WestLangley / http://github.com/WestLangley
  27128. */
  27129. var _vector$7 = new Vector3();
  27130. function SpotLightHelper(light, color) {
  27131. Object3D.call(this);
  27132. this.light = light;
  27133. this.light.updateMatrixWorld();
  27134. this.matrix = light.matrixWorld;
  27135. this.matrixAutoUpdate = false;
  27136. this.color = color;
  27137. var geometry = new BufferGeometry();
  27138. 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];
  27139. for (var i = 0, j = 1, l = 32; i < l; i++, j++) {
  27140. var p1 = i / l * Math.PI * 2;
  27141. var p2 = j / l * Math.PI * 2;
  27142. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  27143. }
  27144. geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));
  27145. var material = new LineBasicMaterial({
  27146. fog: false
  27147. });
  27148. this.cone = new LineSegments(geometry, material);
  27149. this.add(this.cone);
  27150. this.update();
  27151. }
  27152. SpotLightHelper.prototype = Object.create(Object3D.prototype);
  27153. SpotLightHelper.prototype.constructor = SpotLightHelper;
  27154. SpotLightHelper.prototype.dispose = function () {
  27155. this.cone.geometry.dispose();
  27156. this.cone.material.dispose();
  27157. };
  27158. SpotLightHelper.prototype.update = function () {
  27159. this.light.updateMatrixWorld();
  27160. var coneLength = this.light.distance ? this.light.distance : 1000;
  27161. var coneWidth = coneLength * Math.tan(this.light.angle);
  27162. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  27163. _vector$7.setFromMatrixPosition(this.light.target.matrixWorld);
  27164. this.cone.lookAt(_vector$7);
  27165. if (this.color !== undefined) {
  27166. this.cone.material.color.set(this.color);
  27167. } else {
  27168. this.cone.material.color.copy(this.light.color);
  27169. }
  27170. };
  27171. /**
  27172. * @author Sean Griffin / http://twitter.com/sgrif
  27173. * @author Michael Guerrero / http://realitymeltdown.com
  27174. * @author mrdoob / http://mrdoob.com/
  27175. * @author ikerr / http://verold.com
  27176. * @author Mugen87 / https://github.com/Mugen87
  27177. */
  27178. var _vector$8 = new Vector3();
  27179. var _boneMatrix = new Matrix4();
  27180. var _matrixWorldInv = new Matrix4();
  27181. function getBoneList(object) {
  27182. var boneList = [];
  27183. if (object && object.isBone) {
  27184. boneList.push(object);
  27185. }
  27186. for (var i = 0; i < object.children.length; i++) {
  27187. boneList.push.apply(boneList, getBoneList(object.children[i]));
  27188. }
  27189. return boneList;
  27190. }
  27191. function SkeletonHelper(object) {
  27192. var bones = getBoneList(object);
  27193. var geometry = new BufferGeometry();
  27194. var vertices = [];
  27195. var colors = [];
  27196. var color1 = new Color(0, 0, 1);
  27197. var color2 = new Color(0, 1, 0);
  27198. for (var i = 0; i < bones.length; i++) {
  27199. var bone = bones[i];
  27200. if (bone.parent && bone.parent.isBone) {
  27201. vertices.push(0, 0, 0);
  27202. vertices.push(0, 0, 0);
  27203. colors.push(color1.r, color1.g, color1.b);
  27204. colors.push(color2.r, color2.g, color2.b);
  27205. }
  27206. }
  27207. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  27208. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  27209. var material = new LineBasicMaterial({
  27210. vertexColors: VertexColors,
  27211. depthTest: false,
  27212. depthWrite: false,
  27213. transparent: true
  27214. });
  27215. LineSegments.call(this, geometry, material);
  27216. this.root = object;
  27217. this.bones = bones;
  27218. this.matrix = object.matrixWorld;
  27219. this.matrixAutoUpdate = false;
  27220. }
  27221. SkeletonHelper.prototype = Object.create(LineSegments.prototype);
  27222. SkeletonHelper.prototype.constructor = SkeletonHelper;
  27223. SkeletonHelper.prototype.updateMatrixWorld = function (force) {
  27224. var bones = this.bones;
  27225. var geometry = this.geometry;
  27226. var position = geometry.getAttribute('position');
  27227. _matrixWorldInv.getInverse(this.root.matrixWorld);
  27228. for (var i = 0, j = 0; i < bones.length; i++) {
  27229. var bone = bones[i];
  27230. if (bone.parent && bone.parent.isBone) {
  27231. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  27232. _vector$8.setFromMatrixPosition(_boneMatrix);
  27233. position.setXYZ(j, _vector$8.x, _vector$8.y, _vector$8.z);
  27234. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  27235. _vector$8.setFromMatrixPosition(_boneMatrix);
  27236. position.setXYZ(j + 1, _vector$8.x, _vector$8.y, _vector$8.z);
  27237. j += 2;
  27238. }
  27239. }
  27240. geometry.getAttribute('position').needsUpdate = true;
  27241. Object3D.prototype.updateMatrixWorld.call(this, force);
  27242. };
  27243. /**
  27244. * @author alteredq / http://alteredqualia.com/
  27245. * @author mrdoob / http://mrdoob.com/
  27246. */
  27247. function PointLightHelper(light, sphereSize, color) {
  27248. this.light = light;
  27249. this.light.updateMatrixWorld();
  27250. this.color = color;
  27251. var geometry = new SphereBufferGeometry(sphereSize, 4, 2);
  27252. var material = new MeshBasicMaterial({
  27253. wireframe: true,
  27254. fog: false
  27255. });
  27256. Mesh.call(this, geometry, material);
  27257. this.matrix = this.light.matrixWorld;
  27258. this.matrixAutoUpdate = false;
  27259. this.update();
  27260. /*
  27261. var distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  27262. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  27263. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  27264. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  27265. var d = light.distance;
  27266. if ( d === 0.0 ) {
  27267. this.lightDistance.visible = false;
  27268. } else {
  27269. this.lightDistance.scale.set( d, d, d );
  27270. }
  27271. this.add( this.lightDistance );
  27272. */
  27273. }
  27274. PointLightHelper.prototype = Object.create(Mesh.prototype);
  27275. PointLightHelper.prototype.constructor = PointLightHelper;
  27276. PointLightHelper.prototype.dispose = function () {
  27277. this.geometry.dispose();
  27278. this.material.dispose();
  27279. };
  27280. PointLightHelper.prototype.update = function () {
  27281. if (this.color !== undefined) {
  27282. this.material.color.set(this.color);
  27283. } else {
  27284. this.material.color.copy(this.light.color);
  27285. }
  27286. /*
  27287. var d = this.light.distance;
  27288. if ( d === 0.0 ) {
  27289. this.lightDistance.visible = false;
  27290. } else {
  27291. this.lightDistance.visible = true;
  27292. this.lightDistance.scale.set( d, d, d );
  27293. }
  27294. */
  27295. };
  27296. /**
  27297. * @author abelnation / http://github.com/abelnation
  27298. * @author Mugen87 / http://github.com/Mugen87
  27299. * @author WestLangley / http://github.com/WestLangley
  27300. *
  27301. * This helper must be added as a child of the light
  27302. */
  27303. function RectAreaLightHelper(light, color) {
  27304. this.type = 'RectAreaLightHelper';
  27305. this.light = light;
  27306. this.color = color; // optional hardwired color for the helper
  27307. var positions = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, -1, 0, 1, 1, 0];
  27308. var geometry = new BufferGeometry();
  27309. geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));
  27310. geometry.computeBoundingSphere();
  27311. var material = new LineBasicMaterial({
  27312. fog: false
  27313. });
  27314. Line.call(this, geometry, material); //
  27315. var positions2 = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0];
  27316. var geometry2 = new BufferGeometry();
  27317. geometry2.addAttribute('position', new Float32BufferAttribute(positions2, 3));
  27318. geometry2.computeBoundingSphere();
  27319. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  27320. side: BackSide,
  27321. fog: false
  27322. })));
  27323. this.update();
  27324. }
  27325. RectAreaLightHelper.prototype = Object.create(Line.prototype);
  27326. RectAreaLightHelper.prototype.constructor = RectAreaLightHelper;
  27327. RectAreaLightHelper.prototype.update = function () {
  27328. this.scale.set(0.5 * this.light.width, 0.5 * this.light.height, 1);
  27329. if (this.color !== undefined) {
  27330. this.material.color.set(this.color);
  27331. this.children[0].material.color.set(this.color);
  27332. } else {
  27333. this.material.color.copy(this.light.color).multiplyScalar(this.light.intensity); // prevent hue shift
  27334. var c = this.material.color;
  27335. var max = Math.max(c.r, c.g, c.b);
  27336. if (max > 1) c.multiplyScalar(1 / max);
  27337. this.children[0].material.color.copy(this.material.color);
  27338. }
  27339. };
  27340. RectAreaLightHelper.prototype.dispose = function () {
  27341. this.geometry.dispose();
  27342. this.material.dispose();
  27343. this.children[0].geometry.dispose();
  27344. this.children[0].material.dispose();
  27345. };
  27346. /**
  27347. * @author alteredq / http://alteredqualia.com/
  27348. * @author mrdoob / http://mrdoob.com/
  27349. * @author Mugen87 / https://github.com/Mugen87
  27350. */
  27351. var _vector$9 = new Vector3();
  27352. var _color1 = new Color();
  27353. var _color2 = new Color();
  27354. function HemisphereLightHelper(light, size, color) {
  27355. Object3D.call(this);
  27356. this.light = light;
  27357. this.light.updateMatrixWorld();
  27358. this.matrix = light.matrixWorld;
  27359. this.matrixAutoUpdate = false;
  27360. this.color = color;
  27361. var geometry = new OctahedronBufferGeometry(size);
  27362. geometry.rotateY(Math.PI * 0.5);
  27363. this.material = new MeshBasicMaterial({
  27364. wireframe: true,
  27365. fog: false
  27366. });
  27367. if (this.color === undefined) this.material.vertexColors = VertexColors;
  27368. var position = geometry.getAttribute('position');
  27369. var colors = new Float32Array(position.count * 3);
  27370. geometry.addAttribute('color', new BufferAttribute(colors, 3));
  27371. this.add(new Mesh(geometry, this.material));
  27372. this.update();
  27373. }
  27374. HemisphereLightHelper.prototype = Object.create(Object3D.prototype);
  27375. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  27376. HemisphereLightHelper.prototype.dispose = function () {
  27377. this.children[0].geometry.dispose();
  27378. this.children[0].material.dispose();
  27379. };
  27380. HemisphereLightHelper.prototype.update = function () {
  27381. var mesh = this.children[0];
  27382. if (this.color !== undefined) {
  27383. this.material.color.set(this.color);
  27384. } else {
  27385. var colors = mesh.geometry.getAttribute('color');
  27386. _color1.copy(this.light.color);
  27387. _color2.copy(this.light.groundColor);
  27388. for (var i = 0, l = colors.count; i < l; i++) {
  27389. var color = i < l / 2 ? _color1 : _color2;
  27390. colors.setXYZ(i, color.r, color.g, color.b);
  27391. }
  27392. colors.needsUpdate = true;
  27393. }
  27394. mesh.lookAt(_vector$9.setFromMatrixPosition(this.light.matrixWorld).negate());
  27395. };
  27396. /**
  27397. * @author WestLangley / http://github.com/WestLangley
  27398. */
  27399. function LightProbeHelper(lightProbe, size) {
  27400. this.lightProbe = lightProbe;
  27401. this.size = size;
  27402. var defines = {};
  27403. defines['GAMMA_OUTPUT'] = ""; // material
  27404. var material = new ShaderMaterial({
  27405. defines: defines,
  27406. uniforms: {
  27407. sh: {
  27408. value: this.lightProbe.sh.coefficients
  27409. },
  27410. // by reference
  27411. intensity: {
  27412. value: this.lightProbe.intensity
  27413. }
  27414. },
  27415. vertexShader: ['varying vec3 vNormal;', 'void main() {', ' vNormal = normalize( normalMatrix * normal );', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'),
  27416. 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')
  27417. });
  27418. var geometry = new SphereBufferGeometry(1, 32, 16);
  27419. Mesh.call(this, geometry, material);
  27420. this.onBeforeRender();
  27421. }
  27422. LightProbeHelper.prototype = Object.create(Mesh.prototype);
  27423. LightProbeHelper.prototype.constructor = LightProbeHelper;
  27424. LightProbeHelper.prototype.dispose = function () {
  27425. this.geometry.dispose();
  27426. this.material.dispose();
  27427. };
  27428. LightProbeHelper.prototype.onBeforeRender = function () {
  27429. this.position.copy(this.lightProbe.position);
  27430. this.scale.set(1, 1, 1).multiplyScalar(this.size);
  27431. this.material.uniforms.intensity.value = this.lightProbe.intensity;
  27432. };
  27433. /**
  27434. * @author mrdoob / http://mrdoob.com/
  27435. */
  27436. function GridHelper(size, divisions, color1, color2) {
  27437. size = size || 10;
  27438. divisions = divisions || 10;
  27439. color1 = new Color(color1 !== undefined ? color1 : 0x444444);
  27440. color2 = new Color(color2 !== undefined ? color2 : 0x888888);
  27441. var center = divisions / 2;
  27442. var step = size / divisions;
  27443. var halfSize = size / 2;
  27444. var vertices = [],
  27445. colors = [];
  27446. for (var i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  27447. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  27448. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  27449. var color = i === center ? color1 : color2;
  27450. color.toArray(colors, j);
  27451. j += 3;
  27452. color.toArray(colors, j);
  27453. j += 3;
  27454. color.toArray(colors, j);
  27455. j += 3;
  27456. color.toArray(colors, j);
  27457. j += 3;
  27458. }
  27459. var geometry = new BufferGeometry();
  27460. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  27461. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  27462. var material = new LineBasicMaterial({
  27463. vertexColors: VertexColors
  27464. });
  27465. LineSegments.call(this, geometry, material);
  27466. }
  27467. GridHelper.prototype = Object.assign(Object.create(LineSegments.prototype), {
  27468. constructor: GridHelper,
  27469. copy: function (source) {
  27470. LineSegments.prototype.copy.call(this, source);
  27471. this.geometry.copy(source.geometry);
  27472. this.material.copy(source.material);
  27473. return this;
  27474. },
  27475. clone: function () {
  27476. return new this.constructor().copy(this);
  27477. }
  27478. });
  27479. /**
  27480. * @author mrdoob / http://mrdoob.com/
  27481. * @author Mugen87 / http://github.com/Mugen87
  27482. * @author Hectate / http://www.github.com/Hectate
  27483. */
  27484. function PolarGridHelper(radius, radials, circles, divisions, color1, color2) {
  27485. radius = radius || 10;
  27486. radials = radials || 16;
  27487. circles = circles || 8;
  27488. divisions = divisions || 64;
  27489. color1 = new Color(color1 !== undefined ? color1 : 0x444444);
  27490. color2 = new Color(color2 !== undefined ? color2 : 0x888888);
  27491. var vertices = [];
  27492. var colors = [];
  27493. var x, z;
  27494. var v, i, j, r, color; // create the radials
  27495. for (i = 0; i <= radials; i++) {
  27496. v = i / radials * (Math.PI * 2);
  27497. x = Math.sin(v) * radius;
  27498. z = Math.cos(v) * radius;
  27499. vertices.push(0, 0, 0);
  27500. vertices.push(x, 0, z);
  27501. color = i & 1 ? color1 : color2;
  27502. colors.push(color.r, color.g, color.b);
  27503. colors.push(color.r, color.g, color.b);
  27504. } // create the circles
  27505. for (i = 0; i <= circles; i++) {
  27506. color = i & 1 ? color1 : color2;
  27507. r = radius - radius / circles * i;
  27508. for (j = 0; j < divisions; j++) {
  27509. // first vertex
  27510. v = j / divisions * (Math.PI * 2);
  27511. x = Math.sin(v) * r;
  27512. z = Math.cos(v) * r;
  27513. vertices.push(x, 0, z);
  27514. colors.push(color.r, color.g, color.b); // second vertex
  27515. v = (j + 1) / divisions * (Math.PI * 2);
  27516. x = Math.sin(v) * r;
  27517. z = Math.cos(v) * r;
  27518. vertices.push(x, 0, z);
  27519. colors.push(color.r, color.g, color.b);
  27520. }
  27521. }
  27522. var geometry = new BufferGeometry();
  27523. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  27524. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  27525. var material = new LineBasicMaterial({
  27526. vertexColors: VertexColors
  27527. });
  27528. LineSegments.call(this, geometry, material);
  27529. }
  27530. PolarGridHelper.prototype = Object.create(LineSegments.prototype);
  27531. PolarGridHelper.prototype.constructor = PolarGridHelper;
  27532. /**
  27533. * @author Mugen87 / http://github.com/Mugen87
  27534. */
  27535. function PositionalAudioHelper(audio, range, divisionsInnerAngle, divisionsOuterAngle) {
  27536. this.audio = audio;
  27537. this.range = range || 1;
  27538. this.divisionsInnerAngle = divisionsInnerAngle || 16;
  27539. this.divisionsOuterAngle = divisionsOuterAngle || 2;
  27540. var geometry = new BufferGeometry();
  27541. var divisions = this.divisionsInnerAngle + this.divisionsOuterAngle * 2;
  27542. var positions = new Float32Array((divisions * 3 + 3) * 3);
  27543. geometry.addAttribute('position', new BufferAttribute(positions, 3));
  27544. var materialInnerAngle = new LineBasicMaterial({
  27545. color: 0x00ff00
  27546. });
  27547. var materialOuterAngle = new LineBasicMaterial({
  27548. color: 0xffff00
  27549. });
  27550. Line.call(this, geometry, [materialOuterAngle, materialInnerAngle]);
  27551. this.update();
  27552. }
  27553. PositionalAudioHelper.prototype = Object.create(Line.prototype);
  27554. PositionalAudioHelper.prototype.constructor = PositionalAudioHelper;
  27555. PositionalAudioHelper.prototype.update = function () {
  27556. var audio = this.audio;
  27557. var range = this.range;
  27558. var divisionsInnerAngle = this.divisionsInnerAngle;
  27559. var divisionsOuterAngle = this.divisionsOuterAngle;
  27560. var coneInnerAngle = _Math.degToRad(audio.panner.coneInnerAngle);
  27561. var coneOuterAngle = _Math.degToRad(audio.panner.coneOuterAngle);
  27562. var halfConeInnerAngle = coneInnerAngle / 2;
  27563. var halfConeOuterAngle = coneOuterAngle / 2;
  27564. var start = 0;
  27565. var count = 0;
  27566. var i, stride;
  27567. var geometry = this.geometry;
  27568. var positionAttribute = geometry.attributes.position;
  27569. geometry.clearGroups(); //
  27570. function generateSegment(from, to, divisions, materialIndex) {
  27571. var step = (to - from) / divisions;
  27572. positionAttribute.setXYZ(start, 0, 0, 0);
  27573. count++;
  27574. for (i = from; i < to; i += step) {
  27575. stride = start + count;
  27576. positionAttribute.setXYZ(stride, Math.sin(i) * range, 0, Math.cos(i) * range);
  27577. positionAttribute.setXYZ(stride + 1, Math.sin(Math.min(i + step, to)) * range, 0, Math.cos(Math.min(i + step, to)) * range);
  27578. positionAttribute.setXYZ(stride + 2, 0, 0, 0);
  27579. count += 3;
  27580. }
  27581. geometry.addGroup(start, count, materialIndex);
  27582. start += count;
  27583. count = 0;
  27584. } //
  27585. generateSegment(-halfConeOuterAngle, -halfConeInnerAngle, divisionsOuterAngle, 0);
  27586. generateSegment(-halfConeInnerAngle, halfConeInnerAngle, divisionsInnerAngle, 1);
  27587. generateSegment(halfConeInnerAngle, halfConeOuterAngle, divisionsOuterAngle, 0); //
  27588. positionAttribute.needsUpdate = true;
  27589. if (coneInnerAngle === coneOuterAngle) this.material[0].visible = false;
  27590. };
  27591. PositionalAudioHelper.prototype.dispose = function () {
  27592. this.geometry.dispose();
  27593. this.material[0].dispose();
  27594. this.material[1].dispose();
  27595. };
  27596. /**
  27597. * @author mrdoob / http://mrdoob.com/
  27598. * @author WestLangley / http://github.com/WestLangley
  27599. */
  27600. var _v1$6 = new Vector3();
  27601. var _v2$4 = new Vector3();
  27602. var _normalMatrix$2 = new Matrix3();
  27603. function FaceNormalsHelper(object, size, hex, linewidth) {
  27604. // FaceNormalsHelper only supports THREE.Geometry
  27605. this.object = object;
  27606. this.size = size !== undefined ? size : 1;
  27607. var color = hex !== undefined ? hex : 0xffff00;
  27608. var width = linewidth !== undefined ? linewidth : 1; //
  27609. var nNormals = 0;
  27610. var objGeometry = this.object.geometry;
  27611. if (objGeometry && objGeometry.isGeometry) {
  27612. nNormals = objGeometry.faces.length;
  27613. } else {
  27614. console.warn('THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.');
  27615. } //
  27616. var geometry = new BufferGeometry();
  27617. var positions = new Float32BufferAttribute(nNormals * 2 * 3, 3);
  27618. geometry.addAttribute('position', positions);
  27619. LineSegments.call(this, geometry, new LineBasicMaterial({
  27620. color: color,
  27621. linewidth: width
  27622. })); //
  27623. this.matrixAutoUpdate = false;
  27624. this.update();
  27625. }
  27626. FaceNormalsHelper.prototype = Object.create(LineSegments.prototype);
  27627. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  27628. FaceNormalsHelper.prototype.update = function () {
  27629. this.object.updateMatrixWorld(true);
  27630. _normalMatrix$2.getNormalMatrix(this.object.matrixWorld);
  27631. var matrixWorld = this.object.matrixWorld;
  27632. var position = this.geometry.attributes.position; //
  27633. var objGeometry = this.object.geometry;
  27634. var vertices = objGeometry.vertices;
  27635. var faces = objGeometry.faces;
  27636. var idx = 0;
  27637. for (var i = 0, l = faces.length; i < l; i++) {
  27638. var face = faces[i];
  27639. var normal = face.normal;
  27640. _v1$6.copy(vertices[face.a]).add(vertices[face.b]).add(vertices[face.c]).divideScalar(3).applyMatrix4(matrixWorld);
  27641. _v2$4.copy(normal).applyMatrix3(_normalMatrix$2).normalize().multiplyScalar(this.size).add(_v1$6);
  27642. position.setXYZ(idx, _v1$6.x, _v1$6.y, _v1$6.z);
  27643. idx = idx + 1;
  27644. position.setXYZ(idx, _v2$4.x, _v2$4.y, _v2$4.z);
  27645. idx = idx + 1;
  27646. }
  27647. position.needsUpdate = true;
  27648. };
  27649. /**
  27650. * @author alteredq / http://alteredqualia.com/
  27651. * @author mrdoob / http://mrdoob.com/
  27652. * @author WestLangley / http://github.com/WestLangley
  27653. */
  27654. var _v1$7 = new Vector3();
  27655. var _v2$5 = new Vector3();
  27656. var _v3$1 = new Vector3();
  27657. function DirectionalLightHelper(light, size, color) {
  27658. Object3D.call(this);
  27659. this.light = light;
  27660. this.light.updateMatrixWorld();
  27661. this.matrix = light.matrixWorld;
  27662. this.matrixAutoUpdate = false;
  27663. this.color = color;
  27664. if (size === undefined) size = 1;
  27665. var geometry = new BufferGeometry();
  27666. geometry.addAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  27667. var material = new LineBasicMaterial({
  27668. fog: false
  27669. });
  27670. this.lightPlane = new Line(geometry, material);
  27671. this.add(this.lightPlane);
  27672. geometry = new BufferGeometry();
  27673. geometry.addAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  27674. this.targetLine = new Line(geometry, material);
  27675. this.add(this.targetLine);
  27676. this.update();
  27677. }
  27678. DirectionalLightHelper.prototype = Object.create(Object3D.prototype);
  27679. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  27680. DirectionalLightHelper.prototype.dispose = function () {
  27681. this.lightPlane.geometry.dispose();
  27682. this.lightPlane.material.dispose();
  27683. this.targetLine.geometry.dispose();
  27684. this.targetLine.material.dispose();
  27685. };
  27686. DirectionalLightHelper.prototype.update = function () {
  27687. _v1$7.setFromMatrixPosition(this.light.matrixWorld);
  27688. _v2$5.setFromMatrixPosition(this.light.target.matrixWorld);
  27689. _v3$1.subVectors(_v2$5, _v1$7);
  27690. this.lightPlane.lookAt(_v2$5);
  27691. if (this.color !== undefined) {
  27692. this.lightPlane.material.color.set(this.color);
  27693. this.targetLine.material.color.set(this.color);
  27694. } else {
  27695. this.lightPlane.material.color.copy(this.light.color);
  27696. this.targetLine.material.color.copy(this.light.color);
  27697. }
  27698. this.targetLine.lookAt(_v2$5);
  27699. this.targetLine.scale.z = _v3$1.length();
  27700. };
  27701. /**
  27702. * @author alteredq / http://alteredqualia.com/
  27703. * @author Mugen87 / https://github.com/Mugen87
  27704. *
  27705. * - shows frustum, line of sight and up of the camera
  27706. * - suitable for fast updates
  27707. * - based on frustum visualization in lightgl.js shadowmap example
  27708. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  27709. */
  27710. var _vector$a = new Vector3();
  27711. var _camera = new Camera();
  27712. function CameraHelper(camera) {
  27713. var geometry = new BufferGeometry();
  27714. var material = new LineBasicMaterial({
  27715. color: 0xffffff,
  27716. vertexColors: FaceColors
  27717. });
  27718. var vertices = [];
  27719. var colors = [];
  27720. var pointMap = {}; // colors
  27721. var colorFrustum = new Color(0xffaa00);
  27722. var colorCone = new Color(0xff0000);
  27723. var colorUp = new Color(0x00aaff);
  27724. var colorTarget = new Color(0xffffff);
  27725. var colorCross = new Color(0x333333); // near
  27726. addLine('n1', 'n2', colorFrustum);
  27727. addLine('n2', 'n4', colorFrustum);
  27728. addLine('n4', 'n3', colorFrustum);
  27729. addLine('n3', 'n1', colorFrustum); // far
  27730. addLine('f1', 'f2', colorFrustum);
  27731. addLine('f2', 'f4', colorFrustum);
  27732. addLine('f4', 'f3', colorFrustum);
  27733. addLine('f3', 'f1', colorFrustum); // sides
  27734. addLine('n1', 'f1', colorFrustum);
  27735. addLine('n2', 'f2', colorFrustum);
  27736. addLine('n3', 'f3', colorFrustum);
  27737. addLine('n4', 'f4', colorFrustum); // cone
  27738. addLine('p', 'n1', colorCone);
  27739. addLine('p', 'n2', colorCone);
  27740. addLine('p', 'n3', colorCone);
  27741. addLine('p', 'n4', colorCone); // up
  27742. addLine('u1', 'u2', colorUp);
  27743. addLine('u2', 'u3', colorUp);
  27744. addLine('u3', 'u1', colorUp); // target
  27745. addLine('c', 't', colorTarget);
  27746. addLine('p', 'c', colorCross); // cross
  27747. addLine('cn1', 'cn2', colorCross);
  27748. addLine('cn3', 'cn4', colorCross);
  27749. addLine('cf1', 'cf2', colorCross);
  27750. addLine('cf3', 'cf4', colorCross);
  27751. function addLine(a, b, color) {
  27752. addPoint(a, color);
  27753. addPoint(b, color);
  27754. }
  27755. function addPoint(id, color) {
  27756. vertices.push(0, 0, 0);
  27757. colors.push(color.r, color.g, color.b);
  27758. if (pointMap[id] === undefined) {
  27759. pointMap[id] = [];
  27760. }
  27761. pointMap[id].push(vertices.length / 3 - 1);
  27762. }
  27763. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  27764. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  27765. LineSegments.call(this, geometry, material);
  27766. this.camera = camera;
  27767. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  27768. this.matrix = camera.matrixWorld;
  27769. this.matrixAutoUpdate = false;
  27770. this.pointMap = pointMap;
  27771. this.update();
  27772. }
  27773. CameraHelper.prototype = Object.create(LineSegments.prototype);
  27774. CameraHelper.prototype.constructor = CameraHelper;
  27775. CameraHelper.prototype.update = function () {
  27776. var geometry = this.geometry;
  27777. var pointMap = this.pointMap;
  27778. var w = 1,
  27779. h = 1; // we need just camera projection matrix inverse
  27780. // world matrix must be identity
  27781. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  27782. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  27783. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  27784. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  27785. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  27786. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  27787. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  27788. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  27789. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  27790. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  27791. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  27792. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  27793. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  27794. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  27795. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  27796. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  27797. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  27798. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  27799. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  27800. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  27801. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  27802. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  27803. geometry.getAttribute('position').needsUpdate = true;
  27804. };
  27805. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  27806. _vector$a.set(x, y, z).unproject(camera);
  27807. var points = pointMap[point];
  27808. if (points !== undefined) {
  27809. var position = geometry.getAttribute('position');
  27810. for (var i = 0, l = points.length; i < l; i++) {
  27811. position.setXYZ(points[i], _vector$a.x, _vector$a.y, _vector$a.z);
  27812. }
  27813. }
  27814. }
  27815. /**
  27816. * @author mrdoob / http://mrdoob.com/
  27817. * @author Mugen87 / http://github.com/Mugen87
  27818. */
  27819. var _box$2 = new Box3();
  27820. function BoxHelper(object, color) {
  27821. this.object = object;
  27822. if (color === undefined) color = 0xffff00;
  27823. 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]);
  27824. var positions = new Float32Array(8 * 3);
  27825. var geometry = new BufferGeometry();
  27826. geometry.setIndex(new BufferAttribute(indices, 1));
  27827. geometry.addAttribute('position', new BufferAttribute(positions, 3));
  27828. LineSegments.call(this, geometry, new LineBasicMaterial({
  27829. color: color
  27830. }));
  27831. this.matrixAutoUpdate = false;
  27832. this.update();
  27833. }
  27834. BoxHelper.prototype = Object.create(LineSegments.prototype);
  27835. BoxHelper.prototype.constructor = BoxHelper;
  27836. BoxHelper.prototype.update = function (object) {
  27837. if (object !== undefined) {
  27838. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  27839. }
  27840. if (this.object !== undefined) {
  27841. _box$2.setFromObject(this.object);
  27842. }
  27843. if (_box$2.isEmpty()) return;
  27844. var min = _box$2.min;
  27845. var max = _box$2.max;
  27846. /*
  27847. 5____4
  27848. 1/___0/|
  27849. | 6__|_7
  27850. 2/___3/
  27851. 0: max.x, max.y, max.z
  27852. 1: min.x, max.y, max.z
  27853. 2: min.x, min.y, max.z
  27854. 3: max.x, min.y, max.z
  27855. 4: max.x, max.y, min.z
  27856. 5: min.x, max.y, min.z
  27857. 6: min.x, min.y, min.z
  27858. 7: max.x, min.y, min.z
  27859. */
  27860. var position = this.geometry.attributes.position;
  27861. var array = position.array;
  27862. array[0] = max.x;
  27863. array[1] = max.y;
  27864. array[2] = max.z;
  27865. array[3] = min.x;
  27866. array[4] = max.y;
  27867. array[5] = max.z;
  27868. array[6] = min.x;
  27869. array[7] = min.y;
  27870. array[8] = max.z;
  27871. array[9] = max.x;
  27872. array[10] = min.y;
  27873. array[11] = max.z;
  27874. array[12] = max.x;
  27875. array[13] = max.y;
  27876. array[14] = min.z;
  27877. array[15] = min.x;
  27878. array[16] = max.y;
  27879. array[17] = min.z;
  27880. array[18] = min.x;
  27881. array[19] = min.y;
  27882. array[20] = min.z;
  27883. array[21] = max.x;
  27884. array[22] = min.y;
  27885. array[23] = min.z;
  27886. position.needsUpdate = true;
  27887. this.geometry.computeBoundingSphere();
  27888. };
  27889. BoxHelper.prototype.setFromObject = function (object) {
  27890. this.object = object;
  27891. this.update();
  27892. return this;
  27893. };
  27894. BoxHelper.prototype.copy = function (source) {
  27895. LineSegments.prototype.copy.call(this, source);
  27896. this.object = source.object;
  27897. return this;
  27898. };
  27899. BoxHelper.prototype.clone = function () {
  27900. return new this.constructor().copy(this);
  27901. };
  27902. /**
  27903. * @author WestLangley / http://github.com/WestLangley
  27904. */
  27905. function Box3Helper(box, color) {
  27906. this.type = 'Box3Helper';
  27907. this.box = box;
  27908. color = color || 0xffff00;
  27909. 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]);
  27910. 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];
  27911. var geometry = new BufferGeometry();
  27912. geometry.setIndex(new BufferAttribute(indices, 1));
  27913. geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));
  27914. LineSegments.call(this, geometry, new LineBasicMaterial({
  27915. color: color
  27916. }));
  27917. this.geometry.computeBoundingSphere();
  27918. }
  27919. Box3Helper.prototype = Object.create(LineSegments.prototype);
  27920. Box3Helper.prototype.constructor = Box3Helper;
  27921. Box3Helper.prototype.updateMatrixWorld = function (force) {
  27922. var box = this.box;
  27923. if (box.isEmpty()) return;
  27924. box.getCenter(this.position);
  27925. box.getSize(this.scale);
  27926. this.scale.multiplyScalar(0.5);
  27927. Object3D.prototype.updateMatrixWorld.call(this, force);
  27928. };
  27929. /**
  27930. * @author WestLangley / http://github.com/WestLangley
  27931. */
  27932. function PlaneHelper(plane, size, hex) {
  27933. this.type = 'PlaneHelper';
  27934. this.plane = plane;
  27935. this.size = size === undefined ? 1 : size;
  27936. var color = hex !== undefined ? hex : 0xffff00;
  27937. 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];
  27938. var geometry = new BufferGeometry();
  27939. geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));
  27940. geometry.computeBoundingSphere();
  27941. Line.call(this, geometry, new LineBasicMaterial({
  27942. color: color
  27943. })); //
  27944. var positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
  27945. var geometry2 = new BufferGeometry();
  27946. geometry2.addAttribute('position', new Float32BufferAttribute(positions2, 3));
  27947. geometry2.computeBoundingSphere();
  27948. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  27949. color: color,
  27950. opacity: 0.2,
  27951. transparent: true,
  27952. depthWrite: false
  27953. })));
  27954. }
  27955. PlaneHelper.prototype = Object.create(Line.prototype);
  27956. PlaneHelper.prototype.constructor = PlaneHelper;
  27957. PlaneHelper.prototype.updateMatrixWorld = function (force) {
  27958. var scale = -this.plane.constant;
  27959. if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
  27960. this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
  27961. this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  27962. this.lookAt(this.plane.normal);
  27963. Object3D.prototype.updateMatrixWorld.call(this, force);
  27964. };
  27965. /**
  27966. * @author WestLangley / http://github.com/WestLangley
  27967. * @author zz85 / http://github.com/zz85
  27968. * @author bhouston / http://clara.io
  27969. *
  27970. * Creates an arrow for visualizing directions
  27971. *
  27972. * Parameters:
  27973. * dir - Vector3
  27974. * origin - Vector3
  27975. * length - Number
  27976. * color - color in hex value
  27977. * headLength - Number
  27978. * headWidth - Number
  27979. */
  27980. var _axis = new Vector3();
  27981. var _lineGeometry, _coneGeometry;
  27982. function ArrowHelper(dir, origin, length, color, headLength, headWidth) {
  27983. // dir is assumed to be normalized
  27984. Object3D.call(this);
  27985. if (dir === undefined) dir = new Vector3(0, 0, 1);
  27986. if (origin === undefined) origin = new Vector3(0, 0, 0);
  27987. if (length === undefined) length = 1;
  27988. if (color === undefined) color = 0xffff00;
  27989. if (headLength === undefined) headLength = 0.2 * length;
  27990. if (headWidth === undefined) headWidth = 0.2 * headLength;
  27991. if (_lineGeometry === undefined) {
  27992. _lineGeometry = new BufferGeometry();
  27993. _lineGeometry.addAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  27994. _coneGeometry = new CylinderBufferGeometry(0, 0.5, 1, 5, 1);
  27995. _coneGeometry.translate(0, -0.5, 0);
  27996. }
  27997. this.position.copy(origin);
  27998. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  27999. color: color
  28000. }));
  28001. this.line.matrixAutoUpdate = false;
  28002. this.add(this.line);
  28003. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  28004. color: color
  28005. }));
  28006. this.cone.matrixAutoUpdate = false;
  28007. this.add(this.cone);
  28008. this.setDirection(dir);
  28009. this.setLength(length, headLength, headWidth);
  28010. }
  28011. ArrowHelper.prototype = Object.create(Object3D.prototype);
  28012. ArrowHelper.prototype.constructor = ArrowHelper;
  28013. ArrowHelper.prototype.setDirection = function (dir) {
  28014. // dir is assumed to be normalized
  28015. if (dir.y > 0.99999) {
  28016. this.quaternion.set(0, 0, 0, 1);
  28017. } else if (dir.y < -0.99999) {
  28018. this.quaternion.set(1, 0, 0, 0);
  28019. } else {
  28020. _axis.set(dir.z, 0, -dir.x).normalize();
  28021. var radians = Math.acos(dir.y);
  28022. this.quaternion.setFromAxisAngle(_axis, radians);
  28023. }
  28024. };
  28025. ArrowHelper.prototype.setLength = function (length, headLength, headWidth) {
  28026. if (headLength === undefined) headLength = 0.2 * length;
  28027. if (headWidth === undefined) headWidth = 0.2 * headLength;
  28028. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  28029. this.line.updateMatrix();
  28030. this.cone.scale.set(headWidth, headLength, headWidth);
  28031. this.cone.position.y = length;
  28032. this.cone.updateMatrix();
  28033. };
  28034. ArrowHelper.prototype.setColor = function (color) {
  28035. this.line.material.color.set(color);
  28036. this.cone.material.color.set(color);
  28037. };
  28038. ArrowHelper.prototype.copy = function (source) {
  28039. Object3D.prototype.copy.call(this, source, false);
  28040. this.line.copy(source.line);
  28041. this.cone.copy(source.cone);
  28042. return this;
  28043. };
  28044. ArrowHelper.prototype.clone = function () {
  28045. return new this.constructor().copy(this);
  28046. };
  28047. /**
  28048. * @author sroucheray / http://sroucheray.org/
  28049. * @author mrdoob / http://mrdoob.com/
  28050. */
  28051. function AxesHelper(size) {
  28052. size = size || 1;
  28053. var vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  28054. var colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  28055. var geometry = new BufferGeometry();
  28056. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  28057. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  28058. var material = new LineBasicMaterial({
  28059. vertexColors: VertexColors
  28060. });
  28061. LineSegments.call(this, geometry, material);
  28062. }
  28063. AxesHelper.prototype = Object.create(LineSegments.prototype);
  28064. AxesHelper.prototype.constructor = AxesHelper;
  28065. /**
  28066. * @author mrdoob / http://mrdoob.com/
  28067. */
  28068. function Face4(a, b, c, d, normal, color, materialIndex) {
  28069. console.warn('THREE.Face4 has been removed. A THREE.Face3 will be created instead.');
  28070. return new Face3(a, b, c, normal, color, materialIndex);
  28071. }
  28072. var LineStrip = 0;
  28073. exports.LineStrip = LineStrip;
  28074. var LinePieces = 1;
  28075. exports.LinePieces = LinePieces;
  28076. function MeshFaceMaterial(materials) {
  28077. console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
  28078. return materials;
  28079. }
  28080. function MultiMaterial(materials) {
  28081. if (materials === undefined) materials = [];
  28082. console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
  28083. materials.isMultiMaterial = true;
  28084. materials.materials = materials;
  28085. materials.clone = function () {
  28086. return materials.slice();
  28087. };
  28088. return materials;
  28089. }
  28090. function PointCloud(geometry, material) {
  28091. console.warn('THREE.PointCloud has been renamed to THREE.Points.');
  28092. return new Points(geometry, material);
  28093. }
  28094. function Particle(material) {
  28095. console.warn('THREE.Particle has been renamed to THREE.Sprite.');
  28096. return new Sprite(material);
  28097. }
  28098. function ParticleSystem(geometry, material) {
  28099. console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
  28100. return new Points(geometry, material);
  28101. }
  28102. function PointCloudMaterial(parameters) {
  28103. console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
  28104. return new PointsMaterial(parameters);
  28105. }
  28106. function ParticleBasicMaterial(parameters) {
  28107. console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
  28108. return new PointsMaterial(parameters);
  28109. }
  28110. function ParticleSystemMaterial(parameters) {
  28111. console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
  28112. return new PointsMaterial(parameters);
  28113. }
  28114. function Vertex(x, y, z) {
  28115. console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
  28116. return new Vector3(x, y, z);
  28117. } //
  28118. function DynamicBufferAttribute(array, itemSize) {
  28119. console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.');
  28120. return new BufferAttribute(array, itemSize).setDynamic(true);
  28121. }
  28122. function Int8Attribute(array, itemSize) {
  28123. console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
  28124. return new Int8BufferAttribute(array, itemSize);
  28125. }
  28126. function Uint8Attribute(array, itemSize) {
  28127. console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
  28128. return new Uint8BufferAttribute(array, itemSize);
  28129. }
  28130. function Uint8ClampedAttribute(array, itemSize) {
  28131. console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
  28132. return new Uint8ClampedBufferAttribute(array, itemSize);
  28133. }
  28134. function Int16Attribute(array, itemSize) {
  28135. console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
  28136. return new Int16BufferAttribute(array, itemSize);
  28137. }
  28138. function Uint16Attribute(array, itemSize) {
  28139. console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
  28140. return new Uint16BufferAttribute(array, itemSize);
  28141. }
  28142. function Int32Attribute(array, itemSize) {
  28143. console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
  28144. return new Int32BufferAttribute(array, itemSize);
  28145. }
  28146. function Uint32Attribute(array, itemSize) {
  28147. console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
  28148. return new Uint32BufferAttribute(array, itemSize);
  28149. }
  28150. function Float32Attribute(array, itemSize) {
  28151. console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
  28152. return new Float32BufferAttribute(array, itemSize);
  28153. }
  28154. function Float64Attribute(array, itemSize) {
  28155. console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
  28156. return new Float64BufferAttribute(array, itemSize);
  28157. } //
  28158. Curve.create = function (construct, getPoint) {
  28159. console.log('THREE.Curve.create() has been deprecated');
  28160. construct.prototype = Object.create(Curve.prototype);
  28161. construct.prototype.constructor = construct;
  28162. construct.prototype.getPoint = getPoint;
  28163. return construct;
  28164. }; //
  28165. Object.assign(CurvePath.prototype, {
  28166. createPointsGeometry: function (divisions) {
  28167. 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)
  28168. var pts = this.getPoints(divisions);
  28169. return this.createGeometry(pts);
  28170. },
  28171. createSpacedPointsGeometry: function (divisions) {
  28172. console.warn('THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.'); // generate geometry from equidistant sampling along the path
  28173. var pts = this.getSpacedPoints(divisions);
  28174. return this.createGeometry(pts);
  28175. },
  28176. createGeometry: function (points) {
  28177. console.warn('THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.');
  28178. var geometry = new Geometry();
  28179. for (var i = 0, l = points.length; i < l; i++) {
  28180. var point = points[i];
  28181. geometry.vertices.push(new Vector3(point.x, point.y, point.z || 0));
  28182. }
  28183. return geometry;
  28184. }
  28185. }); //
  28186. Object.assign(Path.prototype, {
  28187. fromPoints: function (points) {
  28188. console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
  28189. this.setFromPoints(points);
  28190. }
  28191. }); //
  28192. function ClosedSplineCurve3(points) {
  28193. console.warn('THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
  28194. CatmullRomCurve3.call(this, points);
  28195. this.type = 'catmullrom';
  28196. this.closed = true;
  28197. }
  28198. ClosedSplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
  28199. function SplineCurve3(points) {
  28200. console.warn('THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
  28201. CatmullRomCurve3.call(this, points);
  28202. this.type = 'catmullrom';
  28203. }
  28204. SplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
  28205. function Spline(points) {
  28206. console.warn('THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.');
  28207. CatmullRomCurve3.call(this, points);
  28208. this.type = 'catmullrom';
  28209. }
  28210. Spline.prototype = Object.create(CatmullRomCurve3.prototype);
  28211. Object.assign(Spline.prototype, {
  28212. initFromArray: function ()
  28213. /* a */
  28214. {
  28215. console.error('THREE.Spline: .initFromArray() has been removed.');
  28216. },
  28217. getControlPointsArray: function ()
  28218. /* optionalTarget */
  28219. {
  28220. console.error('THREE.Spline: .getControlPointsArray() has been removed.');
  28221. },
  28222. reparametrizeByArcLength: function ()
  28223. /* samplingCoef */
  28224. {
  28225. console.error('THREE.Spline: .reparametrizeByArcLength() has been removed.');
  28226. }
  28227. }); //
  28228. function AxisHelper(size) {
  28229. console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
  28230. return new AxesHelper(size);
  28231. }
  28232. function BoundingBoxHelper(object, color) {
  28233. console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
  28234. return new BoxHelper(object, color);
  28235. }
  28236. function EdgesHelper(object, hex) {
  28237. console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
  28238. return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
  28239. color: hex !== undefined ? hex : 0xffffff
  28240. }));
  28241. }
  28242. GridHelper.prototype.setColors = function () {
  28243. console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
  28244. };
  28245. SkeletonHelper.prototype.update = function () {
  28246. console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
  28247. };
  28248. function WireframeHelper(object, hex) {
  28249. console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
  28250. return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
  28251. color: hex !== undefined ? hex : 0xffffff
  28252. }));
  28253. } //
  28254. Object.assign(Loader.prototype, {
  28255. extractUrlBase: function (url) {
  28256. console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
  28257. return LoaderUtils.extractUrlBase(url);
  28258. }
  28259. });
  28260. Loader.Handlers = {
  28261. add: function ()
  28262. /* regex, loader */
  28263. {
  28264. console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
  28265. },
  28266. get: function ()
  28267. /* file */
  28268. {
  28269. console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
  28270. }
  28271. };
  28272. function XHRLoader(manager) {
  28273. console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
  28274. return new FileLoader(manager);
  28275. }
  28276. function BinaryTextureLoader(manager) {
  28277. console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
  28278. return new DataTextureLoader(manager);
  28279. }
  28280. Object.assign(ObjectLoader.prototype, {
  28281. setTexturePath: function (value) {
  28282. console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
  28283. return this.setResourcePath(value);
  28284. }
  28285. }); //
  28286. Object.assign(Box2.prototype, {
  28287. center: function (optionalTarget) {
  28288. console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
  28289. return this.getCenter(optionalTarget);
  28290. },
  28291. empty: function () {
  28292. console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
  28293. return this.isEmpty();
  28294. },
  28295. isIntersectionBox: function (box) {
  28296. console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
  28297. return this.intersectsBox(box);
  28298. },
  28299. size: function (optionalTarget) {
  28300. console.warn('THREE.Box2: .size() has been renamed to .getSize().');
  28301. return this.getSize(optionalTarget);
  28302. }
  28303. });
  28304. Object.assign(Box3.prototype, {
  28305. center: function (optionalTarget) {
  28306. console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
  28307. return this.getCenter(optionalTarget);
  28308. },
  28309. empty: function () {
  28310. console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
  28311. return this.isEmpty();
  28312. },
  28313. isIntersectionBox: function (box) {
  28314. console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
  28315. return this.intersectsBox(box);
  28316. },
  28317. isIntersectionSphere: function (sphere) {
  28318. console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  28319. return this.intersectsSphere(sphere);
  28320. },
  28321. size: function (optionalTarget) {
  28322. console.warn('THREE.Box3: .size() has been renamed to .getSize().');
  28323. return this.getSize(optionalTarget);
  28324. }
  28325. });
  28326. Line3.prototype.center = function (optionalTarget) {
  28327. console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
  28328. return this.getCenter(optionalTarget);
  28329. };
  28330. Object.assign(_Math, {
  28331. random16: function () {
  28332. console.warn('THREE.Math: .random16() has been deprecated. Use Math.random() instead.');
  28333. return Math.random();
  28334. },
  28335. nearestPowerOfTwo: function (value) {
  28336. console.warn('THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().');
  28337. return _Math.floorPowerOfTwo(value);
  28338. },
  28339. nextPowerOfTwo: function (value) {
  28340. console.warn('THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().');
  28341. return _Math.ceilPowerOfTwo(value);
  28342. }
  28343. });
  28344. Object.assign(Matrix3.prototype, {
  28345. flattenToArrayOffset: function (array, offset) {
  28346. console.warn("THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");
  28347. return this.toArray(array, offset);
  28348. },
  28349. multiplyVector3: function (vector) {
  28350. console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
  28351. return vector.applyMatrix3(this);
  28352. },
  28353. multiplyVector3Array: function ()
  28354. /* a */
  28355. {
  28356. console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
  28357. },
  28358. applyToBuffer: function (buffer
  28359. /*, offset, length */
  28360. ) {
  28361. console.warn('THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.');
  28362. return this.applyToBufferAttribute(buffer);
  28363. },
  28364. applyToVector3Array: function ()
  28365. /* array, offset, length */
  28366. {
  28367. console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
  28368. }
  28369. });
  28370. Object.assign(Matrix4.prototype, {
  28371. extractPosition: function (m) {
  28372. console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
  28373. return this.copyPosition(m);
  28374. },
  28375. flattenToArrayOffset: function (array, offset) {
  28376. console.warn("THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");
  28377. return this.toArray(array, offset);
  28378. },
  28379. getPosition: function () {
  28380. console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
  28381. return new Vector3().setFromMatrixColumn(this, 3);
  28382. },
  28383. setRotationFromQuaternion: function (q) {
  28384. console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
  28385. return this.makeRotationFromQuaternion(q);
  28386. },
  28387. multiplyToArray: function () {
  28388. console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
  28389. },
  28390. multiplyVector3: function (vector) {
  28391. console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28392. return vector.applyMatrix4(this);
  28393. },
  28394. multiplyVector4: function (vector) {
  28395. console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28396. return vector.applyMatrix4(this);
  28397. },
  28398. multiplyVector3Array: function ()
  28399. /* a */
  28400. {
  28401. console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
  28402. },
  28403. rotateAxis: function (v) {
  28404. console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
  28405. v.transformDirection(this);
  28406. },
  28407. crossVector: function (vector) {
  28408. console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28409. return vector.applyMatrix4(this);
  28410. },
  28411. translate: function () {
  28412. console.error('THREE.Matrix4: .translate() has been removed.');
  28413. },
  28414. rotateX: function () {
  28415. console.error('THREE.Matrix4: .rotateX() has been removed.');
  28416. },
  28417. rotateY: function () {
  28418. console.error('THREE.Matrix4: .rotateY() has been removed.');
  28419. },
  28420. rotateZ: function () {
  28421. console.error('THREE.Matrix4: .rotateZ() has been removed.');
  28422. },
  28423. rotateByAxis: function () {
  28424. console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
  28425. },
  28426. applyToBuffer: function (buffer
  28427. /*, offset, length */
  28428. ) {
  28429. console.warn('THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.');
  28430. return this.applyToBufferAttribute(buffer);
  28431. },
  28432. applyToVector3Array: function ()
  28433. /* array, offset, length */
  28434. {
  28435. console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
  28436. },
  28437. makeFrustum: function (left, right, bottom, top, near, far) {
  28438. console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
  28439. return this.makePerspective(left, right, top, bottom, near, far);
  28440. }
  28441. });
  28442. Plane.prototype.isIntersectionLine = function (line) {
  28443. console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
  28444. return this.intersectsLine(line);
  28445. };
  28446. Quaternion.prototype.multiplyVector3 = function (vector) {
  28447. console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
  28448. return vector.applyQuaternion(this);
  28449. };
  28450. Object.assign(Ray.prototype, {
  28451. isIntersectionBox: function (box) {
  28452. console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
  28453. return this.intersectsBox(box);
  28454. },
  28455. isIntersectionPlane: function (plane) {
  28456. console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
  28457. return this.intersectsPlane(plane);
  28458. },
  28459. isIntersectionSphere: function (sphere) {
  28460. console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  28461. return this.intersectsSphere(sphere);
  28462. }
  28463. });
  28464. Object.assign(Triangle.prototype, {
  28465. area: function () {
  28466. console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
  28467. return this.getArea();
  28468. },
  28469. barycoordFromPoint: function (point, target) {
  28470. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  28471. return this.getBarycoord(point, target);
  28472. },
  28473. midpoint: function (target) {
  28474. console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
  28475. return this.getMidpoint(target);
  28476. },
  28477. normal: function (target) {
  28478. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  28479. return this.getNormal(target);
  28480. },
  28481. plane: function (target) {
  28482. console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
  28483. return this.getPlane(target);
  28484. }
  28485. });
  28486. Object.assign(Triangle, {
  28487. barycoordFromPoint: function (point, a, b, c, target) {
  28488. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  28489. return Triangle.getBarycoord(point, a, b, c, target);
  28490. },
  28491. normal: function (a, b, c, target) {
  28492. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  28493. return Triangle.getNormal(a, b, c, target);
  28494. }
  28495. });
  28496. Object.assign(Shape.prototype, {
  28497. extractAllPoints: function (divisions) {
  28498. console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
  28499. return this.extractPoints(divisions);
  28500. },
  28501. extrude: function (options) {
  28502. console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
  28503. return new ExtrudeGeometry(this, options);
  28504. },
  28505. makeGeometry: function (options) {
  28506. console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
  28507. return new ShapeGeometry(this, options);
  28508. }
  28509. });
  28510. Object.assign(Vector2.prototype, {
  28511. fromAttribute: function (attribute, index, offset) {
  28512. console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28513. return this.fromBufferAttribute(attribute, index, offset);
  28514. },
  28515. distanceToManhattan: function (v) {
  28516. console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  28517. return this.manhattanDistanceTo(v);
  28518. },
  28519. lengthManhattan: function () {
  28520. console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
  28521. return this.manhattanLength();
  28522. }
  28523. });
  28524. Object.assign(Vector3.prototype, {
  28525. setEulerFromRotationMatrix: function () {
  28526. console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
  28527. },
  28528. setEulerFromQuaternion: function () {
  28529. console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
  28530. },
  28531. getPositionFromMatrix: function (m) {
  28532. console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
  28533. return this.setFromMatrixPosition(m);
  28534. },
  28535. getScaleFromMatrix: function (m) {
  28536. console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
  28537. return this.setFromMatrixScale(m);
  28538. },
  28539. getColumnFromMatrix: function (index, matrix) {
  28540. console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
  28541. return this.setFromMatrixColumn(matrix, index);
  28542. },
  28543. applyProjection: function (m) {
  28544. console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
  28545. return this.applyMatrix4(m);
  28546. },
  28547. fromAttribute: function (attribute, index, offset) {
  28548. console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28549. return this.fromBufferAttribute(attribute, index, offset);
  28550. },
  28551. distanceToManhattan: function (v) {
  28552. console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  28553. return this.manhattanDistanceTo(v);
  28554. },
  28555. lengthManhattan: function () {
  28556. console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
  28557. return this.manhattanLength();
  28558. }
  28559. });
  28560. Object.assign(Vector4.prototype, {
  28561. fromAttribute: function (attribute, index, offset) {
  28562. console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28563. return this.fromBufferAttribute(attribute, index, offset);
  28564. },
  28565. lengthManhattan: function () {
  28566. console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
  28567. return this.manhattanLength();
  28568. }
  28569. }); //
  28570. Object.assign(Geometry.prototype, {
  28571. computeTangents: function () {
  28572. console.error('THREE.Geometry: .computeTangents() has been removed.');
  28573. },
  28574. computeLineDistances: function () {
  28575. console.error('THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.');
  28576. }
  28577. });
  28578. Object.assign(Object3D.prototype, {
  28579. getChildByName: function (name) {
  28580. console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
  28581. return this.getObjectByName(name);
  28582. },
  28583. renderDepth: function () {
  28584. console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
  28585. },
  28586. translate: function (distance, axis) {
  28587. console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
  28588. return this.translateOnAxis(axis, distance);
  28589. },
  28590. getWorldRotation: function () {
  28591. console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
  28592. }
  28593. });
  28594. Object.defineProperties(Object3D.prototype, {
  28595. eulerOrder: {
  28596. get: function () {
  28597. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  28598. return this.rotation.order;
  28599. },
  28600. set: function (value) {
  28601. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  28602. this.rotation.order = value;
  28603. }
  28604. },
  28605. useQuaternion: {
  28606. get: function () {
  28607. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  28608. },
  28609. set: function () {
  28610. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  28611. }
  28612. }
  28613. });
  28614. Object.defineProperties(LOD.prototype, {
  28615. objects: {
  28616. get: function () {
  28617. console.warn('THREE.LOD: .objects has been renamed to .levels.');
  28618. return this.levels;
  28619. }
  28620. }
  28621. });
  28622. Object.defineProperty(Skeleton.prototype, 'useVertexTexture', {
  28623. get: function () {
  28624. console.warn('THREE.Skeleton: useVertexTexture has been removed.');
  28625. },
  28626. set: function () {
  28627. console.warn('THREE.Skeleton: useVertexTexture has been removed.');
  28628. }
  28629. });
  28630. SkinnedMesh.prototype.initBones = function () {
  28631. console.error('THREE.SkinnedMesh: initBones() has been removed.');
  28632. };
  28633. Object.defineProperty(Curve.prototype, '__arcLengthDivisions', {
  28634. get: function () {
  28635. console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
  28636. return this.arcLengthDivisions;
  28637. },
  28638. set: function (value) {
  28639. console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
  28640. this.arcLengthDivisions = value;
  28641. }
  28642. }); //
  28643. PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
  28644. console.warn("THREE.PerspectiveCamera.setLens is deprecated. " + "Use .setFocalLength and .filmGauge for a photographic setup.");
  28645. if (filmGauge !== undefined) this.filmGauge = filmGauge;
  28646. this.setFocalLength(focalLength);
  28647. }; //
  28648. Object.defineProperties(Light.prototype, {
  28649. onlyShadow: {
  28650. set: function () {
  28651. console.warn('THREE.Light: .onlyShadow has been removed.');
  28652. }
  28653. },
  28654. shadowCameraFov: {
  28655. set: function (value) {
  28656. console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
  28657. this.shadow.camera.fov = value;
  28658. }
  28659. },
  28660. shadowCameraLeft: {
  28661. set: function (value) {
  28662. console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
  28663. this.shadow.camera.left = value;
  28664. }
  28665. },
  28666. shadowCameraRight: {
  28667. set: function (value) {
  28668. console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
  28669. this.shadow.camera.right = value;
  28670. }
  28671. },
  28672. shadowCameraTop: {
  28673. set: function (value) {
  28674. console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
  28675. this.shadow.camera.top = value;
  28676. }
  28677. },
  28678. shadowCameraBottom: {
  28679. set: function (value) {
  28680. console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
  28681. this.shadow.camera.bottom = value;
  28682. }
  28683. },
  28684. shadowCameraNear: {
  28685. set: function (value) {
  28686. console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
  28687. this.shadow.camera.near = value;
  28688. }
  28689. },
  28690. shadowCameraFar: {
  28691. set: function (value) {
  28692. console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
  28693. this.shadow.camera.far = value;
  28694. }
  28695. },
  28696. shadowCameraVisible: {
  28697. set: function () {
  28698. console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
  28699. }
  28700. },
  28701. shadowBias: {
  28702. set: function (value) {
  28703. console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
  28704. this.shadow.bias = value;
  28705. }
  28706. },
  28707. shadowDarkness: {
  28708. set: function () {
  28709. console.warn('THREE.Light: .shadowDarkness has been removed.');
  28710. }
  28711. },
  28712. shadowMapWidth: {
  28713. set: function (value) {
  28714. console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
  28715. this.shadow.mapSize.width = value;
  28716. }
  28717. },
  28718. shadowMapHeight: {
  28719. set: function (value) {
  28720. console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
  28721. this.shadow.mapSize.height = value;
  28722. }
  28723. }
  28724. }); //
  28725. Object.defineProperties(BufferAttribute.prototype, {
  28726. length: {
  28727. get: function () {
  28728. console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
  28729. return this.array.length;
  28730. }
  28731. }
  28732. });
  28733. Object.assign(BufferAttribute.prototype, {
  28734. copyIndicesArray: function ()
  28735. /* indices */
  28736. {
  28737. console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
  28738. },
  28739. setArray: function (array) {
  28740. console.warn('THREE.BufferAttribute: .setArray has been deprecated. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  28741. this.count = array !== undefined ? array.length / this.itemSize : 0;
  28742. this.array = array;
  28743. return this;
  28744. }
  28745. });
  28746. Object.assign(BufferGeometry.prototype, {
  28747. addIndex: function (index) {
  28748. console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
  28749. this.setIndex(index);
  28750. },
  28751. addDrawCall: function (start, count, indexOffset) {
  28752. if (indexOffset !== undefined) {
  28753. console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
  28754. }
  28755. console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
  28756. this.addGroup(start, count);
  28757. },
  28758. clearDrawCalls: function () {
  28759. console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
  28760. this.clearGroups();
  28761. },
  28762. computeTangents: function () {
  28763. console.warn('THREE.BufferGeometry: .computeTangents() has been removed.');
  28764. },
  28765. computeOffsets: function () {
  28766. console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
  28767. }
  28768. });
  28769. Object.defineProperties(BufferGeometry.prototype, {
  28770. drawcalls: {
  28771. get: function () {
  28772. console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
  28773. return this.groups;
  28774. }
  28775. },
  28776. offsets: {
  28777. get: function () {
  28778. console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
  28779. return this.groups;
  28780. }
  28781. }
  28782. });
  28783. Object.assign(InterleavedBuffer.prototype, {
  28784. setArray: function (array) {
  28785. console.warn('THREE.InterleavedBuffer: .setArray has been deprecated. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  28786. this.count = array !== undefined ? array.length / this.stride : 0;
  28787. this.array = array;
  28788. return this;
  28789. }
  28790. }); //
  28791. Object.assign(ExtrudeBufferGeometry.prototype, {
  28792. getArrays: function () {
  28793. console.error('THREE.ExtrudeBufferGeometry: .getArrays() has been removed.');
  28794. },
  28795. addShapeList: function () {
  28796. console.error('THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.');
  28797. },
  28798. addShape: function () {
  28799. console.error('THREE.ExtrudeBufferGeometry: .addShape() has been removed.');
  28800. }
  28801. }); //
  28802. Object.defineProperties(Uniform.prototype, {
  28803. dynamic: {
  28804. set: function () {
  28805. console.warn('THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.');
  28806. }
  28807. },
  28808. onUpdate: {
  28809. value: function () {
  28810. console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
  28811. return this;
  28812. }
  28813. }
  28814. }); //
  28815. Object.defineProperties(Material.prototype, {
  28816. wrapAround: {
  28817. get: function () {
  28818. console.warn('THREE.Material: .wrapAround has been removed.');
  28819. },
  28820. set: function () {
  28821. console.warn('THREE.Material: .wrapAround has been removed.');
  28822. }
  28823. },
  28824. overdraw: {
  28825. get: function () {
  28826. console.warn('THREE.Material: .overdraw has been removed.');
  28827. },
  28828. set: function () {
  28829. console.warn('THREE.Material: .overdraw has been removed.');
  28830. }
  28831. },
  28832. wrapRGB: {
  28833. get: function () {
  28834. console.warn('THREE.Material: .wrapRGB has been removed.');
  28835. return new Color();
  28836. }
  28837. },
  28838. shading: {
  28839. get: function () {
  28840. console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  28841. },
  28842. set: function (value) {
  28843. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  28844. this.flatShading = value === FlatShading;
  28845. }
  28846. },
  28847. stencilMask: {
  28848. get: function () {
  28849. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  28850. return this.stencilFuncMask;
  28851. },
  28852. set: function (value) {
  28853. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  28854. this.stencilFuncMask = value;
  28855. }
  28856. }
  28857. });
  28858. Object.defineProperties(MeshPhongMaterial.prototype, {
  28859. metal: {
  28860. get: function () {
  28861. console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.');
  28862. return false;
  28863. },
  28864. set: function () {
  28865. console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead');
  28866. }
  28867. }
  28868. });
  28869. Object.defineProperties(ShaderMaterial.prototype, {
  28870. derivatives: {
  28871. get: function () {
  28872. console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  28873. return this.extensions.derivatives;
  28874. },
  28875. set: function (value) {
  28876. console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  28877. this.extensions.derivatives = value;
  28878. }
  28879. }
  28880. }); //
  28881. Object.assign(WebGLRenderer.prototype, {
  28882. clearTarget: function (renderTarget, color, depth, stencil) {
  28883. console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
  28884. this.setRenderTarget(renderTarget);
  28885. this.clear(color, depth, stencil);
  28886. },
  28887. animate: function (callback) {
  28888. console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
  28889. this.setAnimationLoop(callback);
  28890. },
  28891. getCurrentRenderTarget: function () {
  28892. console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
  28893. return this.getRenderTarget();
  28894. },
  28895. getMaxAnisotropy: function () {
  28896. console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
  28897. return this.capabilities.getMaxAnisotropy();
  28898. },
  28899. getPrecision: function () {
  28900. console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
  28901. return this.capabilities.precision;
  28902. },
  28903. resetGLState: function () {
  28904. console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
  28905. return this.state.reset();
  28906. },
  28907. supportsFloatTextures: function () {
  28908. console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
  28909. return this.extensions.get('OES_texture_float');
  28910. },
  28911. supportsHalfFloatTextures: function () {
  28912. console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
  28913. return this.extensions.get('OES_texture_half_float');
  28914. },
  28915. supportsStandardDerivatives: function () {
  28916. console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
  28917. return this.extensions.get('OES_standard_derivatives');
  28918. },
  28919. supportsCompressedTextureS3TC: function () {
  28920. console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
  28921. return this.extensions.get('WEBGL_compressed_texture_s3tc');
  28922. },
  28923. supportsCompressedTexturePVRTC: function () {
  28924. console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
  28925. return this.extensions.get('WEBGL_compressed_texture_pvrtc');
  28926. },
  28927. supportsBlendMinMax: function () {
  28928. console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
  28929. return this.extensions.get('EXT_blend_minmax');
  28930. },
  28931. supportsVertexTextures: function () {
  28932. console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
  28933. return this.capabilities.vertexTextures;
  28934. },
  28935. supportsInstancedArrays: function () {
  28936. console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
  28937. return this.extensions.get('ANGLE_instanced_arrays');
  28938. },
  28939. enableScissorTest: function (boolean) {
  28940. console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
  28941. this.setScissorTest(boolean);
  28942. },
  28943. initMaterial: function () {
  28944. console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
  28945. },
  28946. addPrePlugin: function () {
  28947. console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
  28948. },
  28949. addPostPlugin: function () {
  28950. console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
  28951. },
  28952. updateShadowMap: function () {
  28953. console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
  28954. },
  28955. setFaceCulling: function () {
  28956. console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
  28957. },
  28958. allocTextureUnit: function () {
  28959. console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
  28960. },
  28961. setTexture: function () {
  28962. console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
  28963. },
  28964. setTexture2D: function () {
  28965. console.warn('THREE.WebGLRenderer: .setTexture2D() has been removed.');
  28966. },
  28967. setTextureCube: function () {
  28968. console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
  28969. },
  28970. getActiveMipMapLevel: function () {
  28971. console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
  28972. return this.getActiveMipmapLevel();
  28973. }
  28974. });
  28975. Object.defineProperties(WebGLRenderer.prototype, {
  28976. shadowMapEnabled: {
  28977. get: function () {
  28978. return this.shadowMap.enabled;
  28979. },
  28980. set: function (value) {
  28981. console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
  28982. this.shadowMap.enabled = value;
  28983. }
  28984. },
  28985. shadowMapType: {
  28986. get: function () {
  28987. return this.shadowMap.type;
  28988. },
  28989. set: function (value) {
  28990. console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
  28991. this.shadowMap.type = value;
  28992. }
  28993. },
  28994. shadowMapCullFace: {
  28995. get: function () {
  28996. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  28997. return undefined;
  28998. },
  28999. set: function ()
  29000. /* value */
  29001. {
  29002. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  29003. }
  29004. },
  29005. context: {
  29006. get: function () {
  29007. console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
  29008. return this.getContext();
  29009. }
  29010. }
  29011. });
  29012. Object.defineProperties(WebGLShadowMap.prototype, {
  29013. cullFace: {
  29014. get: function () {
  29015. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  29016. return undefined;
  29017. },
  29018. set: function ()
  29019. /* cullFace */
  29020. {
  29021. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  29022. }
  29023. },
  29024. renderReverseSided: {
  29025. get: function () {
  29026. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  29027. return undefined;
  29028. },
  29029. set: function () {
  29030. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  29031. }
  29032. },
  29033. renderSingleSided: {
  29034. get: function () {
  29035. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  29036. return undefined;
  29037. },
  29038. set: function () {
  29039. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  29040. }
  29041. }
  29042. }); //
  29043. Object.defineProperties(WebGLRenderTargetCube.prototype, {
  29044. activeCubeFace: {
  29045. set: function ()
  29046. /* value */
  29047. {
  29048. console.warn('THREE.WebGLRenderTargetCube: .activeCubeFace has been removed. It is now the second parameter of WebGLRenderer.setRenderTarget().');
  29049. }
  29050. },
  29051. activeMipMapLevel: {
  29052. set: function ()
  29053. /* value */
  29054. {
  29055. console.warn('THREE.WebGLRenderTargetCube: .activeMipMapLevel has been removed. It is now the third parameter of WebGLRenderer.setRenderTarget().');
  29056. }
  29057. }
  29058. }); //
  29059. Object.defineProperties(WebGLRenderTarget.prototype, {
  29060. wrapS: {
  29061. get: function () {
  29062. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  29063. return this.texture.wrapS;
  29064. },
  29065. set: function (value) {
  29066. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  29067. this.texture.wrapS = value;
  29068. }
  29069. },
  29070. wrapT: {
  29071. get: function () {
  29072. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  29073. return this.texture.wrapT;
  29074. },
  29075. set: function (value) {
  29076. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  29077. this.texture.wrapT = value;
  29078. }
  29079. },
  29080. magFilter: {
  29081. get: function () {
  29082. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  29083. return this.texture.magFilter;
  29084. },
  29085. set: function (value) {
  29086. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  29087. this.texture.magFilter = value;
  29088. }
  29089. },
  29090. minFilter: {
  29091. get: function () {
  29092. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  29093. return this.texture.minFilter;
  29094. },
  29095. set: function (value) {
  29096. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  29097. this.texture.minFilter = value;
  29098. }
  29099. },
  29100. anisotropy: {
  29101. get: function () {
  29102. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  29103. return this.texture.anisotropy;
  29104. },
  29105. set: function (value) {
  29106. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  29107. this.texture.anisotropy = value;
  29108. }
  29109. },
  29110. offset: {
  29111. get: function () {
  29112. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  29113. return this.texture.offset;
  29114. },
  29115. set: function (value) {
  29116. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  29117. this.texture.offset = value;
  29118. }
  29119. },
  29120. repeat: {
  29121. get: function () {
  29122. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  29123. return this.texture.repeat;
  29124. },
  29125. set: function (value) {
  29126. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  29127. this.texture.repeat = value;
  29128. }
  29129. },
  29130. format: {
  29131. get: function () {
  29132. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  29133. return this.texture.format;
  29134. },
  29135. set: function (value) {
  29136. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  29137. this.texture.format = value;
  29138. }
  29139. },
  29140. type: {
  29141. get: function () {
  29142. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  29143. return this.texture.type;
  29144. },
  29145. set: function (value) {
  29146. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  29147. this.texture.type = value;
  29148. }
  29149. },
  29150. generateMipmaps: {
  29151. get: function () {
  29152. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  29153. return this.texture.generateMipmaps;
  29154. },
  29155. set: function (value) {
  29156. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  29157. this.texture.generateMipmaps = value;
  29158. }
  29159. }
  29160. }); //
  29161. Object.defineProperties(WebVRManager.prototype, {
  29162. standing: {
  29163. set: function ()
  29164. /* value */
  29165. {
  29166. console.warn('THREE.WebVRManager: .standing has been removed.');
  29167. }
  29168. },
  29169. userHeight: {
  29170. set: function ()
  29171. /* value */
  29172. {
  29173. console.warn('THREE.WebVRManager: .userHeight has been removed.');
  29174. }
  29175. }
  29176. }); //
  29177. Audio.prototype.load = function (file) {
  29178. console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
  29179. var scope = this;
  29180. var audioLoader = new AudioLoader();
  29181. audioLoader.load(file, function (buffer) {
  29182. scope.setBuffer(buffer);
  29183. });
  29184. return this;
  29185. };
  29186. AudioAnalyser.prototype.getData = function () {
  29187. console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
  29188. return this.getFrequencyData();
  29189. }; //
  29190. CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
  29191. console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
  29192. return this.update(renderer, scene);
  29193. }; //
  29194. var GeometryUtils = {
  29195. merge: function (geometry1, geometry2, materialIndexOffset) {
  29196. console.warn('THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.');
  29197. var matrix;
  29198. if (geometry2.isMesh) {
  29199. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  29200. matrix = geometry2.matrix;
  29201. geometry2 = geometry2.geometry;
  29202. }
  29203. geometry1.merge(geometry2, matrix, materialIndexOffset);
  29204. },
  29205. center: function (geometry) {
  29206. console.warn('THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.');
  29207. return geometry.center();
  29208. }
  29209. };
  29210. exports.GeometryUtils = GeometryUtils;
  29211. ImageUtils.crossOrigin = undefined;
  29212. ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
  29213. console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
  29214. var loader = new TextureLoader();
  29215. loader.setCrossOrigin(this.crossOrigin);
  29216. var texture = loader.load(url, onLoad, undefined, onError);
  29217. if (mapping) texture.mapping = mapping;
  29218. return texture;
  29219. };
  29220. ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
  29221. console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
  29222. var loader = new CubeTextureLoader();
  29223. loader.setCrossOrigin(this.crossOrigin);
  29224. var texture = loader.load(urls, onLoad, undefined, onError);
  29225. if (mapping) texture.mapping = mapping;
  29226. return texture;
  29227. };
  29228. ImageUtils.loadCompressedTexture = function () {
  29229. console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
  29230. };
  29231. ImageUtils.loadCompressedTextureCube = function () {
  29232. console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
  29233. }; //
  29234. function CanvasRenderer() {
  29235. console.error('THREE.CanvasRenderer has been removed');
  29236. } //
  29237. function JSONLoader() {
  29238. console.error('THREE.JSONLoader has been removed.');
  29239. } //
  29240. var SceneUtils = {
  29241. createMultiMaterialObject: function ()
  29242. /* geometry, materials */
  29243. {
  29244. console.error('THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js');
  29245. },
  29246. detach: function ()
  29247. /* child, parent, scene */
  29248. {
  29249. console.error('THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js');
  29250. },
  29251. attach: function ()
  29252. /* child, scene, parent */
  29253. {
  29254. console.error('THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js');
  29255. }
  29256. }; //
  29257. exports.SceneUtils = SceneUtils;
  29258. function LensFlare() {
  29259. console.error('THREE.LensFlare has been moved to /examples/js/objects/Lensflare.js');
  29260. }
  29261. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  29262. /* eslint-disable no-undef */
  29263. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  29264. detail: {
  29265. revision: REVISION
  29266. }
  29267. }));
  29268. /* eslint-enable no-undef */
  29269. }
  29270. },{}],"../node_modules/process/browser.js":[function(require,module,exports) {
  29271. // shim for using process in browser
  29272. var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it
  29273. // don't break things. But we need to wrap it in a try catch in case it is
  29274. // wrapped in strict mode code which doesn't define any globals. It's inside a
  29275. // function because try/catches deoptimize in certain engines.
  29276. var cachedSetTimeout;
  29277. var cachedClearTimeout;
  29278. function defaultSetTimout() {
  29279. throw new Error('setTimeout has not been defined');
  29280. }
  29281. function defaultClearTimeout() {
  29282. throw new Error('clearTimeout has not been defined');
  29283. }
  29284. (function () {
  29285. try {
  29286. if (typeof setTimeout === 'function') {
  29287. cachedSetTimeout = setTimeout;
  29288. } else {
  29289. cachedSetTimeout = defaultSetTimout;
  29290. }
  29291. } catch (e) {
  29292. cachedSetTimeout = defaultSetTimout;
  29293. }
  29294. try {
  29295. if (typeof clearTimeout === 'function') {
  29296. cachedClearTimeout = clearTimeout;
  29297. } else {
  29298. cachedClearTimeout = defaultClearTimeout;
  29299. }
  29300. } catch (e) {
  29301. cachedClearTimeout = defaultClearTimeout;
  29302. }
  29303. })();
  29304. function runTimeout(fun) {
  29305. if (cachedSetTimeout === setTimeout) {
  29306. //normal enviroments in sane situations
  29307. return setTimeout(fun, 0);
  29308. } // if setTimeout wasn't available but was latter defined
  29309. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  29310. cachedSetTimeout = setTimeout;
  29311. return setTimeout(fun, 0);
  29312. }
  29313. try {
  29314. // when when somebody has screwed with setTimeout but no I.E. maddness
  29315. return cachedSetTimeout(fun, 0);
  29316. } catch (e) {
  29317. try {
  29318. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  29319. return cachedSetTimeout.call(null, fun, 0);
  29320. } catch (e) {
  29321. // 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
  29322. return cachedSetTimeout.call(this, fun, 0);
  29323. }
  29324. }
  29325. }
  29326. function runClearTimeout(marker) {
  29327. if (cachedClearTimeout === clearTimeout) {
  29328. //normal enviroments in sane situations
  29329. return clearTimeout(marker);
  29330. } // if clearTimeout wasn't available but was latter defined
  29331. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  29332. cachedClearTimeout = clearTimeout;
  29333. return clearTimeout(marker);
  29334. }
  29335. try {
  29336. // when when somebody has screwed with setTimeout but no I.E. maddness
  29337. return cachedClearTimeout(marker);
  29338. } catch (e) {
  29339. try {
  29340. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  29341. return cachedClearTimeout.call(null, marker);
  29342. } catch (e) {
  29343. // 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.
  29344. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  29345. return cachedClearTimeout.call(this, marker);
  29346. }
  29347. }
  29348. }
  29349. var queue = [];
  29350. var draining = false;
  29351. var currentQueue;
  29352. var queueIndex = -1;
  29353. function cleanUpNextTick() {
  29354. if (!draining || !currentQueue) {
  29355. return;
  29356. }
  29357. draining = false;
  29358. if (currentQueue.length) {
  29359. queue = currentQueue.concat(queue);
  29360. } else {
  29361. queueIndex = -1;
  29362. }
  29363. if (queue.length) {
  29364. drainQueue();
  29365. }
  29366. }
  29367. function drainQueue() {
  29368. if (draining) {
  29369. return;
  29370. }
  29371. var timeout = runTimeout(cleanUpNextTick);
  29372. draining = true;
  29373. var len = queue.length;
  29374. while (len) {
  29375. currentQueue = queue;
  29376. queue = [];
  29377. while (++queueIndex < len) {
  29378. if (currentQueue) {
  29379. currentQueue[queueIndex].run();
  29380. }
  29381. }
  29382. queueIndex = -1;
  29383. len = queue.length;
  29384. }
  29385. currentQueue = null;
  29386. draining = false;
  29387. runClearTimeout(timeout);
  29388. }
  29389. process.nextTick = function (fun) {
  29390. var args = new Array(arguments.length - 1);
  29391. if (arguments.length > 1) {
  29392. for (var i = 1; i < arguments.length; i++) {
  29393. args[i - 1] = arguments[i];
  29394. }
  29395. }
  29396. queue.push(new Item(fun, args));
  29397. if (queue.length === 1 && !draining) {
  29398. runTimeout(drainQueue);
  29399. }
  29400. }; // v8 likes predictible objects
  29401. function Item(fun, array) {
  29402. this.fun = fun;
  29403. this.array = array;
  29404. }
  29405. Item.prototype.run = function () {
  29406. this.fun.apply(null, this.array);
  29407. };
  29408. process.title = 'browser';
  29409. process.env = {};
  29410. process.argv = [];
  29411. process.version = ''; // empty string to avoid regexp issues
  29412. process.versions = {};
  29413. function noop() {}
  29414. process.on = noop;
  29415. process.addListener = noop;
  29416. process.once = noop;
  29417. process.off = noop;
  29418. process.removeListener = noop;
  29419. process.removeAllListeners = noop;
  29420. process.emit = noop;
  29421. process.prependListener = noop;
  29422. process.prependOnceListener = noop;
  29423. process.listeners = function (name) {
  29424. return [];
  29425. };
  29426. process.binding = function (name) {
  29427. throw new Error('process.binding is not supported');
  29428. };
  29429. process.cwd = function () {
  29430. return '/';
  29431. };
  29432. process.chdir = function (dir) {
  29433. throw new Error('process.chdir is not supported');
  29434. };
  29435. process.umask = function () {
  29436. return 0;
  29437. };
  29438. },{}],"../node_modules/path-browserify/index.js":[function(require,module,exports) {
  29439. var process = require("process");
  29440. // .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1,
  29441. // backported and transplited with Babel, with backwards-compat fixes
  29442. // Copyright Joyent, Inc. and other Node contributors.
  29443. //
  29444. // Permission is hereby granted, free of charge, to any person obtaining a
  29445. // copy of this software and associated documentation files (the
  29446. // "Software"), to deal in the Software without restriction, including
  29447. // without limitation the rights to use, copy, modify, merge, publish,
  29448. // distribute, sublicense, and/or sell copies of the Software, and to permit
  29449. // persons to whom the Software is furnished to do so, subject to the
  29450. // following conditions:
  29451. //
  29452. // The above copyright notice and this permission notice shall be included
  29453. // in all copies or substantial portions of the Software.
  29454. //
  29455. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  29456. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  29457. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  29458. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  29459. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  29460. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  29461. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  29462. // resolves . and .. elements in a path array with directory names there
  29463. // must be no slashes, empty elements, or device names (c:\) in the array
  29464. // (so also no leading and trailing slashes - it does not distinguish
  29465. // relative and absolute paths)
  29466. function normalizeArray(parts, allowAboveRoot) {
  29467. // if the path tries to go above the root, `up` ends up > 0
  29468. var up = 0;
  29469. for (var i = parts.length - 1; i >= 0; i--) {
  29470. var last = parts[i];
  29471. if (last === '.') {
  29472. parts.splice(i, 1);
  29473. } else if (last === '..') {
  29474. parts.splice(i, 1);
  29475. up++;
  29476. } else if (up) {
  29477. parts.splice(i, 1);
  29478. up--;
  29479. }
  29480. }
  29481. // if the path is allowed to go above the root, restore leading ..s
  29482. if (allowAboveRoot) {
  29483. for (; up--; up) {
  29484. parts.unshift('..');
  29485. }
  29486. }
  29487. return parts;
  29488. }
  29489. // path.resolve([from ...], to)
  29490. // posix version
  29491. exports.resolve = function() {
  29492. var resolvedPath = '',
  29493. resolvedAbsolute = false;
  29494. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  29495. var path = (i >= 0) ? arguments[i] : process.cwd();
  29496. // Skip empty and invalid entries
  29497. if (typeof path !== 'string') {
  29498. throw new TypeError('Arguments to path.resolve must be strings');
  29499. } else if (!path) {
  29500. continue;
  29501. }
  29502. resolvedPath = path + '/' + resolvedPath;
  29503. resolvedAbsolute = path.charAt(0) === '/';
  29504. }
  29505. // At this point the path should be resolved to a full absolute path, but
  29506. // handle relative paths to be safe (might happen when process.cwd() fails)
  29507. // Normalize the path
  29508. resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
  29509. return !!p;
  29510. }), !resolvedAbsolute).join('/');
  29511. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  29512. };
  29513. // path.normalize(path)
  29514. // posix version
  29515. exports.normalize = function(path) {
  29516. var isAbsolute = exports.isAbsolute(path),
  29517. trailingSlash = substr(path, -1) === '/';
  29518. // Normalize the path
  29519. path = normalizeArray(filter(path.split('/'), function(p) {
  29520. return !!p;
  29521. }), !isAbsolute).join('/');
  29522. if (!path && !isAbsolute) {
  29523. path = '.';
  29524. }
  29525. if (path && trailingSlash) {
  29526. path += '/';
  29527. }
  29528. return (isAbsolute ? '/' : '') + path;
  29529. };
  29530. // posix version
  29531. exports.isAbsolute = function(path) {
  29532. return path.charAt(0) === '/';
  29533. };
  29534. // posix version
  29535. exports.join = function() {
  29536. var paths = Array.prototype.slice.call(arguments, 0);
  29537. return exports.normalize(filter(paths, function(p, index) {
  29538. if (typeof p !== 'string') {
  29539. throw new TypeError('Arguments to path.join must be strings');
  29540. }
  29541. return p;
  29542. }).join('/'));
  29543. };
  29544. // path.relative(from, to)
  29545. // posix version
  29546. exports.relative = function(from, to) {
  29547. from = exports.resolve(from).substr(1);
  29548. to = exports.resolve(to).substr(1);
  29549. function trim(arr) {
  29550. var start = 0;
  29551. for (; start < arr.length; start++) {
  29552. if (arr[start] !== '') break;
  29553. }
  29554. var end = arr.length - 1;
  29555. for (; end >= 0; end--) {
  29556. if (arr[end] !== '') break;
  29557. }
  29558. if (start > end) return [];
  29559. return arr.slice(start, end - start + 1);
  29560. }
  29561. var fromParts = trim(from.split('/'));
  29562. var toParts = trim(to.split('/'));
  29563. var length = Math.min(fromParts.length, toParts.length);
  29564. var samePartsLength = length;
  29565. for (var i = 0; i < length; i++) {
  29566. if (fromParts[i] !== toParts[i]) {
  29567. samePartsLength = i;
  29568. break;
  29569. }
  29570. }
  29571. var outputParts = [];
  29572. for (var i = samePartsLength; i < fromParts.length; i++) {
  29573. outputParts.push('..');
  29574. }
  29575. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  29576. return outputParts.join('/');
  29577. };
  29578. exports.sep = '/';
  29579. exports.delimiter = ':';
  29580. exports.dirname = function (path) {
  29581. if (typeof path !== 'string') path = path + '';
  29582. if (path.length === 0) return '.';
  29583. var code = path.charCodeAt(0);
  29584. var hasRoot = code === 47 /*/*/;
  29585. var end = -1;
  29586. var matchedSlash = true;
  29587. for (var i = path.length - 1; i >= 1; --i) {
  29588. code = path.charCodeAt(i);
  29589. if (code === 47 /*/*/) {
  29590. if (!matchedSlash) {
  29591. end = i;
  29592. break;
  29593. }
  29594. } else {
  29595. // We saw the first non-path separator
  29596. matchedSlash = false;
  29597. }
  29598. }
  29599. if (end === -1) return hasRoot ? '/' : '.';
  29600. if (hasRoot && end === 1) {
  29601. // return '//';
  29602. // Backwards-compat fix:
  29603. return '/';
  29604. }
  29605. return path.slice(0, end);
  29606. };
  29607. function basename(path) {
  29608. if (typeof path !== 'string') path = path + '';
  29609. var start = 0;
  29610. var end = -1;
  29611. var matchedSlash = true;
  29612. var i;
  29613. for (i = path.length - 1; i >= 0; --i) {
  29614. if (path.charCodeAt(i) === 47 /*/*/) {
  29615. // If we reached a path separator that was not part of a set of path
  29616. // separators at the end of the string, stop now
  29617. if (!matchedSlash) {
  29618. start = i + 1;
  29619. break;
  29620. }
  29621. } else if (end === -1) {
  29622. // We saw the first non-path separator, mark this as the end of our
  29623. // path component
  29624. matchedSlash = false;
  29625. end = i + 1;
  29626. }
  29627. }
  29628. if (end === -1) return '';
  29629. return path.slice(start, end);
  29630. }
  29631. // Uses a mixed approach for backwards-compatibility, as ext behavior changed
  29632. // in new Node.js versions, so only basename() above is backported here
  29633. exports.basename = function (path, ext) {
  29634. var f = basename(path);
  29635. if (ext && f.substr(-1 * ext.length) === ext) {
  29636. f = f.substr(0, f.length - ext.length);
  29637. }
  29638. return f;
  29639. };
  29640. exports.extname = function (path) {
  29641. if (typeof path !== 'string') path = path + '';
  29642. var startDot = -1;
  29643. var startPart = 0;
  29644. var end = -1;
  29645. var matchedSlash = true;
  29646. // Track the state of characters (if any) we see before our first dot and
  29647. // after any path separator we find
  29648. var preDotState = 0;
  29649. for (var i = path.length - 1; i >= 0; --i) {
  29650. var code = path.charCodeAt(i);
  29651. if (code === 47 /*/*/) {
  29652. // If we reached a path separator that was not part of a set of path
  29653. // separators at the end of the string, stop now
  29654. if (!matchedSlash) {
  29655. startPart = i + 1;
  29656. break;
  29657. }
  29658. continue;
  29659. }
  29660. if (end === -1) {
  29661. // We saw the first non-path separator, mark this as the end of our
  29662. // extension
  29663. matchedSlash = false;
  29664. end = i + 1;
  29665. }
  29666. if (code === 46 /*.*/) {
  29667. // If this is our first dot, mark it as the start of our extension
  29668. if (startDot === -1)
  29669. startDot = i;
  29670. else if (preDotState !== 1)
  29671. preDotState = 1;
  29672. } else if (startDot !== -1) {
  29673. // We saw a non-dot and non-path separator before our dot, so we should
  29674. // have a good chance at having a non-empty extension
  29675. preDotState = -1;
  29676. }
  29677. }
  29678. if (startDot === -1 || end === -1 ||
  29679. // We saw a non-dot character immediately before the dot
  29680. preDotState === 0 ||
  29681. // The (right-most) trimmed path component is exactly '..'
  29682. preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
  29683. return '';
  29684. }
  29685. return path.slice(startDot, end);
  29686. };
  29687. function filter (xs, f) {
  29688. if (xs.filter) return xs.filter(f);
  29689. var res = [];
  29690. for (var i = 0; i < xs.length; i++) {
  29691. if (f(xs[i], i, xs)) res.push(xs[i]);
  29692. }
  29693. return res;
  29694. }
  29695. // String.prototype.substr - negative index don't work in IE8
  29696. var substr = 'ab'.substr(-1) === 'b'
  29697. ? function (str, start, len) { return str.substr(start, len) }
  29698. : function (str, start, len) {
  29699. if (start < 0) start = str.length + start;
  29700. return str.substr(start, len);
  29701. }
  29702. ;
  29703. },{"process":"../node_modules/process/browser.js"}],"../src/utilities/LRUCache.js":[function(require,module,exports) {
  29704. "use strict";
  29705. Object.defineProperty(exports, "__esModule", {
  29706. value: true
  29707. });
  29708. exports.LRUCache = void 0;
  29709. // TODO: can we remove the use of `indexOf` here because it's potentially slow? Possibly use time and sort as needed?
  29710. // Keep a used list that we can sort as needed when it's dirty, a map of item to last used time, and a binary search
  29711. // of the array to find an item that needs to be removed
  29712. class LRUCache {
  29713. constructor() {
  29714. // options
  29715. this.maxSize = 800;
  29716. this.minSize = 600;
  29717. this.unloadPercent = 0.2;
  29718. this.usedSet = new Set();
  29719. this.itemSet = new Set();
  29720. this.itemList = [];
  29721. this.callbacks = new Map();
  29722. } // Returns whether or not the cache has reached the maximum size
  29723. isFull() {
  29724. return this.itemSet.size >= this.maxSize;
  29725. }
  29726. add(item, removeCb) {
  29727. const itemSet = this.itemSet;
  29728. if (itemSet.has(item)) {
  29729. return false;
  29730. }
  29731. if (this.isFull()) {
  29732. return false;
  29733. }
  29734. const usedSet = this.usedSet;
  29735. const itemList = this.itemList;
  29736. const callbacks = this.callbacks;
  29737. itemList.push(item);
  29738. usedSet.add(item);
  29739. itemSet.add(item);
  29740. callbacks.set(item, removeCb);
  29741. return true;
  29742. }
  29743. remove(item) {
  29744. const usedSet = this.usedSet;
  29745. const itemSet = this.itemSet;
  29746. const itemList = this.itemList;
  29747. const callbacks = this.callbacks;
  29748. if (itemSet.has(item)) {
  29749. callbacks.get(item)(item);
  29750. const index = itemList.indexOf(item);
  29751. itemList.splice(index, 1);
  29752. usedSet.delete(item);
  29753. itemSet.delete(item);
  29754. callbacks.delete(item);
  29755. return true;
  29756. }
  29757. return false;
  29758. }
  29759. markUsed(item) {
  29760. const itemSet = this.itemSet;
  29761. const usedSet = this.usedSet;
  29762. if (itemSet.has(item) && !usedSet.has(item)) {
  29763. const itemList = this.itemList;
  29764. const index = itemList.indexOf(item);
  29765. itemList.splice(index, 1);
  29766. itemList.push(item);
  29767. usedSet.add(item);
  29768. }
  29769. }
  29770. markAllUnused() {
  29771. this.usedSet.clear();
  29772. } // TODO: this should be renamed because it's not necessarily unloading all unused content
  29773. // Maybe call it "cleanup" or "unloadToMinSize"
  29774. unloadUnusedContent(prioritySortCb) {
  29775. const unloadPercent = this.unloadPercent;
  29776. const targetSize = this.minSize;
  29777. const itemList = this.itemList;
  29778. const itemSet = this.itemSet;
  29779. const usedSet = this.usedSet;
  29780. const callbacks = this.callbacks;
  29781. const unused = itemList.length - usedSet.size;
  29782. if (itemList.length > targetSize && unused > 0) {
  29783. // TODO: sort by priority
  29784. let nodesToUnload = Math.max(itemList.length - targetSize, targetSize) * unloadPercent;
  29785. nodesToUnload = Math.ceil(nodesToUnload);
  29786. nodesToUnload = Math.min(unused, nodesToUnload);
  29787. const removedItems = itemList.splice(0, nodesToUnload);
  29788. for (let i = 0, l = removedItems.length; i < l; i++) {
  29789. const item = removedItems[i];
  29790. callbacks.get(item)(item);
  29791. itemSet.delete(item);
  29792. callbacks.delete(item);
  29793. }
  29794. }
  29795. }
  29796. scheduleUnload(prioritySortCb, markAllUnused = true) {
  29797. if (!this.scheduled) {
  29798. this.scheduled = true;
  29799. Promise.resolve().then(() => {
  29800. this.scheduled = false;
  29801. this.unloadUnusedContent(prioritySortCb);
  29802. if (markAllUnused) {
  29803. this.markAllUnused();
  29804. }
  29805. });
  29806. }
  29807. }
  29808. }
  29809. exports.LRUCache = LRUCache;
  29810. },{}],"../src/utilities/PriorityQueue.js":[function(require,module,exports) {
  29811. "use strict";
  29812. Object.defineProperty(exports, "__esModule", {
  29813. value: true
  29814. });
  29815. exports.PriorityQueue = void 0;
  29816. class PriorityQueue {
  29817. constructor(maxJobs = 6) {
  29818. // options
  29819. this.maxJobs = maxJobs;
  29820. this.items = [];
  29821. this.currJobs = 0;
  29822. this.scheduled = false;
  29823. }
  29824. add(item, priority, callback) {
  29825. return new Promise((resolve, reject) => {
  29826. const prCallback = (...args) => callback(...args).then(resolve).catch(reject);
  29827. const items = this.items;
  29828. for (let i = 0, l = items.length; i < l; i++) {
  29829. const thisItem = items[i];
  29830. if (thisItem.priority > priority) {
  29831. items.splice(i, 0, {
  29832. priority,
  29833. item,
  29834. callback: prCallback
  29835. });
  29836. this.scheduleJobRun();
  29837. return;
  29838. }
  29839. }
  29840. items.push({
  29841. priority,
  29842. item,
  29843. callback: prCallback
  29844. });
  29845. this.scheduleJobRun();
  29846. });
  29847. }
  29848. remove(item) {
  29849. const items = this.items;
  29850. for (let i = 0, l = items.length; i < l; i++) {
  29851. const thisItem = items[i];
  29852. if (thisItem.item === item) {
  29853. items.splice(i, 1);
  29854. break;
  29855. }
  29856. }
  29857. }
  29858. tryRunJobs() {
  29859. const items = this.items;
  29860. const maxJobs = this.maxJobs;
  29861. while (maxJobs > this.currJobs && items.length > 0) {
  29862. this.currJobs++;
  29863. const {
  29864. item,
  29865. priority,
  29866. callback
  29867. } = items.pop();
  29868. callback(item, priority).then(() => {
  29869. this.currJobs--;
  29870. this.scheduleJobRun();
  29871. }).catch(() => {
  29872. this.currJobs--;
  29873. this.scheduleJobRun();
  29874. });
  29875. }
  29876. }
  29877. scheduleJobRun() {
  29878. if (!this.scheduled) {
  29879. Promise.resolve().then(() => {
  29880. this.tryRunJobs();
  29881. this.scheduled = false;
  29882. });
  29883. this.scheduled = true;
  29884. }
  29885. }
  29886. }
  29887. exports.PriorityQueue = PriorityQueue;
  29888. },{}],"../src/base/constants.js":[function(require,module,exports) {
  29889. "use strict";
  29890. Object.defineProperty(exports, "__esModule", {
  29891. value: true
  29892. });
  29893. exports.FAILED = exports.LOADED = exports.PARSING = exports.LOADING = exports.UNLOADED = void 0;
  29894. const UNLOADED = 0;
  29895. exports.UNLOADED = UNLOADED;
  29896. const LOADING = 1;
  29897. exports.LOADING = LOADING;
  29898. const PARSING = 2;
  29899. exports.PARSING = PARSING;
  29900. const LOADED = 3;
  29901. exports.LOADED = LOADED;
  29902. const FAILED = 4;
  29903. exports.FAILED = FAILED;
  29904. },{}],"../src/base/traverseFunctions.js":[function(require,module,exports) {
  29905. "use strict";
  29906. Object.defineProperty(exports, "__esModule", {
  29907. value: true
  29908. });
  29909. exports.traverseSet = traverseSet;
  29910. exports.determineFrustumSet = determineFrustumSet;
  29911. exports.markUsedSetLeaves = markUsedSetLeaves;
  29912. exports.skipTraversal = skipTraversal;
  29913. exports.toggleTiles = toggleTiles;
  29914. var _constants = require("./constants.js");
  29915. function isUsedThisFrame(tile, frameCount) {
  29916. return tile.__lastFrameVisited === frameCount && tile.__used;
  29917. }
  29918. function resetFrameState(tile, frameCount) {
  29919. if (tile.__lastFrameVisited !== frameCount) {
  29920. tile.__lastFrameVisited = frameCount;
  29921. tile.__used = false;
  29922. tile.__inFrustum = false;
  29923. tile.__isLeaf = false;
  29924. tile.__visible = false;
  29925. tile.__active = false;
  29926. tile.__error = 0;
  29927. }
  29928. }
  29929. function recursivelyMarkUsed(tile, frameCount, lruCache) {
  29930. resetFrameState(tile, frameCount);
  29931. tile.__used = true;
  29932. lruCache.markUsed(tile);
  29933. if (tile.__contentEmpty) {
  29934. const children = tile.children;
  29935. for (let i = 0, l = children.length; i < l; i++) {
  29936. recursivelyMarkUsed(children[i], frameCount, lruCache);
  29937. }
  29938. }
  29939. }
  29940. function traverseSet(tile, beforeCb = null, afterCb = null, parent = null, depth = 0) {
  29941. if (beforeCb && beforeCb(tile, parent, depth)) {
  29942. if (afterCb) {
  29943. afterCb(tile, parent, depth);
  29944. }
  29945. return;
  29946. }
  29947. const children = tile.children;
  29948. for (let i = 0, l = children.length; i < l; i++) {
  29949. traverseSet(children[i], beforeCb, afterCb, tile, depth + 1);
  29950. }
  29951. if (afterCb) {
  29952. afterCb(tile, parent, depth);
  29953. }
  29954. } // TODO: include frustum mask here?
  29955. // TODO: this is marking items as used in the lrucache, which means some data is
  29956. // being kept around that isn't being used -- is that okay?
  29957. function determineFrustumSet(tile, renderer) {
  29958. const stats = renderer.stats;
  29959. const frameCount = renderer.frameCount;
  29960. const errorTarget = renderer.errorTarget;
  29961. const maxDepth = renderer.maxDepth;
  29962. const loadSiblings = renderer.loadSiblings;
  29963. const lruCache = renderer.lruCache;
  29964. resetFrameState(tile, frameCount);
  29965. const inFrustum = renderer.tileInView(tile);
  29966. if (inFrustum === false) {
  29967. return false;
  29968. }
  29969. tile.__used = true;
  29970. lruCache.markUsed(tile);
  29971. tile.__inFrustum = true;
  29972. stats.inFrustum++;
  29973. if (!tile.__contentEmpty) {
  29974. const error = renderer.calculateError(tile);
  29975. tile.__error = error;
  29976. if (error <= errorTarget) {
  29977. return true;
  29978. }
  29979. }
  29980. if (renderer.maxDepth > 0 && tile.__depth + 1 >= maxDepth) {
  29981. return true;
  29982. }
  29983. let anyChildrenUsed = false;
  29984. const children = tile.children;
  29985. for (let i = 0, l = children.length; i < l; i++) {
  29986. const c = children[i];
  29987. const r = determineFrustumSet(c, renderer);
  29988. anyChildrenUsed = anyChildrenUsed || r;
  29989. }
  29990. if (anyChildrenUsed && loadSiblings) {
  29991. for (let i = 0, l = children.length; i < l; i++) {
  29992. recursivelyMarkUsed(tile, frameCount, lruCache);
  29993. }
  29994. }
  29995. return true;
  29996. }
  29997. function markUsedSetLeaves(tile, renderer) {
  29998. const stats = renderer.stats;
  29999. const frameCount = renderer.frameCount;
  30000. if (!isUsedThisFrame(tile, frameCount)) {
  30001. return;
  30002. }
  30003. stats.used++;
  30004. const children = tile.children;
  30005. let anyChildrenUsed = false;
  30006. for (let i = 0, l = children.length; i < l; i++) {
  30007. const c = children[i];
  30008. anyChildrenUsed = anyChildrenUsed || isUsedThisFrame(c, frameCount);
  30009. }
  30010. if (!anyChildrenUsed) {
  30011. tile.__isLeaf = true; // TODO: stats
  30012. } else {
  30013. for (let i = 0, l = children.length; i < l; i++) {
  30014. const c = children[i];
  30015. markUsedSetLeaves(c, renderer);
  30016. }
  30017. }
  30018. }
  30019. function skipTraversal(tile, renderer) {
  30020. const stats = renderer.stats;
  30021. const frameCount = renderer.frameCount;
  30022. if (!isUsedThisFrame(tile, frameCount)) {
  30023. return;
  30024. }
  30025. const lruCache = renderer.lruCache;
  30026. if (tile.__isLeaf) {
  30027. if (tile.__loadingState === _constants.LOADED) {
  30028. if (tile.__inFrustum) {
  30029. tile.__visible = true;
  30030. stats.visible++;
  30031. }
  30032. tile.__active = true;
  30033. stats.active++;
  30034. } else if (!lruCache.isFull()) {
  30035. renderer.requestTileContents(tile);
  30036. }
  30037. return;
  30038. }
  30039. const errorRequirement = renderer.errorTarget * renderer.errorThreshold;
  30040. const meetsSSE = tile.__error < errorRequirement;
  30041. const hasContent = !tile.__contentEmpty;
  30042. const loadedContent = tile.__loadingState === _constants.LOADED && !tile.__contentEmpty;
  30043. const children = tile.children;
  30044. let allChildrenHaveContent = true;
  30045. for (let i = 0, l = children.length; i < l; i++) {
  30046. const c = children[i];
  30047. if (isUsedThisFrame(c, frameCount)) {
  30048. const childContent = c.__loadingState === _constants.LOADED || tile.__contentEmpty;
  30049. allChildrenHaveContent = allChildrenHaveContent && childContent;
  30050. }
  30051. }
  30052. if (meetsSSE && !loadedContent && !lruCache.isFull() && hasContent) {
  30053. renderer.requestTileContents(tile);
  30054. }
  30055. if (meetsSSE && loadedContent && !allChildrenHaveContent) {
  30056. if (tile.__inFrustum) {
  30057. tile.__visible = true;
  30058. stats.visible++;
  30059. }
  30060. tile.__active = true;
  30061. stats.active++;
  30062. for (let i = 0, l = children.length; i < l; i++) {
  30063. const c = children[i];
  30064. if (isUsedThisFrame(c, frameCount) && !lruCache.isFull()) {
  30065. renderer.requestTileContents(c);
  30066. }
  30067. }
  30068. return;
  30069. }
  30070. for (let i = 0, l = children.length; i < l; i++) {
  30071. const c = children[i];
  30072. if (isUsedThisFrame(c, frameCount)) {
  30073. skipTraversal(c, renderer);
  30074. }
  30075. }
  30076. }
  30077. function toggleTiles(tile, renderer) {
  30078. const frameCount = renderer.frameCount;
  30079. const isUsed = isUsedThisFrame(tile, frameCount);
  30080. if (isUsed || tile.__usedLastFrame) {
  30081. if (!isUsed) {
  30082. if (!tile.__contentEmpty && tile.__loadingState === _constants.LOADED) {
  30083. renderer.setTileVisible(tile, false);
  30084. renderer.setTileActive(tile, false);
  30085. }
  30086. tile.__usedLastFrame = false;
  30087. } else {
  30088. if (!tile.__contentEmpty && tile.__loadingState === _constants.LOADED) {
  30089. // enable visibility if active due to shadows
  30090. renderer.setTileActive(tile, tile.__active);
  30091. renderer.setTileVisible(tile, tile.__active || tile.__visible);
  30092. }
  30093. tile.__usedLastFrame = true;
  30094. }
  30095. const children = tile.children;
  30096. for (let i = 0, l = children.length; i < l; i++) {
  30097. const c = children[i];
  30098. toggleTiles(c, renderer);
  30099. }
  30100. }
  30101. }
  30102. },{"./constants.js":"../src/base/constants.js"}],"../src/base/TilesRendererBase.js":[function(require,module,exports) {
  30103. "use strict";
  30104. Object.defineProperty(exports, "__esModule", {
  30105. value: true
  30106. });
  30107. exports.TilesRendererBase = void 0;
  30108. var _path = _interopRequireDefault(require("path"));
  30109. var _LRUCache = require("../utilities/LRUCache.js");
  30110. var _PriorityQueue = require("../utilities/PriorityQueue.js");
  30111. var _traverseFunctions = require("./traverseFunctions.js");
  30112. var _constants = require("./constants.js");
  30113. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  30114. // TODO: find out why tiles are left dangling in the hierarchy
  30115. // TODO: Address the issue of too many promises, garbage collection
  30116. // TODO: remove more redundant computation
  30117. // TODO: See if using classes improves performance
  30118. // TODO: See if declaring function inline improves performance
  30119. // TODO: Make sure active state works as expected
  30120. class TilesRendererBase {
  30121. get rootTileSet() {
  30122. const tileSet = this.tileSets[this.rootURL];
  30123. if (!tileSet || tileSet instanceof Promise) {
  30124. return null;
  30125. } else {
  30126. return tileSet;
  30127. }
  30128. }
  30129. get root() {
  30130. const tileSet = this.rootTileSet;
  30131. return tileSet ? tileSet.root : null;
  30132. }
  30133. constructor(url) {
  30134. // state
  30135. this.tileSets = {};
  30136. this.rootURL = url;
  30137. this.fetchOptions = {};
  30138. this.lruCache = new _LRUCache.LRUCache();
  30139. this.downloadQueue = new _PriorityQueue.PriorityQueue(6);
  30140. this.parseQueue = new _PriorityQueue.PriorityQueue(1);
  30141. this.stats = {
  30142. parsing: 0,
  30143. downloading: 0,
  30144. inFrustum: 0,
  30145. used: 0,
  30146. active: 0,
  30147. visible: 0
  30148. };
  30149. this.frameCount = 0; // options
  30150. this.errorTarget = 6.0;
  30151. this.errorThreshold = 6.0;
  30152. this.loadSiblings = true;
  30153. this.maxDepth = Infinity;
  30154. }
  30155. traverse(cb) {
  30156. const tileSets = this.tileSets;
  30157. const rootTileSet = tileSets[this.rootURL];
  30158. if (!rootTileSet || !rootTileSet.root) return;
  30159. (0, _traverseFunctions.traverseSet)(rootTileSet.root, cb);
  30160. } // Public API
  30161. update() {
  30162. const stats = this.stats;
  30163. const lruCache = this.lruCache;
  30164. const tileSets = this.tileSets;
  30165. const rootTileSet = tileSets[this.rootURL];
  30166. if (!(this.rootURL in tileSets)) {
  30167. this.loadTileSet(this.rootURL);
  30168. return;
  30169. } else if (!rootTileSet || !rootTileSet.root) {
  30170. return;
  30171. }
  30172. const root = rootTileSet.root;
  30173. stats.inFrustum = 0, stats.used = 0, stats.active = 0, stats.visible = 0, this.frameCount++;
  30174. (0, _traverseFunctions.determineFrustumSet)(root, this);
  30175. (0, _traverseFunctions.markUsedSetLeaves)(root, this);
  30176. (0, _traverseFunctions.skipTraversal)(root, this);
  30177. (0, _traverseFunctions.toggleTiles)(root, this); // TODO: We may want to add this function in the requestTileContents function
  30178. lruCache.scheduleUnload(null);
  30179. } // Overrideable
  30180. parseTile(buffer, tile) {
  30181. return null;
  30182. }
  30183. disposeTile(tile) {}
  30184. preprocessNode(tile, parentTile, tileSetDir) {
  30185. if (tile.content) {
  30186. if (!('uri' in tile.content) && 'url' in tile.content) {
  30187. tile.content.uri = tile.content.url;
  30188. delete tile.content.url;
  30189. }
  30190. if (tile.content.uri) {
  30191. tile.content.uri = _path.default.join(tileSetDir, tile.content.uri);
  30192. } // TODO: fix for some cases where tilesets provide the bounding volume
  30193. // but volumes are not present. See
  30194. if (tile.content.boundingVolume && !('box' in tile.content.boundingVolume || 'sphere' in tile.content.boundingVolume || 'region' in tile.content.boundingVolume)) {
  30195. delete tile.content.boundingVolume;
  30196. }
  30197. }
  30198. tile.parent = parentTile;
  30199. tile.children = tile.children || [];
  30200. tile.__contentEmpty = !tile.content || !tile.content.uri;
  30201. tile.__error = 0.0;
  30202. tile.__inFrustum = false;
  30203. tile.__isLeaf = false;
  30204. tile.__wasUsed = false;
  30205. tile.__used = false;
  30206. tile.__wasVisible = false;
  30207. tile.__visible = false;
  30208. tile.__wasActive = false;
  30209. tile.__active = false;
  30210. tile.__childrenActive = false;
  30211. tile.__loadingState = _constants.UNLOADED;
  30212. tile.__loadIndex = 0;
  30213. tile.__loadAbort = null;
  30214. if (parentTile === null) {
  30215. tile.__depth = 0;
  30216. } else {
  30217. tile.__depth = parentTile.__depth + 1;
  30218. }
  30219. }
  30220. setTileActive(tile, state) {}
  30221. setTileVisible(tile, state) {}
  30222. calculateError(tile) {
  30223. return 0;
  30224. }
  30225. tileInView(tile) {
  30226. return true;
  30227. } // Private Functions
  30228. loadTileSet(url) {
  30229. const tileSets = this.tileSets;
  30230. if (!(url in tileSets)) {
  30231. const pr = fetch(url, this.fetchOptions).then(res => {
  30232. if (res.ok) {
  30233. return res.json();
  30234. } else {
  30235. throw new Error(`Status ${res.status} (${res.statusText})`);
  30236. }
  30237. }).then(json => {
  30238. // TODO: Add version query?
  30239. const version = json.asset.version;
  30240. console.assert(version === '1.0' || version === '0.0');
  30241. const basePath = _path.default.dirname(url);
  30242. (0, _traverseFunctions.traverseSet)(json.root, (node, parent) => this.preprocessNode(node, parent, basePath));
  30243. tileSets[url] = json; // TODO: schedule an update to avoid doing this too many times
  30244. this.update();
  30245. });
  30246. pr.catch(e => {
  30247. console.error(`TilesLoader: Failed to load tile set json "${url}"`);
  30248. console.error(e);
  30249. delete tileSets[url];
  30250. });
  30251. tileSets[url] = pr;
  30252. }
  30253. return Promise.resolve(tileSets[url]);
  30254. }
  30255. requestTileContents(tile) {
  30256. // If the tile is already being loaded then don't
  30257. // start it again.
  30258. if (tile.__loadingState !== _constants.UNLOADED) {
  30259. return;
  30260. } // TODO: reuse the functions created here?
  30261. const lruCache = this.lruCache;
  30262. const downloadQueue = this.downloadQueue;
  30263. const parseQueue = this.parseQueue;
  30264. lruCache.add(tile, t => {
  30265. if (t.__loadingState === _constants.LOADING) {
  30266. t.__loadAbort.abort();
  30267. t.__loadAbort = null;
  30268. } else {
  30269. this.disposeTile(t);
  30270. }
  30271. if (t.__loadingState === _constants.LOADING) {
  30272. stats.downloading--;
  30273. } else if (t.__loadingState === _constants.PARSING) {
  30274. stats.parsing--;
  30275. }
  30276. t.__loadingState = _constants.UNLOADED;
  30277. t.__loadIndex++; // TODO: Removing from the queues here is slow
  30278. // parseQueue.remove( t );
  30279. // downloadQueue.remove( t );
  30280. });
  30281. tile.__loadIndex++;
  30282. const loadIndex = tile.__loadIndex;
  30283. const priority = 1 / (tile.__depth + 1);
  30284. const stats = this.stats;
  30285. const controller = new AbortController();
  30286. const signal = controller.signal;
  30287. stats.downloading++;
  30288. tile.__loadAbort = controller;
  30289. tile.__loadingState = _constants.LOADING;
  30290. downloadQueue.add(tile, priority, tile => {
  30291. if (tile.__loadIndex !== loadIndex) {
  30292. return Promise.resolve();
  30293. }
  30294. return fetch(tile.content.uri, Object.assign({
  30295. signal
  30296. }, this.fetchOptions));
  30297. }).then(res => {
  30298. if (tile.__loadIndex !== loadIndex) {
  30299. return;
  30300. }
  30301. if (res.ok) {
  30302. return res.arrayBuffer();
  30303. } else {
  30304. throw new Error(`Failed to load model with error code ${res.status}`);
  30305. }
  30306. }).then(buffer => {
  30307. if (tile.__loadIndex !== loadIndex) {
  30308. return;
  30309. }
  30310. stats.downloading--;
  30311. stats.parsing++;
  30312. tile.__loadAbort = null;
  30313. tile.__loadingState = _constants.PARSING;
  30314. return parseQueue.add(buffer, priority, buffer => {
  30315. if (tile.__loadIndex !== loadIndex) {
  30316. return Promise.resolve();
  30317. }
  30318. return this.parseTile(buffer, tile);
  30319. });
  30320. }).then(() => {
  30321. if (tile.__loadIndex !== loadIndex) {
  30322. return;
  30323. }
  30324. stats.parsing--;
  30325. tile.__loadingState = _constants.LOADED;
  30326. this.setTileActive(tile, tile.__active);
  30327. this.setTileVisible(tile, tile.__visible);
  30328. }).catch(e => {
  30329. // if it has been unloaded then the tile has been disposed
  30330. if (tile.__loadIndex !== loadIndex) {
  30331. return;
  30332. }
  30333. if (e.name !== 'AbortError') {
  30334. console.error('TilesRenderer : Failed to load tile.');
  30335. console.error(e);
  30336. tile.__loadingState = _constants.FAILED;
  30337. } else {
  30338. lruCache.remove(tile);
  30339. }
  30340. });
  30341. }
  30342. }
  30343. exports.TilesRendererBase = TilesRendererBase;
  30344. },{"path":"../node_modules/path-browserify/index.js","../utilities/LRUCache.js":"../src/utilities/LRUCache.js","../utilities/PriorityQueue.js":"../src/utilities/PriorityQueue.js","./traverseFunctions.js":"../src/base/traverseFunctions.js","./constants.js":"../src/base/constants.js"}],"../src/base/B3DMLoaderBase.js":[function(require,module,exports) {
  30345. "use strict";
  30346. Object.defineProperty(exports, "__esModule", {
  30347. value: true
  30348. });
  30349. exports.B3DMLoaderBase = void 0;
  30350. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/Batched3DModel/README.md
  30351. // convert an array of numbers to a string
  30352. function arrayToString(array) {
  30353. let str = '';
  30354. for (let i = 0, l = array.length; i < l; i++) {
  30355. str += String.fromCharCode(array[i]);
  30356. }
  30357. return str;
  30358. }
  30359. class B3DMLoaderBase {
  30360. constructor() {
  30361. this.fetchOptions = {};
  30362. }
  30363. load(url) {
  30364. return fetch(url, this.fetchOptions).then(res => res.arrayBuffer()).then(buffer => this.parse(buffer));
  30365. }
  30366. parse(buffer) {
  30367. const dataView = new DataView(buffer); // 28-byte header
  30368. // 4 bytes
  30369. const magic = String.fromCharCode(dataView.getUint8(0)) + String.fromCharCode(dataView.getUint8(1)) + String.fromCharCode(dataView.getUint8(2)) + String.fromCharCode(dataView.getUint8(3));
  30370. console.assert(magic === 'b3dm'); // 4 bytes
  30371. const version = dataView.getUint32(4, true);
  30372. console.assert(version === 1); // 4 bytes
  30373. const byteLength = dataView.getUint32(8, true);
  30374. console.assert(byteLength === buffer.byteLength); // 4 bytes
  30375. const featureTableJSONByteLength = dataView.getUint32(12, true); // 4 bytes
  30376. const featureTableBinaryByteLength = dataView.getUint32(16, true); // 4 bytes
  30377. const batchTableJSONByteLength = dataView.getUint32(20, true); // 4 bytes
  30378. const batchTableBinaryByteLength = dataView.getUint32(24, true); // Feature Table
  30379. const featureTableStart = 28;
  30380. const jsonFeatureTableData = new Uint8Array(buffer, featureTableStart, featureTableJSONByteLength);
  30381. const jsonFeatureTable = featureTableJSONByteLength === 0 ? {} : JSON.parse(arrayToString(jsonFeatureTableData)); // const binFeatureTableData = new Uint8Array( buffer, featureTableStart + featureTableJSONByteLength, featureTableBinaryByteLength );
  30382. // TODO: dereference the json feature table data in to the binary array.
  30383. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/FeatureTable/README.md#json-header
  30384. // Batch Table
  30385. const batchTableStart = featureTableStart + featureTableJSONByteLength + featureTableBinaryByteLength;
  30386. const jsonBatchTableData = new Uint8Array(buffer, batchTableStart, batchTableJSONByteLength);
  30387. const jsonBatchTable = batchTableJSONByteLength === 0 ? {} : JSON.parse(arrayToString(jsonBatchTableData)); // const binBatchTableData = new Uint8Array( buffer, batchTableStart + batchTableJSONByteLength, batchTableBinaryByteLength );
  30388. // TODO: dereference the json batch table data in to the binary array.
  30389. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/FeatureTable/README.md#json-header
  30390. const glbStart = batchTableStart + batchTableJSONByteLength + batchTableBinaryByteLength;
  30391. const glbBytes = new Uint8Array(buffer, glbStart, byteLength - glbStart); // TODO: Understand how to apply the batchId semantics
  30392. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/Batched3DModel/README.md#binary-gltf
  30393. return {
  30394. version,
  30395. featureTable: jsonFeatureTable,
  30396. batchTable: jsonBatchTable,
  30397. glbBytes
  30398. };
  30399. }
  30400. }
  30401. exports.B3DMLoaderBase = B3DMLoaderBase;
  30402. },{}],"../node_modules/three/examples/jsm/loaders/GLTFLoader.js":[function(require,module,exports) {
  30403. "use strict";
  30404. Object.defineProperty(exports, "__esModule", {
  30405. value: true
  30406. });
  30407. exports.GLTFLoader = void 0;
  30408. var _threeModule = require("../../../build/three.module.js");
  30409. /**
  30410. * @author Rich Tibbett / https://github.com/richtr
  30411. * @author mrdoob / http://mrdoob.com/
  30412. * @author Tony Parisi / http://www.tonyparisi.com/
  30413. * @author Takahiro / https://github.com/takahirox
  30414. * @author Don McCurdy / https://www.donmccurdy.com
  30415. */
  30416. var GLTFLoader = function () {
  30417. function GLTFLoader(manager) {
  30418. _threeModule.Loader.call(this, manager);
  30419. this.dracoLoader = null;
  30420. this.ddsLoader = null;
  30421. }
  30422. GLTFLoader.prototype = Object.assign(Object.create(_threeModule.Loader.prototype), {
  30423. constructor: GLTFLoader,
  30424. load: function (url, onLoad, onProgress, onError) {
  30425. var scope = this;
  30426. var resourcePath;
  30427. if (this.resourcePath !== '') {
  30428. resourcePath = this.resourcePath;
  30429. } else if (this.path !== '') {
  30430. resourcePath = this.path;
  30431. } else {
  30432. resourcePath = _threeModule.LoaderUtils.extractUrlBase(url);
  30433. } // Tells the LoadingManager to track an extra item, which resolves after
  30434. // the model is fully loaded. This means the count of items loaded will
  30435. // be incorrect, but ensures manager.onLoad() does not fire early.
  30436. scope.manager.itemStart(url);
  30437. var _onError = function (e) {
  30438. if (onError) {
  30439. onError(e);
  30440. } else {
  30441. console.error(e);
  30442. }
  30443. scope.manager.itemError(url);
  30444. scope.manager.itemEnd(url);
  30445. };
  30446. var loader = new _threeModule.FileLoader(scope.manager);
  30447. loader.setPath(this.path);
  30448. loader.setResponseType('arraybuffer');
  30449. if (scope.crossOrigin === 'use-credentials') {
  30450. loader.setWithCredentials(true);
  30451. }
  30452. loader.load(url, function (data) {
  30453. try {
  30454. scope.parse(data, resourcePath, function (gltf) {
  30455. onLoad(gltf);
  30456. scope.manager.itemEnd(url);
  30457. }, _onError);
  30458. } catch (e) {
  30459. _onError(e);
  30460. }
  30461. }, onProgress, _onError);
  30462. },
  30463. setDRACOLoader: function (dracoLoader) {
  30464. this.dracoLoader = dracoLoader;
  30465. return this;
  30466. },
  30467. setDDSLoader: function (ddsLoader) {
  30468. this.ddsLoader = ddsLoader;
  30469. return this;
  30470. },
  30471. parse: function (data, path, onLoad, onError) {
  30472. var content;
  30473. var extensions = {};
  30474. if (typeof data === 'string') {
  30475. content = data;
  30476. } else {
  30477. var magic = _threeModule.LoaderUtils.decodeText(new Uint8Array(data, 0, 4));
  30478. if (magic === BINARY_EXTENSION_HEADER_MAGIC) {
  30479. try {
  30480. extensions[EXTENSIONS.KHR_BINARY_GLTF] = new GLTFBinaryExtension(data);
  30481. } catch (error) {
  30482. if (onError) onError(error);
  30483. return;
  30484. }
  30485. content = extensions[EXTENSIONS.KHR_BINARY_GLTF].content;
  30486. } else {
  30487. content = _threeModule.LoaderUtils.decodeText(new Uint8Array(data));
  30488. }
  30489. }
  30490. var json = JSON.parse(content);
  30491. if (json.asset === undefined || json.asset.version[0] < 2) {
  30492. if (onError) onError(new Error('THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported. Use LegacyGLTFLoader instead.'));
  30493. return;
  30494. }
  30495. if (json.extensionsUsed) {
  30496. for (var i = 0; i < json.extensionsUsed.length; ++i) {
  30497. var extensionName = json.extensionsUsed[i];
  30498. var extensionsRequired = json.extensionsRequired || [];
  30499. switch (extensionName) {
  30500. case EXTENSIONS.KHR_LIGHTS_PUNCTUAL:
  30501. extensions[extensionName] = new GLTFLightsExtension(json);
  30502. break;
  30503. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  30504. extensions[extensionName] = new GLTFMaterialsUnlitExtension();
  30505. break;
  30506. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  30507. extensions[extensionName] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  30508. break;
  30509. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  30510. extensions[extensionName] = new GLTFDracoMeshCompressionExtension(json, this.dracoLoader);
  30511. break;
  30512. case EXTENSIONS.MSFT_TEXTURE_DDS:
  30513. extensions[EXTENSIONS.MSFT_TEXTURE_DDS] = new GLTFTextureDDSExtension(this.ddsLoader);
  30514. break;
  30515. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  30516. extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] = new GLTFTextureTransformExtension();
  30517. break;
  30518. default:
  30519. if (extensionsRequired.indexOf(extensionName) >= 0) {
  30520. console.warn('THREE.GLTFLoader: Unknown extension "' + extensionName + '".');
  30521. }
  30522. }
  30523. }
  30524. }
  30525. var parser = new GLTFParser(json, extensions, {
  30526. path: path || this.resourcePath || '',
  30527. crossOrigin: this.crossOrigin,
  30528. manager: this.manager
  30529. });
  30530. parser.parse(onLoad, onError);
  30531. }
  30532. });
  30533. /* GLTFREGISTRY */
  30534. function GLTFRegistry() {
  30535. var objects = {};
  30536. return {
  30537. get: function (key) {
  30538. return objects[key];
  30539. },
  30540. add: function (key, object) {
  30541. objects[key] = object;
  30542. },
  30543. remove: function (key) {
  30544. delete objects[key];
  30545. },
  30546. removeAll: function () {
  30547. objects = {};
  30548. }
  30549. };
  30550. }
  30551. /*********************************/
  30552. /********** EXTENSIONS ***********/
  30553. /*********************************/
  30554. var EXTENSIONS = {
  30555. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  30556. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  30557. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  30558. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  30559. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  30560. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  30561. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  30562. };
  30563. /**
  30564. * DDS Texture Extension
  30565. *
  30566. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  30567. *
  30568. */
  30569. function GLTFTextureDDSExtension(ddsLoader) {
  30570. if (!ddsLoader) {
  30571. throw new Error('THREE.GLTFLoader: Attempting to load .dds texture without importing DDSLoader');
  30572. }
  30573. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  30574. this.ddsLoader = ddsLoader;
  30575. }
  30576. /**
  30577. * Punctual Lights Extension
  30578. *
  30579. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  30580. */
  30581. function GLTFLightsExtension(json) {
  30582. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  30583. var extension = json.extensions && json.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL] || {};
  30584. this.lightDefs = extension.lights || [];
  30585. }
  30586. GLTFLightsExtension.prototype.loadLight = function (lightIndex) {
  30587. var lightDef = this.lightDefs[lightIndex];
  30588. var lightNode;
  30589. var color = new _threeModule.Color(0xffffff);
  30590. if (lightDef.color !== undefined) color.fromArray(lightDef.color);
  30591. var range = lightDef.range !== undefined ? lightDef.range : 0;
  30592. switch (lightDef.type) {
  30593. case 'directional':
  30594. lightNode = new _threeModule.DirectionalLight(color);
  30595. lightNode.target.position.set(0, 0, -1);
  30596. lightNode.add(lightNode.target);
  30597. break;
  30598. case 'point':
  30599. lightNode = new _threeModule.PointLight(color);
  30600. lightNode.distance = range;
  30601. break;
  30602. case 'spot':
  30603. lightNode = new _threeModule.SpotLight(color);
  30604. lightNode.distance = range; // Handle spotlight properties.
  30605. lightDef.spot = lightDef.spot || {};
  30606. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  30607. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  30608. lightNode.angle = lightDef.spot.outerConeAngle;
  30609. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  30610. lightNode.target.position.set(0, 0, -1);
  30611. lightNode.add(lightNode.target);
  30612. break;
  30613. default:
  30614. throw new Error('THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".');
  30615. } // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  30616. // here, because node-level parsing will only override position if explicitly specified.
  30617. lightNode.position.set(0, 0, 0);
  30618. lightNode.decay = 2;
  30619. if (lightDef.intensity !== undefined) lightNode.intensity = lightDef.intensity;
  30620. lightNode.name = lightDef.name || 'light_' + lightIndex;
  30621. return Promise.resolve(lightNode);
  30622. };
  30623. /**
  30624. * Unlit Materials Extension
  30625. *
  30626. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  30627. */
  30628. function GLTFMaterialsUnlitExtension() {
  30629. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  30630. }
  30631. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () {
  30632. return _threeModule.MeshBasicMaterial;
  30633. };
  30634. GLTFMaterialsUnlitExtension.prototype.extendParams = function (materialParams, materialDef, parser) {
  30635. var pending = [];
  30636. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  30637. materialParams.opacity = 1.0;
  30638. var metallicRoughness = materialDef.pbrMetallicRoughness;
  30639. if (metallicRoughness) {
  30640. if (Array.isArray(metallicRoughness.baseColorFactor)) {
  30641. var array = metallicRoughness.baseColorFactor;
  30642. materialParams.color.fromArray(array);
  30643. materialParams.opacity = array[3];
  30644. }
  30645. if (metallicRoughness.baseColorTexture !== undefined) {
  30646. pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture));
  30647. }
  30648. }
  30649. return Promise.all(pending);
  30650. };
  30651. /* BINARY EXTENSION */
  30652. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  30653. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  30654. var BINARY_EXTENSION_CHUNK_TYPES = {
  30655. JSON: 0x4E4F534A,
  30656. BIN: 0x004E4942
  30657. };
  30658. function GLTFBinaryExtension(data) {
  30659. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  30660. this.content = null;
  30661. this.body = null;
  30662. var headerView = new DataView(data, 0, BINARY_EXTENSION_HEADER_LENGTH);
  30663. this.header = {
  30664. magic: _threeModule.LoaderUtils.decodeText(new Uint8Array(data.slice(0, 4))),
  30665. version: headerView.getUint32(4, true),
  30666. length: headerView.getUint32(8, true)
  30667. };
  30668. if (this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC) {
  30669. throw new Error('THREE.GLTFLoader: Unsupported glTF-Binary header.');
  30670. } else if (this.header.version < 2.0) {
  30671. throw new Error('THREE.GLTFLoader: Legacy binary file detected. Use LegacyGLTFLoader instead.');
  30672. }
  30673. var chunkView = new DataView(data, BINARY_EXTENSION_HEADER_LENGTH);
  30674. var chunkIndex = 0;
  30675. while (chunkIndex < chunkView.byteLength) {
  30676. var chunkLength = chunkView.getUint32(chunkIndex, true);
  30677. chunkIndex += 4;
  30678. var chunkType = chunkView.getUint32(chunkIndex, true);
  30679. chunkIndex += 4;
  30680. if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON) {
  30681. var contentArray = new Uint8Array(data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength);
  30682. this.content = _threeModule.LoaderUtils.decodeText(contentArray);
  30683. } else if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN) {
  30684. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  30685. this.body = data.slice(byteOffset, byteOffset + chunkLength);
  30686. } // Clients must ignore chunks with unknown types.
  30687. chunkIndex += chunkLength;
  30688. }
  30689. if (this.content === null) {
  30690. throw new Error('THREE.GLTFLoader: JSON content not found.');
  30691. }
  30692. }
  30693. /**
  30694. * DRACO Mesh Compression Extension
  30695. *
  30696. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  30697. */
  30698. function GLTFDracoMeshCompressionExtension(json, dracoLoader) {
  30699. if (!dracoLoader) {
  30700. throw new Error('THREE.GLTFLoader: No DRACOLoader instance provided.');
  30701. }
  30702. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  30703. this.json = json;
  30704. this.dracoLoader = dracoLoader;
  30705. }
  30706. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function (primitive, parser) {
  30707. var json = this.json;
  30708. var dracoLoader = this.dracoLoader;
  30709. var bufferViewIndex = primitive.extensions[this.name].bufferView;
  30710. var gltfAttributeMap = primitive.extensions[this.name].attributes;
  30711. var threeAttributeMap = {};
  30712. var attributeNormalizedMap = {};
  30713. var attributeTypeMap = {};
  30714. for (var attributeName in gltfAttributeMap) {
  30715. var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
  30716. threeAttributeMap[threeAttributeName] = gltfAttributeMap[attributeName];
  30717. }
  30718. for (attributeName in primitive.attributes) {
  30719. var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
  30720. if (gltfAttributeMap[attributeName] !== undefined) {
  30721. var accessorDef = json.accessors[primitive.attributes[attributeName]];
  30722. var componentType = WEBGL_COMPONENT_TYPES[accessorDef.componentType];
  30723. attributeTypeMap[threeAttributeName] = componentType;
  30724. attributeNormalizedMap[threeAttributeName] = accessorDef.normalized === true;
  30725. }
  30726. }
  30727. return parser.getDependency('bufferView', bufferViewIndex).then(function (bufferView) {
  30728. return new Promise(function (resolve) {
  30729. dracoLoader.decodeDracoFile(bufferView, function (geometry) {
  30730. for (var attributeName in geometry.attributes) {
  30731. var attribute = geometry.attributes[attributeName];
  30732. var normalized = attributeNormalizedMap[attributeName];
  30733. if (normalized !== undefined) attribute.normalized = normalized;
  30734. }
  30735. resolve(geometry);
  30736. }, threeAttributeMap, attributeTypeMap);
  30737. });
  30738. });
  30739. };
  30740. /**
  30741. * Texture Transform Extension
  30742. *
  30743. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
  30744. */
  30745. function GLTFTextureTransformExtension() {
  30746. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  30747. }
  30748. GLTFTextureTransformExtension.prototype.extendTexture = function (texture, transform) {
  30749. texture = texture.clone();
  30750. if (transform.offset !== undefined) {
  30751. texture.offset.fromArray(transform.offset);
  30752. }
  30753. if (transform.rotation !== undefined) {
  30754. texture.rotation = transform.rotation;
  30755. }
  30756. if (transform.scale !== undefined) {
  30757. texture.repeat.fromArray(transform.scale);
  30758. }
  30759. if (transform.texCoord !== undefined) {
  30760. console.warn('THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.');
  30761. }
  30762. texture.needsUpdate = true;
  30763. return texture;
  30764. };
  30765. /**
  30766. * Specular-Glossiness Extension
  30767. *
  30768. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  30769. */
  30770. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  30771. return {
  30772. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  30773. specularGlossinessParams: ['color', 'map', 'lightMap', 'lightMapIntensity', 'aoMap', 'aoMapIntensity', 'emissive', 'emissiveIntensity', 'emissiveMap', 'bumpMap', 'bumpScale', 'normalMap', 'displacementMap', 'displacementScale', 'displacementBias', 'specularMap', 'specular', 'glossinessMap', 'glossiness', 'alphaMap', 'envMap', 'envMapIntensity', 'refractionRatio'],
  30774. getMaterialType: function () {
  30775. return _threeModule.ShaderMaterial;
  30776. },
  30777. extendParams: function (materialParams, materialDef, parser) {
  30778. var pbrSpecularGlossiness = materialDef.extensions[this.name];
  30779. var shader = _threeModule.ShaderLib['standard'];
  30780. var uniforms = _threeModule.UniformsUtils.clone(shader.uniforms);
  30781. var specularMapParsFragmentChunk = ['#ifdef USE_SPECULARMAP', ' uniform sampler2D specularMap;', '#endif'].join('\n');
  30782. var glossinessMapParsFragmentChunk = ['#ifdef USE_GLOSSINESSMAP', ' uniform sampler2D glossinessMap;', '#endif'].join('\n');
  30783. 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');
  30784. 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');
  30785. var lightPhysicalFragmentChunk = ['PhysicalMaterial material;', 'material.diffuseColor = diffuseColor.rgb;', 'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );', 'material.specularColor = specularFactor.rgb;'].join('\n');
  30786. 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);
  30787. delete uniforms.roughness;
  30788. delete uniforms.metalness;
  30789. delete uniforms.roughnessMap;
  30790. delete uniforms.metalnessMap;
  30791. uniforms.specular = {
  30792. value: new _threeModule.Color().setHex(0x111111)
  30793. };
  30794. uniforms.glossiness = {
  30795. value: 0.5
  30796. };
  30797. uniforms.specularMap = {
  30798. value: null
  30799. };
  30800. uniforms.glossinessMap = {
  30801. value: null
  30802. };
  30803. materialParams.vertexShader = shader.vertexShader;
  30804. materialParams.fragmentShader = fragmentShader;
  30805. materialParams.uniforms = uniforms;
  30806. materialParams.defines = {
  30807. 'STANDARD': ''
  30808. };
  30809. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  30810. materialParams.opacity = 1.0;
  30811. var pending = [];
  30812. if (Array.isArray(pbrSpecularGlossiness.diffuseFactor)) {
  30813. var array = pbrSpecularGlossiness.diffuseFactor;
  30814. materialParams.color.fromArray(array);
  30815. materialParams.opacity = array[3];
  30816. }
  30817. if (pbrSpecularGlossiness.diffuseTexture !== undefined) {
  30818. pending.push(parser.assignTexture(materialParams, 'map', pbrSpecularGlossiness.diffuseTexture));
  30819. }
  30820. materialParams.emissive = new _threeModule.Color(0.0, 0.0, 0.0);
  30821. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  30822. materialParams.specular = new _threeModule.Color(1.0, 1.0, 1.0);
  30823. if (Array.isArray(pbrSpecularGlossiness.specularFactor)) {
  30824. materialParams.specular.fromArray(pbrSpecularGlossiness.specularFactor);
  30825. }
  30826. if (pbrSpecularGlossiness.specularGlossinessTexture !== undefined) {
  30827. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  30828. pending.push(parser.assignTexture(materialParams, 'glossinessMap', specGlossMapDef));
  30829. pending.push(parser.assignTexture(materialParams, 'specularMap', specGlossMapDef));
  30830. }
  30831. return Promise.all(pending);
  30832. },
  30833. createMaterial: function (params) {
  30834. // setup material properties based on MeshStandardMaterial for Specular-Glossiness
  30835. var material = new _threeModule.ShaderMaterial({
  30836. defines: params.defines,
  30837. vertexShader: params.vertexShader,
  30838. fragmentShader: params.fragmentShader,
  30839. uniforms: params.uniforms,
  30840. fog: true,
  30841. lights: true,
  30842. opacity: params.opacity,
  30843. transparent: params.transparent
  30844. });
  30845. material.isGLTFSpecularGlossinessMaterial = true;
  30846. material.color = params.color;
  30847. material.map = params.map === undefined ? null : params.map;
  30848. material.lightMap = null;
  30849. material.lightMapIntensity = 1.0;
  30850. material.aoMap = params.aoMap === undefined ? null : params.aoMap;
  30851. material.aoMapIntensity = 1.0;
  30852. material.emissive = params.emissive;
  30853. material.emissiveIntensity = 1.0;
  30854. material.emissiveMap = params.emissiveMap === undefined ? null : params.emissiveMap;
  30855. material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap;
  30856. material.bumpScale = 1;
  30857. material.normalMap = params.normalMap === undefined ? null : params.normalMap;
  30858. if (params.normalScale) material.normalScale = params.normalScale;
  30859. material.displacementMap = null;
  30860. material.displacementScale = 1;
  30861. material.displacementBias = 0;
  30862. material.specularMap = params.specularMap === undefined ? null : params.specularMap;
  30863. material.specular = params.specular;
  30864. material.glossinessMap = params.glossinessMap === undefined ? null : params.glossinessMap;
  30865. material.glossiness = params.glossiness;
  30866. material.alphaMap = null;
  30867. material.envMap = params.envMap === undefined ? null : params.envMap;
  30868. material.envMapIntensity = 1.0;
  30869. material.refractionRatio = 0.98;
  30870. material.extensions.derivatives = true;
  30871. return material;
  30872. },
  30873. /**
  30874. * Clones a GLTFSpecularGlossinessMaterial instance. The ShaderMaterial.copy() method can
  30875. * copy only properties it knows about or inherits, and misses many properties that would
  30876. * normally be defined by MeshStandardMaterial.
  30877. *
  30878. * This method allows GLTFSpecularGlossinessMaterials to be cloned in the process of
  30879. * loading a glTF model, but cloning later (e.g. by the user) would require these changes
  30880. * AND also updating `.onBeforeRender` on the parent mesh.
  30881. *
  30882. * @param {ShaderMaterial} source
  30883. * @return {ShaderMaterial}
  30884. */
  30885. cloneMaterial: function (source) {
  30886. var target = source.clone();
  30887. target.isGLTFSpecularGlossinessMaterial = true;
  30888. var params = this.specularGlossinessParams;
  30889. for (var i = 0, il = params.length; i < il; i++) {
  30890. var value = source[params[i]];
  30891. target[params[i]] = value && value.isColor ? value.clone() : value;
  30892. }
  30893. return target;
  30894. },
  30895. // Here's based on refreshUniformsCommon() and refreshUniformsStandard() in WebGLRenderer.
  30896. refreshUniforms: function (renderer, scene, camera, geometry, material) {
  30897. if (material.isGLTFSpecularGlossinessMaterial !== true) {
  30898. return;
  30899. }
  30900. var uniforms = material.uniforms;
  30901. var defines = material.defines;
  30902. uniforms.opacity.value = material.opacity;
  30903. uniforms.diffuse.value.copy(material.color);
  30904. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  30905. uniforms.map.value = material.map;
  30906. uniforms.specularMap.value = material.specularMap;
  30907. uniforms.alphaMap.value = material.alphaMap;
  30908. uniforms.lightMap.value = material.lightMap;
  30909. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  30910. uniforms.aoMap.value = material.aoMap;
  30911. uniforms.aoMapIntensity.value = material.aoMapIntensity; // uv repeat and offset setting priorities
  30912. // 1. color map
  30913. // 2. specular map
  30914. // 3. normal map
  30915. // 4. bump map
  30916. // 5. alpha map
  30917. // 6. emissive map
  30918. var uvScaleMap;
  30919. if (material.map) {
  30920. uvScaleMap = material.map;
  30921. } else if (material.specularMap) {
  30922. uvScaleMap = material.specularMap;
  30923. } else if (material.displacementMap) {
  30924. uvScaleMap = material.displacementMap;
  30925. } else if (material.normalMap) {
  30926. uvScaleMap = material.normalMap;
  30927. } else if (material.bumpMap) {
  30928. uvScaleMap = material.bumpMap;
  30929. } else if (material.glossinessMap) {
  30930. uvScaleMap = material.glossinessMap;
  30931. } else if (material.alphaMap) {
  30932. uvScaleMap = material.alphaMap;
  30933. } else if (material.emissiveMap) {
  30934. uvScaleMap = material.emissiveMap;
  30935. }
  30936. if (uvScaleMap !== undefined) {
  30937. // backwards compatibility
  30938. if (uvScaleMap.isWebGLRenderTarget) {
  30939. uvScaleMap = uvScaleMap.texture;
  30940. }
  30941. if (uvScaleMap.matrixAutoUpdate === true) {
  30942. uvScaleMap.updateMatrix();
  30943. }
  30944. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  30945. }
  30946. if (material.envMap) {
  30947. uniforms.envMap.value = material.envMap;
  30948. uniforms.envMapIntensity.value = material.envMapIntensity; // don't flip CubeTexture envMaps, flip everything else:
  30949. // WebGLRenderTargetCube will be flipped for backwards compatibility
  30950. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  30951. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  30952. uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? -1 : 1;
  30953. uniforms.reflectivity.value = material.reflectivity;
  30954. uniforms.refractionRatio.value = material.refractionRatio;
  30955. uniforms.maxMipLevel.value = renderer.properties.get(material.envMap).__maxMipLevel;
  30956. }
  30957. uniforms.specular.value.copy(material.specular);
  30958. uniforms.glossiness.value = material.glossiness;
  30959. uniforms.glossinessMap.value = material.glossinessMap;
  30960. uniforms.emissiveMap.value = material.emissiveMap;
  30961. uniforms.bumpMap.value = material.bumpMap;
  30962. uniforms.normalMap.value = material.normalMap;
  30963. uniforms.displacementMap.value = material.displacementMap;
  30964. uniforms.displacementScale.value = material.displacementScale;
  30965. uniforms.displacementBias.value = material.displacementBias;
  30966. if (uniforms.glossinessMap.value !== null && defines.USE_GLOSSINESSMAP === undefined) {
  30967. defines.USE_GLOSSINESSMAP = ''; // set USE_ROUGHNESSMAP to enable vUv
  30968. defines.USE_ROUGHNESSMAP = '';
  30969. }
  30970. if (uniforms.glossinessMap.value === null && defines.USE_GLOSSINESSMAP !== undefined) {
  30971. delete defines.USE_GLOSSINESSMAP;
  30972. delete defines.USE_ROUGHNESSMAP;
  30973. }
  30974. }
  30975. };
  30976. }
  30977. /*********************************/
  30978. /********** INTERPOLATION ********/
  30979. /*********************************/
  30980. // Spline Interpolation
  30981. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  30982. function GLTFCubicSplineInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  30983. _threeModule.Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  30984. }
  30985. GLTFCubicSplineInterpolant.prototype = Object.create(_threeModule.Interpolant.prototype);
  30986. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  30987. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function (index) {
  30988. // Copies a sample value to the result buffer. See description of glTF
  30989. // CUBICSPLINE values layout in interpolate_() function below.
  30990. var result = this.resultBuffer,
  30991. values = this.sampleValues,
  30992. valueSize = this.valueSize,
  30993. offset = index * valueSize * 3 + valueSize;
  30994. for (var i = 0; i !== valueSize; i++) {
  30995. result[i] = values[offset + i];
  30996. }
  30997. return result;
  30998. };
  30999. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  31000. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  31001. GLTFCubicSplineInterpolant.prototype.interpolate_ = function (i1, t0, t, t1) {
  31002. var result = this.resultBuffer;
  31003. var values = this.sampleValues;
  31004. var stride = this.valueSize;
  31005. var stride2 = stride * 2;
  31006. var stride3 = stride * 3;
  31007. var td = t1 - t0;
  31008. var p = (t - t0) / td;
  31009. var pp = p * p;
  31010. var ppp = pp * p;
  31011. var offset1 = i1 * stride3;
  31012. var offset0 = offset1 - stride3;
  31013. var s2 = -2 * ppp + 3 * pp;
  31014. var s3 = ppp - pp;
  31015. var s0 = 1 - s2;
  31016. var s1 = s3 - pp + p; // Layout of keyframe output values for CUBICSPLINE animations:
  31017. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  31018. for (var i = 0; i !== stride; i++) {
  31019. var p0 = values[offset0 + i + stride]; // splineVertex_k
  31020. var m0 = values[offset0 + i + stride2] * td; // outTangent_k * (t_k+1 - t_k)
  31021. var p1 = values[offset1 + i + stride]; // splineVertex_k+1
  31022. var m1 = values[offset1 + i] * td; // inTangent_k+1 * (t_k+1 - t_k)
  31023. result[i] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  31024. }
  31025. return result;
  31026. };
  31027. /*********************************/
  31028. /********** INTERNALS ************/
  31029. /*********************************/
  31030. /* CONSTANTS */
  31031. var WEBGL_CONSTANTS = {
  31032. FLOAT: 5126,
  31033. //FLOAT_MAT2: 35674,
  31034. FLOAT_MAT3: 35675,
  31035. FLOAT_MAT4: 35676,
  31036. FLOAT_VEC2: 35664,
  31037. FLOAT_VEC3: 35665,
  31038. FLOAT_VEC4: 35666,
  31039. LINEAR: 9729,
  31040. REPEAT: 10497,
  31041. SAMPLER_2D: 35678,
  31042. POINTS: 0,
  31043. LINES: 1,
  31044. LINE_LOOP: 2,
  31045. LINE_STRIP: 3,
  31046. TRIANGLES: 4,
  31047. TRIANGLE_STRIP: 5,
  31048. TRIANGLE_FAN: 6,
  31049. UNSIGNED_BYTE: 5121,
  31050. UNSIGNED_SHORT: 5123
  31051. };
  31052. var WEBGL_COMPONENT_TYPES = {
  31053. 5120: Int8Array,
  31054. 5121: Uint8Array,
  31055. 5122: Int16Array,
  31056. 5123: Uint16Array,
  31057. 5125: Uint32Array,
  31058. 5126: Float32Array
  31059. };
  31060. var WEBGL_FILTERS = {
  31061. 9728: _threeModule.NearestFilter,
  31062. 9729: _threeModule.LinearFilter,
  31063. 9984: _threeModule.NearestMipmapNearestFilter,
  31064. 9985: _threeModule.LinearMipmapNearestFilter,
  31065. 9986: _threeModule.NearestMipmapLinearFilter,
  31066. 9987: _threeModule.LinearMipmapLinearFilter
  31067. };
  31068. var WEBGL_WRAPPINGS = {
  31069. 33071: _threeModule.ClampToEdgeWrapping,
  31070. 33648: _threeModule.MirroredRepeatWrapping,
  31071. 10497: _threeModule.RepeatWrapping
  31072. };
  31073. var WEBGL_TYPE_SIZES = {
  31074. 'SCALAR': 1,
  31075. 'VEC2': 2,
  31076. 'VEC3': 3,
  31077. 'VEC4': 4,
  31078. 'MAT2': 4,
  31079. 'MAT3': 9,
  31080. 'MAT4': 16
  31081. };
  31082. var ATTRIBUTES = {
  31083. POSITION: 'position',
  31084. NORMAL: 'normal',
  31085. TANGENT: 'tangent',
  31086. TEXCOORD_0: 'uv',
  31087. TEXCOORD_1: 'uv2',
  31088. COLOR_0: 'color',
  31089. WEIGHTS_0: 'skinWeight',
  31090. JOINTS_0: 'skinIndex'
  31091. };
  31092. var PATH_PROPERTIES = {
  31093. scale: 'scale',
  31094. translation: 'position',
  31095. rotation: 'quaternion',
  31096. weights: 'morphTargetInfluences'
  31097. };
  31098. var INTERPOLATION = {
  31099. CUBICSPLINE: undefined,
  31100. // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  31101. // keyframe track will be initialized with a default interpolation type, then modified.
  31102. LINEAR: _threeModule.InterpolateLinear,
  31103. STEP: _threeModule.InterpolateDiscrete
  31104. };
  31105. var ALPHA_MODES = {
  31106. OPAQUE: 'OPAQUE',
  31107. MASK: 'MASK',
  31108. BLEND: 'BLEND'
  31109. };
  31110. var MIME_TYPE_FORMATS = {
  31111. 'image/png': _threeModule.RGBAFormat,
  31112. 'image/jpeg': _threeModule.RGBFormat
  31113. };
  31114. /* UTILITY FUNCTIONS */
  31115. function resolveURL(url, path) {
  31116. // Invalid URL
  31117. if (typeof url !== 'string' || url === '') return ''; // Host Relative URL
  31118. if (/^https?:\/\//i.test(path) && /^\//.test(url)) {
  31119. path = path.replace(/(^https?:\/\/[^\/]+).*/i, '$1');
  31120. } // Absolute URL http://,https://,//
  31121. if (/^(https?:)?\/\//i.test(url)) return url; // Data URI
  31122. if (/^data:.*,.*$/i.test(url)) return url; // Blob URL
  31123. if (/^blob:.*$/i.test(url)) return url; // Relative URL
  31124. return path + url;
  31125. }
  31126. var defaultMaterial;
  31127. /**
  31128. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  31129. */
  31130. function createDefaultMaterial() {
  31131. defaultMaterial = defaultMaterial || new _threeModule.MeshStandardMaterial({
  31132. color: 0xFFFFFF,
  31133. emissive: 0x000000,
  31134. metalness: 1,
  31135. roughness: 1,
  31136. transparent: false,
  31137. depthTest: true,
  31138. side: _threeModule.FrontSide
  31139. });
  31140. return defaultMaterial;
  31141. }
  31142. function addUnknownExtensionsToUserData(knownExtensions, object, objectDef) {
  31143. // Add unknown glTF extensions to an object's userData.
  31144. for (var name in objectDef.extensions) {
  31145. if (knownExtensions[name] === undefined) {
  31146. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  31147. object.userData.gltfExtensions[name] = objectDef.extensions[name];
  31148. }
  31149. }
  31150. }
  31151. /**
  31152. * @param {Object3D|Material|BufferGeometry} object
  31153. * @param {GLTF.definition} gltfDef
  31154. */
  31155. function assignExtrasToUserData(object, gltfDef) {
  31156. if (gltfDef.extras !== undefined) {
  31157. if (typeof gltfDef.extras === 'object') {
  31158. Object.assign(object.userData, gltfDef.extras);
  31159. } else {
  31160. console.warn('THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras);
  31161. }
  31162. }
  31163. }
  31164. /**
  31165. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  31166. *
  31167. * @param {BufferGeometry} geometry
  31168. * @param {Array<GLTF.Target>} targets
  31169. * @param {GLTFParser} parser
  31170. * @return {Promise<BufferGeometry>}
  31171. */
  31172. function addMorphTargets(geometry, targets, parser) {
  31173. var hasMorphPosition = false;
  31174. var hasMorphNormal = false;
  31175. for (var i = 0, il = targets.length; i < il; i++) {
  31176. var target = targets[i];
  31177. if (target.POSITION !== undefined) hasMorphPosition = true;
  31178. if (target.NORMAL !== undefined) hasMorphNormal = true;
  31179. if (hasMorphPosition && hasMorphNormal) break;
  31180. }
  31181. if (!hasMorphPosition && !hasMorphNormal) return Promise.resolve(geometry);
  31182. var pendingPositionAccessors = [];
  31183. var pendingNormalAccessors = [];
  31184. for (var i = 0, il = targets.length; i < il; i++) {
  31185. var target = targets[i];
  31186. if (hasMorphPosition) {
  31187. var pendingAccessor = target.POSITION !== undefined ? parser.getDependency('accessor', target.POSITION) : geometry.attributes.position;
  31188. pendingPositionAccessors.push(pendingAccessor);
  31189. }
  31190. if (hasMorphNormal) {
  31191. var pendingAccessor = target.NORMAL !== undefined ? parser.getDependency('accessor', target.NORMAL) : geometry.attributes.normal;
  31192. pendingNormalAccessors.push(pendingAccessor);
  31193. }
  31194. }
  31195. return Promise.all([Promise.all(pendingPositionAccessors), Promise.all(pendingNormalAccessors)]).then(function (accessors) {
  31196. var morphPositions = accessors[0];
  31197. var morphNormals = accessors[1]; // Clone morph target accessors before modifying them.
  31198. for (var i = 0, il = morphPositions.length; i < il; i++) {
  31199. if (geometry.attributes.position === morphPositions[i]) continue;
  31200. morphPositions[i] = cloneBufferAttribute(morphPositions[i]);
  31201. }
  31202. for (var i = 0, il = morphNormals.length; i < il; i++) {
  31203. if (geometry.attributes.normal === morphNormals[i]) continue;
  31204. morphNormals[i] = cloneBufferAttribute(morphNormals[i]);
  31205. }
  31206. for (var i = 0, il = targets.length; i < il; i++) {
  31207. var target = targets[i];
  31208. var attributeName = 'morphTarget' + i;
  31209. if (hasMorphPosition) {
  31210. // Three.js morph position is absolute value. The formula is
  31211. // basePosition
  31212. // + weight0 * ( morphPosition0 - basePosition )
  31213. // + weight1 * ( morphPosition1 - basePosition )
  31214. // ...
  31215. // while the glTF one is relative
  31216. // basePosition
  31217. // + weight0 * glTFmorphPosition0
  31218. // + weight1 * glTFmorphPosition1
  31219. // ...
  31220. // then we need to convert from relative to absolute here.
  31221. if (target.POSITION !== undefined) {
  31222. var positionAttribute = morphPositions[i];
  31223. positionAttribute.name = attributeName;
  31224. var position = geometry.attributes.position;
  31225. for (var j = 0, jl = positionAttribute.count; j < jl; j++) {
  31226. positionAttribute.setXYZ(j, positionAttribute.getX(j) + position.getX(j), positionAttribute.getY(j) + position.getY(j), positionAttribute.getZ(j) + position.getZ(j));
  31227. }
  31228. }
  31229. }
  31230. if (hasMorphNormal) {
  31231. // see target.POSITION's comment
  31232. if (target.NORMAL !== undefined) {
  31233. var normalAttribute = morphNormals[i];
  31234. normalAttribute.name = attributeName;
  31235. var normal = geometry.attributes.normal;
  31236. for (var j = 0, jl = normalAttribute.count; j < jl; j++) {
  31237. normalAttribute.setXYZ(j, normalAttribute.getX(j) + normal.getX(j), normalAttribute.getY(j) + normal.getY(j), normalAttribute.getZ(j) + normal.getZ(j));
  31238. }
  31239. }
  31240. }
  31241. }
  31242. if (hasMorphPosition) geometry.morphAttributes.position = morphPositions;
  31243. if (hasMorphNormal) geometry.morphAttributes.normal = morphNormals;
  31244. return geometry;
  31245. });
  31246. }
  31247. /**
  31248. * @param {Mesh} mesh
  31249. * @param {GLTF.Mesh} meshDef
  31250. */
  31251. function updateMorphTargets(mesh, meshDef) {
  31252. mesh.updateMorphTargets();
  31253. if (meshDef.weights !== undefined) {
  31254. for (var i = 0, il = meshDef.weights.length; i < il; i++) {
  31255. mesh.morphTargetInfluences[i] = meshDef.weights[i];
  31256. }
  31257. } // .extras has user-defined data, so check that .extras.targetNames is an array.
  31258. if (meshDef.extras && Array.isArray(meshDef.extras.targetNames)) {
  31259. var targetNames = meshDef.extras.targetNames;
  31260. if (mesh.morphTargetInfluences.length === targetNames.length) {
  31261. mesh.morphTargetDictionary = {};
  31262. for (var i = 0, il = targetNames.length; i < il; i++) {
  31263. mesh.morphTargetDictionary[targetNames[i]] = i;
  31264. }
  31265. } else {
  31266. console.warn('THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.');
  31267. }
  31268. }
  31269. }
  31270. function createPrimitiveKey(primitiveDef) {
  31271. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION];
  31272. var geometryKey;
  31273. if (dracoExtension) {
  31274. geometryKey = 'draco:' + dracoExtension.bufferView + ':' + dracoExtension.indices + ':' + createAttributesKey(dracoExtension.attributes);
  31275. } else {
  31276. geometryKey = primitiveDef.indices + ':' + createAttributesKey(primitiveDef.attributes) + ':' + primitiveDef.mode;
  31277. }
  31278. return geometryKey;
  31279. }
  31280. function createAttributesKey(attributes) {
  31281. var attributesKey = '';
  31282. var keys = Object.keys(attributes).sort();
  31283. for (var i = 0, il = keys.length; i < il; i++) {
  31284. attributesKey += keys[i] + ':' + attributes[keys[i]] + ';';
  31285. }
  31286. return attributesKey;
  31287. }
  31288. function cloneBufferAttribute(attribute) {
  31289. if (attribute.isInterleavedBufferAttribute) {
  31290. var count = attribute.count;
  31291. var itemSize = attribute.itemSize;
  31292. var array = attribute.array.slice(0, count * itemSize);
  31293. for (var i = 0, j = 0; i < count; ++i) {
  31294. array[j++] = attribute.getX(i);
  31295. if (itemSize >= 2) array[j++] = attribute.getY(i);
  31296. if (itemSize >= 3) array[j++] = attribute.getZ(i);
  31297. if (itemSize >= 4) array[j++] = attribute.getW(i);
  31298. }
  31299. return new _threeModule.BufferAttribute(array, itemSize, attribute.normalized);
  31300. }
  31301. return attribute.clone();
  31302. }
  31303. /* GLTF PARSER */
  31304. function GLTFParser(json, extensions, options) {
  31305. this.json = json || {};
  31306. this.extensions = extensions || {};
  31307. this.options = options || {}; // loader object cache
  31308. this.cache = new GLTFRegistry(); // BufferGeometry caching
  31309. this.primitiveCache = {};
  31310. this.textureLoader = new _threeModule.TextureLoader(this.options.manager);
  31311. this.textureLoader.setCrossOrigin(this.options.crossOrigin);
  31312. this.fileLoader = new _threeModule.FileLoader(this.options.manager);
  31313. this.fileLoader.setResponseType('arraybuffer');
  31314. if (this.options.crossOrigin === 'use-credentials') {
  31315. this.fileLoader.setWithCredentials(true);
  31316. }
  31317. }
  31318. GLTFParser.prototype.parse = function (onLoad, onError) {
  31319. var parser = this;
  31320. var json = this.json;
  31321. var extensions = this.extensions; // Clear the loader cache
  31322. this.cache.removeAll(); // Mark the special nodes/meshes in json for efficient parse
  31323. this.markDefs();
  31324. Promise.all([this.getDependencies('scene'), this.getDependencies('animation'), this.getDependencies('camera')]).then(function (dependencies) {
  31325. var result = {
  31326. scene: dependencies[0][json.scene || 0],
  31327. scenes: dependencies[0],
  31328. animations: dependencies[1],
  31329. cameras: dependencies[2],
  31330. asset: json.asset,
  31331. parser: parser,
  31332. userData: {}
  31333. };
  31334. addUnknownExtensionsToUserData(extensions, result, json);
  31335. assignExtrasToUserData(result, json);
  31336. onLoad(result);
  31337. }).catch(onError);
  31338. };
  31339. /**
  31340. * Marks the special nodes/meshes in json for efficient parse.
  31341. */
  31342. GLTFParser.prototype.markDefs = function () {
  31343. var nodeDefs = this.json.nodes || [];
  31344. var skinDefs = this.json.skins || [];
  31345. var meshDefs = this.json.meshes || [];
  31346. var meshReferences = {};
  31347. var meshUses = {}; // Nothing in the node definition indicates whether it is a Bone or an
  31348. // Object3D. Use the skins' joint references to mark bones.
  31349. for (var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex++) {
  31350. var joints = skinDefs[skinIndex].joints;
  31351. for (var i = 0, il = joints.length; i < il; i++) {
  31352. nodeDefs[joints[i]].isBone = true;
  31353. }
  31354. } // Meshes can (and should) be reused by multiple nodes in a glTF asset. To
  31355. // avoid having more than one Mesh with the same name, count
  31356. // references and rename instances below.
  31357. //
  31358. // Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  31359. for (var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) {
  31360. var nodeDef = nodeDefs[nodeIndex];
  31361. if (nodeDef.mesh !== undefined) {
  31362. if (meshReferences[nodeDef.mesh] === undefined) {
  31363. meshReferences[nodeDef.mesh] = meshUses[nodeDef.mesh] = 0;
  31364. }
  31365. meshReferences[nodeDef.mesh]++; // Nothing in the mesh definition indicates whether it is
  31366. // a SkinnedMesh or Mesh. Use the node's mesh reference
  31367. // to mark SkinnedMesh if node has skin.
  31368. if (nodeDef.skin !== undefined) {
  31369. meshDefs[nodeDef.mesh].isSkinnedMesh = true;
  31370. }
  31371. }
  31372. }
  31373. this.json.meshReferences = meshReferences;
  31374. this.json.meshUses = meshUses;
  31375. };
  31376. /**
  31377. * Requests the specified dependency asynchronously, with caching.
  31378. * @param {string} type
  31379. * @param {number} index
  31380. * @return {Promise<Object3D|Material|THREE.Texture|AnimationClip|ArrayBuffer|Object>}
  31381. */
  31382. GLTFParser.prototype.getDependency = function (type, index) {
  31383. var cacheKey = type + ':' + index;
  31384. var dependency = this.cache.get(cacheKey);
  31385. if (!dependency) {
  31386. switch (type) {
  31387. case 'scene':
  31388. dependency = this.loadScene(index);
  31389. break;
  31390. case 'node':
  31391. dependency = this.loadNode(index);
  31392. break;
  31393. case 'mesh':
  31394. dependency = this.loadMesh(index);
  31395. break;
  31396. case 'accessor':
  31397. dependency = this.loadAccessor(index);
  31398. break;
  31399. case 'bufferView':
  31400. dependency = this.loadBufferView(index);
  31401. break;
  31402. case 'buffer':
  31403. dependency = this.loadBuffer(index);
  31404. break;
  31405. case 'material':
  31406. dependency = this.loadMaterial(index);
  31407. break;
  31408. case 'texture':
  31409. dependency = this.loadTexture(index);
  31410. break;
  31411. case 'skin':
  31412. dependency = this.loadSkin(index);
  31413. break;
  31414. case 'animation':
  31415. dependency = this.loadAnimation(index);
  31416. break;
  31417. case 'camera':
  31418. dependency = this.loadCamera(index);
  31419. break;
  31420. case 'light':
  31421. dependency = this.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].loadLight(index);
  31422. break;
  31423. default:
  31424. throw new Error('Unknown type: ' + type);
  31425. }
  31426. this.cache.add(cacheKey, dependency);
  31427. }
  31428. return dependency;
  31429. };
  31430. /**
  31431. * Requests all dependencies of the specified type asynchronously, with caching.
  31432. * @param {string} type
  31433. * @return {Promise<Array<Object>>}
  31434. */
  31435. GLTFParser.prototype.getDependencies = function (type) {
  31436. var dependencies = this.cache.get(type);
  31437. if (!dependencies) {
  31438. var parser = this;
  31439. var defs = this.json[type + (type === 'mesh' ? 'es' : 's')] || [];
  31440. dependencies = Promise.all(defs.map(function (def, index) {
  31441. return parser.getDependency(type, index);
  31442. }));
  31443. this.cache.add(type, dependencies);
  31444. }
  31445. return dependencies;
  31446. };
  31447. /**
  31448. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  31449. * @param {number} bufferIndex
  31450. * @return {Promise<ArrayBuffer>}
  31451. */
  31452. GLTFParser.prototype.loadBuffer = function (bufferIndex) {
  31453. var bufferDef = this.json.buffers[bufferIndex];
  31454. var loader = this.fileLoader;
  31455. if (bufferDef.type && bufferDef.type !== 'arraybuffer') {
  31456. throw new Error('THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.');
  31457. } // If present, GLB container is required to be the first buffer.
  31458. if (bufferDef.uri === undefined && bufferIndex === 0) {
  31459. return Promise.resolve(this.extensions[EXTENSIONS.KHR_BINARY_GLTF].body);
  31460. }
  31461. var options = this.options;
  31462. return new Promise(function (resolve, reject) {
  31463. loader.load(resolveURL(bufferDef.uri, options.path), resolve, undefined, function () {
  31464. reject(new Error('THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".'));
  31465. });
  31466. });
  31467. };
  31468. /**
  31469. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  31470. * @param {number} bufferViewIndex
  31471. * @return {Promise<ArrayBuffer>}
  31472. */
  31473. GLTFParser.prototype.loadBufferView = function (bufferViewIndex) {
  31474. var bufferViewDef = this.json.bufferViews[bufferViewIndex];
  31475. return this.getDependency('buffer', bufferViewDef.buffer).then(function (buffer) {
  31476. var byteLength = bufferViewDef.byteLength || 0;
  31477. var byteOffset = bufferViewDef.byteOffset || 0;
  31478. return buffer.slice(byteOffset, byteOffset + byteLength);
  31479. });
  31480. };
  31481. /**
  31482. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  31483. * @param {number} accessorIndex
  31484. * @return {Promise<BufferAttribute|InterleavedBufferAttribute>}
  31485. */
  31486. GLTFParser.prototype.loadAccessor = function (accessorIndex) {
  31487. var parser = this;
  31488. var json = this.json;
  31489. var accessorDef = this.json.accessors[accessorIndex];
  31490. if (accessorDef.bufferView === undefined && accessorDef.sparse === undefined) {
  31491. // Ignore empty accessors, which may be used to declare runtime
  31492. // information about attributes coming from another source (e.g. Draco
  31493. // compression extension).
  31494. return Promise.resolve(null);
  31495. }
  31496. var pendingBufferViews = [];
  31497. if (accessorDef.bufferView !== undefined) {
  31498. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.bufferView));
  31499. } else {
  31500. pendingBufferViews.push(null);
  31501. }
  31502. if (accessorDef.sparse !== undefined) {
  31503. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.indices.bufferView));
  31504. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.values.bufferView));
  31505. }
  31506. return Promise.all(pendingBufferViews).then(function (bufferViews) {
  31507. var bufferView = bufferViews[0];
  31508. var itemSize = WEBGL_TYPE_SIZES[accessorDef.type];
  31509. var TypedArray = WEBGL_COMPONENT_TYPES[accessorDef.componentType]; // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  31510. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  31511. var itemBytes = elementBytes * itemSize;
  31512. var byteOffset = accessorDef.byteOffset || 0;
  31513. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[accessorDef.bufferView].byteStride : undefined;
  31514. var normalized = accessorDef.normalized === true;
  31515. var array, bufferAttribute; // The buffer is not interleaved if the stride is the item size in bytes.
  31516. if (byteStride && byteStride !== itemBytes) {
  31517. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
  31518. // This makes sure that IBA.count reflects accessor.count properly
  31519. var ibSlice = Math.floor(byteOffset / byteStride);
  31520. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
  31521. var ib = parser.cache.get(ibCacheKey);
  31522. if (!ib) {
  31523. array = new TypedArray(bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes); // Integer parameters to IB/IBA are in array elements, not bytes.
  31524. ib = new _threeModule.InterleavedBuffer(array, byteStride / elementBytes);
  31525. parser.cache.add(ibCacheKey, ib);
  31526. }
  31527. bufferAttribute = new _threeModule.InterleavedBufferAttribute(ib, itemSize, byteOffset % byteStride / elementBytes, normalized);
  31528. } else {
  31529. if (bufferView === null) {
  31530. array = new TypedArray(accessorDef.count * itemSize);
  31531. } else {
  31532. array = new TypedArray(bufferView, byteOffset, accessorDef.count * itemSize);
  31533. }
  31534. bufferAttribute = new _threeModule.BufferAttribute(array, itemSize, normalized);
  31535. } // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  31536. if (accessorDef.sparse !== undefined) {
  31537. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  31538. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[accessorDef.sparse.indices.componentType];
  31539. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  31540. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  31541. var sparseIndices = new TypedArrayIndices(bufferViews[1], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices);
  31542. var sparseValues = new TypedArray(bufferViews[2], byteOffsetValues, accessorDef.sparse.count * itemSize);
  31543. if (bufferView !== null) {
  31544. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  31545. bufferAttribute = new _threeModule.BufferAttribute(bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized);
  31546. }
  31547. for (var i = 0, il = sparseIndices.length; i < il; i++) {
  31548. var index = sparseIndices[i];
  31549. bufferAttribute.setX(index, sparseValues[i * itemSize]);
  31550. if (itemSize >= 2) bufferAttribute.setY(index, sparseValues[i * itemSize + 1]);
  31551. if (itemSize >= 3) bufferAttribute.setZ(index, sparseValues[i * itemSize + 2]);
  31552. if (itemSize >= 4) bufferAttribute.setW(index, sparseValues[i * itemSize + 3]);
  31553. if (itemSize >= 5) throw new Error('THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.');
  31554. }
  31555. }
  31556. return bufferAttribute;
  31557. });
  31558. };
  31559. /**
  31560. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  31561. * @param {number} textureIndex
  31562. * @return {Promise<THREE.Texture>}
  31563. */
  31564. GLTFParser.prototype.loadTexture = function (textureIndex) {
  31565. var parser = this;
  31566. var json = this.json;
  31567. var options = this.options;
  31568. var textureLoader = this.textureLoader;
  31569. var URL = window.URL || window.webkitURL;
  31570. var textureDef = json.textures[textureIndex];
  31571. var textureExtensions = textureDef.extensions || {};
  31572. var source;
  31573. if (textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS]) {
  31574. source = json.images[textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS].source];
  31575. } else {
  31576. source = json.images[textureDef.source];
  31577. }
  31578. var sourceURI = source.uri;
  31579. var isObjectURL = false;
  31580. if (source.bufferView !== undefined) {
  31581. // Load binary image data from bufferView, if provided.
  31582. sourceURI = parser.getDependency('bufferView', source.bufferView).then(function (bufferView) {
  31583. isObjectURL = true;
  31584. var blob = new Blob([bufferView], {
  31585. type: source.mimeType
  31586. });
  31587. sourceURI = URL.createObjectURL(blob);
  31588. return sourceURI;
  31589. });
  31590. }
  31591. return Promise.resolve(sourceURI).then(function (sourceURI) {
  31592. // Load Texture resource.
  31593. var loader = options.manager.getHandler(sourceURI);
  31594. if (!loader) {
  31595. loader = textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS] ? parser.extensions[EXTENSIONS.MSFT_TEXTURE_DDS].ddsLoader : textureLoader;
  31596. }
  31597. return new Promise(function (resolve, reject) {
  31598. loader.load(resolveURL(sourceURI, options.path), resolve, undefined, reject);
  31599. });
  31600. }).then(function (texture) {
  31601. // Clean up resources and configure Texture.
  31602. if (isObjectURL === true) {
  31603. URL.revokeObjectURL(sourceURI);
  31604. }
  31605. texture.flipY = false;
  31606. if (textureDef.name !== undefined) texture.name = textureDef.name; // Ignore unknown mime types, like DDS files.
  31607. if (source.mimeType in MIME_TYPE_FORMATS) {
  31608. texture.format = MIME_TYPE_FORMATS[source.mimeType];
  31609. }
  31610. var samplers = json.samplers || {};
  31611. var sampler = samplers[textureDef.sampler] || {};
  31612. texture.magFilter = WEBGL_FILTERS[sampler.magFilter] || _threeModule.LinearFilter;
  31613. texture.minFilter = WEBGL_FILTERS[sampler.minFilter] || _threeModule.LinearMipmapLinearFilter;
  31614. texture.wrapS = WEBGL_WRAPPINGS[sampler.wrapS] || _threeModule.RepeatWrapping;
  31615. texture.wrapT = WEBGL_WRAPPINGS[sampler.wrapT] || _threeModule.RepeatWrapping;
  31616. return texture;
  31617. });
  31618. };
  31619. /**
  31620. * Asynchronously assigns a texture to the given material parameters.
  31621. * @param {Object} materialParams
  31622. * @param {string} mapName
  31623. * @param {Object} mapDef
  31624. * @return {Promise}
  31625. */
  31626. GLTFParser.prototype.assignTexture = function (materialParams, mapName, mapDef) {
  31627. var parser = this;
  31628. return this.getDependency('texture', mapDef.index).then(function (texture) {
  31629. if (!texture.isCompressedTexture) {
  31630. switch (mapName) {
  31631. case 'aoMap':
  31632. case 'emissiveMap':
  31633. case 'metalnessMap':
  31634. case 'normalMap':
  31635. case 'roughnessMap':
  31636. texture.format = _threeModule.RGBFormat;
  31637. break;
  31638. }
  31639. }
  31640. if (parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM]) {
  31641. var transform = mapDef.extensions !== undefined ? mapDef.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] : undefined;
  31642. if (transform) {
  31643. texture = parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM].extendTexture(texture, transform);
  31644. }
  31645. }
  31646. materialParams[mapName] = texture;
  31647. });
  31648. };
  31649. /**
  31650. * Assigns final material to a Mesh, Line, or Points instance. The instance
  31651. * already has a material (generated from the glTF material options alone)
  31652. * but reuse of the same glTF material may require multiple threejs materials
  31653. * to accomodate different primitive types, defines, etc. New materials will
  31654. * be created if necessary, and reused from a cache.
  31655. * @param {Object3D} mesh Mesh, Line, or Points instance.
  31656. */
  31657. GLTFParser.prototype.assignFinalMaterial = function (mesh) {
  31658. var geometry = mesh.geometry;
  31659. var material = mesh.material;
  31660. var extensions = this.extensions;
  31661. var useVertexTangents = geometry.attributes.tangent !== undefined;
  31662. var useVertexColors = geometry.attributes.color !== undefined;
  31663. var useFlatShading = geometry.attributes.normal === undefined;
  31664. var useSkinning = mesh.isSkinnedMesh === true;
  31665. var useMorphTargets = Object.keys(geometry.morphAttributes).length > 0;
  31666. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  31667. if (mesh.isPoints) {
  31668. var cacheKey = 'PointsMaterial:' + material.uuid;
  31669. var pointsMaterial = this.cache.get(cacheKey);
  31670. if (!pointsMaterial) {
  31671. pointsMaterial = new _threeModule.PointsMaterial();
  31672. _threeModule.Material.prototype.copy.call(pointsMaterial, material);
  31673. pointsMaterial.color.copy(material.color);
  31674. pointsMaterial.map = material.map;
  31675. pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
  31676. this.cache.add(cacheKey, pointsMaterial);
  31677. }
  31678. material = pointsMaterial;
  31679. } else if (mesh.isLine) {
  31680. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  31681. var lineMaterial = this.cache.get(cacheKey);
  31682. if (!lineMaterial) {
  31683. lineMaterial = new _threeModule.LineBasicMaterial();
  31684. _threeModule.Material.prototype.copy.call(lineMaterial, material);
  31685. lineMaterial.color.copy(material.color);
  31686. this.cache.add(cacheKey, lineMaterial);
  31687. }
  31688. material = lineMaterial;
  31689. } // Clone the material if it will be modified
  31690. if (useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets) {
  31691. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  31692. if (material.isGLTFSpecularGlossinessMaterial) cacheKey += 'specular-glossiness:';
  31693. if (useSkinning) cacheKey += 'skinning:';
  31694. if (useVertexTangents) cacheKey += 'vertex-tangents:';
  31695. if (useVertexColors) cacheKey += 'vertex-colors:';
  31696. if (useFlatShading) cacheKey += 'flat-shading:';
  31697. if (useMorphTargets) cacheKey += 'morph-targets:';
  31698. if (useMorphNormals) cacheKey += 'morph-normals:';
  31699. var cachedMaterial = this.cache.get(cacheKey);
  31700. if (!cachedMaterial) {
  31701. cachedMaterial = material.isGLTFSpecularGlossinessMaterial ? extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].cloneMaterial(material) : material.clone();
  31702. if (useSkinning) cachedMaterial.skinning = true;
  31703. if (useVertexTangents) cachedMaterial.vertexTangents = true;
  31704. if (useVertexColors) cachedMaterial.vertexColors = _threeModule.VertexColors;
  31705. if (useFlatShading) cachedMaterial.flatShading = true;
  31706. if (useMorphTargets) cachedMaterial.morphTargets = true;
  31707. if (useMorphNormals) cachedMaterial.morphNormals = true;
  31708. this.cache.add(cacheKey, cachedMaterial);
  31709. }
  31710. material = cachedMaterial;
  31711. } // workarounds for mesh and geometry
  31712. if (material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined) {
  31713. console.log('THREE.GLTFLoader: Duplicating UVs to support aoMap.');
  31714. geometry.addAttribute('uv2', new _threeModule.BufferAttribute(geometry.attributes.uv.array, 2));
  31715. }
  31716. if (material.isGLTFSpecularGlossinessMaterial) {
  31717. // for GLTFSpecularGlossinessMaterial(ShaderMaterial) uniforms runtime update
  31718. mesh.onBeforeRender = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].refreshUniforms;
  31719. }
  31720. mesh.material = material;
  31721. };
  31722. /**
  31723. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  31724. * @param {number} materialIndex
  31725. * @return {Promise<Material>}
  31726. */
  31727. GLTFParser.prototype.loadMaterial = function (materialIndex) {
  31728. var parser = this;
  31729. var json = this.json;
  31730. var extensions = this.extensions;
  31731. var materialDef = json.materials[materialIndex];
  31732. var materialType;
  31733. var materialParams = {};
  31734. var materialExtensions = materialDef.extensions || {};
  31735. var pending = [];
  31736. if (materialExtensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS]) {
  31737. var sgExtension = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS];
  31738. materialType = sgExtension.getMaterialType();
  31739. pending.push(sgExtension.extendParams(materialParams, materialDef, parser));
  31740. } else if (materialExtensions[EXTENSIONS.KHR_MATERIALS_UNLIT]) {
  31741. var kmuExtension = extensions[EXTENSIONS.KHR_MATERIALS_UNLIT];
  31742. materialType = kmuExtension.getMaterialType();
  31743. pending.push(kmuExtension.extendParams(materialParams, materialDef, parser));
  31744. } else {
  31745. // Specification:
  31746. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  31747. materialType = _threeModule.MeshStandardMaterial;
  31748. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  31749. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  31750. materialParams.opacity = 1.0;
  31751. if (Array.isArray(metallicRoughness.baseColorFactor)) {
  31752. var array = metallicRoughness.baseColorFactor;
  31753. materialParams.color.fromArray(array);
  31754. materialParams.opacity = array[3];
  31755. }
  31756. if (metallicRoughness.baseColorTexture !== undefined) {
  31757. pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture));
  31758. }
  31759. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  31760. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  31761. if (metallicRoughness.metallicRoughnessTexture !== undefined) {
  31762. pending.push(parser.assignTexture(materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture));
  31763. pending.push(parser.assignTexture(materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture));
  31764. }
  31765. }
  31766. if (materialDef.doubleSided === true) {
  31767. materialParams.side = _threeModule.DoubleSide;
  31768. }
  31769. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  31770. if (alphaMode === ALPHA_MODES.BLEND) {
  31771. materialParams.transparent = true;
  31772. } else {
  31773. materialParams.transparent = false;
  31774. if (alphaMode === ALPHA_MODES.MASK) {
  31775. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  31776. }
  31777. }
  31778. if (materialDef.normalTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  31779. pending.push(parser.assignTexture(materialParams, 'normalMap', materialDef.normalTexture));
  31780. materialParams.normalScale = new _threeModule.Vector2(1, 1);
  31781. if (materialDef.normalTexture.scale !== undefined) {
  31782. materialParams.normalScale.set(materialDef.normalTexture.scale, materialDef.normalTexture.scale);
  31783. }
  31784. }
  31785. if (materialDef.occlusionTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  31786. pending.push(parser.assignTexture(materialParams, 'aoMap', materialDef.occlusionTexture));
  31787. if (materialDef.occlusionTexture.strength !== undefined) {
  31788. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  31789. }
  31790. }
  31791. if (materialDef.emissiveFactor !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  31792. materialParams.emissive = new _threeModule.Color().fromArray(materialDef.emissiveFactor);
  31793. }
  31794. if (materialDef.emissiveTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  31795. pending.push(parser.assignTexture(materialParams, 'emissiveMap', materialDef.emissiveTexture));
  31796. }
  31797. return Promise.all(pending).then(function () {
  31798. var material;
  31799. if (materialType === _threeModule.ShaderMaterial) {
  31800. material = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].createMaterial(materialParams);
  31801. } else {
  31802. material = new materialType(materialParams);
  31803. }
  31804. if (materialDef.name !== undefined) material.name = materialDef.name; // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  31805. if (material.map) material.map.encoding = _threeModule.sRGBEncoding;
  31806. if (material.emissiveMap) material.emissiveMap.encoding = _threeModule.sRGBEncoding;
  31807. if (material.specularMap) material.specularMap.encoding = _threeModule.sRGBEncoding;
  31808. assignExtrasToUserData(material, materialDef);
  31809. if (materialDef.extensions) addUnknownExtensionsToUserData(extensions, material, materialDef);
  31810. return material;
  31811. });
  31812. };
  31813. /**
  31814. * @param {BufferGeometry} geometry
  31815. * @param {GLTF.Primitive} primitiveDef
  31816. * @param {GLTFParser} parser
  31817. * @return {Promise<BufferGeometry>}
  31818. */
  31819. function addPrimitiveAttributes(geometry, primitiveDef, parser) {
  31820. var attributes = primitiveDef.attributes;
  31821. var pending = [];
  31822. function assignAttributeAccessor(accessorIndex, attributeName) {
  31823. return parser.getDependency('accessor', accessorIndex).then(function (accessor) {
  31824. geometry.addAttribute(attributeName, accessor);
  31825. });
  31826. }
  31827. for (var gltfAttributeName in attributes) {
  31828. var threeAttributeName = ATTRIBUTES[gltfAttributeName] || gltfAttributeName.toLowerCase(); // Skip attributes already provided by e.g. Draco extension.
  31829. if (threeAttributeName in geometry.attributes) continue;
  31830. pending.push(assignAttributeAccessor(attributes[gltfAttributeName], threeAttributeName));
  31831. }
  31832. if (primitiveDef.indices !== undefined && !geometry.index) {
  31833. var accessor = parser.getDependency('accessor', primitiveDef.indices).then(function (accessor) {
  31834. geometry.setIndex(accessor);
  31835. });
  31836. pending.push(accessor);
  31837. }
  31838. assignExtrasToUserData(geometry, primitiveDef);
  31839. return Promise.all(pending).then(function () {
  31840. return primitiveDef.targets !== undefined ? addMorphTargets(geometry, primitiveDef.targets, parser) : geometry;
  31841. });
  31842. }
  31843. /**
  31844. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  31845. *
  31846. * Creates BufferGeometries from primitives.
  31847. *
  31848. * @param {Array<GLTF.Primitive>} primitives
  31849. * @return {Promise<Array<BufferGeometry>>}
  31850. */
  31851. GLTFParser.prototype.loadGeometries = function (primitives) {
  31852. var parser = this;
  31853. var extensions = this.extensions;
  31854. var cache = this.primitiveCache;
  31855. function createDracoPrimitive(primitive) {
  31856. return extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(primitive, parser).then(function (geometry) {
  31857. return addPrimitiveAttributes(geometry, primitive, parser);
  31858. });
  31859. }
  31860. var pending = [];
  31861. for (var i = 0, il = primitives.length; i < il; i++) {
  31862. var primitive = primitives[i];
  31863. var cacheKey = createPrimitiveKey(primitive); // See if we've already created this geometry
  31864. var cached = cache[cacheKey];
  31865. if (cached) {
  31866. // Use the cached geometry if it exists
  31867. pending.push(cached.promise);
  31868. } else {
  31869. var geometryPromise;
  31870. if (primitive.extensions && primitive.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]) {
  31871. // Use DRACO geometry if available
  31872. geometryPromise = createDracoPrimitive(primitive);
  31873. } else {
  31874. // Otherwise create a new geometry
  31875. geometryPromise = addPrimitiveAttributes(new _threeModule.BufferGeometry(), primitive, parser);
  31876. } // Cache this geometry
  31877. cache[cacheKey] = {
  31878. primitive: primitive,
  31879. promise: geometryPromise
  31880. };
  31881. pending.push(geometryPromise);
  31882. }
  31883. }
  31884. return Promise.all(pending);
  31885. };
  31886. /**
  31887. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  31888. * @param {number} meshIndex
  31889. * @return {Promise<Group|Mesh|SkinnedMesh>}
  31890. */
  31891. GLTFParser.prototype.loadMesh = function (meshIndex) {
  31892. var parser = this;
  31893. var json = this.json;
  31894. var meshDef = json.meshes[meshIndex];
  31895. var primitives = meshDef.primitives;
  31896. var pending = [];
  31897. for (var i = 0, il = primitives.length; i < il; i++) {
  31898. var material = primitives[i].material === undefined ? createDefaultMaterial() : this.getDependency('material', primitives[i].material);
  31899. pending.push(material);
  31900. }
  31901. return Promise.all(pending).then(function (originalMaterials) {
  31902. return parser.loadGeometries(primitives).then(function (geometries) {
  31903. var meshes = [];
  31904. for (var i = 0, il = geometries.length; i < il; i++) {
  31905. var geometry = geometries[i];
  31906. var primitive = primitives[i]; // 1. create Mesh
  31907. var mesh;
  31908. var material = originalMaterials[i];
  31909. if (primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN || primitive.mode === undefined) {
  31910. // .isSkinnedMesh isn't in glTF spec. See .markDefs()
  31911. mesh = meshDef.isSkinnedMesh === true ? new _threeModule.SkinnedMesh(geometry, material) : new _threeModule.Mesh(geometry, material);
  31912. if (mesh.isSkinnedMesh === true && !mesh.geometry.attributes.skinWeight.normalized) {
  31913. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  31914. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  31915. mesh.normalizeSkinWeights();
  31916. }
  31917. if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP) {
  31918. mesh.drawMode = _threeModule.TriangleStripDrawMode;
  31919. } else if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN) {
  31920. mesh.drawMode = _threeModule.TriangleFanDrawMode;
  31921. }
  31922. } else if (primitive.mode === WEBGL_CONSTANTS.LINES) {
  31923. mesh = new _threeModule.LineSegments(geometry, material);
  31924. } else if (primitive.mode === WEBGL_CONSTANTS.LINE_STRIP) {
  31925. mesh = new _threeModule.Line(geometry, material);
  31926. } else if (primitive.mode === WEBGL_CONSTANTS.LINE_LOOP) {
  31927. mesh = new _threeModule.LineLoop(geometry, material);
  31928. } else if (primitive.mode === WEBGL_CONSTANTS.POINTS) {
  31929. mesh = new _threeModule.Points(geometry, material);
  31930. } else {
  31931. throw new Error('THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode);
  31932. }
  31933. if (Object.keys(mesh.geometry.morphAttributes).length > 0) {
  31934. updateMorphTargets(mesh, meshDef);
  31935. }
  31936. mesh.name = meshDef.name || 'mesh_' + meshIndex;
  31937. if (geometries.length > 1) mesh.name += '_' + i;
  31938. assignExtrasToUserData(mesh, meshDef);
  31939. parser.assignFinalMaterial(mesh);
  31940. meshes.push(mesh);
  31941. }
  31942. if (meshes.length === 1) {
  31943. return meshes[0];
  31944. }
  31945. var group = new _threeModule.Group();
  31946. for (var i = 0, il = meshes.length; i < il; i++) {
  31947. group.add(meshes[i]);
  31948. }
  31949. return group;
  31950. });
  31951. });
  31952. };
  31953. /**
  31954. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  31955. * @param {number} cameraIndex
  31956. * @return {Promise<THREE.Camera>}
  31957. */
  31958. GLTFParser.prototype.loadCamera = function (cameraIndex) {
  31959. var camera;
  31960. var cameraDef = this.json.cameras[cameraIndex];
  31961. var params = cameraDef[cameraDef.type];
  31962. if (!params) {
  31963. console.warn('THREE.GLTFLoader: Missing camera parameters.');
  31964. return;
  31965. }
  31966. if (cameraDef.type === 'perspective') {
  31967. camera = new _threeModule.PerspectiveCamera(_threeModule.Math.radToDeg(params.yfov), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6);
  31968. } else if (cameraDef.type === 'orthographic') {
  31969. camera = new _threeModule.OrthographicCamera(params.xmag / -2, params.xmag / 2, params.ymag / 2, params.ymag / -2, params.znear, params.zfar);
  31970. }
  31971. if (cameraDef.name !== undefined) camera.name = cameraDef.name;
  31972. assignExtrasToUserData(camera, cameraDef);
  31973. return Promise.resolve(camera);
  31974. };
  31975. /**
  31976. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  31977. * @param {number} skinIndex
  31978. * @return {Promise<Object>}
  31979. */
  31980. GLTFParser.prototype.loadSkin = function (skinIndex) {
  31981. var skinDef = this.json.skins[skinIndex];
  31982. var skinEntry = {
  31983. joints: skinDef.joints
  31984. };
  31985. if (skinDef.inverseBindMatrices === undefined) {
  31986. return Promise.resolve(skinEntry);
  31987. }
  31988. return this.getDependency('accessor', skinDef.inverseBindMatrices).then(function (accessor) {
  31989. skinEntry.inverseBindMatrices = accessor;
  31990. return skinEntry;
  31991. });
  31992. };
  31993. /**
  31994. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  31995. * @param {number} animationIndex
  31996. * @return {Promise<AnimationClip>}
  31997. */
  31998. GLTFParser.prototype.loadAnimation = function (animationIndex) {
  31999. var json = this.json;
  32000. var animationDef = json.animations[animationIndex];
  32001. var pendingNodes = [];
  32002. var pendingInputAccessors = [];
  32003. var pendingOutputAccessors = [];
  32004. var pendingSamplers = [];
  32005. var pendingTargets = [];
  32006. for (var i = 0, il = animationDef.channels.length; i < il; i++) {
  32007. var channel = animationDef.channels[i];
  32008. var sampler = animationDef.samplers[channel.sampler];
  32009. var target = channel.target;
  32010. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  32011. var input = animationDef.parameters !== undefined ? animationDef.parameters[sampler.input] : sampler.input;
  32012. var output = animationDef.parameters !== undefined ? animationDef.parameters[sampler.output] : sampler.output;
  32013. pendingNodes.push(this.getDependency('node', name));
  32014. pendingInputAccessors.push(this.getDependency('accessor', input));
  32015. pendingOutputAccessors.push(this.getDependency('accessor', output));
  32016. pendingSamplers.push(sampler);
  32017. pendingTargets.push(target);
  32018. }
  32019. return Promise.all([Promise.all(pendingNodes), Promise.all(pendingInputAccessors), Promise.all(pendingOutputAccessors), Promise.all(pendingSamplers), Promise.all(pendingTargets)]).then(function (dependencies) {
  32020. var nodes = dependencies[0];
  32021. var inputAccessors = dependencies[1];
  32022. var outputAccessors = dependencies[2];
  32023. var samplers = dependencies[3];
  32024. var targets = dependencies[4];
  32025. var tracks = [];
  32026. for (var i = 0, il = nodes.length; i < il; i++) {
  32027. var node = nodes[i];
  32028. var inputAccessor = inputAccessors[i];
  32029. var outputAccessor = outputAccessors[i];
  32030. var sampler = samplers[i];
  32031. var target = targets[i];
  32032. if (node === undefined) continue;
  32033. node.updateMatrix();
  32034. node.matrixAutoUpdate = true;
  32035. var TypedKeyframeTrack;
  32036. switch (PATH_PROPERTIES[target.path]) {
  32037. case PATH_PROPERTIES.weights:
  32038. TypedKeyframeTrack = _threeModule.NumberKeyframeTrack;
  32039. break;
  32040. case PATH_PROPERTIES.rotation:
  32041. TypedKeyframeTrack = _threeModule.QuaternionKeyframeTrack;
  32042. break;
  32043. case PATH_PROPERTIES.position:
  32044. case PATH_PROPERTIES.scale:
  32045. default:
  32046. TypedKeyframeTrack = _threeModule.VectorKeyframeTrack;
  32047. break;
  32048. }
  32049. var targetName = node.name ? node.name : node.uuid;
  32050. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[sampler.interpolation] : _threeModule.InterpolateLinear;
  32051. var targetNames = [];
  32052. if (PATH_PROPERTIES[target.path] === PATH_PROPERTIES.weights) {
  32053. // Node may be a Group (glTF mesh with several primitives) or a Mesh.
  32054. node.traverse(function (object) {
  32055. if (object.isMesh === true && object.morphTargetInfluences) {
  32056. targetNames.push(object.name ? object.name : object.uuid);
  32057. }
  32058. });
  32059. } else {
  32060. targetNames.push(targetName);
  32061. }
  32062. var outputArray = outputAccessor.array;
  32063. if (outputAccessor.normalized) {
  32064. var scale;
  32065. if (outputArray.constructor === Int8Array) {
  32066. scale = 1 / 127;
  32067. } else if (outputArray.constructor === Uint8Array) {
  32068. scale = 1 / 255;
  32069. } else if (outputArray.constructor == Int16Array) {
  32070. scale = 1 / 32767;
  32071. } else if (outputArray.constructor === Uint16Array) {
  32072. scale = 1 / 65535;
  32073. } else {
  32074. throw new Error('THREE.GLTFLoader: Unsupported output accessor component type.');
  32075. }
  32076. var scaled = new Float32Array(outputArray.length);
  32077. for (var j = 0, jl = outputArray.length; j < jl; j++) {
  32078. scaled[j] = outputArray[j] * scale;
  32079. }
  32080. outputArray = scaled;
  32081. }
  32082. for (var j = 0, jl = targetNames.length; j < jl; j++) {
  32083. var track = new TypedKeyframeTrack(targetNames[j] + '.' + PATH_PROPERTIES[target.path], inputAccessor.array, outputArray, interpolation); // Override interpolation with custom factory method.
  32084. if (sampler.interpolation === 'CUBICSPLINE') {
  32085. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline(result) {
  32086. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  32087. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  32088. // must be divided by three to get the interpolant's sampleSize argument.
  32089. return new GLTFCubicSplineInterpolant(this.times, this.values, this.getValueSize() / 3, result);
  32090. }; // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  32091. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  32092. }
  32093. tracks.push(track);
  32094. }
  32095. }
  32096. var name = animationDef.name !== undefined ? animationDef.name : 'animation_' + animationIndex;
  32097. return new _threeModule.AnimationClip(name, undefined, tracks);
  32098. });
  32099. };
  32100. /**
  32101. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  32102. * @param {number} nodeIndex
  32103. * @return {Promise<Object3D>}
  32104. */
  32105. GLTFParser.prototype.loadNode = function (nodeIndex) {
  32106. var json = this.json;
  32107. var extensions = this.extensions;
  32108. var parser = this;
  32109. var meshReferences = json.meshReferences;
  32110. var meshUses = json.meshUses;
  32111. var nodeDef = json.nodes[nodeIndex];
  32112. return function () {
  32113. var pending = [];
  32114. if (nodeDef.mesh !== undefined) {
  32115. pending.push(parser.getDependency('mesh', nodeDef.mesh).then(function (mesh) {
  32116. var node;
  32117. if (meshReferences[nodeDef.mesh] > 1) {
  32118. var instanceNum = meshUses[nodeDef.mesh]++;
  32119. node = mesh.clone();
  32120. node.name += '_instance_' + instanceNum; // onBeforeRender copy for Specular-Glossiness
  32121. node.onBeforeRender = mesh.onBeforeRender;
  32122. for (var i = 0, il = node.children.length; i < il; i++) {
  32123. node.children[i].name += '_instance_' + instanceNum;
  32124. node.children[i].onBeforeRender = mesh.children[i].onBeforeRender;
  32125. }
  32126. } else {
  32127. node = mesh;
  32128. } // if weights are provided on the node, override weights on the mesh.
  32129. if (nodeDef.weights !== undefined) {
  32130. node.traverse(function (o) {
  32131. if (!o.isMesh) return;
  32132. for (var i = 0, il = nodeDef.weights.length; i < il; i++) {
  32133. o.morphTargetInfluences[i] = nodeDef.weights[i];
  32134. }
  32135. });
  32136. }
  32137. return node;
  32138. }));
  32139. }
  32140. if (nodeDef.camera !== undefined) {
  32141. pending.push(parser.getDependency('camera', nodeDef.camera));
  32142. }
  32143. if (nodeDef.extensions && nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL] && nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].light !== undefined) {
  32144. pending.push(parser.getDependency('light', nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].light));
  32145. }
  32146. return Promise.all(pending);
  32147. }().then(function (objects) {
  32148. var node; // .isBone isn't in glTF spec. See .markDefs
  32149. if (nodeDef.isBone === true) {
  32150. node = new _threeModule.Bone();
  32151. } else if (objects.length > 1) {
  32152. node = new _threeModule.Group();
  32153. } else if (objects.length === 1) {
  32154. node = objects[0];
  32155. } else {
  32156. node = new _threeModule.Object3D();
  32157. }
  32158. if (node !== objects[0]) {
  32159. for (var i = 0, il = objects.length; i < il; i++) {
  32160. node.add(objects[i]);
  32161. }
  32162. }
  32163. if (nodeDef.name !== undefined) {
  32164. node.userData.name = nodeDef.name;
  32165. node.name = _threeModule.PropertyBinding.sanitizeNodeName(nodeDef.name);
  32166. }
  32167. assignExtrasToUserData(node, nodeDef);
  32168. if (nodeDef.extensions) addUnknownExtensionsToUserData(extensions, node, nodeDef);
  32169. if (nodeDef.matrix !== undefined) {
  32170. var matrix = new _threeModule.Matrix4();
  32171. matrix.fromArray(nodeDef.matrix);
  32172. node.applyMatrix(matrix);
  32173. } else {
  32174. if (nodeDef.translation !== undefined) {
  32175. node.position.fromArray(nodeDef.translation);
  32176. }
  32177. if (nodeDef.rotation !== undefined) {
  32178. node.quaternion.fromArray(nodeDef.rotation);
  32179. }
  32180. if (nodeDef.scale !== undefined) {
  32181. node.scale.fromArray(nodeDef.scale);
  32182. }
  32183. }
  32184. return node;
  32185. });
  32186. };
  32187. /**
  32188. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  32189. * @param {number} sceneIndex
  32190. * @return {Promise<Scene>}
  32191. */
  32192. GLTFParser.prototype.loadScene = function () {
  32193. // scene node hierachy builder
  32194. function buildNodeHierachy(nodeId, parentObject, json, parser) {
  32195. var nodeDef = json.nodes[nodeId];
  32196. return parser.getDependency('node', nodeId).then(function (node) {
  32197. if (nodeDef.skin === undefined) return node; // build skeleton here as well
  32198. var skinEntry;
  32199. return parser.getDependency('skin', nodeDef.skin).then(function (skin) {
  32200. skinEntry = skin;
  32201. var pendingJoints = [];
  32202. for (var i = 0, il = skinEntry.joints.length; i < il; i++) {
  32203. pendingJoints.push(parser.getDependency('node', skinEntry.joints[i]));
  32204. }
  32205. return Promise.all(pendingJoints);
  32206. }).then(function (jointNodes) {
  32207. node.traverse(function (mesh) {
  32208. if (!mesh.isMesh) return;
  32209. var bones = [];
  32210. var boneInverses = [];
  32211. for (var j = 0, jl = jointNodes.length; j < jl; j++) {
  32212. var jointNode = jointNodes[j];
  32213. if (jointNode) {
  32214. bones.push(jointNode);
  32215. var mat = new _threeModule.Matrix4();
  32216. if (skinEntry.inverseBindMatrices !== undefined) {
  32217. mat.fromArray(skinEntry.inverseBindMatrices.array, j * 16);
  32218. }
  32219. boneInverses.push(mat);
  32220. } else {
  32221. console.warn('THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[j]);
  32222. }
  32223. }
  32224. mesh.bind(new _threeModule.Skeleton(bones, boneInverses), mesh.matrixWorld);
  32225. });
  32226. return node;
  32227. });
  32228. }).then(function (node) {
  32229. // build node hierachy
  32230. parentObject.add(node);
  32231. var pending = [];
  32232. if (nodeDef.children) {
  32233. var children = nodeDef.children;
  32234. for (var i = 0, il = children.length; i < il; i++) {
  32235. var child = children[i];
  32236. pending.push(buildNodeHierachy(child, node, json, parser));
  32237. }
  32238. }
  32239. return Promise.all(pending);
  32240. });
  32241. }
  32242. return function loadScene(sceneIndex) {
  32243. var json = this.json;
  32244. var extensions = this.extensions;
  32245. var sceneDef = this.json.scenes[sceneIndex];
  32246. var parser = this;
  32247. var scene = new _threeModule.Scene();
  32248. if (sceneDef.name !== undefined) scene.name = sceneDef.name;
  32249. assignExtrasToUserData(scene, sceneDef);
  32250. if (sceneDef.extensions) addUnknownExtensionsToUserData(extensions, scene, sceneDef);
  32251. var nodeIds = sceneDef.nodes || [];
  32252. var pending = [];
  32253. for (var i = 0, il = nodeIds.length; i < il; i++) {
  32254. pending.push(buildNodeHierachy(nodeIds[i], scene, json, parser));
  32255. }
  32256. return Promise.all(pending).then(function () {
  32257. return scene;
  32258. });
  32259. };
  32260. }();
  32261. return GLTFLoader;
  32262. }();
  32263. exports.GLTFLoader = GLTFLoader;
  32264. },{"../../../build/three.module.js":"../node_modules/three/build/three.module.js"}],"../src/three/B3DMLoader.js":[function(require,module,exports) {
  32265. "use strict";
  32266. Object.defineProperty(exports, "__esModule", {
  32267. value: true
  32268. });
  32269. exports.B3DMLoader = void 0;
  32270. var _B3DMLoaderBase = require("../base/B3DMLoaderBase.js");
  32271. var _GLTFLoader = require("three/examples/jsm/loaders/GLTFLoader.js");
  32272. class B3DMLoader extends _B3DMLoaderBase.B3DMLoaderBase {
  32273. parse(buffer) {
  32274. const b3dm = super.parse(buffer);
  32275. const gltfBuffer = b3dm.glbBytes.slice().buffer;
  32276. return new Promise((resolve, reject) => {
  32277. new _GLTFLoader.GLTFLoader().parse(gltfBuffer, null, resolve, reject);
  32278. });
  32279. }
  32280. }
  32281. exports.B3DMLoader = B3DMLoader;
  32282. },{"../base/B3DMLoaderBase.js":"../src/base/B3DMLoaderBase.js","three/examples/jsm/loaders/GLTFLoader.js":"../node_modules/three/examples/jsm/loaders/GLTFLoader.js"}],"../src/three/TilesGroup.js":[function(require,module,exports) {
  32283. "use strict";
  32284. Object.defineProperty(exports, "__esModule", {
  32285. value: true
  32286. });
  32287. exports.TilesGroup = void 0;
  32288. var _three = require("three");
  32289. // Specialization of "Group" that only updates world matrices of children if
  32290. // the transform has changed since the last update and ignores the "force"
  32291. // parameter under the assumption that the children tiles will not move.
  32292. const tempMat = new _three.Matrix4();
  32293. class TilesGroup extends _three.Group {
  32294. constructor(tilesRenderer) {
  32295. super();
  32296. this.tilesRenderer = tilesRenderer;
  32297. }
  32298. raycast(raycaster, intersects) {
  32299. this.tilesRenderer.raycast(raycaster, intersects);
  32300. }
  32301. updateMatrixWorld(force) {
  32302. if (this.matrixAutoUpdate) {
  32303. this.updateMatrix();
  32304. }
  32305. if (this.matrixWorldNeedsUpdate || force) {
  32306. if (this.parent === null) {
  32307. tempMat.copy(this.matrix);
  32308. } else {
  32309. tempMat.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  32310. }
  32311. this.matrixWorldNeedsUpdate = false;
  32312. const elA = tempMat.elements;
  32313. const elB = this.matrixWorld.elements;
  32314. let isDifferent = false;
  32315. for (let i = 0; i < 16; i++) {
  32316. const itemA = elA[i];
  32317. const itemB = elB[i];
  32318. const diff = Math.abs(itemA - itemB);
  32319. if (diff > Number.EPSILON) {
  32320. isDifferent = true;
  32321. break;
  32322. }
  32323. }
  32324. if (isDifferent) {
  32325. this.matrixWorld.copy(tempMat); // update children
  32326. // the children will not have to change unless the parent group has updated
  32327. const children = this.children;
  32328. for (let i = 0, l = children.length; i < l; i++) {
  32329. children[i].updateMatrixWorld();
  32330. }
  32331. }
  32332. }
  32333. }
  32334. }
  32335. exports.TilesGroup = TilesGroup;
  32336. },{"three":"../node_modules/three/build/three.module.js"}],"../src/three/raycastTraverse.js":[function(require,module,exports) {
  32337. "use strict";
  32338. Object.defineProperty(exports, "__esModule", {
  32339. value: true
  32340. });
  32341. exports.raycastTraverseFirstHit = raycastTraverseFirstHit;
  32342. exports.raycastTraverse = raycastTraverse;
  32343. var _three = require("three");
  32344. const _sphere = new _three.Sphere();
  32345. const _mat = new _three.Matrix4();
  32346. const _vec = new _three.Vector3();
  32347. const _vec2 = new _three.Vector3();
  32348. const _ray = new _three.Ray();
  32349. const _hitArray = [];
  32350. function distanceSort(a, b) {
  32351. return a.distance - b.distance;
  32352. }
  32353. function intersectTileScene(scene, raycaster, intersects) {
  32354. // Don't intersect the box3 helpers because those are used for debugging
  32355. scene.traverse(c => {
  32356. if (!(c instanceof _three.Box3Helper)) {
  32357. Object.getPrototypeOf(c).raycast.call(c, raycaster, intersects);
  32358. }
  32359. });
  32360. } // Returns the closest hit when traversing the tree
  32361. function raycastTraverseFirstHit(root, group, activeTiles, raycaster) {
  32362. // If the root is active make sure we've checked it
  32363. if (activeTiles.has(root)) {
  32364. intersectTileScene(root.cached.scene, raycaster, _hitArray);
  32365. if (_hitArray.length > 0) {
  32366. if (_hitArray.length > 1) {
  32367. _hitArray.sort(distanceSort);
  32368. }
  32369. _hitArray.length = 0;
  32370. return _hitArray[0];
  32371. } else {
  32372. return null;
  32373. }
  32374. } // TODO: see if we can avoid creating a new array here every time to save on memory
  32375. const array = [];
  32376. const children = root.children;
  32377. for (let i = 0, l = children.length; i < l; i++) {
  32378. const tile = children[i];
  32379. const cached = tile.cached;
  32380. const groupMatrixWorld = group.matrixWorld;
  32381. const transformMat = cached.transform;
  32382. _mat.copy(groupMatrixWorld);
  32383. _mat.multiply(transformMat); // if we don't hit the sphere then early out
  32384. const sphere = cached.sphere;
  32385. if (sphere) {
  32386. _sphere.copy(sphere);
  32387. _sphere.applyMatrix4(_mat);
  32388. if (!raycaster.ray.intersectsSphere(_sphere)) {
  32389. continue;
  32390. }
  32391. } // TODO: check region
  32392. const boundingBox = cached.box;
  32393. const obbMat = cached.boxTransform;
  32394. if (boundingBox) {
  32395. _mat.multiply(obbMat);
  32396. _mat.getInverse(_mat);
  32397. _ray.copy(raycaster.ray).applyMatrix4(_mat);
  32398. if (_ray.intersectBox(boundingBox, _vec)) {
  32399. // account for tile scale
  32400. let invScale;
  32401. _vec2.setFromMatrixScale(_mat);
  32402. invScale = _vec2.x;
  32403. if (Math.abs(Math.max(_vec2.x - _vec2.y, _vec2.x - _vec2.z)) > 1e-6) {
  32404. console.warn('ThreeTilesRenderer : Non uniform scale used for tile which may cause issues when raycasting.');
  32405. } // if we intersect the box save the distance to the tile bounds
  32406. let data = {
  32407. distance: Infinity,
  32408. tile: null
  32409. };
  32410. array.push(data);
  32411. data.distance = _vec.distanceToSquared(_ray.origin) * invScale * invScale;
  32412. data.tile = tile;
  32413. } else {
  32414. continue;
  32415. }
  32416. }
  32417. } // sort them by ascending distance
  32418. array.sort(distanceSort); // traverse until we find the best hit and early out if a tile bounds
  32419. // couldn't possible include a best hit
  32420. let bestDistanceSquared = Infinity;
  32421. let bestHit = null;
  32422. for (let i = 0, l = array.length; i < l; i++) {
  32423. const data = array[i];
  32424. const distanceSquared = data.distance;
  32425. if (distanceSquared > bestDistanceSquared) {
  32426. break;
  32427. } else {
  32428. const tile = data.tile;
  32429. const scene = tile.cached.scene;
  32430. let hit = null;
  32431. if (activeTiles.has(tile)) {
  32432. // save the hit if it's closer
  32433. intersectTileScene(scene, raycaster, _hitArray);
  32434. if (_hitArray.length > 0) {
  32435. if (_hitArray.length > 1) {
  32436. _hitArray.sort(distanceSort);
  32437. }
  32438. hit = _hitArray[0];
  32439. }
  32440. } else {
  32441. hit = raycastTraverseFirstHit(tile, group, activeTiles, raycaster);
  32442. }
  32443. if (hit) {
  32444. const hitDistanceSquared = hit.distance * hit.distance;
  32445. if (hitDistanceSquared < bestDistanceSquared) {
  32446. bestDistanceSquared = hitDistanceSquared;
  32447. bestHit = hit;
  32448. }
  32449. _hitArray.length = 0;
  32450. }
  32451. }
  32452. }
  32453. return bestHit;
  32454. }
  32455. function raycastTraverse(tile, group, activeTiles, raycaster, intersects) {
  32456. const cached = tile.cached;
  32457. const groupMatrixWorld = group.matrixWorld;
  32458. const transformMat = cached.transform;
  32459. _mat.copy(groupMatrixWorld);
  32460. _mat.multiply(transformMat);
  32461. const sphere = cached.sphere;
  32462. if (sphere) {
  32463. _sphere.copy(sphere);
  32464. _sphere.applyMatrix4(_mat);
  32465. if (!raycaster.ray.intersectsSphere(_sphere)) {
  32466. return;
  32467. }
  32468. }
  32469. const boundingBox = cached.box;
  32470. const obbMat = cached.boxTransform;
  32471. if (boundingBox) {
  32472. _mat.multiply(obbMat);
  32473. _mat.getInverse(_mat);
  32474. _ray.copy(raycaster.ray).applyMatrix4(_mat);
  32475. if (!_ray.intersectsBox(boundingBox)) {
  32476. return;
  32477. }
  32478. } // TODO: check region
  32479. const scene = cached.scene;
  32480. if (activeTiles.has(tile)) {
  32481. scene.traverse(c => {
  32482. if (!(c instanceof _three.Box3Helper)) {
  32483. Object.getPrototypeOf(c).raycast.call(c, raycaster, intersects);
  32484. }
  32485. });
  32486. return;
  32487. }
  32488. const children = tile.children;
  32489. for (let i = 0, l = children.length; i < l; i++) {
  32490. raycastTraverse(children[i], group, activeTiles, raycaster, intersects);
  32491. }
  32492. }
  32493. },{"three":"../node_modules/three/build/three.module.js"}],"../src/three/TilesRenderer.js":[function(require,module,exports) {
  32494. "use strict";
  32495. Object.defineProperty(exports, "__esModule", {
  32496. value: true
  32497. });
  32498. exports.TilesRenderer = void 0;
  32499. var _TilesRendererBase = require("../base/TilesRendererBase.js");
  32500. var _B3DMLoader = require("./B3DMLoader.js");
  32501. var _TilesGroup = require("./TilesGroup.js");
  32502. var _three = require("three");
  32503. var _raycastTraverse = require("./raycastTraverse.js");
  32504. const DEG2RAD = _three.Math.DEG2RAD;
  32505. const tempMat = new _three.Matrix4();
  32506. const tempQuaternion = new _three.Quaternion();
  32507. const tempVector = new _three.Vector3();
  32508. const vecX = new _three.Vector3();
  32509. const vecY = new _three.Vector3();
  32510. const vecZ = new _three.Vector3();
  32511. const _sphere = new _three.Sphere();
  32512. const X_AXIS = new _three.Vector3(1, 0, 0);
  32513. const Y_AXIS = new _three.Vector3(0, 1, 0);
  32514. function emptyRaycast() {}
  32515. class TilesRenderer extends _TilesRendererBase.TilesRendererBase {
  32516. get camera() {
  32517. return this.cameras[0];
  32518. }
  32519. set camera(camera) {
  32520. const cameras = this.cameras;
  32521. cameras.length = 1;
  32522. cameras[0] = camera;
  32523. }
  32524. constructor(...args) {
  32525. super(...args);
  32526. this.group = new _TilesGroup.TilesGroup(this);
  32527. this.cameras = [];
  32528. this.resolution = new _three.Vector2();
  32529. this.frustums = [];
  32530. this.activeTiles = new Set();
  32531. this.visibleTiles = new Set();
  32532. }
  32533. /* Public API */
  32534. getBounds(box) {
  32535. if (!this.root) {
  32536. return false;
  32537. }
  32538. const cached = this.root.cached;
  32539. const boundingBox = cached.box;
  32540. const obbMat = cached.boxTransform;
  32541. const transformMat = cached.transform;
  32542. box.copy(boundingBox);
  32543. tempMat.multiplyMatrices(transformMat, obbMat);
  32544. box.applyMatrix4(tempMat);
  32545. return true;
  32546. }
  32547. raycast(raycaster, intersects) {
  32548. if (!this.root) {
  32549. return;
  32550. }
  32551. if (raycaster.firstHitOnly) {
  32552. const hit = (0, _raycastTraverse.raycastTraverseFirstHit)(this.root, this.group, this.activeTiles, raycaster);
  32553. if (hit) {
  32554. intersects.push(hit);
  32555. }
  32556. } else {
  32557. (0, _raycastTraverse.raycastTraverse)(this.root, this.group, this.activeTiles, raycaster, intersects);
  32558. }
  32559. }
  32560. setResolutionFromRenderer(renderer) {
  32561. const resolution = this.resolution;
  32562. renderer.getSize(resolution);
  32563. resolution.multiplyScalar(renderer.getPixelRatio());
  32564. }
  32565. /* Overriden */
  32566. update() {
  32567. const group = this.group;
  32568. const cameras = this.cameras;
  32569. const frustums = this.frustums;
  32570. const resolution = this.resolution;
  32571. if (cameras.length === 0) {
  32572. console.warn('TilesRenderer: no cameras to use are defined. Cannot update 3d tiles.');
  32573. return;
  32574. }
  32575. if (resolution.width === 0 || resolution.height === 0) {
  32576. console.warn('TilesRenderer: resolution for error calculation is not set. Cannot updated 3d tiles.');
  32577. return;
  32578. } // automatically scale the array of frustums to match the cameras
  32579. while (frustums.length > cameras.length) {
  32580. frustums.pop();
  32581. }
  32582. while (frustums.length < cameras.length) {
  32583. frustums.push(new _three.Frustum());
  32584. } // store the camera frustums in the 3d tiles root frame
  32585. for (let i = 0, l = frustums.length; i < l; i++) {
  32586. const camera = cameras[i];
  32587. const frustum = frustums[i];
  32588. tempMat.copy(group.matrixWorld);
  32589. tempMat.premultiply(camera.matrixWorldInverse);
  32590. tempMat.premultiply(camera.projectionMatrix);
  32591. frustum.setFromMatrix(tempMat);
  32592. }
  32593. super.update();
  32594. }
  32595. preprocessNode(tile, parentTile, tileSetDir) {
  32596. super.preprocessNode(tile, parentTile, tileSetDir);
  32597. const transform = new _three.Matrix4();
  32598. if (tile.transform) {
  32599. const transformArr = tile.transform;
  32600. for (let i = 0; i < 16; i++) {
  32601. transform.elements[i] = transformArr[i];
  32602. }
  32603. } else {
  32604. transform.identity();
  32605. }
  32606. if (parentTile) {
  32607. transform.multiply(parentTile.cached.transform);
  32608. }
  32609. let box = null;
  32610. let boxTransform = null;
  32611. if ('box' in tile.boundingVolume) {
  32612. const data = tile.boundingVolume.box;
  32613. box = new _three.Box3();
  32614. boxTransform = new _three.Matrix4(); // get the extents of the bounds in each axis
  32615. vecX.set(data[3], data[4], data[5]);
  32616. vecY.set(data[6], data[7], data[8]);
  32617. vecZ.set(data[9], data[10], data[11]);
  32618. const scaleX = vecX.length();
  32619. const scaleY = vecY.length();
  32620. const scaleZ = vecZ.length();
  32621. vecX.normalize();
  32622. vecY.normalize();
  32623. vecZ.normalize(); // create the oriented frame that the box exists in
  32624. 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
  32625. box.min.set(-scaleX, -scaleY, -scaleZ);
  32626. box.max.set(scaleX, scaleY, scaleZ);
  32627. }
  32628. let sphere = null;
  32629. if ('sphere' in tile.boundingVolume) {
  32630. const data = tile.boundingVolume.sphere;
  32631. sphere = new _three.Sphere();
  32632. sphere.center.set(data[0], data[1], data[2]);
  32633. sphere.radius = data[3];
  32634. } else if ('box' in tile.boundingVolume) {
  32635. sphere = new _three.Sphere();
  32636. box.getBoundingSphere(sphere);
  32637. boxTransform.decompose(sphere.center, tempQuaternion, tempVector);
  32638. }
  32639. let region = null;
  32640. if ('region' in tile.boundingVolume) {
  32641. console.warn('ThreeTilesRenderer: region bounding volume not supported.');
  32642. }
  32643. tile.cached = {
  32644. loadIndex: 0,
  32645. transform,
  32646. active: false,
  32647. box,
  32648. boxTransform,
  32649. sphere,
  32650. region,
  32651. scene: null,
  32652. geometry: null,
  32653. material: null,
  32654. distance: Infinity
  32655. };
  32656. }
  32657. parseTile(buffer, tile) {
  32658. tile._loadIndex = tile._loadIndex || 0;
  32659. tile._loadIndex++;
  32660. const loadIndex = tile._loadIndex;
  32661. return new _B3DMLoader.B3DMLoader().parse(buffer).then(res => {
  32662. if (tile._loadIndex !== loadIndex) {
  32663. return;
  32664. }
  32665. const upAxis = this.rootTileSet.asset && this.rootTileSet.asset.gltfUpAxis || 'y';
  32666. const cached = tile.cached;
  32667. const cachedTransform = cached.transform;
  32668. const scene = res.scene;
  32669. switch (upAxis.toLowerCase()) {
  32670. case 'x':
  32671. scene.matrix.makeRotationAxis(Y_AXIS, -Math.PI / 2);
  32672. break;
  32673. case 'y':
  32674. scene.matrix.makeRotationAxis(X_AXIS, Math.PI / 2);
  32675. break;
  32676. case 'z':
  32677. break;
  32678. }
  32679. scene.matrix.premultiply(cachedTransform);
  32680. scene.matrix.decompose(scene.position, scene.quaternion, scene.scale);
  32681. scene.traverse(c => c.frustumCulled = false);
  32682. cached.scene = scene; // We handle raycasting in a custom way so remove it from here
  32683. scene.traverse(c => {
  32684. c.raycast = emptyRaycast;
  32685. });
  32686. const materials = [];
  32687. const geometry = [];
  32688. scene.traverse(c => {
  32689. if (c.geometry) {
  32690. geometry.push(c.geometry);
  32691. }
  32692. if (c.material) {
  32693. materials.push(c.material);
  32694. }
  32695. });
  32696. cached.materials = materials;
  32697. cached.geometry = geometry;
  32698. });
  32699. }
  32700. disposeTile(tile) {
  32701. const cached = tile.cached;
  32702. if (cached.scene) {
  32703. const scene = cached.scene;
  32704. const materials = cached.materials;
  32705. const geometry = cached.geometry;
  32706. if (scene.parent) {
  32707. scene.parent.remove(scene);
  32708. }
  32709. for (let i = 0, l = geometry.length; i < l; i++) {
  32710. geometry[i].dispose();
  32711. }
  32712. for (let i = 0, l = materials.length; i < l; i++) {
  32713. const material = materials[i];
  32714. for (const key in material) {
  32715. const value = material[key];
  32716. if (value && value.isTexture) {
  32717. value.dispose();
  32718. }
  32719. }
  32720. material.dispose();
  32721. }
  32722. cached.scene = null;
  32723. cached.materials = null;
  32724. cached.geometry = null;
  32725. }
  32726. tile._loadIndex++;
  32727. }
  32728. setTileVisible(tile, visible) {
  32729. const scene = tile.cached.scene;
  32730. const visibleTiles = this.visibleTiles;
  32731. const group = this.group;
  32732. if (visible) {
  32733. // TODO: Should set visible be called if the scene hasn't been loaded yet?
  32734. // Ideally this would only be called on state change and when it's relevant
  32735. if (scene && !scene.parent) {
  32736. group.add(scene);
  32737. visibleTiles.add(tile);
  32738. scene.updateMatrixWorld(true);
  32739. }
  32740. } else {
  32741. group.remove(scene);
  32742. visibleTiles.delete(tile);
  32743. }
  32744. }
  32745. setTileActive(tile, active) {
  32746. const cached = tile.cached;
  32747. const activeTiles = this.activeTiles;
  32748. if (active !== cached.active) {
  32749. cached.active = active;
  32750. if (active) {
  32751. activeTiles.add(tile);
  32752. } else {
  32753. activeTiles.delete(tile);
  32754. }
  32755. }
  32756. }
  32757. calculateError(tile) {
  32758. const cached = tile.cached;
  32759. const cameras = this.cameras; // TODO: Use the content bounding volume here?
  32760. const boundingVolume = tile.boundingVolume;
  32761. const transformMat = cached.transform;
  32762. const resolution = this.resolution;
  32763. if ('box' in boundingVolume) {
  32764. const group = this.group;
  32765. const boundingBox = cached.box;
  32766. const obbMat = cached.boxTransform; // TODO: these can likely be cached? Or the world transform mat can be used
  32767. // transformMat can be rolled into oobMat
  32768. tempMat.copy(group.matrixWorld);
  32769. tempMat.multiply(transformMat);
  32770. tempMat.multiply(obbMat);
  32771. tempMat.getInverse(tempMat); // NOTE: scale is inverted here.
  32772. // assume the scales on all axes are uniform.
  32773. let invScale; // account for tile scale.
  32774. tempVector.setFromMatrixScale(tempMat);
  32775. invScale = tempVector.x;
  32776. if (Math.abs(Math.max(tempVector.x - tempVector.y, tempVector.x - tempVector.z)) > 1e-6) {
  32777. console.warn('ThreeTilesRenderer : Non uniform scale used for tile which may cause issues when calculating screen space error.');
  32778. }
  32779. let minError = Infinity;
  32780. for (let i = 0, l = cameras.length; i < l; i++) {
  32781. // transform camera position into local frame of the tile bounding box
  32782. const cam = cameras[i];
  32783. tempVector.copy(cam.position);
  32784. tempVector.applyMatrix4(tempMat);
  32785. let error;
  32786. if (cam.isOrthographicCamera) {
  32787. const w = cam.right - cam.left;
  32788. const h = cam.top - cam.bottom;
  32789. const pixelSize = Math.max(h / resolution.height, w / resolution.width);
  32790. error = tile.geometricError / (pixelSize * invScale);
  32791. } else {
  32792. const distance = boundingBox.distanceToPoint(tempVector);
  32793. const scaledDistance = distance * invScale;
  32794. const sseDenominator = 2 * Math.tan(0.5 * cam.fov * DEG2RAD);
  32795. error = tile.geometricError * resolution.height / (scaledDistance * sseDenominator);
  32796. tile.cached.distance = scaledDistance;
  32797. }
  32798. minError = Math.min(minError, error);
  32799. }
  32800. return minError;
  32801. } else if ('sphere' in boundingVolume) {
  32802. // const sphere = cached.sphere;
  32803. console.warn('ThreeTilesRenderer : Sphere bounds not supported.');
  32804. } else if ('region' in boundingVolume) {
  32805. // unsupported
  32806. console.warn('ThreeTilesRenderer : Region bounds not supported.');
  32807. }
  32808. return Infinity;
  32809. }
  32810. tileInView(tile) {
  32811. // TODO: we should use the more precise bounding volumes here if possible
  32812. // cache the root-space planes
  32813. // Use separating axis theorem for frustum and obb
  32814. const sphere = tile.cached.sphere;
  32815. if (sphere) {
  32816. _sphere.copy(sphere);
  32817. _sphere.applyMatrix4(tile.cached.transform);
  32818. const frustums = this.frustums;
  32819. for (let i = 0, l = frustums.length; i < l; i++) {
  32820. const frustum = frustums[i];
  32821. if (frustum.intersectsSphere(_sphere)) {
  32822. return true;
  32823. }
  32824. }
  32825. return false;
  32826. }
  32827. return true;
  32828. }
  32829. }
  32830. exports.TilesRenderer = TilesRenderer;
  32831. },{"../base/TilesRendererBase.js":"../src/base/TilesRendererBase.js","./B3DMLoader.js":"../src/three/B3DMLoader.js","./TilesGroup.js":"../src/three/TilesGroup.js","three":"../node_modules/three/build/three.module.js","./raycastTraverse.js":"../src/three/raycastTraverse.js"}],"../src/three/SphereHelper.js":[function(require,module,exports) {
  32832. "use strict";
  32833. Object.defineProperty(exports, "__esModule", {
  32834. value: true
  32835. });
  32836. exports.SphereHelper = void 0;
  32837. var _three = require("three");
  32838. const _vector = new _three.Vector3();
  32839. const axes = ['x', 'y', 'z'];
  32840. class SphereHelper extends _three.LineSegments {
  32841. constructor(sphere, color = 0xffff00, angleSteps = 40) {
  32842. const geometry = new _three.BufferGeometry();
  32843. const positions = [];
  32844. for (let i = 0; i < 3; i++) {
  32845. const axis1 = axes[i];
  32846. const axis2 = axes[(i + 1) % 3];
  32847. _vector.set(0, 0, 0);
  32848. for (let a = 0; a < angleSteps; a++) {
  32849. let angle;
  32850. angle = 2 * Math.PI * a / (angleSteps - 1);
  32851. _vector[axis1] = Math.sin(angle);
  32852. _vector[axis2] = Math.cos(angle);
  32853. positions.push(_vector.x, _vector.y, _vector.z);
  32854. angle = 2 * Math.PI * (a + 1) / (angleSteps - 1);
  32855. _vector[axis1] = Math.sin(angle);
  32856. _vector[axis2] = Math.cos(angle);
  32857. positions.push(_vector.x, _vector.y, _vector.z);
  32858. }
  32859. }
  32860. geometry.setAttribute('position', new _three.BufferAttribute(new Float32Array(positions), 3));
  32861. geometry.computeBoundingSphere();
  32862. super(geometry, new _three.LineBasicMaterial({
  32863. color: color,
  32864. toneMapped: false
  32865. }));
  32866. this.sphere = sphere;
  32867. this.type = 'SphereHelper';
  32868. }
  32869. updateMatrixWorld(force) {
  32870. // TODO: Why doesn't this radius have to be multiplied by 0.5?
  32871. const sphere = this.sphere;
  32872. this.position.copy(sphere.center);
  32873. this.scale.setScalar(sphere.radius);
  32874. super.updateMatrixWorld(force);
  32875. }
  32876. }
  32877. exports.SphereHelper = SphereHelper;
  32878. },{"three":"../node_modules/three/build/three.module.js"}],"../src/three/DebugTilesRenderer.js":[function(require,module,exports) {
  32879. "use strict";
  32880. Object.defineProperty(exports, "__esModule", {
  32881. value: true
  32882. });
  32883. exports.DebugTilesRenderer = void 0;
  32884. var _three = require("three");
  32885. var _TilesRenderer = require("./TilesRenderer.js");
  32886. var _SphereHelper = require("./SphereHelper.js");
  32887. const ORIGINAL_MATERIAL = Symbol('ORIGINAL_MATERIAL');
  32888. const NONE = 0;
  32889. const SCREEN_ERROR = 1;
  32890. const GEOMETRIC_ERROR = 2;
  32891. const DISTANCE = 3;
  32892. const DEPTH = 4;
  32893. const IS_LEAF = 5;
  32894. class DebugTilesRenderer extends _TilesRenderer.TilesRenderer {
  32895. constructor(...args) {
  32896. super(...args);
  32897. const tilesGroup = this.group;
  32898. const boxGroup = new _three.Group();
  32899. tilesGroup.add(boxGroup);
  32900. const sphereGroup = new _three.Group();
  32901. tilesGroup.add(sphereGroup);
  32902. this.displayBoxBounds = false;
  32903. this.displaySphereBounds = false;
  32904. this.colorMode = NONE;
  32905. this.boxGroup = boxGroup;
  32906. this.sphereGroup = sphereGroup;
  32907. this.maxDepth = -1;
  32908. this.maxDistance = -1;
  32909. this.maxError = -1;
  32910. this.extremeDepth = -1;
  32911. this.extremeError = -1;
  32912. }
  32913. initExtremes() {
  32914. let maxDepth = -1;
  32915. this.traverse(tile => {
  32916. maxDepth = Math.max(maxDepth, tile.__depth);
  32917. });
  32918. let maxError = -1;
  32919. this.traverse(tile => {
  32920. maxError = Math.max(maxError, tile.geometricError);
  32921. });
  32922. this.extremeDepth = maxDepth;
  32923. this.extremeError = maxError;
  32924. }
  32925. loadTileSet(...args) {
  32926. const pr = super.loadTileSet(...args);
  32927. pr.then(() => this.initExtremes());
  32928. return pr;
  32929. }
  32930. getTileInformationFromActiveObject(object) {
  32931. let targetTile = null;
  32932. const activeTiles = this.activeTiles;
  32933. activeTiles.forEach(tile => {
  32934. if (targetTile) {
  32935. return true;
  32936. }
  32937. const scene = tile.cached.scene;
  32938. if (scene) {
  32939. scene.traverse(c => {
  32940. if (c === object) {
  32941. targetTile = tile;
  32942. }
  32943. });
  32944. }
  32945. });
  32946. if (targetTile) {
  32947. return {
  32948. distanceToCamera: targetTile.cached.distance,
  32949. geometricError: targetTile.geometricError,
  32950. screenSpaceError: targetTile.__error,
  32951. depth: targetTile.__depth,
  32952. isLeaf: targetTile.__isLeaf
  32953. };
  32954. } else {
  32955. return null;
  32956. }
  32957. }
  32958. update() {
  32959. super.update();
  32960. if (!this.root) {
  32961. return;
  32962. }
  32963. this.boxGroup.visible = this.displayBoxBounds;
  32964. this.sphereGroup.visible = this.displaySphereBounds;
  32965. let maxDepth = -1;
  32966. if (this.maxDepth === -1) {
  32967. maxDepth = this.extremeDepth;
  32968. } else {
  32969. maxDepth = this.maxDepth;
  32970. }
  32971. let maxError = -1;
  32972. if (this.maxError === -1) {
  32973. maxError = this.extremeError;
  32974. } else {
  32975. maxError = this.maxError;
  32976. }
  32977. let maxDistance = -1;
  32978. if (this.maxDistance === -1) {
  32979. maxDistance = this.root.cached.sphere.radius;
  32980. } else {
  32981. maxDistance = this.maxDistance;
  32982. }
  32983. const errorTarget = this.errorTarget;
  32984. const colorMode = this.colorMode;
  32985. const visibleTiles = this.visibleTiles;
  32986. visibleTiles.forEach(tile => {
  32987. const scene = tile.cached.scene;
  32988. scene.traverse(c => {
  32989. const currMaterial = c.material;
  32990. if (currMaterial) {
  32991. const originalMaterial = c[ORIGINAL_MATERIAL];
  32992. if (colorMode === NONE && currMaterial !== originalMaterial) {
  32993. c.material.dispose();
  32994. c.material = c[ORIGINAL_MATERIAL];
  32995. } else if (colorMode !== NONE && currMaterial === originalMaterial) {
  32996. c.material = new _three.MeshBasicMaterial();
  32997. }
  32998. switch (colorMode) {
  32999. case DEPTH:
  33000. {
  33001. const val = tile.__depth / maxDepth;
  33002. c.material.color.setRGB(val, val, val);
  33003. break;
  33004. }
  33005. case SCREEN_ERROR:
  33006. {
  33007. const val = tile.__error / errorTarget;
  33008. if (val > 1.0) {
  33009. c.material.color.setRGB(1.0, 0.0, 0.0);
  33010. } else {
  33011. c.material.color.setRGB(val, val, val);
  33012. }
  33013. break;
  33014. }
  33015. case GEOMETRIC_ERROR:
  33016. {
  33017. const val = Math.min(tile.geometricError / maxError, 1);
  33018. c.material.color.setRGB(val, val, val);
  33019. break;
  33020. }
  33021. case DISTANCE:
  33022. {
  33023. const val = Math.min(tile.cached.distance / maxDistance, 1);
  33024. c.material.color.setRGB(val, val, val);
  33025. break;
  33026. }
  33027. case IS_LEAF:
  33028. {
  33029. if (!tile.children || tile.children.length === 0) {
  33030. c.material.color.set(0xffffff);
  33031. } else {
  33032. c.material.color.set(0);
  33033. }
  33034. break;
  33035. }
  33036. }
  33037. }
  33038. });
  33039. });
  33040. }
  33041. setTileVisible(tile, visible) {
  33042. super.setTileVisible(tile, visible);
  33043. const cached = tile.cached;
  33044. const sphereGroup = this.sphereGroup;
  33045. const boxGroup = this.boxGroup;
  33046. const boxHelperGroup = cached.boxHelperGroup;
  33047. const sphereHelper = cached.sphereHelper;
  33048. if (!visible && boxHelperGroup.parent) {
  33049. boxGroup.remove(boxHelperGroup);
  33050. sphereGroup.remove(sphereHelper);
  33051. } else if (visible && !boxHelperGroup.parent) {
  33052. boxGroup.add(boxHelperGroup);
  33053. boxHelperGroup.updateMatrixWorld(true);
  33054. sphereGroup.add(sphereHelper);
  33055. sphereHelper.updateMatrixWorld(true);
  33056. }
  33057. }
  33058. parseTile(buffer, tile) {
  33059. return super.parseTile(buffer, tile).then(() => {
  33060. const cached = tile.cached;
  33061. const scene = cached.scene;
  33062. if (scene) {
  33063. const cachedBox = cached.box;
  33064. const cachedBoxMat = cached.boxTransform;
  33065. const cachedTransform = cached.transform;
  33066. const boxHelperGroup = new _three.Group();
  33067. boxHelperGroup.matrix.copy(cachedBoxMat);
  33068. boxHelperGroup.matrix.premultiply(cachedTransform);
  33069. boxHelperGroup.matrix.decompose(boxHelperGroup.position, boxHelperGroup.quaternion, boxHelperGroup.scale);
  33070. const boxHelper = new _three.Box3Helper(cachedBox);
  33071. boxHelperGroup.add(boxHelper);
  33072. cached.boxHelperGroup = boxHelperGroup;
  33073. if (this.displayBoxBounds) {
  33074. this.boxGroup.add(boxHelperGroup);
  33075. boxHelperGroup.updateMatrixWorld(true);
  33076. }
  33077. const cachedSphere = cached.sphere;
  33078. const sphereHelper = new _SphereHelper.SphereHelper(cachedSphere);
  33079. cached.sphereHelper = sphereHelper;
  33080. if (this.displaySphereBounds) {
  33081. this.sphereGroup.add(sphereHelper);
  33082. sphereHelper.updateMatrixWorld(true);
  33083. }
  33084. scene.traverse(c => {
  33085. const material = c.material;
  33086. if (material) {
  33087. c[ORIGINAL_MATERIAL] = material;
  33088. }
  33089. });
  33090. }
  33091. });
  33092. }
  33093. disposeTile(tile) {
  33094. super.disposeTile(tile);
  33095. tile.cached.boxHelperGroup.children[0].geometry.dispose();
  33096. tile.cached.sphereHelper.geometry.dispose();
  33097. delete tile.cached.boxHelperGroup;
  33098. delete tile.cached.sphereHelper;
  33099. }
  33100. }
  33101. exports.DebugTilesRenderer = DebugTilesRenderer;
  33102. },{"three":"../node_modules/three/build/three.module.js","./TilesRenderer.js":"../src/three/TilesRenderer.js","./SphereHelper.js":"../src/three/SphereHelper.js"}],"../src/index.js":[function(require,module,exports) {
  33103. "use strict";
  33104. Object.defineProperty(exports, "__esModule", {
  33105. value: true
  33106. });
  33107. Object.defineProperty(exports, "DebugTilesRenderer", {
  33108. enumerable: true,
  33109. get: function () {
  33110. return _DebugTilesRenderer.DebugTilesRenderer;
  33111. }
  33112. });
  33113. Object.defineProperty(exports, "TilesRenderer", {
  33114. enumerable: true,
  33115. get: function () {
  33116. return _TilesRenderer.TilesRenderer;
  33117. }
  33118. });
  33119. Object.defineProperty(exports, "B3DMLoader", {
  33120. enumerable: true,
  33121. get: function () {
  33122. return _B3DMLoader.B3DMLoader;
  33123. }
  33124. });
  33125. Object.defineProperty(exports, "TilesRendererBase", {
  33126. enumerable: true,
  33127. get: function () {
  33128. return _TilesRendererBase.TilesRendererBase;
  33129. }
  33130. });
  33131. Object.defineProperty(exports, "B3DMLoaderBase", {
  33132. enumerable: true,
  33133. get: function () {
  33134. return _B3DMLoaderBase.B3DMLoaderBase;
  33135. }
  33136. });
  33137. Object.defineProperty(exports, "LRUCache", {
  33138. enumerable: true,
  33139. get: function () {
  33140. return _LRUCache.LRUCache;
  33141. }
  33142. });
  33143. Object.defineProperty(exports, "PriorityQueue", {
  33144. enumerable: true,
  33145. get: function () {
  33146. return _PriorityQueue.PriorityQueue;
  33147. }
  33148. });
  33149. var _DebugTilesRenderer = require("./three/DebugTilesRenderer.js");
  33150. var _TilesRenderer = require("./three/TilesRenderer.js");
  33151. var _B3DMLoader = require("./three/B3DMLoader.js");
  33152. var _TilesRendererBase = require("./base/TilesRendererBase.js");
  33153. var _B3DMLoaderBase = require("./base/B3DMLoaderBase.js");
  33154. var _LRUCache = require("./utilities/LRUCache.js");
  33155. var _PriorityQueue = require("./utilities/PriorityQueue.js");
  33156. },{"./three/DebugTilesRenderer.js":"../src/three/DebugTilesRenderer.js","./three/TilesRenderer.js":"../src/three/TilesRenderer.js","./three/B3DMLoader.js":"../src/three/B3DMLoader.js","./base/TilesRendererBase.js":"../src/base/TilesRendererBase.js","./base/B3DMLoaderBase.js":"../src/base/B3DMLoaderBase.js","./utilities/LRUCache.js":"../src/utilities/LRUCache.js","./utilities/PriorityQueue.js":"../src/utilities/PriorityQueue.js"}],"../node_modules/three/examples/jsm/controls/OrbitControls.js":[function(require,module,exports) {
  33157. "use strict";
  33158. Object.defineProperty(exports, "__esModule", {
  33159. value: true
  33160. });
  33161. exports.MapControls = exports.OrbitControls = void 0;
  33162. var _threeModule = require("../../../build/three.module.js");
  33163. /**
  33164. * @author qiao / https://github.com/qiao
  33165. * @author mrdoob / http://mrdoob.com
  33166. * @author alteredq / http://alteredqualia.com/
  33167. * @author WestLangley / http://github.com/WestLangley
  33168. * @author erich666 / http://erichaines.com
  33169. * @author ScieCode / http://github.com/sciecode
  33170. */
  33171. // This set of controls performs orbiting, dollying (zooming), and panning.
  33172. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  33173. //
  33174. // Orbit - left mouse / touch: one-finger move
  33175. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  33176. // Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move
  33177. var OrbitControls = function (object, domElement) {
  33178. this.object = object;
  33179. this.domElement = domElement !== undefined ? domElement : document; // Set to false to disable this control
  33180. this.enabled = true; // "target" sets the location of focus, where the object orbits around
  33181. this.target = new _threeModule.Vector3(); // How far you can dolly in and out ( PerspectiveCamera only )
  33182. this.minDistance = 0;
  33183. this.maxDistance = Infinity; // How far you can zoom in and out ( OrthographicCamera only )
  33184. this.minZoom = 0;
  33185. this.maxZoom = Infinity; // How far you can orbit vertically, upper and lower limits.
  33186. // Range is 0 to Math.PI radians.
  33187. this.minPolarAngle = 0; // radians
  33188. this.maxPolarAngle = Math.PI; // radians
  33189. // How far you can orbit horizontally, upper and lower limits.
  33190. // If set, must be a sub-interval of the interval [ - Math.PI, Math.PI ].
  33191. this.minAzimuthAngle = -Infinity; // radians
  33192. this.maxAzimuthAngle = Infinity; // radians
  33193. // Set to true to enable damping (inertia)
  33194. // If damping is enabled, you must call controls.update() in your animation loop
  33195. this.enableDamping = false;
  33196. this.dampingFactor = 0.05; // This option actually enables dollying in and out; left as "zoom" for backwards compatibility.
  33197. // Set to false to disable zooming
  33198. this.enableZoom = true;
  33199. this.zoomSpeed = 1.0; // Set to false to disable rotating
  33200. this.enableRotate = true;
  33201. this.rotateSpeed = 1.0; // Set to false to disable panning
  33202. this.enablePan = true;
  33203. this.panSpeed = 1.0;
  33204. this.screenSpacePanning = false; // if true, pan in screen-space
  33205. this.keyPanSpeed = 7.0; // pixels moved per arrow key push
  33206. // Set to true to automatically rotate around the target
  33207. // If auto-rotate is enabled, you must call controls.update() in your animation loop
  33208. this.autoRotate = false;
  33209. this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60
  33210. // Set to false to disable use of the keys
  33211. this.enableKeys = true; // The four arrow keys
  33212. this.keys = {
  33213. LEFT: 37,
  33214. UP: 38,
  33215. RIGHT: 39,
  33216. BOTTOM: 40
  33217. }; // Mouse buttons
  33218. this.mouseButtons = {
  33219. LEFT: _threeModule.MOUSE.ROTATE,
  33220. MIDDLE: _threeModule.MOUSE.DOLLY,
  33221. RIGHT: _threeModule.MOUSE.PAN
  33222. }; // Touch fingers
  33223. this.touches = {
  33224. ONE: _threeModule.TOUCH.ROTATE,
  33225. TWO: _threeModule.TOUCH.DOLLY_PAN
  33226. }; // for reset
  33227. this.target0 = this.target.clone();
  33228. this.position0 = this.object.position.clone();
  33229. this.zoom0 = this.object.zoom; //
  33230. // public methods
  33231. //
  33232. this.getPolarAngle = function () {
  33233. return spherical.phi;
  33234. };
  33235. this.getAzimuthalAngle = function () {
  33236. return spherical.theta;
  33237. };
  33238. this.saveState = function () {
  33239. scope.target0.copy(scope.target);
  33240. scope.position0.copy(scope.object.position);
  33241. scope.zoom0 = scope.object.zoom;
  33242. };
  33243. this.reset = function () {
  33244. scope.target.copy(scope.target0);
  33245. scope.object.position.copy(scope.position0);
  33246. scope.object.zoom = scope.zoom0;
  33247. scope.object.updateProjectionMatrix();
  33248. scope.dispatchEvent(changeEvent);
  33249. scope.update();
  33250. state = STATE.NONE;
  33251. }; // this method is exposed, but perhaps it would be better if we can make it private...
  33252. this.update = function () {
  33253. var offset = new _threeModule.Vector3(); // so camera.up is the orbit axis
  33254. var quat = new _threeModule.Quaternion().setFromUnitVectors(object.up, new _threeModule.Vector3(0, 1, 0));
  33255. var quatInverse = quat.clone().inverse();
  33256. var lastPosition = new _threeModule.Vector3();
  33257. var lastQuaternion = new _threeModule.Quaternion();
  33258. return function update() {
  33259. var position = scope.object.position;
  33260. offset.copy(position).sub(scope.target); // rotate offset to "y-axis-is-up" space
  33261. offset.applyQuaternion(quat); // angle from z-axis around y-axis
  33262. spherical.setFromVector3(offset);
  33263. if (scope.autoRotate && state === STATE.NONE) {
  33264. rotateLeft(getAutoRotationAngle());
  33265. }
  33266. if (scope.enableDamping) {
  33267. spherical.theta += sphericalDelta.theta * scope.dampingFactor;
  33268. spherical.phi += sphericalDelta.phi * scope.dampingFactor;
  33269. } else {
  33270. spherical.theta += sphericalDelta.theta;
  33271. spherical.phi += sphericalDelta.phi;
  33272. } // restrict theta to be between desired limits
  33273. spherical.theta = Math.max(scope.minAzimuthAngle, Math.min(scope.maxAzimuthAngle, spherical.theta)); // restrict phi to be between desired limits
  33274. spherical.phi = Math.max(scope.minPolarAngle, Math.min(scope.maxPolarAngle, spherical.phi));
  33275. spherical.makeSafe();
  33276. spherical.radius *= scale; // restrict radius to be between desired limits
  33277. spherical.radius = Math.max(scope.minDistance, Math.min(scope.maxDistance, spherical.radius)); // move target to panned location
  33278. if (scope.enableDamping === true) {
  33279. scope.target.addScaledVector(panOffset, scope.dampingFactor);
  33280. } else {
  33281. scope.target.add(panOffset);
  33282. }
  33283. offset.setFromSpherical(spherical); // rotate offset back to "camera-up-vector-is-up" space
  33284. offset.applyQuaternion(quatInverse);
  33285. position.copy(scope.target).add(offset);
  33286. scope.object.lookAt(scope.target);
  33287. if (scope.enableDamping === true) {
  33288. sphericalDelta.theta *= 1 - scope.dampingFactor;
  33289. sphericalDelta.phi *= 1 - scope.dampingFactor;
  33290. panOffset.multiplyScalar(1 - scope.dampingFactor);
  33291. } else {
  33292. sphericalDelta.set(0, 0, 0);
  33293. panOffset.set(0, 0, 0);
  33294. }
  33295. scale = 1; // update condition is:
  33296. // min(camera displacement, camera rotation in radians)^2 > EPS
  33297. // using small-angle approximation cos(x/2) = 1 - x^2 / 8
  33298. if (zoomChanged || lastPosition.distanceToSquared(scope.object.position) > EPS || 8 * (1 - lastQuaternion.dot(scope.object.quaternion)) > EPS) {
  33299. scope.dispatchEvent(changeEvent);
  33300. lastPosition.copy(scope.object.position);
  33301. lastQuaternion.copy(scope.object.quaternion);
  33302. zoomChanged = false;
  33303. return true;
  33304. }
  33305. return false;
  33306. };
  33307. }();
  33308. this.dispose = function () {
  33309. scope.domElement.removeEventListener('contextmenu', onContextMenu, false);
  33310. scope.domElement.removeEventListener('mousedown', onMouseDown, false);
  33311. scope.domElement.removeEventListener('wheel', onMouseWheel, false);
  33312. scope.domElement.removeEventListener('touchstart', onTouchStart, false);
  33313. scope.domElement.removeEventListener('touchend', onTouchEnd, false);
  33314. scope.domElement.removeEventListener('touchmove', onTouchMove, false);
  33315. document.removeEventListener('mousemove', onMouseMove, false);
  33316. document.removeEventListener('mouseup', onMouseUp, false);
  33317. window.removeEventListener('keydown', onKeyDown, false); //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here?
  33318. }; //
  33319. // internals
  33320. //
  33321. var scope = this;
  33322. var changeEvent = {
  33323. type: 'change'
  33324. };
  33325. var startEvent = {
  33326. type: 'start'
  33327. };
  33328. var endEvent = {
  33329. type: 'end'
  33330. };
  33331. var STATE = {
  33332. NONE: -1,
  33333. ROTATE: 0,
  33334. DOLLY: 1,
  33335. PAN: 2,
  33336. TOUCH_ROTATE: 3,
  33337. TOUCH_PAN: 4,
  33338. TOUCH_DOLLY_PAN: 5,
  33339. TOUCH_DOLLY_ROTATE: 6
  33340. };
  33341. var state = STATE.NONE;
  33342. var EPS = 0.000001; // current position in spherical coordinates
  33343. var spherical = new _threeModule.Spherical();
  33344. var sphericalDelta = new _threeModule.Spherical();
  33345. var scale = 1;
  33346. var panOffset = new _threeModule.Vector3();
  33347. var zoomChanged = false;
  33348. var rotateStart = new _threeModule.Vector2();
  33349. var rotateEnd = new _threeModule.Vector2();
  33350. var rotateDelta = new _threeModule.Vector2();
  33351. var panStart = new _threeModule.Vector2();
  33352. var panEnd = new _threeModule.Vector2();
  33353. var panDelta = new _threeModule.Vector2();
  33354. var dollyStart = new _threeModule.Vector2();
  33355. var dollyEnd = new _threeModule.Vector2();
  33356. var dollyDelta = new _threeModule.Vector2();
  33357. function getAutoRotationAngle() {
  33358. return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
  33359. }
  33360. function getZoomScale() {
  33361. return Math.pow(0.95, scope.zoomSpeed);
  33362. }
  33363. function rotateLeft(angle) {
  33364. sphericalDelta.theta -= angle;
  33365. }
  33366. function rotateUp(angle) {
  33367. sphericalDelta.phi -= angle;
  33368. }
  33369. var panLeft = function () {
  33370. var v = new _threeModule.Vector3();
  33371. return function panLeft(distance, objectMatrix) {
  33372. v.setFromMatrixColumn(objectMatrix, 0); // get X column of objectMatrix
  33373. v.multiplyScalar(-distance);
  33374. panOffset.add(v);
  33375. };
  33376. }();
  33377. var panUp = function () {
  33378. var v = new _threeModule.Vector3();
  33379. return function panUp(distance, objectMatrix) {
  33380. if (scope.screenSpacePanning === true) {
  33381. v.setFromMatrixColumn(objectMatrix, 1);
  33382. } else {
  33383. v.setFromMatrixColumn(objectMatrix, 0);
  33384. v.crossVectors(scope.object.up, v);
  33385. }
  33386. v.multiplyScalar(distance);
  33387. panOffset.add(v);
  33388. };
  33389. }(); // deltaX and deltaY are in pixels; right and down are positive
  33390. var pan = function () {
  33391. var offset = new _threeModule.Vector3();
  33392. return function pan(deltaX, deltaY) {
  33393. var element = scope.domElement === document ? scope.domElement.body : scope.domElement;
  33394. if (scope.object.isPerspectiveCamera) {
  33395. // perspective
  33396. var position = scope.object.position;
  33397. offset.copy(position).sub(scope.target);
  33398. var targetDistance = offset.length(); // half of the fov is center to top of screen
  33399. targetDistance *= Math.tan(scope.object.fov / 2 * Math.PI / 180.0); // we use only clientHeight here so aspect ratio does not distort speed
  33400. panLeft(2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix);
  33401. panUp(2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix);
  33402. } else if (scope.object.isOrthographicCamera) {
  33403. // orthographic
  33404. panLeft(deltaX * (scope.object.right - scope.object.left) / scope.object.zoom / element.clientWidth, scope.object.matrix);
  33405. panUp(deltaY * (scope.object.top - scope.object.bottom) / scope.object.zoom / element.clientHeight, scope.object.matrix);
  33406. } else {
  33407. // camera neither orthographic nor perspective
  33408. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.');
  33409. scope.enablePan = false;
  33410. }
  33411. };
  33412. }();
  33413. function dollyIn(dollyScale) {
  33414. if (scope.object.isPerspectiveCamera) {
  33415. scale /= dollyScale;
  33416. } else if (scope.object.isOrthographicCamera) {
  33417. scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom * dollyScale));
  33418. scope.object.updateProjectionMatrix();
  33419. zoomChanged = true;
  33420. } else {
  33421. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.');
  33422. scope.enableZoom = false;
  33423. }
  33424. }
  33425. function dollyOut(dollyScale) {
  33426. if (scope.object.isPerspectiveCamera) {
  33427. scale *= dollyScale;
  33428. } else if (scope.object.isOrthographicCamera) {
  33429. scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom / dollyScale));
  33430. scope.object.updateProjectionMatrix();
  33431. zoomChanged = true;
  33432. } else {
  33433. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.');
  33434. scope.enableZoom = false;
  33435. }
  33436. } //
  33437. // event callbacks - update the object state
  33438. //
  33439. function handleMouseDownRotate(event) {
  33440. rotateStart.set(event.clientX, event.clientY);
  33441. }
  33442. function handleMouseDownDolly(event) {
  33443. dollyStart.set(event.clientX, event.clientY);
  33444. }
  33445. function handleMouseDownPan(event) {
  33446. panStart.set(event.clientX, event.clientY);
  33447. }
  33448. function handleMouseMoveRotate(event) {
  33449. rotateEnd.set(event.clientX, event.clientY);
  33450. rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);
  33451. var element = scope.domElement === document ? scope.domElement.body : scope.domElement;
  33452. rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height
  33453. rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight);
  33454. rotateStart.copy(rotateEnd);
  33455. scope.update();
  33456. }
  33457. function handleMouseMoveDolly(event) {
  33458. dollyEnd.set(event.clientX, event.clientY);
  33459. dollyDelta.subVectors(dollyEnd, dollyStart);
  33460. if (dollyDelta.y > 0) {
  33461. dollyIn(getZoomScale());
  33462. } else if (dollyDelta.y < 0) {
  33463. dollyOut(getZoomScale());
  33464. }
  33465. dollyStart.copy(dollyEnd);
  33466. scope.update();
  33467. }
  33468. function handleMouseMovePan(event) {
  33469. panEnd.set(event.clientX, event.clientY);
  33470. panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);
  33471. pan(panDelta.x, panDelta.y);
  33472. panStart.copy(panEnd);
  33473. scope.update();
  33474. }
  33475. function handleMouseUp()
  33476. /*event*/
  33477. {// no-op
  33478. }
  33479. function handleMouseWheel(event) {
  33480. if (event.deltaY < 0) {
  33481. dollyOut(getZoomScale());
  33482. } else if (event.deltaY > 0) {
  33483. dollyIn(getZoomScale());
  33484. }
  33485. scope.update();
  33486. }
  33487. function handleKeyDown(event) {
  33488. var needsUpdate = false;
  33489. switch (event.keyCode) {
  33490. case scope.keys.UP:
  33491. pan(0, scope.keyPanSpeed);
  33492. needsUpdate = true;
  33493. break;
  33494. case scope.keys.BOTTOM:
  33495. pan(0, -scope.keyPanSpeed);
  33496. needsUpdate = true;
  33497. break;
  33498. case scope.keys.LEFT:
  33499. pan(scope.keyPanSpeed, 0);
  33500. needsUpdate = true;
  33501. break;
  33502. case scope.keys.RIGHT:
  33503. pan(-scope.keyPanSpeed, 0);
  33504. needsUpdate = true;
  33505. break;
  33506. }
  33507. if (needsUpdate) {
  33508. // prevent the browser from scrolling on cursor keys
  33509. event.preventDefault();
  33510. scope.update();
  33511. }
  33512. }
  33513. function handleTouchStartRotate(event) {
  33514. if (event.touches.length == 1) {
  33515. rotateStart.set(event.touches[0].pageX, event.touches[0].pageY);
  33516. } else {
  33517. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  33518. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  33519. rotateStart.set(x, y);
  33520. }
  33521. }
  33522. function handleTouchStartPan(event) {
  33523. if (event.touches.length == 1) {
  33524. panStart.set(event.touches[0].pageX, event.touches[0].pageY);
  33525. } else {
  33526. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  33527. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  33528. panStart.set(x, y);
  33529. }
  33530. }
  33531. function handleTouchStartDolly(event) {
  33532. var dx = event.touches[0].pageX - event.touches[1].pageX;
  33533. var dy = event.touches[0].pageY - event.touches[1].pageY;
  33534. var distance = Math.sqrt(dx * dx + dy * dy);
  33535. dollyStart.set(0, distance);
  33536. }
  33537. function handleTouchStartDollyPan(event) {
  33538. if (scope.enableZoom) handleTouchStartDolly(event);
  33539. if (scope.enablePan) handleTouchStartPan(event);
  33540. }
  33541. function handleTouchStartDollyRotate(event) {
  33542. if (scope.enableZoom) handleTouchStartDolly(event);
  33543. if (scope.enableRotate) handleTouchStartRotate(event);
  33544. }
  33545. function handleTouchMoveRotate(event) {
  33546. if (event.touches.length == 1) {
  33547. rotateEnd.set(event.touches[0].pageX, event.touches[0].pageY);
  33548. } else {
  33549. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  33550. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  33551. rotateEnd.set(x, y);
  33552. }
  33553. rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);
  33554. var element = scope.domElement === document ? scope.domElement.body : scope.domElement;
  33555. rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height
  33556. rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight);
  33557. rotateStart.copy(rotateEnd);
  33558. }
  33559. function handleTouchMovePan(event) {
  33560. if (event.touches.length == 1) {
  33561. panEnd.set(event.touches[0].pageX, event.touches[0].pageY);
  33562. } else {
  33563. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  33564. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  33565. panEnd.set(x, y);
  33566. }
  33567. panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);
  33568. pan(panDelta.x, panDelta.y);
  33569. panStart.copy(panEnd);
  33570. }
  33571. function handleTouchMoveDolly(event) {
  33572. var dx = event.touches[0].pageX - event.touches[1].pageX;
  33573. var dy = event.touches[0].pageY - event.touches[1].pageY;
  33574. var distance = Math.sqrt(dx * dx + dy * dy);
  33575. dollyEnd.set(0, distance);
  33576. dollyDelta.set(0, Math.pow(dollyEnd.y / dollyStart.y, scope.zoomSpeed));
  33577. dollyIn(dollyDelta.y);
  33578. dollyStart.copy(dollyEnd);
  33579. }
  33580. function handleTouchMoveDollyPan(event) {
  33581. if (scope.enableZoom) handleTouchMoveDolly(event);
  33582. if (scope.enablePan) handleTouchMovePan(event);
  33583. }
  33584. function handleTouchMoveDollyRotate(event) {
  33585. if (scope.enableZoom) handleTouchMoveDolly(event);
  33586. if (scope.enableRotate) handleTouchMoveRotate(event);
  33587. }
  33588. function handleTouchEnd()
  33589. /*event*/
  33590. {} // no-op
  33591. //
  33592. // event handlers - FSM: listen for events and reset state
  33593. //
  33594. function onMouseDown(event) {
  33595. if (scope.enabled === false) return; // Prevent the browser from scrolling.
  33596. event.preventDefault(); // Manually set the focus since calling preventDefault above
  33597. // prevents the browser from setting it automatically.
  33598. scope.domElement.focus ? scope.domElement.focus() : window.focus();
  33599. switch (event.button) {
  33600. case 0:
  33601. switch (scope.mouseButtons.LEFT) {
  33602. case _threeModule.MOUSE.ROTATE:
  33603. if (event.ctrlKey || event.metaKey || event.shiftKey) {
  33604. if (scope.enablePan === false) return;
  33605. handleMouseDownPan(event);
  33606. state = STATE.PAN;
  33607. } else {
  33608. if (scope.enableRotate === false) return;
  33609. handleMouseDownRotate(event);
  33610. state = STATE.ROTATE;
  33611. }
  33612. break;
  33613. case _threeModule.MOUSE.PAN:
  33614. if (event.ctrlKey || event.metaKey || event.shiftKey) {
  33615. if (scope.enableRotate === false) return;
  33616. handleMouseDownRotate(event);
  33617. state = STATE.ROTATE;
  33618. } else {
  33619. if (scope.enablePan === false) return;
  33620. handleMouseDownPan(event);
  33621. state = STATE.PAN;
  33622. }
  33623. break;
  33624. default:
  33625. state = STATE.NONE;
  33626. }
  33627. break;
  33628. case 1:
  33629. switch (scope.mouseButtons.MIDDLE) {
  33630. case _threeModule.MOUSE.DOLLY:
  33631. if (scope.enableZoom === false) return;
  33632. handleMouseDownDolly(event);
  33633. state = STATE.DOLLY;
  33634. break;
  33635. default:
  33636. state = STATE.NONE;
  33637. }
  33638. break;
  33639. case 2:
  33640. switch (scope.mouseButtons.RIGHT) {
  33641. case _threeModule.MOUSE.ROTATE:
  33642. if (scope.enableRotate === false) return;
  33643. handleMouseDownRotate(event);
  33644. state = STATE.ROTATE;
  33645. break;
  33646. case _threeModule.MOUSE.PAN:
  33647. if (scope.enablePan === false) return;
  33648. handleMouseDownPan(event);
  33649. state = STATE.PAN;
  33650. break;
  33651. default:
  33652. state = STATE.NONE;
  33653. }
  33654. break;
  33655. }
  33656. if (state !== STATE.NONE) {
  33657. document.addEventListener('mousemove', onMouseMove, false);
  33658. document.addEventListener('mouseup', onMouseUp, false);
  33659. scope.dispatchEvent(startEvent);
  33660. }
  33661. }
  33662. function onMouseMove(event) {
  33663. if (scope.enabled === false) return;
  33664. event.preventDefault();
  33665. switch (state) {
  33666. case STATE.ROTATE:
  33667. if (scope.enableRotate === false) return;
  33668. handleMouseMoveRotate(event);
  33669. break;
  33670. case STATE.DOLLY:
  33671. if (scope.enableZoom === false) return;
  33672. handleMouseMoveDolly(event);
  33673. break;
  33674. case STATE.PAN:
  33675. if (scope.enablePan === false) return;
  33676. handleMouseMovePan(event);
  33677. break;
  33678. }
  33679. }
  33680. function onMouseUp(event) {
  33681. if (scope.enabled === false) return;
  33682. handleMouseUp(event);
  33683. document.removeEventListener('mousemove', onMouseMove, false);
  33684. document.removeEventListener('mouseup', onMouseUp, false);
  33685. scope.dispatchEvent(endEvent);
  33686. state = STATE.NONE;
  33687. }
  33688. function onMouseWheel(event) {
  33689. if (scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE && state !== STATE.ROTATE) return;
  33690. event.preventDefault();
  33691. event.stopPropagation();
  33692. scope.dispatchEvent(startEvent);
  33693. handleMouseWheel(event);
  33694. scope.dispatchEvent(endEvent);
  33695. }
  33696. function onKeyDown(event) {
  33697. if (scope.enabled === false || scope.enableKeys === false || scope.enablePan === false) return;
  33698. handleKeyDown(event);
  33699. }
  33700. function onTouchStart(event) {
  33701. if (scope.enabled === false) return;
  33702. event.preventDefault();
  33703. switch (event.touches.length) {
  33704. case 1:
  33705. switch (scope.touches.ONE) {
  33706. case _threeModule.TOUCH.ROTATE:
  33707. if (scope.enableRotate === false) return;
  33708. handleTouchStartRotate(event);
  33709. state = STATE.TOUCH_ROTATE;
  33710. break;
  33711. case _threeModule.TOUCH.PAN:
  33712. if (scope.enablePan === false) return;
  33713. handleTouchStartPan(event);
  33714. state = STATE.TOUCH_PAN;
  33715. break;
  33716. default:
  33717. state = STATE.NONE;
  33718. }
  33719. break;
  33720. case 2:
  33721. switch (scope.touches.TWO) {
  33722. case _threeModule.TOUCH.DOLLY_PAN:
  33723. if (scope.enableZoom === false && scope.enablePan === false) return;
  33724. handleTouchStartDollyPan(event);
  33725. state = STATE.TOUCH_DOLLY_PAN;
  33726. break;
  33727. case _threeModule.TOUCH.DOLLY_ROTATE:
  33728. if (scope.enableZoom === false && scope.enableRotate === false) return;
  33729. handleTouchStartDollyRotate(event);
  33730. state = STATE.TOUCH_DOLLY_ROTATE;
  33731. break;
  33732. default:
  33733. state = STATE.NONE;
  33734. }
  33735. break;
  33736. default:
  33737. state = STATE.NONE;
  33738. }
  33739. if (state !== STATE.NONE) {
  33740. scope.dispatchEvent(startEvent);
  33741. }
  33742. }
  33743. function onTouchMove(event) {
  33744. if (scope.enabled === false) return;
  33745. event.preventDefault();
  33746. event.stopPropagation();
  33747. switch (state) {
  33748. case STATE.TOUCH_ROTATE:
  33749. if (scope.enableRotate === false) return;
  33750. handleTouchMoveRotate(event);
  33751. scope.update();
  33752. break;
  33753. case STATE.TOUCH_PAN:
  33754. if (scope.enablePan === false) return;
  33755. handleTouchMovePan(event);
  33756. scope.update();
  33757. break;
  33758. case STATE.TOUCH_DOLLY_PAN:
  33759. if (scope.enableZoom === false && scope.enablePan === false) return;
  33760. handleTouchMoveDollyPan(event);
  33761. scope.update();
  33762. break;
  33763. case STATE.TOUCH_DOLLY_ROTATE:
  33764. if (scope.enableZoom === false && scope.enableRotate === false) return;
  33765. handleTouchMoveDollyRotate(event);
  33766. scope.update();
  33767. break;
  33768. default:
  33769. state = STATE.NONE;
  33770. }
  33771. }
  33772. function onTouchEnd(event) {
  33773. if (scope.enabled === false) return;
  33774. handleTouchEnd(event);
  33775. scope.dispatchEvent(endEvent);
  33776. state = STATE.NONE;
  33777. }
  33778. function onContextMenu(event) {
  33779. if (scope.enabled === false) return;
  33780. event.preventDefault();
  33781. } //
  33782. scope.domElement.addEventListener('contextmenu', onContextMenu, false);
  33783. scope.domElement.addEventListener('mousedown', onMouseDown, false);
  33784. scope.domElement.addEventListener('wheel', onMouseWheel, false);
  33785. scope.domElement.addEventListener('touchstart', onTouchStart, false);
  33786. scope.domElement.addEventListener('touchend', onTouchEnd, false);
  33787. scope.domElement.addEventListener('touchmove', onTouchMove, false);
  33788. window.addEventListener('keydown', onKeyDown, false); // force an update at start
  33789. this.update();
  33790. };
  33791. exports.OrbitControls = OrbitControls;
  33792. OrbitControls.prototype = Object.create(_threeModule.EventDispatcher.prototype);
  33793. OrbitControls.prototype.constructor = OrbitControls; // This set of controls performs orbiting, dollying (zooming), and panning.
  33794. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  33795. // This is very similar to OrbitControls, another set of touch behavior
  33796. //
  33797. // Orbit - right mouse, or left mouse + ctrl/meta/shiftKey / touch: two-finger rotate
  33798. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  33799. // Pan - left mouse, or arrow keys / touch: one-finger move
  33800. var MapControls = function (object, domElement) {
  33801. OrbitControls.call(this, object, domElement);
  33802. this.mouseButtons.LEFT = _threeModule.MOUSE.PAN;
  33803. this.mouseButtons.RIGHT = _threeModule.MOUSE.ROTATE;
  33804. this.touches.ONE = _threeModule.TOUCH.PAN;
  33805. this.touches.TWO = _threeModule.TOUCH.DOLLY_ROTATE;
  33806. };
  33807. exports.MapControls = MapControls;
  33808. MapControls.prototype = Object.create(_threeModule.EventDispatcher.prototype);
  33809. MapControls.prototype.constructor = MapControls;
  33810. },{"../../../build/three.module.js":"../node_modules/three/build/three.module.js"}],"../node_modules/three/examples/jsm/utils/BufferGeometryUtils.js":[function(require,module,exports) {
  33811. "use strict";
  33812. Object.defineProperty(exports, "__esModule", {
  33813. value: true
  33814. });
  33815. exports.BufferGeometryUtils = void 0;
  33816. var _threeModule = require("../../../build/three.module.js");
  33817. /**
  33818. * @author mrdoob / http://mrdoob.com/
  33819. */
  33820. var BufferGeometryUtils = {
  33821. computeTangents: function (geometry) {
  33822. var index = geometry.index;
  33823. var attributes = geometry.attributes; // based on http://www.terathon.com/code/tangent.html
  33824. // (per vertex tangents)
  33825. if (index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) {
  33826. console.warn('THREE.BufferGeometry: Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()');
  33827. return;
  33828. }
  33829. var indices = index.array;
  33830. var positions = attributes.position.array;
  33831. var normals = attributes.normal.array;
  33832. var uvs = attributes.uv.array;
  33833. var nVertices = positions.length / 3;
  33834. if (attributes.tangent === undefined) {
  33835. geometry.addAttribute('tangent', new _threeModule.BufferAttribute(new Float32Array(4 * nVertices), 4));
  33836. }
  33837. var tangents = attributes.tangent.array;
  33838. var tan1 = [],
  33839. tan2 = [];
  33840. for (var i = 0; i < nVertices; i++) {
  33841. tan1[i] = new _threeModule.Vector3();
  33842. tan2[i] = new _threeModule.Vector3();
  33843. }
  33844. var vA = new _threeModule.Vector3(),
  33845. vB = new _threeModule.Vector3(),
  33846. vC = new _threeModule.Vector3(),
  33847. uvA = new _threeModule.Vector2(),
  33848. uvB = new _threeModule.Vector2(),
  33849. uvC = new _threeModule.Vector2(),
  33850. sdir = new _threeModule.Vector3(),
  33851. tdir = new _threeModule.Vector3();
  33852. function handleTriangle(a, b, c) {
  33853. vA.fromArray(positions, a * 3);
  33854. vB.fromArray(positions, b * 3);
  33855. vC.fromArray(positions, c * 3);
  33856. uvA.fromArray(uvs, a * 2);
  33857. uvB.fromArray(uvs, b * 2);
  33858. uvC.fromArray(uvs, c * 2);
  33859. var x1 = vB.x - vA.x;
  33860. var x2 = vC.x - vA.x;
  33861. var y1 = vB.y - vA.y;
  33862. var y2 = vC.y - vA.y;
  33863. var z1 = vB.z - vA.z;
  33864. var z2 = vC.z - vA.z;
  33865. var s1 = uvB.x - uvA.x;
  33866. var s2 = uvC.x - uvA.x;
  33867. var t1 = uvB.y - uvA.y;
  33868. var t2 = uvC.y - uvA.y;
  33869. var r = 1.0 / (s1 * t2 - s2 * t1);
  33870. sdir.set((t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r, (t2 * z1 - t1 * z2) * r);
  33871. tdir.set((s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r, (s1 * z2 - s2 * z1) * r);
  33872. tan1[a].add(sdir);
  33873. tan1[b].add(sdir);
  33874. tan1[c].add(sdir);
  33875. tan2[a].add(tdir);
  33876. tan2[b].add(tdir);
  33877. tan2[c].add(tdir);
  33878. }
  33879. var groups = geometry.groups;
  33880. if (groups.length === 0) {
  33881. groups = [{
  33882. start: 0,
  33883. count: indices.length
  33884. }];
  33885. }
  33886. for (var i = 0, il = groups.length; i < il; ++i) {
  33887. var group = groups[i];
  33888. var start = group.start;
  33889. var count = group.count;
  33890. for (var j = start, jl = start + count; j < jl; j += 3) {
  33891. handleTriangle(indices[j + 0], indices[j + 1], indices[j + 2]);
  33892. }
  33893. }
  33894. var tmp = new _threeModule.Vector3(),
  33895. tmp2 = new _threeModule.Vector3();
  33896. var n = new _threeModule.Vector3(),
  33897. n2 = new _threeModule.Vector3();
  33898. var w, t, test;
  33899. function handleVertex(v) {
  33900. n.fromArray(normals, v * 3);
  33901. n2.copy(n);
  33902. t = tan1[v]; // Gram-Schmidt orthogonalize
  33903. tmp.copy(t);
  33904. tmp.sub(n.multiplyScalar(n.dot(t))).normalize(); // Calculate handedness
  33905. tmp2.crossVectors(n2, t);
  33906. test = tmp2.dot(tan2[v]);
  33907. w = test < 0.0 ? -1.0 : 1.0;
  33908. tangents[v * 4] = tmp.x;
  33909. tangents[v * 4 + 1] = tmp.y;
  33910. tangents[v * 4 + 2] = tmp.z;
  33911. tangents[v * 4 + 3] = w;
  33912. }
  33913. for (var i = 0, il = groups.length; i < il; ++i) {
  33914. var group = groups[i];
  33915. var start = group.start;
  33916. var count = group.count;
  33917. for (var j = start, jl = start + count; j < jl; j += 3) {
  33918. handleVertex(indices[j + 0]);
  33919. handleVertex(indices[j + 1]);
  33920. handleVertex(indices[j + 2]);
  33921. }
  33922. }
  33923. },
  33924. /**
  33925. * @param {Array<BufferGeometry>} geometries
  33926. * @param {Boolean} useGroups
  33927. * @return {BufferGeometry}
  33928. */
  33929. mergeBufferGeometries: function (geometries, useGroups) {
  33930. var isIndexed = geometries[0].index !== null;
  33931. var attributesUsed = new Set(Object.keys(geometries[0].attributes));
  33932. var morphAttributesUsed = new Set(Object.keys(geometries[0].morphAttributes));
  33933. var attributes = {};
  33934. var morphAttributes = {};
  33935. var mergedGeometry = new _threeModule.BufferGeometry();
  33936. var offset = 0;
  33937. for (var i = 0; i < geometries.length; ++i) {
  33938. var geometry = geometries[i]; // ensure that all geometries are indexed, or none
  33939. if (isIndexed !== (geometry.index !== null)) return null; // gather attributes, exit early if they're different
  33940. for (var name in geometry.attributes) {
  33941. if (!attributesUsed.has(name)) return null;
  33942. if (attributes[name] === undefined) attributes[name] = [];
  33943. attributes[name].push(geometry.attributes[name]);
  33944. } // gather morph attributes, exit early if they're different
  33945. for (var name in geometry.morphAttributes) {
  33946. if (!morphAttributesUsed.has(name)) return null;
  33947. if (morphAttributes[name] === undefined) morphAttributes[name] = [];
  33948. morphAttributes[name].push(geometry.morphAttributes[name]);
  33949. } // gather .userData
  33950. mergedGeometry.userData.mergedUserData = mergedGeometry.userData.mergedUserData || [];
  33951. mergedGeometry.userData.mergedUserData.push(geometry.userData);
  33952. if (useGroups) {
  33953. var count;
  33954. if (isIndexed) {
  33955. count = geometry.index.count;
  33956. } else if (geometry.attributes.position !== undefined) {
  33957. count = geometry.attributes.position.count;
  33958. } else {
  33959. return null;
  33960. }
  33961. mergedGeometry.addGroup(offset, count, i);
  33962. offset += count;
  33963. }
  33964. } // merge indices
  33965. if (isIndexed) {
  33966. var indexOffset = 0;
  33967. var mergedIndex = [];
  33968. for (var i = 0; i < geometries.length; ++i) {
  33969. var index = geometries[i].index;
  33970. for (var j = 0; j < index.count; ++j) {
  33971. mergedIndex.push(index.getX(j) + indexOffset);
  33972. }
  33973. indexOffset += geometries[i].attributes.position.count;
  33974. }
  33975. mergedGeometry.setIndex(mergedIndex);
  33976. } // merge attributes
  33977. for (var name in attributes) {
  33978. var mergedAttribute = this.mergeBufferAttributes(attributes[name]);
  33979. if (!mergedAttribute) return null;
  33980. mergedGeometry.addAttribute(name, mergedAttribute);
  33981. } // merge morph attributes
  33982. for (var name in morphAttributes) {
  33983. var numMorphTargets = morphAttributes[name][0].length;
  33984. if (numMorphTargets === 0) break;
  33985. mergedGeometry.morphAttributes = mergedGeometry.morphAttributes || {};
  33986. mergedGeometry.morphAttributes[name] = [];
  33987. for (var i = 0; i < numMorphTargets; ++i) {
  33988. var morphAttributesToMerge = [];
  33989. for (var j = 0; j < morphAttributes[name].length; ++j) {
  33990. morphAttributesToMerge.push(morphAttributes[name][j][i]);
  33991. }
  33992. var mergedMorphAttribute = this.mergeBufferAttributes(morphAttributesToMerge);
  33993. if (!mergedMorphAttribute) return null;
  33994. mergedGeometry.morphAttributes[name].push(mergedMorphAttribute);
  33995. }
  33996. }
  33997. return mergedGeometry;
  33998. },
  33999. /**
  34000. * @param {Array<BufferAttribute>} attributes
  34001. * @return {BufferAttribute}
  34002. */
  34003. mergeBufferAttributes: function (attributes) {
  34004. var TypedArray;
  34005. var itemSize;
  34006. var normalized;
  34007. var arrayLength = 0;
  34008. for (var i = 0; i < attributes.length; ++i) {
  34009. var attribute = attributes[i];
  34010. if (attribute.isInterleavedBufferAttribute) return null;
  34011. if (TypedArray === undefined) TypedArray = attribute.array.constructor;
  34012. if (TypedArray !== attribute.array.constructor) return null;
  34013. if (itemSize === undefined) itemSize = attribute.itemSize;
  34014. if (itemSize !== attribute.itemSize) return null;
  34015. if (normalized === undefined) normalized = attribute.normalized;
  34016. if (normalized !== attribute.normalized) return null;
  34017. arrayLength += attribute.array.length;
  34018. }
  34019. var array = new TypedArray(arrayLength);
  34020. var offset = 0;
  34021. for (var i = 0; i < attributes.length; ++i) {
  34022. array.set(attributes[i].array, offset);
  34023. offset += attributes[i].array.length;
  34024. }
  34025. return new _threeModule.BufferAttribute(array, itemSize, normalized);
  34026. },
  34027. /**
  34028. * @param {Array<BufferAttribute>} attributes
  34029. * @return {Array<InterleavedBufferAttribute>}
  34030. */
  34031. interleaveAttributes: function (attributes) {
  34032. // Interleaves the provided attributes into an InterleavedBuffer and returns
  34033. // a set of InterleavedBufferAttributes for each attribute
  34034. var TypedArray;
  34035. var arrayLength = 0;
  34036. var stride = 0; // calculate the the length and type of the interleavedBuffer
  34037. for (var i = 0, l = attributes.length; i < l; ++i) {
  34038. var attribute = attributes[i];
  34039. if (TypedArray === undefined) TypedArray = attribute.array.constructor;
  34040. if (TypedArray !== attribute.array.constructor) {
  34041. console.warn('AttributeBuffers of different types cannot be interleaved');
  34042. return null;
  34043. }
  34044. arrayLength += attribute.array.length;
  34045. stride += attribute.itemSize;
  34046. } // Create the set of buffer attributes
  34047. var interleavedBuffer = new _threeModule.InterleavedBuffer(new TypedArray(arrayLength), stride);
  34048. var offset = 0;
  34049. var res = [];
  34050. var getters = ['getX', 'getY', 'getZ', 'getW'];
  34051. var setters = ['setX', 'setY', 'setZ', 'setW'];
  34052. for (var j = 0, l = attributes.length; j < l; j++) {
  34053. var attribute = attributes[j];
  34054. var itemSize = attribute.itemSize;
  34055. var count = attribute.count;
  34056. var iba = new _threeModule.InterleavedBufferAttribute(interleavedBuffer, itemSize, offset, attribute.normalized);
  34057. res.push(iba);
  34058. offset += itemSize; // Move the data for each attribute into the new interleavedBuffer
  34059. // at the appropriate offset
  34060. for (var c = 0; c < count; c++) {
  34061. for (var k = 0; k < itemSize; k++) {
  34062. iba[setters[k]](c, attribute[getters[k]](c));
  34063. }
  34064. }
  34065. }
  34066. return res;
  34067. },
  34068. /**
  34069. * @param {Array<BufferGeometry>} geometry
  34070. * @return {number}
  34071. */
  34072. estimateBytesUsed: function (geometry) {
  34073. // Return the estimated memory used by this geometry in bytes
  34074. // Calculate using itemSize, count, and BYTES_PER_ELEMENT to account
  34075. // for InterleavedBufferAttributes.
  34076. var mem = 0;
  34077. for (var name in geometry.attributes) {
  34078. var attr = geometry.getAttribute(name);
  34079. mem += attr.count * attr.itemSize * attr.array.BYTES_PER_ELEMENT;
  34080. }
  34081. var indices = geometry.getIndex();
  34082. mem += indices ? indices.count * indices.itemSize * indices.array.BYTES_PER_ELEMENT : 0;
  34083. return mem;
  34084. },
  34085. /**
  34086. * @param {BufferGeometry} geometry
  34087. * @param {number} tolerance
  34088. * @return {BufferGeometry>}
  34089. */
  34090. mergeVertices: function (geometry, tolerance = 1e-4) {
  34091. tolerance = Math.max(tolerance, Number.EPSILON); // Generate an index buffer if the geometry doesn't have one, or optimize it
  34092. // if it's already available.
  34093. var hashToIndex = {};
  34094. var indices = geometry.getIndex();
  34095. var positions = geometry.getAttribute('position');
  34096. var vertexCount = indices ? indices.count : positions.count; // next value for triangle indices
  34097. var nextIndex = 0; // attributes and new attribute arrays
  34098. var attributeNames = Object.keys(geometry.attributes);
  34099. var attrArrays = {};
  34100. var morphAttrsArrays = {};
  34101. var newIndices = [];
  34102. var getters = ['getX', 'getY', 'getZ', 'getW']; // initialize the arrays
  34103. for (var i = 0, l = attributeNames.length; i < l; i++) {
  34104. var name = attributeNames[i];
  34105. attrArrays[name] = [];
  34106. var morphAttr = geometry.morphAttributes[name];
  34107. if (morphAttr) {
  34108. morphAttrsArrays[name] = new Array(morphAttr.length).fill().map(() => []);
  34109. }
  34110. } // convert the error tolerance to an amount of decimal places to truncate to
  34111. var decimalShift = Math.log10(1 / tolerance);
  34112. var shiftMultiplier = Math.pow(10, decimalShift);
  34113. for (var i = 0; i < vertexCount; i++) {
  34114. var index = indices ? indices.getX(i) : i; // Generate a hash for the vertex attributes at the current index 'i'
  34115. var hash = '';
  34116. for (var j = 0, l = attributeNames.length; j < l; j++) {
  34117. var name = attributeNames[j];
  34118. var attribute = geometry.getAttribute(name);
  34119. var itemSize = attribute.itemSize;
  34120. for (var k = 0; k < itemSize; k++) {
  34121. // double tilde truncates the decimal value
  34122. hash += `${~~(attribute[getters[k]](index) * shiftMultiplier)},`;
  34123. }
  34124. } // Add another reference to the vertex if it's already
  34125. // used by another index
  34126. if (hash in hashToIndex) {
  34127. newIndices.push(hashToIndex[hash]);
  34128. } else {
  34129. // copy data to the new index in the attribute arrays
  34130. for (var j = 0, l = attributeNames.length; j < l; j++) {
  34131. var name = attributeNames[j];
  34132. var attribute = geometry.getAttribute(name);
  34133. var morphAttr = geometry.morphAttributes[name];
  34134. var itemSize = attribute.itemSize;
  34135. var newarray = attrArrays[name];
  34136. var newMorphArrays = morphAttrsArrays[name];
  34137. for (var k = 0; k < itemSize; k++) {
  34138. var getterFunc = getters[k];
  34139. newarray.push(attribute[getterFunc](index));
  34140. if (morphAttr) {
  34141. for (var m = 0, ml = morphAttr.length; m < ml; m++) {
  34142. newMorphArrays[m].push(morphAttr[m][getterFunc](index));
  34143. }
  34144. }
  34145. }
  34146. }
  34147. hashToIndex[hash] = nextIndex;
  34148. newIndices.push(nextIndex);
  34149. nextIndex++;
  34150. }
  34151. } // Generate typed arrays from new attribute arrays and update
  34152. // the attributeBuffers
  34153. const result = geometry.clone();
  34154. for (var i = 0, l = attributeNames.length; i < l; i++) {
  34155. var name = attributeNames[i];
  34156. var oldAttribute = geometry.getAttribute(name);
  34157. var buffer = new oldAttribute.array.constructor(attrArrays[name]);
  34158. var attribute = new _threeModule.BufferAttribute(buffer, oldAttribute.itemSize, oldAttribute.normalized);
  34159. result.addAttribute(name, attribute); // Update the attribute arrays
  34160. if (name in morphAttrsArrays) {
  34161. for (var j = 0; j < morphAttrsArrays[name].length; j++) {
  34162. var oldMorphAttribute = geometry.morphAttributes[name][j];
  34163. var buffer = new oldMorphAttribute.array.constructor(morphAttrsArrays[name][j]);
  34164. var morphAttribute = new _threeModule.BufferAttribute(buffer, oldMorphAttribute.itemSize, oldMorphAttribute.normalized);
  34165. result.morphAttributes[name][j] = morphAttribute;
  34166. }
  34167. }
  34168. } // indices
  34169. result.setIndex(newIndices);
  34170. return result;
  34171. }
  34172. };
  34173. exports.BufferGeometryUtils = BufferGeometryUtils;
  34174. },{"../../../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) {
  34175. "use strict";
  34176. Object.defineProperty(exports, "__esModule", {
  34177. value: true
  34178. });
  34179. exports.default = exports.GUI = exports.gui = exports.dom = exports.controllers = exports.color = void 0;
  34180. /**
  34181. * dat-gui JavaScript Controller Library
  34182. * http://code.google.com/p/dat-gui
  34183. *
  34184. * Copyright 2011 Data Arts Team, Google Creative Lab
  34185. *
  34186. * Licensed under the Apache License, Version 2.0 (the "License");
  34187. * you may not use this file except in compliance with the License.
  34188. * You may obtain a copy of the License at
  34189. *
  34190. * http://www.apache.org/licenses/LICENSE-2.0
  34191. */
  34192. function ___$insertStyle(css) {
  34193. if (!css) {
  34194. return;
  34195. }
  34196. if (typeof window === 'undefined') {
  34197. return;
  34198. }
  34199. var style = document.createElement('style');
  34200. style.setAttribute('type', 'text/css');
  34201. style.innerHTML = css;
  34202. document.head.appendChild(style);
  34203. return css;
  34204. }
  34205. function colorToString(color, forceCSSHex) {
  34206. var colorFormat = color.__state.conversionName.toString();
  34207. var r = Math.round(color.r);
  34208. var g = Math.round(color.g);
  34209. var b = Math.round(color.b);
  34210. var a = color.a;
  34211. var h = Math.round(color.h);
  34212. var s = color.s.toFixed(1);
  34213. var v = color.v.toFixed(1);
  34214. if (forceCSSHex || colorFormat === 'THREE_CHAR_HEX' || colorFormat === 'SIX_CHAR_HEX') {
  34215. var str = color.hex.toString(16);
  34216. while (str.length < 6) {
  34217. str = '0' + str;
  34218. }
  34219. return '#' + str;
  34220. } else if (colorFormat === 'CSS_RGB') {
  34221. return 'rgb(' + r + ',' + g + ',' + b + ')';
  34222. } else if (colorFormat === 'CSS_RGBA') {
  34223. return 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
  34224. } else if (colorFormat === 'HEX') {
  34225. return '0x' + color.hex.toString(16);
  34226. } else if (colorFormat === 'RGB_ARRAY') {
  34227. return '[' + r + ',' + g + ',' + b + ']';
  34228. } else if (colorFormat === 'RGBA_ARRAY') {
  34229. return '[' + r + ',' + g + ',' + b + ',' + a + ']';
  34230. } else if (colorFormat === 'RGB_OBJ') {
  34231. return '{r:' + r + ',g:' + g + ',b:' + b + '}';
  34232. } else if (colorFormat === 'RGBA_OBJ') {
  34233. return '{r:' + r + ',g:' + g + ',b:' + b + ',a:' + a + '}';
  34234. } else if (colorFormat === 'HSV_OBJ') {
  34235. return '{h:' + h + ',s:' + s + ',v:' + v + '}';
  34236. } else if (colorFormat === 'HSVA_OBJ') {
  34237. return '{h:' + h + ',s:' + s + ',v:' + v + ',a:' + a + '}';
  34238. }
  34239. return 'unknown format';
  34240. }
  34241. var ARR_EACH = Array.prototype.forEach;
  34242. var ARR_SLICE = Array.prototype.slice;
  34243. var Common = {
  34244. BREAK: {},
  34245. extend: function extend(target) {
  34246. this.each(ARR_SLICE.call(arguments, 1), function (obj) {
  34247. var keys = this.isObject(obj) ? Object.keys(obj) : [];
  34248. keys.forEach(function (key) {
  34249. if (!this.isUndefined(obj[key])) {
  34250. target[key] = obj[key];
  34251. }
  34252. }.bind(this));
  34253. }, this);
  34254. return target;
  34255. },
  34256. defaults: function defaults(target) {
  34257. this.each(ARR_SLICE.call(arguments, 1), function (obj) {
  34258. var keys = this.isObject(obj) ? Object.keys(obj) : [];
  34259. keys.forEach(function (key) {
  34260. if (this.isUndefined(target[key])) {
  34261. target[key] = obj[key];
  34262. }
  34263. }.bind(this));
  34264. }, this);
  34265. return target;
  34266. },
  34267. compose: function compose() {
  34268. var toCall = ARR_SLICE.call(arguments);
  34269. return function () {
  34270. var args = ARR_SLICE.call(arguments);
  34271. for (var i = toCall.length - 1; i >= 0; i--) {
  34272. args = [toCall[i].apply(this, args)];
  34273. }
  34274. return args[0];
  34275. };
  34276. },
  34277. each: function each(obj, itr, scope) {
  34278. if (!obj) {
  34279. return;
  34280. }
  34281. if (ARR_EACH && obj.forEach && obj.forEach === ARR_EACH) {
  34282. obj.forEach(itr, scope);
  34283. } else if (obj.length === obj.length + 0) {
  34284. var key = void 0;
  34285. var l = void 0;
  34286. for (key = 0, l = obj.length; key < l; key++) {
  34287. if (key in obj && itr.call(scope, obj[key], key) === this.BREAK) {
  34288. return;
  34289. }
  34290. }
  34291. } else {
  34292. for (var _key in obj) {
  34293. if (itr.call(scope, obj[_key], _key) === this.BREAK) {
  34294. return;
  34295. }
  34296. }
  34297. }
  34298. },
  34299. defer: function defer(fnc) {
  34300. setTimeout(fnc, 0);
  34301. },
  34302. debounce: function debounce(func, threshold, callImmediately) {
  34303. var timeout = void 0;
  34304. return function () {
  34305. var obj = this;
  34306. var args = arguments;
  34307. function delayed() {
  34308. timeout = null;
  34309. if (!callImmediately) func.apply(obj, args);
  34310. }
  34311. var callNow = callImmediately || !timeout;
  34312. clearTimeout(timeout);
  34313. timeout = setTimeout(delayed, threshold);
  34314. if (callNow) {
  34315. func.apply(obj, args);
  34316. }
  34317. };
  34318. },
  34319. toArray: function toArray(obj) {
  34320. if (obj.toArray) return obj.toArray();
  34321. return ARR_SLICE.call(obj);
  34322. },
  34323. isUndefined: function isUndefined(obj) {
  34324. return obj === undefined;
  34325. },
  34326. isNull: function isNull(obj) {
  34327. return obj === null;
  34328. },
  34329. isNaN: function (_isNaN) {
  34330. function isNaN() {
  34331. return _isNaN.apply(this, arguments);
  34332. }
  34333. isNaN.toString = function () {
  34334. return _isNaN.toString();
  34335. };
  34336. return isNaN;
  34337. }(function (obj) {
  34338. return isNaN(obj);
  34339. }),
  34340. isArray: Array.isArray || function (obj) {
  34341. return obj.constructor === Array;
  34342. },
  34343. isObject: function isObject(obj) {
  34344. return obj === Object(obj);
  34345. },
  34346. isNumber: function isNumber(obj) {
  34347. return obj === obj + 0;
  34348. },
  34349. isString: function isString(obj) {
  34350. return obj === obj + '';
  34351. },
  34352. isBoolean: function isBoolean(obj) {
  34353. return obj === false || obj === true;
  34354. },
  34355. isFunction: function isFunction(obj) {
  34356. return Object.prototype.toString.call(obj) === '[object Function]';
  34357. }
  34358. };
  34359. var INTERPRETATIONS = [{
  34360. litmus: Common.isString,
  34361. conversions: {
  34362. THREE_CHAR_HEX: {
  34363. read: function read(original) {
  34364. var test = original.match(/^#([A-F0-9])([A-F0-9])([A-F0-9])$/i);
  34365. if (test === null) {
  34366. return false;
  34367. }
  34368. return {
  34369. space: 'HEX',
  34370. hex: parseInt('0x' + test[1].toString() + test[1].toString() + test[2].toString() + test[2].toString() + test[3].toString() + test[3].toString(), 0)
  34371. };
  34372. },
  34373. write: colorToString
  34374. },
  34375. SIX_CHAR_HEX: {
  34376. read: function read(original) {
  34377. var test = original.match(/^#([A-F0-9]{6})$/i);
  34378. if (test === null) {
  34379. return false;
  34380. }
  34381. return {
  34382. space: 'HEX',
  34383. hex: parseInt('0x' + test[1].toString(), 0)
  34384. };
  34385. },
  34386. write: colorToString
  34387. },
  34388. CSS_RGB: {
  34389. read: function read(original) {
  34390. var test = original.match(/^rgb\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);
  34391. if (test === null) {
  34392. return false;
  34393. }
  34394. return {
  34395. space: 'RGB',
  34396. r: parseFloat(test[1]),
  34397. g: parseFloat(test[2]),
  34398. b: parseFloat(test[3])
  34399. };
  34400. },
  34401. write: colorToString
  34402. },
  34403. CSS_RGBA: {
  34404. read: function read(original) {
  34405. var test = original.match(/^rgba\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);
  34406. if (test === null) {
  34407. return false;
  34408. }
  34409. return {
  34410. space: 'RGB',
  34411. r: parseFloat(test[1]),
  34412. g: parseFloat(test[2]),
  34413. b: parseFloat(test[3]),
  34414. a: parseFloat(test[4])
  34415. };
  34416. },
  34417. write: colorToString
  34418. }
  34419. }
  34420. }, {
  34421. litmus: Common.isNumber,
  34422. conversions: {
  34423. HEX: {
  34424. read: function read(original) {
  34425. return {
  34426. space: 'HEX',
  34427. hex: original,
  34428. conversionName: 'HEX'
  34429. };
  34430. },
  34431. write: function write(color) {
  34432. return color.hex;
  34433. }
  34434. }
  34435. }
  34436. }, {
  34437. litmus: Common.isArray,
  34438. conversions: {
  34439. RGB_ARRAY: {
  34440. read: function read(original) {
  34441. if (original.length !== 3) {
  34442. return false;
  34443. }
  34444. return {
  34445. space: 'RGB',
  34446. r: original[0],
  34447. g: original[1],
  34448. b: original[2]
  34449. };
  34450. },
  34451. write: function write(color) {
  34452. return [color.r, color.g, color.b];
  34453. }
  34454. },
  34455. RGBA_ARRAY: {
  34456. read: function read(original) {
  34457. if (original.length !== 4) return false;
  34458. return {
  34459. space: 'RGB',
  34460. r: original[0],
  34461. g: original[1],
  34462. b: original[2],
  34463. a: original[3]
  34464. };
  34465. },
  34466. write: function write(color) {
  34467. return [color.r, color.g, color.b, color.a];
  34468. }
  34469. }
  34470. }
  34471. }, {
  34472. litmus: Common.isObject,
  34473. conversions: {
  34474. RGBA_OBJ: {
  34475. read: function read(original) {
  34476. if (Common.isNumber(original.r) && Common.isNumber(original.g) && Common.isNumber(original.b) && Common.isNumber(original.a)) {
  34477. return {
  34478. space: 'RGB',
  34479. r: original.r,
  34480. g: original.g,
  34481. b: original.b,
  34482. a: original.a
  34483. };
  34484. }
  34485. return false;
  34486. },
  34487. write: function write(color) {
  34488. return {
  34489. r: color.r,
  34490. g: color.g,
  34491. b: color.b,
  34492. a: color.a
  34493. };
  34494. }
  34495. },
  34496. RGB_OBJ: {
  34497. read: function read(original) {
  34498. if (Common.isNumber(original.r) && Common.isNumber(original.g) && Common.isNumber(original.b)) {
  34499. return {
  34500. space: 'RGB',
  34501. r: original.r,
  34502. g: original.g,
  34503. b: original.b
  34504. };
  34505. }
  34506. return false;
  34507. },
  34508. write: function write(color) {
  34509. return {
  34510. r: color.r,
  34511. g: color.g,
  34512. b: color.b
  34513. };
  34514. }
  34515. },
  34516. HSVA_OBJ: {
  34517. read: function read(original) {
  34518. if (Common.isNumber(original.h) && Common.isNumber(original.s) && Common.isNumber(original.v) && Common.isNumber(original.a)) {
  34519. return {
  34520. space: 'HSV',
  34521. h: original.h,
  34522. s: original.s,
  34523. v: original.v,
  34524. a: original.a
  34525. };
  34526. }
  34527. return false;
  34528. },
  34529. write: function write(color) {
  34530. return {
  34531. h: color.h,
  34532. s: color.s,
  34533. v: color.v,
  34534. a: color.a
  34535. };
  34536. }
  34537. },
  34538. HSV_OBJ: {
  34539. read: function read(original) {
  34540. if (Common.isNumber(original.h) && Common.isNumber(original.s) && Common.isNumber(original.v)) {
  34541. return {
  34542. space: 'HSV',
  34543. h: original.h,
  34544. s: original.s,
  34545. v: original.v
  34546. };
  34547. }
  34548. return false;
  34549. },
  34550. write: function write(color) {
  34551. return {
  34552. h: color.h,
  34553. s: color.s,
  34554. v: color.v
  34555. };
  34556. }
  34557. }
  34558. }
  34559. }];
  34560. var result = void 0;
  34561. var toReturn = void 0;
  34562. var interpret = function interpret() {
  34563. toReturn = false;
  34564. var original = arguments.length > 1 ? Common.toArray(arguments) : arguments[0];
  34565. Common.each(INTERPRETATIONS, function (family) {
  34566. if (family.litmus(original)) {
  34567. Common.each(family.conversions, function (conversion, conversionName) {
  34568. result = conversion.read(original);
  34569. if (toReturn === false && result !== false) {
  34570. toReturn = result;
  34571. result.conversionName = conversionName;
  34572. result.conversion = conversion;
  34573. return Common.BREAK;
  34574. }
  34575. });
  34576. return Common.BREAK;
  34577. }
  34578. });
  34579. return toReturn;
  34580. };
  34581. var tmpComponent = void 0;
  34582. var ColorMath = {
  34583. hsv_to_rgb: function hsv_to_rgb(h, s, v) {
  34584. var hi = Math.floor(h / 60) % 6;
  34585. var f = h / 60 - Math.floor(h / 60);
  34586. var p = v * (1.0 - s);
  34587. var q = v * (1.0 - f * s);
  34588. var t = v * (1.0 - (1.0 - f) * s);
  34589. var c = [[v, t, p], [q, v, p], [p, v, t], [p, q, v], [t, p, v], [v, p, q]][hi];
  34590. return {
  34591. r: c[0] * 255,
  34592. g: c[1] * 255,
  34593. b: c[2] * 255
  34594. };
  34595. },
  34596. rgb_to_hsv: function rgb_to_hsv(r, g, b) {
  34597. var min = Math.min(r, g, b);
  34598. var max = Math.max(r, g, b);
  34599. var delta = max - min;
  34600. var h = void 0;
  34601. var s = void 0;
  34602. if (max !== 0) {
  34603. s = delta / max;
  34604. } else {
  34605. return {
  34606. h: NaN,
  34607. s: 0,
  34608. v: 0
  34609. };
  34610. }
  34611. if (r === max) {
  34612. h = (g - b) / delta;
  34613. } else if (g === max) {
  34614. h = 2 + (b - r) / delta;
  34615. } else {
  34616. h = 4 + (r - g) / delta;
  34617. }
  34618. h /= 6;
  34619. if (h < 0) {
  34620. h += 1;
  34621. }
  34622. return {
  34623. h: h * 360,
  34624. s: s,
  34625. v: max / 255
  34626. };
  34627. },
  34628. rgb_to_hex: function rgb_to_hex(r, g, b) {
  34629. var hex = this.hex_with_component(0, 2, r);
  34630. hex = this.hex_with_component(hex, 1, g);
  34631. hex = this.hex_with_component(hex, 0, b);
  34632. return hex;
  34633. },
  34634. component_from_hex: function component_from_hex(hex, componentIndex) {
  34635. return hex >> componentIndex * 8 & 0xFF;
  34636. },
  34637. hex_with_component: function hex_with_component(hex, componentIndex, value) {
  34638. return value << (tmpComponent = componentIndex * 8) | hex & ~(0xFF << tmpComponent);
  34639. }
  34640. };
  34641. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  34642. return typeof obj;
  34643. } : function (obj) {
  34644. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  34645. };
  34646. var classCallCheck = function (instance, Constructor) {
  34647. if (!(instance instanceof Constructor)) {
  34648. throw new TypeError("Cannot call a class as a function");
  34649. }
  34650. };
  34651. var createClass = function () {
  34652. function defineProperties(target, props) {
  34653. for (var i = 0; i < props.length; i++) {
  34654. var descriptor = props[i];
  34655. descriptor.enumerable = descriptor.enumerable || false;
  34656. descriptor.configurable = true;
  34657. if ("value" in descriptor) descriptor.writable = true;
  34658. Object.defineProperty(target, descriptor.key, descriptor);
  34659. }
  34660. }
  34661. return function (Constructor, protoProps, staticProps) {
  34662. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  34663. if (staticProps) defineProperties(Constructor, staticProps);
  34664. return Constructor;
  34665. };
  34666. }();
  34667. var get = function get(object, property, receiver) {
  34668. if (object === null) object = Function.prototype;
  34669. var desc = Object.getOwnPropertyDescriptor(object, property);
  34670. if (desc === undefined) {
  34671. var parent = Object.getPrototypeOf(object);
  34672. if (parent === null) {
  34673. return undefined;
  34674. } else {
  34675. return get(parent, property, receiver);
  34676. }
  34677. } else if ("value" in desc) {
  34678. return desc.value;
  34679. } else {
  34680. var getter = desc.get;
  34681. if (getter === undefined) {
  34682. return undefined;
  34683. }
  34684. return getter.call(receiver);
  34685. }
  34686. };
  34687. var inherits = function (subClass, superClass) {
  34688. if (typeof superClass !== "function" && superClass !== null) {
  34689. throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
  34690. }
  34691. subClass.prototype = Object.create(superClass && superClass.prototype, {
  34692. constructor: {
  34693. value: subClass,
  34694. enumerable: false,
  34695. writable: true,
  34696. configurable: true
  34697. }
  34698. });
  34699. if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
  34700. };
  34701. var possibleConstructorReturn = function (self, call) {
  34702. if (!self) {
  34703. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  34704. }
  34705. return call && (typeof call === "object" || typeof call === "function") ? call : self;
  34706. };
  34707. var Color = function () {
  34708. function Color() {
  34709. classCallCheck(this, Color);
  34710. this.__state = interpret.apply(this, arguments);
  34711. if (this.__state === false) {
  34712. throw new Error('Failed to interpret color arguments');
  34713. }
  34714. this.__state.a = this.__state.a || 1;
  34715. }
  34716. createClass(Color, [{
  34717. key: 'toString',
  34718. value: function toString() {
  34719. return colorToString(this);
  34720. }
  34721. }, {
  34722. key: 'toHexString',
  34723. value: function toHexString() {
  34724. return colorToString(this, true);
  34725. }
  34726. }, {
  34727. key: 'toOriginal',
  34728. value: function toOriginal() {
  34729. return this.__state.conversion.write(this);
  34730. }
  34731. }]);
  34732. return Color;
  34733. }();
  34734. function defineRGBComponent(target, component, componentHexIndex) {
  34735. Object.defineProperty(target, component, {
  34736. get: function get$$1() {
  34737. if (this.__state.space === 'RGB') {
  34738. return this.__state[component];
  34739. }
  34740. Color.recalculateRGB(this, component, componentHexIndex);
  34741. return this.__state[component];
  34742. },
  34743. set: function set$$1(v) {
  34744. if (this.__state.space !== 'RGB') {
  34745. Color.recalculateRGB(this, component, componentHexIndex);
  34746. this.__state.space = 'RGB';
  34747. }
  34748. this.__state[component] = v;
  34749. }
  34750. });
  34751. }
  34752. function defineHSVComponent(target, component) {
  34753. Object.defineProperty(target, component, {
  34754. get: function get$$1() {
  34755. if (this.__state.space === 'HSV') {
  34756. return this.__state[component];
  34757. }
  34758. Color.recalculateHSV(this);
  34759. return this.__state[component];
  34760. },
  34761. set: function set$$1(v) {
  34762. if (this.__state.space !== 'HSV') {
  34763. Color.recalculateHSV(this);
  34764. this.__state.space = 'HSV';
  34765. }
  34766. this.__state[component] = v;
  34767. }
  34768. });
  34769. }
  34770. Color.recalculateRGB = function (color, component, componentHexIndex) {
  34771. if (color.__state.space === 'HEX') {
  34772. color.__state[component] = ColorMath.component_from_hex(color.__state.hex, componentHexIndex);
  34773. } else if (color.__state.space === 'HSV') {
  34774. Common.extend(color.__state, ColorMath.hsv_to_rgb(color.__state.h, color.__state.s, color.__state.v));
  34775. } else {
  34776. throw new Error('Corrupted color state');
  34777. }
  34778. };
  34779. Color.recalculateHSV = function (color) {
  34780. var result = ColorMath.rgb_to_hsv(color.r, color.g, color.b);
  34781. Common.extend(color.__state, {
  34782. s: result.s,
  34783. v: result.v
  34784. });
  34785. if (!Common.isNaN(result.h)) {
  34786. color.__state.h = result.h;
  34787. } else if (Common.isUndefined(color.__state.h)) {
  34788. color.__state.h = 0;
  34789. }
  34790. };
  34791. Color.COMPONENTS = ['r', 'g', 'b', 'h', 's', 'v', 'hex', 'a'];
  34792. defineRGBComponent(Color.prototype, 'r', 2);
  34793. defineRGBComponent(Color.prototype, 'g', 1);
  34794. defineRGBComponent(Color.prototype, 'b', 0);
  34795. defineHSVComponent(Color.prototype, 'h');
  34796. defineHSVComponent(Color.prototype, 's');
  34797. defineHSVComponent(Color.prototype, 'v');
  34798. Object.defineProperty(Color.prototype, 'a', {
  34799. get: function get$$1() {
  34800. return this.__state.a;
  34801. },
  34802. set: function set$$1(v) {
  34803. this.__state.a = v;
  34804. }
  34805. });
  34806. Object.defineProperty(Color.prototype, 'hex', {
  34807. get: function get$$1() {
  34808. if (!this.__state.space !== 'HEX') {
  34809. this.__state.hex = ColorMath.rgb_to_hex(this.r, this.g, this.b);
  34810. }
  34811. return this.__state.hex;
  34812. },
  34813. set: function set$$1(v) {
  34814. this.__state.space = 'HEX';
  34815. this.__state.hex = v;
  34816. }
  34817. });
  34818. var Controller = function () {
  34819. function Controller(object, property) {
  34820. classCallCheck(this, Controller);
  34821. this.initialValue = object[property];
  34822. this.domElement = document.createElement('div');
  34823. this.object = object;
  34824. this.property = property;
  34825. this.__onChange = undefined;
  34826. this.__onFinishChange = undefined;
  34827. }
  34828. createClass(Controller, [{
  34829. key: 'onChange',
  34830. value: function onChange(fnc) {
  34831. this.__onChange = fnc;
  34832. return this;
  34833. }
  34834. }, {
  34835. key: 'onFinishChange',
  34836. value: function onFinishChange(fnc) {
  34837. this.__onFinishChange = fnc;
  34838. return this;
  34839. }
  34840. }, {
  34841. key: 'setValue',
  34842. value: function setValue(newValue) {
  34843. this.object[this.property] = newValue;
  34844. if (this.__onChange) {
  34845. this.__onChange.call(this, newValue);
  34846. }
  34847. this.updateDisplay();
  34848. return this;
  34849. }
  34850. }, {
  34851. key: 'getValue',
  34852. value: function getValue() {
  34853. return this.object[this.property];
  34854. }
  34855. }, {
  34856. key: 'updateDisplay',
  34857. value: function updateDisplay() {
  34858. return this;
  34859. }
  34860. }, {
  34861. key: 'isModified',
  34862. value: function isModified() {
  34863. return this.initialValue !== this.getValue();
  34864. }
  34865. }]);
  34866. return Controller;
  34867. }();
  34868. var EVENT_MAP = {
  34869. HTMLEvents: ['change'],
  34870. MouseEvents: ['click', 'mousemove', 'mousedown', 'mouseup', 'mouseover'],
  34871. KeyboardEvents: ['keydown']
  34872. };
  34873. var EVENT_MAP_INV = {};
  34874. Common.each(EVENT_MAP, function (v, k) {
  34875. Common.each(v, function (e) {
  34876. EVENT_MAP_INV[e] = k;
  34877. });
  34878. });
  34879. var CSS_VALUE_PIXELS = /(\d+(\.\d+)?)px/;
  34880. function cssValueToPixels(val) {
  34881. if (val === '0' || Common.isUndefined(val)) {
  34882. return 0;
  34883. }
  34884. var match = val.match(CSS_VALUE_PIXELS);
  34885. if (!Common.isNull(match)) {
  34886. return parseFloat(match[1]);
  34887. }
  34888. return 0;
  34889. }
  34890. var dom = {
  34891. makeSelectable: function makeSelectable(elem, selectable) {
  34892. if (elem === undefined || elem.style === undefined) return;
  34893. elem.onselectstart = selectable ? function () {
  34894. return false;
  34895. } : function () {};
  34896. elem.style.MozUserSelect = selectable ? 'auto' : 'none';
  34897. elem.style.KhtmlUserSelect = selectable ? 'auto' : 'none';
  34898. elem.unselectable = selectable ? 'on' : 'off';
  34899. },
  34900. makeFullscreen: function makeFullscreen(elem, hor, vert) {
  34901. var vertical = vert;
  34902. var horizontal = hor;
  34903. if (Common.isUndefined(horizontal)) {
  34904. horizontal = true;
  34905. }
  34906. if (Common.isUndefined(vertical)) {
  34907. vertical = true;
  34908. }
  34909. elem.style.position = 'absolute';
  34910. if (horizontal) {
  34911. elem.style.left = 0;
  34912. elem.style.right = 0;
  34913. }
  34914. if (vertical) {
  34915. elem.style.top = 0;
  34916. elem.style.bottom = 0;
  34917. }
  34918. },
  34919. fakeEvent: function fakeEvent(elem, eventType, pars, aux) {
  34920. var params = pars || {};
  34921. var className = EVENT_MAP_INV[eventType];
  34922. if (!className) {
  34923. throw new Error('Event type ' + eventType + ' not supported.');
  34924. }
  34925. var evt = document.createEvent(className);
  34926. switch (className) {
  34927. case 'MouseEvents':
  34928. {
  34929. var clientX = params.x || params.clientX || 0;
  34930. var clientY = params.y || params.clientY || 0;
  34931. evt.initMouseEvent(eventType, params.bubbles || false, params.cancelable || true, window, params.clickCount || 1, 0, 0, clientX, clientY, false, false, false, false, 0, null);
  34932. break;
  34933. }
  34934. case 'KeyboardEvents':
  34935. {
  34936. var init = evt.initKeyboardEvent || evt.initKeyEvent;
  34937. Common.defaults(params, {
  34938. cancelable: true,
  34939. ctrlKey: false,
  34940. altKey: false,
  34941. shiftKey: false,
  34942. metaKey: false,
  34943. keyCode: undefined,
  34944. charCode: undefined
  34945. });
  34946. init(eventType, params.bubbles || false, params.cancelable, window, params.ctrlKey, params.altKey, params.shiftKey, params.metaKey, params.keyCode, params.charCode);
  34947. break;
  34948. }
  34949. default:
  34950. {
  34951. evt.initEvent(eventType, params.bubbles || false, params.cancelable || true);
  34952. break;
  34953. }
  34954. }
  34955. Common.defaults(evt, aux);
  34956. elem.dispatchEvent(evt);
  34957. },
  34958. bind: function bind(elem, event, func, newBool) {
  34959. var bool = newBool || false;
  34960. if (elem.addEventListener) {
  34961. elem.addEventListener(event, func, bool);
  34962. } else if (elem.attachEvent) {
  34963. elem.attachEvent('on' + event, func);
  34964. }
  34965. return dom;
  34966. },
  34967. unbind: function unbind(elem, event, func, newBool) {
  34968. var bool = newBool || false;
  34969. if (elem.removeEventListener) {
  34970. elem.removeEventListener(event, func, bool);
  34971. } else if (elem.detachEvent) {
  34972. elem.detachEvent('on' + event, func);
  34973. }
  34974. return dom;
  34975. },
  34976. addClass: function addClass(elem, className) {
  34977. if (elem.className === undefined) {
  34978. elem.className = className;
  34979. } else if (elem.className !== className) {
  34980. var classes = elem.className.split(/ +/);
  34981. if (classes.indexOf(className) === -1) {
  34982. classes.push(className);
  34983. elem.className = classes.join(' ').replace(/^\s+/, '').replace(/\s+$/, '');
  34984. }
  34985. }
  34986. return dom;
  34987. },
  34988. removeClass: function removeClass(elem, className) {
  34989. if (className) {
  34990. if (elem.className === className) {
  34991. elem.removeAttribute('class');
  34992. } else {
  34993. var classes = elem.className.split(/ +/);
  34994. var index = classes.indexOf(className);
  34995. if (index !== -1) {
  34996. classes.splice(index, 1);
  34997. elem.className = classes.join(' ');
  34998. }
  34999. }
  35000. } else {
  35001. elem.className = undefined;
  35002. }
  35003. return dom;
  35004. },
  35005. hasClass: function hasClass(elem, className) {
  35006. return new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)').test(elem.className) || false;
  35007. },
  35008. getWidth: function getWidth(elem) {
  35009. var style = getComputedStyle(elem);
  35010. return cssValueToPixels(style['border-left-width']) + cssValueToPixels(style['border-right-width']) + cssValueToPixels(style['padding-left']) + cssValueToPixels(style['padding-right']) + cssValueToPixels(style.width);
  35011. },
  35012. getHeight: function getHeight(elem) {
  35013. var style = getComputedStyle(elem);
  35014. return cssValueToPixels(style['border-top-width']) + cssValueToPixels(style['border-bottom-width']) + cssValueToPixels(style['padding-top']) + cssValueToPixels(style['padding-bottom']) + cssValueToPixels(style.height);
  35015. },
  35016. getOffset: function getOffset(el) {
  35017. var elem = el;
  35018. var offset = {
  35019. left: 0,
  35020. top: 0
  35021. };
  35022. if (elem.offsetParent) {
  35023. do {
  35024. offset.left += elem.offsetLeft;
  35025. offset.top += elem.offsetTop;
  35026. elem = elem.offsetParent;
  35027. } while (elem);
  35028. }
  35029. return offset;
  35030. },
  35031. isActive: function isActive(elem) {
  35032. return elem === document.activeElement && (elem.type || elem.href);
  35033. }
  35034. };
  35035. var BooleanController = function (_Controller) {
  35036. inherits(BooleanController, _Controller);
  35037. function BooleanController(object, property) {
  35038. classCallCheck(this, BooleanController);
  35039. var _this2 = possibleConstructorReturn(this, (BooleanController.__proto__ || Object.getPrototypeOf(BooleanController)).call(this, object, property));
  35040. var _this = _this2;
  35041. _this2.__prev = _this2.getValue();
  35042. _this2.__checkbox = document.createElement('input');
  35043. _this2.__checkbox.setAttribute('type', 'checkbox');
  35044. function onChange() {
  35045. _this.setValue(!_this.__prev);
  35046. }
  35047. dom.bind(_this2.__checkbox, 'change', onChange, false);
  35048. _this2.domElement.appendChild(_this2.__checkbox);
  35049. _this2.updateDisplay();
  35050. return _this2;
  35051. }
  35052. createClass(BooleanController, [{
  35053. key: 'setValue',
  35054. value: function setValue(v) {
  35055. var toReturn = get(BooleanController.prototype.__proto__ || Object.getPrototypeOf(BooleanController.prototype), 'setValue', this).call(this, v);
  35056. if (this.__onFinishChange) {
  35057. this.__onFinishChange.call(this, this.getValue());
  35058. }
  35059. this.__prev = this.getValue();
  35060. return toReturn;
  35061. }
  35062. }, {
  35063. key: 'updateDisplay',
  35064. value: function updateDisplay() {
  35065. if (this.getValue() === true) {
  35066. this.__checkbox.setAttribute('checked', 'checked');
  35067. this.__checkbox.checked = true;
  35068. this.__prev = true;
  35069. } else {
  35070. this.__checkbox.checked = false;
  35071. this.__prev = false;
  35072. }
  35073. return get(BooleanController.prototype.__proto__ || Object.getPrototypeOf(BooleanController.prototype), 'updateDisplay', this).call(this);
  35074. }
  35075. }]);
  35076. return BooleanController;
  35077. }(Controller);
  35078. var OptionController = function (_Controller) {
  35079. inherits(OptionController, _Controller);
  35080. function OptionController(object, property, opts) {
  35081. classCallCheck(this, OptionController);
  35082. var _this2 = possibleConstructorReturn(this, (OptionController.__proto__ || Object.getPrototypeOf(OptionController)).call(this, object, property));
  35083. var options = opts;
  35084. var _this = _this2;
  35085. _this2.__select = document.createElement('select');
  35086. if (Common.isArray(options)) {
  35087. var map = {};
  35088. Common.each(options, function (element) {
  35089. map[element] = element;
  35090. });
  35091. options = map;
  35092. }
  35093. Common.each(options, function (value, key) {
  35094. var opt = document.createElement('option');
  35095. opt.innerHTML = key;
  35096. opt.setAttribute('value', value);
  35097. _this.__select.appendChild(opt);
  35098. });
  35099. _this2.updateDisplay();
  35100. dom.bind(_this2.__select, 'change', function () {
  35101. var desiredValue = this.options[this.selectedIndex].value;
  35102. _this.setValue(desiredValue);
  35103. });
  35104. _this2.domElement.appendChild(_this2.__select);
  35105. return _this2;
  35106. }
  35107. createClass(OptionController, [{
  35108. key: 'setValue',
  35109. value: function setValue(v) {
  35110. var toReturn = get(OptionController.prototype.__proto__ || Object.getPrototypeOf(OptionController.prototype), 'setValue', this).call(this, v);
  35111. if (this.__onFinishChange) {
  35112. this.__onFinishChange.call(this, this.getValue());
  35113. }
  35114. return toReturn;
  35115. }
  35116. }, {
  35117. key: 'updateDisplay',
  35118. value: function updateDisplay() {
  35119. if (dom.isActive(this.__select)) return this;
  35120. this.__select.value = this.getValue();
  35121. return get(OptionController.prototype.__proto__ || Object.getPrototypeOf(OptionController.prototype), 'updateDisplay', this).call(this);
  35122. }
  35123. }]);
  35124. return OptionController;
  35125. }(Controller);
  35126. var StringController = function (_Controller) {
  35127. inherits(StringController, _Controller);
  35128. function StringController(object, property) {
  35129. classCallCheck(this, StringController);
  35130. var _this2 = possibleConstructorReturn(this, (StringController.__proto__ || Object.getPrototypeOf(StringController)).call(this, object, property));
  35131. var _this = _this2;
  35132. function onChange() {
  35133. _this.setValue(_this.__input.value);
  35134. }
  35135. function onBlur() {
  35136. if (_this.__onFinishChange) {
  35137. _this.__onFinishChange.call(_this, _this.getValue());
  35138. }
  35139. }
  35140. _this2.__input = document.createElement('input');
  35141. _this2.__input.setAttribute('type', 'text');
  35142. dom.bind(_this2.__input, 'keyup', onChange);
  35143. dom.bind(_this2.__input, 'change', onChange);
  35144. dom.bind(_this2.__input, 'blur', onBlur);
  35145. dom.bind(_this2.__input, 'keydown', function (e) {
  35146. if (e.keyCode === 13) {
  35147. this.blur();
  35148. }
  35149. });
  35150. _this2.updateDisplay();
  35151. _this2.domElement.appendChild(_this2.__input);
  35152. return _this2;
  35153. }
  35154. createClass(StringController, [{
  35155. key: 'updateDisplay',
  35156. value: function updateDisplay() {
  35157. if (!dom.isActive(this.__input)) {
  35158. this.__input.value = this.getValue();
  35159. }
  35160. return get(StringController.prototype.__proto__ || Object.getPrototypeOf(StringController.prototype), 'updateDisplay', this).call(this);
  35161. }
  35162. }]);
  35163. return StringController;
  35164. }(Controller);
  35165. function numDecimals(x) {
  35166. var _x = x.toString();
  35167. if (_x.indexOf('.') > -1) {
  35168. return _x.length - _x.indexOf('.') - 1;
  35169. }
  35170. return 0;
  35171. }
  35172. var NumberController = function (_Controller) {
  35173. inherits(NumberController, _Controller);
  35174. function NumberController(object, property, params) {
  35175. classCallCheck(this, NumberController);
  35176. var _this = possibleConstructorReturn(this, (NumberController.__proto__ || Object.getPrototypeOf(NumberController)).call(this, object, property));
  35177. var _params = params || {};
  35178. _this.__min = _params.min;
  35179. _this.__max = _params.max;
  35180. _this.__step = _params.step;
  35181. if (Common.isUndefined(_this.__step)) {
  35182. if (_this.initialValue === 0) {
  35183. _this.__impliedStep = 1;
  35184. } else {
  35185. _this.__impliedStep = Math.pow(10, Math.floor(Math.log(Math.abs(_this.initialValue)) / Math.LN10)) / 10;
  35186. }
  35187. } else {
  35188. _this.__impliedStep = _this.__step;
  35189. }
  35190. _this.__precision = numDecimals(_this.__impliedStep);
  35191. return _this;
  35192. }
  35193. createClass(NumberController, [{
  35194. key: 'setValue',
  35195. value: function setValue(v) {
  35196. var _v = v;
  35197. if (this.__min !== undefined && _v < this.__min) {
  35198. _v = this.__min;
  35199. } else if (this.__max !== undefined && _v > this.__max) {
  35200. _v = this.__max;
  35201. }
  35202. if (this.__step !== undefined && _v % this.__step !== 0) {
  35203. _v = Math.round(_v / this.__step) * this.__step;
  35204. }
  35205. return get(NumberController.prototype.__proto__ || Object.getPrototypeOf(NumberController.prototype), 'setValue', this).call(this, _v);
  35206. }
  35207. }, {
  35208. key: 'min',
  35209. value: function min(minValue) {
  35210. this.__min = minValue;
  35211. return this;
  35212. }
  35213. }, {
  35214. key: 'max',
  35215. value: function max(maxValue) {
  35216. this.__max = maxValue;
  35217. return this;
  35218. }
  35219. }, {
  35220. key: 'step',
  35221. value: function step(stepValue) {
  35222. this.__step = stepValue;
  35223. this.__impliedStep = stepValue;
  35224. this.__precision = numDecimals(stepValue);
  35225. return this;
  35226. }
  35227. }]);
  35228. return NumberController;
  35229. }(Controller);
  35230. function roundToDecimal(value, decimals) {
  35231. var tenTo = Math.pow(10, decimals);
  35232. return Math.round(value * tenTo) / tenTo;
  35233. }
  35234. var NumberControllerBox = function (_NumberController) {
  35235. inherits(NumberControllerBox, _NumberController);
  35236. function NumberControllerBox(object, property, params) {
  35237. classCallCheck(this, NumberControllerBox);
  35238. var _this2 = possibleConstructorReturn(this, (NumberControllerBox.__proto__ || Object.getPrototypeOf(NumberControllerBox)).call(this, object, property, params));
  35239. _this2.__truncationSuspended = false;
  35240. var _this = _this2;
  35241. var prevY = void 0;
  35242. function onChange() {
  35243. var attempted = parseFloat(_this.__input.value);
  35244. if (!Common.isNaN(attempted)) {
  35245. _this.setValue(attempted);
  35246. }
  35247. }
  35248. function onFinish() {
  35249. if (_this.__onFinishChange) {
  35250. _this.__onFinishChange.call(_this, _this.getValue());
  35251. }
  35252. }
  35253. function onBlur() {
  35254. onFinish();
  35255. }
  35256. function onMouseDrag(e) {
  35257. var diff = prevY - e.clientY;
  35258. _this.setValue(_this.getValue() + diff * _this.__impliedStep);
  35259. prevY = e.clientY;
  35260. }
  35261. function onMouseUp() {
  35262. dom.unbind(window, 'mousemove', onMouseDrag);
  35263. dom.unbind(window, 'mouseup', onMouseUp);
  35264. onFinish();
  35265. }
  35266. function onMouseDown(e) {
  35267. dom.bind(window, 'mousemove', onMouseDrag);
  35268. dom.bind(window, 'mouseup', onMouseUp);
  35269. prevY = e.clientY;
  35270. }
  35271. _this2.__input = document.createElement('input');
  35272. _this2.__input.setAttribute('type', 'text');
  35273. dom.bind(_this2.__input, 'change', onChange);
  35274. dom.bind(_this2.__input, 'blur', onBlur);
  35275. dom.bind(_this2.__input, 'mousedown', onMouseDown);
  35276. dom.bind(_this2.__input, 'keydown', function (e) {
  35277. if (e.keyCode === 13) {
  35278. _this.__truncationSuspended = true;
  35279. this.blur();
  35280. _this.__truncationSuspended = false;
  35281. onFinish();
  35282. }
  35283. });
  35284. _this2.updateDisplay();
  35285. _this2.domElement.appendChild(_this2.__input);
  35286. return _this2;
  35287. }
  35288. createClass(NumberControllerBox, [{
  35289. key: 'updateDisplay',
  35290. value: function updateDisplay() {
  35291. this.__input.value = this.__truncationSuspended ? this.getValue() : roundToDecimal(this.getValue(), this.__precision);
  35292. return get(NumberControllerBox.prototype.__proto__ || Object.getPrototypeOf(NumberControllerBox.prototype), 'updateDisplay', this).call(this);
  35293. }
  35294. }]);
  35295. return NumberControllerBox;
  35296. }(NumberController);
  35297. function map(v, i1, i2, o1, o2) {
  35298. return o1 + (o2 - o1) * ((v - i1) / (i2 - i1));
  35299. }
  35300. var NumberControllerSlider = function (_NumberController) {
  35301. inherits(NumberControllerSlider, _NumberController);
  35302. function NumberControllerSlider(object, property, min, max, step) {
  35303. classCallCheck(this, NumberControllerSlider);
  35304. var _this2 = possibleConstructorReturn(this, (NumberControllerSlider.__proto__ || Object.getPrototypeOf(NumberControllerSlider)).call(this, object, property, {
  35305. min: min,
  35306. max: max,
  35307. step: step
  35308. }));
  35309. var _this = _this2;
  35310. _this2.__background = document.createElement('div');
  35311. _this2.__foreground = document.createElement('div');
  35312. dom.bind(_this2.__background, 'mousedown', onMouseDown);
  35313. dom.bind(_this2.__background, 'touchstart', onTouchStart);
  35314. dom.addClass(_this2.__background, 'slider');
  35315. dom.addClass(_this2.__foreground, 'slider-fg');
  35316. function onMouseDown(e) {
  35317. document.activeElement.blur();
  35318. dom.bind(window, 'mousemove', onMouseDrag);
  35319. dom.bind(window, 'mouseup', onMouseUp);
  35320. onMouseDrag(e);
  35321. }
  35322. function onMouseDrag(e) {
  35323. e.preventDefault();
  35324. var bgRect = _this.__background.getBoundingClientRect();
  35325. _this.setValue(map(e.clientX, bgRect.left, bgRect.right, _this.__min, _this.__max));
  35326. return false;
  35327. }
  35328. function onMouseUp() {
  35329. dom.unbind(window, 'mousemove', onMouseDrag);
  35330. dom.unbind(window, 'mouseup', onMouseUp);
  35331. if (_this.__onFinishChange) {
  35332. _this.__onFinishChange.call(_this, _this.getValue());
  35333. }
  35334. }
  35335. function onTouchStart(e) {
  35336. if (e.touches.length !== 1) {
  35337. return;
  35338. }
  35339. dom.bind(window, 'touchmove', onTouchMove);
  35340. dom.bind(window, 'touchend', onTouchEnd);
  35341. onTouchMove(e);
  35342. }
  35343. function onTouchMove(e) {
  35344. var clientX = e.touches[0].clientX;
  35345. var bgRect = _this.__background.getBoundingClientRect();
  35346. _this.setValue(map(clientX, bgRect.left, bgRect.right, _this.__min, _this.__max));
  35347. }
  35348. function onTouchEnd() {
  35349. dom.unbind(window, 'touchmove', onTouchMove);
  35350. dom.unbind(window, 'touchend', onTouchEnd);
  35351. if (_this.__onFinishChange) {
  35352. _this.__onFinishChange.call(_this, _this.getValue());
  35353. }
  35354. }
  35355. _this2.updateDisplay();
  35356. _this2.__background.appendChild(_this2.__foreground);
  35357. _this2.domElement.appendChild(_this2.__background);
  35358. return _this2;
  35359. }
  35360. createClass(NumberControllerSlider, [{
  35361. key: 'updateDisplay',
  35362. value: function updateDisplay() {
  35363. var pct = (this.getValue() - this.__min) / (this.__max - this.__min);
  35364. this.__foreground.style.width = pct * 100 + '%';
  35365. return get(NumberControllerSlider.prototype.__proto__ || Object.getPrototypeOf(NumberControllerSlider.prototype), 'updateDisplay', this).call(this);
  35366. }
  35367. }]);
  35368. return NumberControllerSlider;
  35369. }(NumberController);
  35370. var FunctionController = function (_Controller) {
  35371. inherits(FunctionController, _Controller);
  35372. function FunctionController(object, property, text) {
  35373. classCallCheck(this, FunctionController);
  35374. var _this2 = possibleConstructorReturn(this, (FunctionController.__proto__ || Object.getPrototypeOf(FunctionController)).call(this, object, property));
  35375. var _this = _this2;
  35376. _this2.__button = document.createElement('div');
  35377. _this2.__button.innerHTML = text === undefined ? 'Fire' : text;
  35378. dom.bind(_this2.__button, 'click', function (e) {
  35379. e.preventDefault();
  35380. _this.fire();
  35381. return false;
  35382. });
  35383. dom.addClass(_this2.__button, 'button');
  35384. _this2.domElement.appendChild(_this2.__button);
  35385. return _this2;
  35386. }
  35387. createClass(FunctionController, [{
  35388. key: 'fire',
  35389. value: function fire() {
  35390. if (this.__onChange) {
  35391. this.__onChange.call(this);
  35392. }
  35393. this.getValue().call(this.object);
  35394. if (this.__onFinishChange) {
  35395. this.__onFinishChange.call(this, this.getValue());
  35396. }
  35397. }
  35398. }]);
  35399. return FunctionController;
  35400. }(Controller);
  35401. var ColorController = function (_Controller) {
  35402. inherits(ColorController, _Controller);
  35403. function ColorController(object, property) {
  35404. classCallCheck(this, ColorController);
  35405. var _this2 = possibleConstructorReturn(this, (ColorController.__proto__ || Object.getPrototypeOf(ColorController)).call(this, object, property));
  35406. _this2.__color = new Color(_this2.getValue());
  35407. _this2.__temp = new Color(0);
  35408. var _this = _this2;
  35409. _this2.domElement = document.createElement('div');
  35410. dom.makeSelectable(_this2.domElement, false);
  35411. _this2.__selector = document.createElement('div');
  35412. _this2.__selector.className = 'selector';
  35413. _this2.__saturation_field = document.createElement('div');
  35414. _this2.__saturation_field.className = 'saturation-field';
  35415. _this2.__field_knob = document.createElement('div');
  35416. _this2.__field_knob.className = 'field-knob';
  35417. _this2.__field_knob_border = '2px solid ';
  35418. _this2.__hue_knob = document.createElement('div');
  35419. _this2.__hue_knob.className = 'hue-knob';
  35420. _this2.__hue_field = document.createElement('div');
  35421. _this2.__hue_field.className = 'hue-field';
  35422. _this2.__input = document.createElement('input');
  35423. _this2.__input.type = 'text';
  35424. _this2.__input_textShadow = '0 1px 1px ';
  35425. dom.bind(_this2.__input, 'keydown', function (e) {
  35426. if (e.keyCode === 13) {
  35427. onBlur.call(this);
  35428. }
  35429. });
  35430. dom.bind(_this2.__input, 'blur', onBlur);
  35431. dom.bind(_this2.__selector, 'mousedown', function () {
  35432. dom.addClass(this, 'drag').bind(window, 'mouseup', function () {
  35433. dom.removeClass(_this.__selector, 'drag');
  35434. });
  35435. });
  35436. dom.bind(_this2.__selector, 'touchstart', function () {
  35437. dom.addClass(this, 'drag').bind(window, 'touchend', function () {
  35438. dom.removeClass(_this.__selector, 'drag');
  35439. });
  35440. });
  35441. var valueField = document.createElement('div');
  35442. Common.extend(_this2.__selector.style, {
  35443. width: '122px',
  35444. height: '102px',
  35445. padding: '3px',
  35446. backgroundColor: '#222',
  35447. boxShadow: '0px 1px 3px rgba(0,0,0,0.3)'
  35448. });
  35449. Common.extend(_this2.__field_knob.style, {
  35450. position: 'absolute',
  35451. width: '12px',
  35452. height: '12px',
  35453. border: _this2.__field_knob_border + (_this2.__color.v < 0.5 ? '#fff' : '#000'),
  35454. boxShadow: '0px 1px 3px rgba(0,0,0,0.5)',
  35455. borderRadius: '12px',
  35456. zIndex: 1
  35457. });
  35458. Common.extend(_this2.__hue_knob.style, {
  35459. position: 'absolute',
  35460. width: '15px',
  35461. height: '2px',
  35462. borderRight: '4px solid #fff',
  35463. zIndex: 1
  35464. });
  35465. Common.extend(_this2.__saturation_field.style, {
  35466. width: '100px',
  35467. height: '100px',
  35468. border: '1px solid #555',
  35469. marginRight: '3px',
  35470. display: 'inline-block',
  35471. cursor: 'pointer'
  35472. });
  35473. Common.extend(valueField.style, {
  35474. width: '100%',
  35475. height: '100%',
  35476. background: 'none'
  35477. });
  35478. linearGradient(valueField, 'top', 'rgba(0,0,0,0)', '#000');
  35479. Common.extend(_this2.__hue_field.style, {
  35480. width: '15px',
  35481. height: '100px',
  35482. border: '1px solid #555',
  35483. cursor: 'ns-resize',
  35484. position: 'absolute',
  35485. top: '3px',
  35486. right: '3px'
  35487. });
  35488. hueGradient(_this2.__hue_field);
  35489. Common.extend(_this2.__input.style, {
  35490. outline: 'none',
  35491. textAlign: 'center',
  35492. color: '#fff',
  35493. border: 0,
  35494. fontWeight: 'bold',
  35495. textShadow: _this2.__input_textShadow + 'rgba(0,0,0,0.7)'
  35496. });
  35497. dom.bind(_this2.__saturation_field, 'mousedown', fieldDown);
  35498. dom.bind(_this2.__saturation_field, 'touchstart', fieldDown);
  35499. dom.bind(_this2.__field_knob, 'mousedown', fieldDown);
  35500. dom.bind(_this2.__field_knob, 'touchstart', fieldDown);
  35501. dom.bind(_this2.__hue_field, 'mousedown', fieldDownH);
  35502. dom.bind(_this2.__hue_field, 'touchstart', fieldDownH);
  35503. function fieldDown(e) {
  35504. setSV(e);
  35505. dom.bind(window, 'mousemove', setSV);
  35506. dom.bind(window, 'touchmove', setSV);
  35507. dom.bind(window, 'mouseup', fieldUpSV);
  35508. dom.bind(window, 'touchend', fieldUpSV);
  35509. }
  35510. function fieldDownH(e) {
  35511. setH(e);
  35512. dom.bind(window, 'mousemove', setH);
  35513. dom.bind(window, 'touchmove', setH);
  35514. dom.bind(window, 'mouseup', fieldUpH);
  35515. dom.bind(window, 'touchend', fieldUpH);
  35516. }
  35517. function fieldUpSV() {
  35518. dom.unbind(window, 'mousemove', setSV);
  35519. dom.unbind(window, 'touchmove', setSV);
  35520. dom.unbind(window, 'mouseup', fieldUpSV);
  35521. dom.unbind(window, 'touchend', fieldUpSV);
  35522. onFinish();
  35523. }
  35524. function fieldUpH() {
  35525. dom.unbind(window, 'mousemove', setH);
  35526. dom.unbind(window, 'touchmove', setH);
  35527. dom.unbind(window, 'mouseup', fieldUpH);
  35528. dom.unbind(window, 'touchend', fieldUpH);
  35529. onFinish();
  35530. }
  35531. function onBlur() {
  35532. var i = interpret(this.value);
  35533. if (i !== false) {
  35534. _this.__color.__state = i;
  35535. _this.setValue(_this.__color.toOriginal());
  35536. } else {
  35537. this.value = _this.__color.toString();
  35538. }
  35539. }
  35540. function onFinish() {
  35541. if (_this.__onFinishChange) {
  35542. _this.__onFinishChange.call(_this, _this.__color.toOriginal());
  35543. }
  35544. }
  35545. _this2.__saturation_field.appendChild(valueField);
  35546. _this2.__selector.appendChild(_this2.__field_knob);
  35547. _this2.__selector.appendChild(_this2.__saturation_field);
  35548. _this2.__selector.appendChild(_this2.__hue_field);
  35549. _this2.__hue_field.appendChild(_this2.__hue_knob);
  35550. _this2.domElement.appendChild(_this2.__input);
  35551. _this2.domElement.appendChild(_this2.__selector);
  35552. _this2.updateDisplay();
  35553. function setSV(e) {
  35554. if (e.type.indexOf('touch') === -1) {
  35555. e.preventDefault();
  35556. }
  35557. var fieldRect = _this.__saturation_field.getBoundingClientRect();
  35558. var _ref = e.touches && e.touches[0] || e,
  35559. clientX = _ref.clientX,
  35560. clientY = _ref.clientY;
  35561. var s = (clientX - fieldRect.left) / (fieldRect.right - fieldRect.left);
  35562. var v = 1 - (clientY - fieldRect.top) / (fieldRect.bottom - fieldRect.top);
  35563. if (v > 1) {
  35564. v = 1;
  35565. } else if (v < 0) {
  35566. v = 0;
  35567. }
  35568. if (s > 1) {
  35569. s = 1;
  35570. } else if (s < 0) {
  35571. s = 0;
  35572. }
  35573. _this.__color.v = v;
  35574. _this.__color.s = s;
  35575. _this.setValue(_this.__color.toOriginal());
  35576. return false;
  35577. }
  35578. function setH(e) {
  35579. if (e.type.indexOf('touch') === -1) {
  35580. e.preventDefault();
  35581. }
  35582. var fieldRect = _this.__hue_field.getBoundingClientRect();
  35583. var _ref2 = e.touches && e.touches[0] || e,
  35584. clientY = _ref2.clientY;
  35585. var h = 1 - (clientY - fieldRect.top) / (fieldRect.bottom - fieldRect.top);
  35586. if (h > 1) {
  35587. h = 1;
  35588. } else if (h < 0) {
  35589. h = 0;
  35590. }
  35591. _this.__color.h = h * 360;
  35592. _this.setValue(_this.__color.toOriginal());
  35593. return false;
  35594. }
  35595. return _this2;
  35596. }
  35597. createClass(ColorController, [{
  35598. key: 'updateDisplay',
  35599. value: function updateDisplay() {
  35600. var i = interpret(this.getValue());
  35601. if (i !== false) {
  35602. var mismatch = false;
  35603. Common.each(Color.COMPONENTS, function (component) {
  35604. if (!Common.isUndefined(i[component]) && !Common.isUndefined(this.__color.__state[component]) && i[component] !== this.__color.__state[component]) {
  35605. mismatch = true;
  35606. return {};
  35607. }
  35608. }, this);
  35609. if (mismatch) {
  35610. Common.extend(this.__color.__state, i);
  35611. }
  35612. }
  35613. Common.extend(this.__temp.__state, this.__color.__state);
  35614. this.__temp.a = 1;
  35615. var flip = this.__color.v < 0.5 || this.__color.s > 0.5 ? 255 : 0;
  35616. var _flip = 255 - flip;
  35617. Common.extend(this.__field_knob.style, {
  35618. marginLeft: 100 * this.__color.s - 7 + 'px',
  35619. marginTop: 100 * (1 - this.__color.v) - 7 + 'px',
  35620. backgroundColor: this.__temp.toHexString(),
  35621. border: this.__field_knob_border + 'rgb(' + flip + ',' + flip + ',' + flip + ')'
  35622. });
  35623. this.__hue_knob.style.marginTop = (1 - this.__color.h / 360) * 100 + 'px';
  35624. this.__temp.s = 1;
  35625. this.__temp.v = 1;
  35626. linearGradient(this.__saturation_field, 'left', '#fff', this.__temp.toHexString());
  35627. this.__input.value = this.__color.toString();
  35628. Common.extend(this.__input.style, {
  35629. backgroundColor: this.__color.toHexString(),
  35630. color: 'rgb(' + flip + ',' + flip + ',' + flip + ')',
  35631. textShadow: this.__input_textShadow + 'rgba(' + _flip + ',' + _flip + ',' + _flip + ',.7)'
  35632. });
  35633. }
  35634. }]);
  35635. return ColorController;
  35636. }(Controller);
  35637. var vendors = ['-moz-', '-o-', '-webkit-', '-ms-', ''];
  35638. function linearGradient(elem, x, a, b) {
  35639. elem.style.background = '';
  35640. Common.each(vendors, function (vendor) {
  35641. elem.style.cssText += 'background: ' + vendor + 'linear-gradient(' + x + ', ' + a + ' 0%, ' + b + ' 100%); ';
  35642. });
  35643. }
  35644. function hueGradient(elem) {
  35645. elem.style.background = '';
  35646. elem.style.cssText += 'background: -moz-linear-gradient(top, #ff0000 0%, #ff00ff 17%, #0000ff 34%, #00ffff 50%, #00ff00 67%, #ffff00 84%, #ff0000 100%);';
  35647. elem.style.cssText += 'background: -webkit-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  35648. elem.style.cssText += 'background: -o-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  35649. elem.style.cssText += 'background: -ms-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  35650. elem.style.cssText += 'background: linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  35651. }
  35652. var css = {
  35653. load: function load(url, indoc) {
  35654. var doc = indoc || document;
  35655. var link = doc.createElement('link');
  35656. link.type = 'text/css';
  35657. link.rel = 'stylesheet';
  35658. link.href = url;
  35659. doc.getElementsByTagName('head')[0].appendChild(link);
  35660. },
  35661. inject: function inject(cssContent, indoc) {
  35662. var doc = indoc || document;
  35663. var injected = document.createElement('style');
  35664. injected.type = 'text/css';
  35665. injected.innerHTML = cssContent;
  35666. var head = doc.getElementsByTagName('head')[0];
  35667. try {
  35668. head.appendChild(injected);
  35669. } catch (e) {}
  35670. }
  35671. };
  35672. 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>";
  35673. var ControllerFactory = function ControllerFactory(object, property) {
  35674. var initialValue = object[property];
  35675. if (Common.isArray(arguments[2]) || Common.isObject(arguments[2])) {
  35676. return new OptionController(object, property, arguments[2]);
  35677. }
  35678. if (Common.isNumber(initialValue)) {
  35679. if (Common.isNumber(arguments[2]) && Common.isNumber(arguments[3])) {
  35680. if (Common.isNumber(arguments[4])) {
  35681. return new NumberControllerSlider(object, property, arguments[2], arguments[3], arguments[4]);
  35682. }
  35683. return new NumberControllerSlider(object, property, arguments[2], arguments[3]);
  35684. }
  35685. if (Common.isNumber(arguments[4])) {
  35686. return new NumberControllerBox(object, property, {
  35687. min: arguments[2],
  35688. max: arguments[3],
  35689. step: arguments[4]
  35690. });
  35691. }
  35692. return new NumberControllerBox(object, property, {
  35693. min: arguments[2],
  35694. max: arguments[3]
  35695. });
  35696. }
  35697. if (Common.isString(initialValue)) {
  35698. return new StringController(object, property);
  35699. }
  35700. if (Common.isFunction(initialValue)) {
  35701. return new FunctionController(object, property, '');
  35702. }
  35703. if (Common.isBoolean(initialValue)) {
  35704. return new BooleanController(object, property);
  35705. }
  35706. return null;
  35707. };
  35708. function requestAnimationFrame(callback) {
  35709. setTimeout(callback, 1000 / 60);
  35710. }
  35711. var requestAnimationFrame$1 = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || requestAnimationFrame;
  35712. var CenteredDiv = function () {
  35713. function CenteredDiv() {
  35714. classCallCheck(this, CenteredDiv);
  35715. this.backgroundElement = document.createElement('div');
  35716. Common.extend(this.backgroundElement.style, {
  35717. backgroundColor: 'rgba(0,0,0,0.8)',
  35718. top: 0,
  35719. left: 0,
  35720. display: 'none',
  35721. zIndex: '1000',
  35722. opacity: 0,
  35723. WebkitTransition: 'opacity 0.2s linear',
  35724. transition: 'opacity 0.2s linear'
  35725. });
  35726. dom.makeFullscreen(this.backgroundElement);
  35727. this.backgroundElement.style.position = 'fixed';
  35728. this.domElement = document.createElement('div');
  35729. Common.extend(this.domElement.style, {
  35730. position: 'fixed',
  35731. display: 'none',
  35732. zIndex: '1001',
  35733. opacity: 0,
  35734. WebkitTransition: '-webkit-transform 0.2s ease-out, opacity 0.2s linear',
  35735. transition: 'transform 0.2s ease-out, opacity 0.2s linear'
  35736. });
  35737. document.body.appendChild(this.backgroundElement);
  35738. document.body.appendChild(this.domElement);
  35739. var _this = this;
  35740. dom.bind(this.backgroundElement, 'click', function () {
  35741. _this.hide();
  35742. });
  35743. }
  35744. createClass(CenteredDiv, [{
  35745. key: 'show',
  35746. value: function show() {
  35747. var _this = this;
  35748. this.backgroundElement.style.display = 'block';
  35749. this.domElement.style.display = 'block';
  35750. this.domElement.style.opacity = 0;
  35751. this.domElement.style.webkitTransform = 'scale(1.1)';
  35752. this.layout();
  35753. Common.defer(function () {
  35754. _this.backgroundElement.style.opacity = 1;
  35755. _this.domElement.style.opacity = 1;
  35756. _this.domElement.style.webkitTransform = 'scale(1)';
  35757. });
  35758. }
  35759. }, {
  35760. key: 'hide',
  35761. value: function hide() {
  35762. var _this = this;
  35763. var hide = function hide() {
  35764. _this.domElement.style.display = 'none';
  35765. _this.backgroundElement.style.display = 'none';
  35766. dom.unbind(_this.domElement, 'webkitTransitionEnd', hide);
  35767. dom.unbind(_this.domElement, 'transitionend', hide);
  35768. dom.unbind(_this.domElement, 'oTransitionEnd', hide);
  35769. };
  35770. dom.bind(this.domElement, 'webkitTransitionEnd', hide);
  35771. dom.bind(this.domElement, 'transitionend', hide);
  35772. dom.bind(this.domElement, 'oTransitionEnd', hide);
  35773. this.backgroundElement.style.opacity = 0;
  35774. this.domElement.style.opacity = 0;
  35775. this.domElement.style.webkitTransform = 'scale(1.1)';
  35776. }
  35777. }, {
  35778. key: 'layout',
  35779. value: function layout() {
  35780. this.domElement.style.left = window.innerWidth / 2 - dom.getWidth(this.domElement) / 2 + 'px';
  35781. this.domElement.style.top = window.innerHeight / 2 - dom.getHeight(this.domElement) / 2 + 'px';
  35782. }
  35783. }]);
  35784. return CenteredDiv;
  35785. }();
  35786. 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");
  35787. css.inject(styleSheet);
  35788. var CSS_NAMESPACE = 'dg';
  35789. var HIDE_KEY_CODE = 72;
  35790. var CLOSE_BUTTON_HEIGHT = 20;
  35791. var DEFAULT_DEFAULT_PRESET_NAME = 'Default';
  35792. var SUPPORTS_LOCAL_STORAGE = function () {
  35793. try {
  35794. return !!window.localStorage;
  35795. } catch (e) {
  35796. return false;
  35797. }
  35798. }();
  35799. var SAVE_DIALOGUE = void 0;
  35800. var autoPlaceVirgin = true;
  35801. var autoPlaceContainer = void 0;
  35802. var hide = false;
  35803. var hideableGuis = [];
  35804. var GUI = function GUI(pars) {
  35805. var _this = this;
  35806. var params = pars || {};
  35807. this.domElement = document.createElement('div');
  35808. this.__ul = document.createElement('ul');
  35809. this.domElement.appendChild(this.__ul);
  35810. dom.addClass(this.domElement, CSS_NAMESPACE);
  35811. this.__folders = {};
  35812. this.__controllers = [];
  35813. this.__rememberedObjects = [];
  35814. this.__rememberedObjectIndecesToControllers = [];
  35815. this.__listening = [];
  35816. params = Common.defaults(params, {
  35817. closeOnTop: false,
  35818. autoPlace: true,
  35819. width: GUI.DEFAULT_WIDTH
  35820. });
  35821. params = Common.defaults(params, {
  35822. resizable: params.autoPlace,
  35823. hideable: params.autoPlace
  35824. });
  35825. if (!Common.isUndefined(params.load)) {
  35826. if (params.preset) {
  35827. params.load.preset = params.preset;
  35828. }
  35829. } else {
  35830. params.load = {
  35831. preset: DEFAULT_DEFAULT_PRESET_NAME
  35832. };
  35833. }
  35834. if (Common.isUndefined(params.parent) && params.hideable) {
  35835. hideableGuis.push(this);
  35836. }
  35837. params.resizable = Common.isUndefined(params.parent) && params.resizable;
  35838. if (params.autoPlace && Common.isUndefined(params.scrollable)) {
  35839. params.scrollable = true;
  35840. }
  35841. var useLocalStorage = SUPPORTS_LOCAL_STORAGE && localStorage.getItem(getLocalStorageHash(this, 'isLocal')) === 'true';
  35842. var saveToLocalStorage = void 0;
  35843. var titleRow = void 0;
  35844. Object.defineProperties(this, {
  35845. parent: {
  35846. get: function get$$1() {
  35847. return params.parent;
  35848. }
  35849. },
  35850. scrollable: {
  35851. get: function get$$1() {
  35852. return params.scrollable;
  35853. }
  35854. },
  35855. autoPlace: {
  35856. get: function get$$1() {
  35857. return params.autoPlace;
  35858. }
  35859. },
  35860. closeOnTop: {
  35861. get: function get$$1() {
  35862. return params.closeOnTop;
  35863. }
  35864. },
  35865. preset: {
  35866. get: function get$$1() {
  35867. if (_this.parent) {
  35868. return _this.getRoot().preset;
  35869. }
  35870. return params.load.preset;
  35871. },
  35872. set: function set$$1(v) {
  35873. if (_this.parent) {
  35874. _this.getRoot().preset = v;
  35875. } else {
  35876. params.load.preset = v;
  35877. }
  35878. setPresetSelectIndex(this);
  35879. _this.revert();
  35880. }
  35881. },
  35882. width: {
  35883. get: function get$$1() {
  35884. return params.width;
  35885. },
  35886. set: function set$$1(v) {
  35887. params.width = v;
  35888. setWidth(_this, v);
  35889. }
  35890. },
  35891. name: {
  35892. get: function get$$1() {
  35893. return params.name;
  35894. },
  35895. set: function set$$1(v) {
  35896. params.name = v;
  35897. if (titleRow) {
  35898. titleRow.innerHTML = params.name;
  35899. }
  35900. }
  35901. },
  35902. closed: {
  35903. get: function get$$1() {
  35904. return params.closed;
  35905. },
  35906. set: function set$$1(v) {
  35907. params.closed = v;
  35908. if (params.closed) {
  35909. dom.addClass(_this.__ul, GUI.CLASS_CLOSED);
  35910. } else {
  35911. dom.removeClass(_this.__ul, GUI.CLASS_CLOSED);
  35912. }
  35913. this.onResize();
  35914. if (_this.__closeButton) {
  35915. _this.__closeButton.innerHTML = v ? GUI.TEXT_OPEN : GUI.TEXT_CLOSED;
  35916. }
  35917. }
  35918. },
  35919. load: {
  35920. get: function get$$1() {
  35921. return params.load;
  35922. }
  35923. },
  35924. useLocalStorage: {
  35925. get: function get$$1() {
  35926. return useLocalStorage;
  35927. },
  35928. set: function set$$1(bool) {
  35929. if (SUPPORTS_LOCAL_STORAGE) {
  35930. useLocalStorage = bool;
  35931. if (bool) {
  35932. dom.bind(window, 'unload', saveToLocalStorage);
  35933. } else {
  35934. dom.unbind(window, 'unload', saveToLocalStorage);
  35935. }
  35936. localStorage.setItem(getLocalStorageHash(_this, 'isLocal'), bool);
  35937. }
  35938. }
  35939. }
  35940. });
  35941. if (Common.isUndefined(params.parent)) {
  35942. this.closed = params.closed || false;
  35943. dom.addClass(this.domElement, GUI.CLASS_MAIN);
  35944. dom.makeSelectable(this.domElement, false);
  35945. if (SUPPORTS_LOCAL_STORAGE) {
  35946. if (useLocalStorage) {
  35947. _this.useLocalStorage = true;
  35948. var savedGui = localStorage.getItem(getLocalStorageHash(this, 'gui'));
  35949. if (savedGui) {
  35950. params.load = JSON.parse(savedGui);
  35951. }
  35952. }
  35953. }
  35954. this.__closeButton = document.createElement('div');
  35955. this.__closeButton.innerHTML = GUI.TEXT_CLOSED;
  35956. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BUTTON);
  35957. if (params.closeOnTop) {
  35958. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_TOP);
  35959. this.domElement.insertBefore(this.__closeButton, this.domElement.childNodes[0]);
  35960. } else {
  35961. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BOTTOM);
  35962. this.domElement.appendChild(this.__closeButton);
  35963. }
  35964. dom.bind(this.__closeButton, 'click', function () {
  35965. _this.closed = !_this.closed;
  35966. });
  35967. } else {
  35968. if (params.closed === undefined) {
  35969. params.closed = true;
  35970. }
  35971. var titleRowName = document.createTextNode(params.name);
  35972. dom.addClass(titleRowName, 'controller-name');
  35973. titleRow = addRow(_this, titleRowName);
  35974. var onClickTitle = function onClickTitle(e) {
  35975. e.preventDefault();
  35976. _this.closed = !_this.closed;
  35977. return false;
  35978. };
  35979. dom.addClass(this.__ul, GUI.CLASS_CLOSED);
  35980. dom.addClass(titleRow, 'title');
  35981. dom.bind(titleRow, 'click', onClickTitle);
  35982. if (!params.closed) {
  35983. this.closed = false;
  35984. }
  35985. }
  35986. if (params.autoPlace) {
  35987. if (Common.isUndefined(params.parent)) {
  35988. if (autoPlaceVirgin) {
  35989. autoPlaceContainer = document.createElement('div');
  35990. dom.addClass(autoPlaceContainer, CSS_NAMESPACE);
  35991. dom.addClass(autoPlaceContainer, GUI.CLASS_AUTO_PLACE_CONTAINER);
  35992. document.body.appendChild(autoPlaceContainer);
  35993. autoPlaceVirgin = false;
  35994. }
  35995. autoPlaceContainer.appendChild(this.domElement);
  35996. dom.addClass(this.domElement, GUI.CLASS_AUTO_PLACE);
  35997. }
  35998. if (!this.parent) {
  35999. setWidth(_this, params.width);
  36000. }
  36001. }
  36002. this.__resizeHandler = function () {
  36003. _this.onResizeDebounced();
  36004. };
  36005. dom.bind(window, 'resize', this.__resizeHandler);
  36006. dom.bind(this.__ul, 'webkitTransitionEnd', this.__resizeHandler);
  36007. dom.bind(this.__ul, 'transitionend', this.__resizeHandler);
  36008. dom.bind(this.__ul, 'oTransitionEnd', this.__resizeHandler);
  36009. this.onResize();
  36010. if (params.resizable) {
  36011. addResizeHandle(this);
  36012. }
  36013. saveToLocalStorage = function saveToLocalStorage() {
  36014. if (SUPPORTS_LOCAL_STORAGE && localStorage.getItem(getLocalStorageHash(_this, 'isLocal')) === 'true') {
  36015. localStorage.setItem(getLocalStorageHash(_this, 'gui'), JSON.stringify(_this.getSaveObject()));
  36016. }
  36017. };
  36018. this.saveToLocalStorageIfPossible = saveToLocalStorage;
  36019. function resetWidth() {
  36020. var root = _this.getRoot();
  36021. root.width += 1;
  36022. Common.defer(function () {
  36023. root.width -= 1;
  36024. });
  36025. }
  36026. if (!params.parent) {
  36027. resetWidth();
  36028. }
  36029. };
  36030. GUI.toggleHide = function () {
  36031. hide = !hide;
  36032. Common.each(hideableGuis, function (gui) {
  36033. gui.domElement.style.display = hide ? 'none' : '';
  36034. });
  36035. };
  36036. GUI.CLASS_AUTO_PLACE = 'a';
  36037. GUI.CLASS_AUTO_PLACE_CONTAINER = 'ac';
  36038. GUI.CLASS_MAIN = 'main';
  36039. GUI.CLASS_CONTROLLER_ROW = 'cr';
  36040. GUI.CLASS_TOO_TALL = 'taller-than-window';
  36041. GUI.CLASS_CLOSED = 'closed';
  36042. GUI.CLASS_CLOSE_BUTTON = 'close-button';
  36043. GUI.CLASS_CLOSE_TOP = 'close-top';
  36044. GUI.CLASS_CLOSE_BOTTOM = 'close-bottom';
  36045. GUI.CLASS_DRAG = 'drag';
  36046. GUI.DEFAULT_WIDTH = 245;
  36047. GUI.TEXT_CLOSED = 'Close Controls';
  36048. GUI.TEXT_OPEN = 'Open Controls';
  36049. GUI._keydownHandler = function (e) {
  36050. if (document.activeElement.type !== 'text' && (e.which === HIDE_KEY_CODE || e.keyCode === HIDE_KEY_CODE)) {
  36051. GUI.toggleHide();
  36052. }
  36053. };
  36054. dom.bind(window, 'keydown', GUI._keydownHandler, false);
  36055. Common.extend(GUI.prototype, {
  36056. add: function add(object, property) {
  36057. return _add(this, object, property, {
  36058. factoryArgs: Array.prototype.slice.call(arguments, 2)
  36059. });
  36060. },
  36061. addColor: function addColor(object, property) {
  36062. return _add(this, object, property, {
  36063. color: true
  36064. });
  36065. },
  36066. remove: function remove(controller) {
  36067. this.__ul.removeChild(controller.__li);
  36068. this.__controllers.splice(this.__controllers.indexOf(controller), 1);
  36069. var _this = this;
  36070. Common.defer(function () {
  36071. _this.onResize();
  36072. });
  36073. },
  36074. destroy: function destroy() {
  36075. if (this.parent) {
  36076. throw new Error('Only the root GUI should be removed with .destroy(). ' + 'For subfolders, use gui.removeFolder(folder) instead.');
  36077. }
  36078. if (this.autoPlace) {
  36079. autoPlaceContainer.removeChild(this.domElement);
  36080. }
  36081. var _this = this;
  36082. Common.each(this.__folders, function (subfolder) {
  36083. _this.removeFolder(subfolder);
  36084. });
  36085. dom.unbind(window, 'keydown', GUI._keydownHandler, false);
  36086. removeListeners(this);
  36087. },
  36088. addFolder: function addFolder(name) {
  36089. if (this.__folders[name] !== undefined) {
  36090. throw new Error('You already have a folder in this GUI by the' + ' name "' + name + '"');
  36091. }
  36092. var newGuiParams = {
  36093. name: name,
  36094. parent: this
  36095. };
  36096. newGuiParams.autoPlace = this.autoPlace;
  36097. if (this.load && this.load.folders && this.load.folders[name]) {
  36098. newGuiParams.closed = this.load.folders[name].closed;
  36099. newGuiParams.load = this.load.folders[name];
  36100. }
  36101. var gui = new GUI(newGuiParams);
  36102. this.__folders[name] = gui;
  36103. var li = addRow(this, gui.domElement);
  36104. dom.addClass(li, 'folder');
  36105. return gui;
  36106. },
  36107. removeFolder: function removeFolder(folder) {
  36108. this.__ul.removeChild(folder.domElement.parentElement);
  36109. delete this.__folders[folder.name];
  36110. if (this.load && this.load.folders && this.load.folders[folder.name]) {
  36111. delete this.load.folders[folder.name];
  36112. }
  36113. removeListeners(folder);
  36114. var _this = this;
  36115. Common.each(folder.__folders, function (subfolder) {
  36116. folder.removeFolder(subfolder);
  36117. });
  36118. Common.defer(function () {
  36119. _this.onResize();
  36120. });
  36121. },
  36122. open: function open() {
  36123. this.closed = false;
  36124. },
  36125. close: function close() {
  36126. this.closed = true;
  36127. },
  36128. hide: function hide() {
  36129. this.domElement.style.display = 'none';
  36130. },
  36131. show: function show() {
  36132. this.domElement.style.display = '';
  36133. },
  36134. onResize: function onResize() {
  36135. var root = this.getRoot();
  36136. if (root.scrollable) {
  36137. var top = dom.getOffset(root.__ul).top;
  36138. var h = 0;
  36139. Common.each(root.__ul.childNodes, function (node) {
  36140. if (!(root.autoPlace && node === root.__save_row)) {
  36141. h += dom.getHeight(node);
  36142. }
  36143. });
  36144. if (window.innerHeight - top - CLOSE_BUTTON_HEIGHT < h) {
  36145. dom.addClass(root.domElement, GUI.CLASS_TOO_TALL);
  36146. root.__ul.style.height = window.innerHeight - top - CLOSE_BUTTON_HEIGHT + 'px';
  36147. } else {
  36148. dom.removeClass(root.domElement, GUI.CLASS_TOO_TALL);
  36149. root.__ul.style.height = 'auto';
  36150. }
  36151. }
  36152. if (root.__resize_handle) {
  36153. Common.defer(function () {
  36154. root.__resize_handle.style.height = root.__ul.offsetHeight + 'px';
  36155. });
  36156. }
  36157. if (root.__closeButton) {
  36158. root.__closeButton.style.width = root.width + 'px';
  36159. }
  36160. },
  36161. onResizeDebounced: Common.debounce(function () {
  36162. this.onResize();
  36163. }, 50),
  36164. remember: function remember() {
  36165. if (Common.isUndefined(SAVE_DIALOGUE)) {
  36166. SAVE_DIALOGUE = new CenteredDiv();
  36167. SAVE_DIALOGUE.domElement.innerHTML = saveDialogContents;
  36168. }
  36169. if (this.parent) {
  36170. throw new Error('You can only call remember on a top level GUI.');
  36171. }
  36172. var _this = this;
  36173. Common.each(Array.prototype.slice.call(arguments), function (object) {
  36174. if (_this.__rememberedObjects.length === 0) {
  36175. addSaveMenu(_this);
  36176. }
  36177. if (_this.__rememberedObjects.indexOf(object) === -1) {
  36178. _this.__rememberedObjects.push(object);
  36179. }
  36180. });
  36181. if (this.autoPlace) {
  36182. setWidth(this, this.width);
  36183. }
  36184. },
  36185. getRoot: function getRoot() {
  36186. var gui = this;
  36187. while (gui.parent) {
  36188. gui = gui.parent;
  36189. }
  36190. return gui;
  36191. },
  36192. getSaveObject: function getSaveObject() {
  36193. var toReturn = this.load;
  36194. toReturn.closed = this.closed;
  36195. if (this.__rememberedObjects.length > 0) {
  36196. toReturn.preset = this.preset;
  36197. if (!toReturn.remembered) {
  36198. toReturn.remembered = {};
  36199. }
  36200. toReturn.remembered[this.preset] = getCurrentPreset(this);
  36201. }
  36202. toReturn.folders = {};
  36203. Common.each(this.__folders, function (element, key) {
  36204. toReturn.folders[key] = element.getSaveObject();
  36205. });
  36206. return toReturn;
  36207. },
  36208. save: function save() {
  36209. if (!this.load.remembered) {
  36210. this.load.remembered = {};
  36211. }
  36212. this.load.remembered[this.preset] = getCurrentPreset(this);
  36213. markPresetModified(this, false);
  36214. this.saveToLocalStorageIfPossible();
  36215. },
  36216. saveAs: function saveAs(presetName) {
  36217. if (!this.load.remembered) {
  36218. this.load.remembered = {};
  36219. this.load.remembered[DEFAULT_DEFAULT_PRESET_NAME] = getCurrentPreset(this, true);
  36220. }
  36221. this.load.remembered[presetName] = getCurrentPreset(this);
  36222. this.preset = presetName;
  36223. addPresetOption(this, presetName, true);
  36224. this.saveToLocalStorageIfPossible();
  36225. },
  36226. revert: function revert(gui) {
  36227. Common.each(this.__controllers, function (controller) {
  36228. if (!this.getRoot().load.remembered) {
  36229. controller.setValue(controller.initialValue);
  36230. } else {
  36231. recallSavedValue(gui || this.getRoot(), controller);
  36232. }
  36233. if (controller.__onFinishChange) {
  36234. controller.__onFinishChange.call(controller, controller.getValue());
  36235. }
  36236. }, this);
  36237. Common.each(this.__folders, function (folder) {
  36238. folder.revert(folder);
  36239. });
  36240. if (!gui) {
  36241. markPresetModified(this.getRoot(), false);
  36242. }
  36243. },
  36244. listen: function listen(controller) {
  36245. var init = this.__listening.length === 0;
  36246. this.__listening.push(controller);
  36247. if (init) {
  36248. updateDisplays(this.__listening);
  36249. }
  36250. },
  36251. updateDisplay: function updateDisplay() {
  36252. Common.each(this.__controllers, function (controller) {
  36253. controller.updateDisplay();
  36254. });
  36255. Common.each(this.__folders, function (folder) {
  36256. folder.updateDisplay();
  36257. });
  36258. }
  36259. });
  36260. function addRow(gui, newDom, liBefore) {
  36261. var li = document.createElement('li');
  36262. if (newDom) {
  36263. li.appendChild(newDom);
  36264. }
  36265. if (liBefore) {
  36266. gui.__ul.insertBefore(li, liBefore);
  36267. } else {
  36268. gui.__ul.appendChild(li);
  36269. }
  36270. gui.onResize();
  36271. return li;
  36272. }
  36273. function removeListeners(gui) {
  36274. dom.unbind(window, 'resize', gui.__resizeHandler);
  36275. if (gui.saveToLocalStorageIfPossible) {
  36276. dom.unbind(window, 'unload', gui.saveToLocalStorageIfPossible);
  36277. }
  36278. }
  36279. function markPresetModified(gui, modified) {
  36280. var opt = gui.__preset_select[gui.__preset_select.selectedIndex];
  36281. if (modified) {
  36282. opt.innerHTML = opt.value + '*';
  36283. } else {
  36284. opt.innerHTML = opt.value;
  36285. }
  36286. }
  36287. function augmentController(gui, li, controller) {
  36288. controller.__li = li;
  36289. controller.__gui = gui;
  36290. Common.extend(controller, {
  36291. options: function options(_options) {
  36292. if (arguments.length > 1) {
  36293. var nextSibling = controller.__li.nextElementSibling;
  36294. controller.remove();
  36295. return _add(gui, controller.object, controller.property, {
  36296. before: nextSibling,
  36297. factoryArgs: [Common.toArray(arguments)]
  36298. });
  36299. }
  36300. if (Common.isArray(_options) || Common.isObject(_options)) {
  36301. var _nextSibling = controller.__li.nextElementSibling;
  36302. controller.remove();
  36303. return _add(gui, controller.object, controller.property, {
  36304. before: _nextSibling,
  36305. factoryArgs: [_options]
  36306. });
  36307. }
  36308. },
  36309. name: function name(_name) {
  36310. controller.__li.firstElementChild.firstElementChild.innerHTML = _name;
  36311. return controller;
  36312. },
  36313. listen: function listen() {
  36314. controller.__gui.listen(controller);
  36315. return controller;
  36316. },
  36317. remove: function remove() {
  36318. controller.__gui.remove(controller);
  36319. return controller;
  36320. }
  36321. });
  36322. if (controller instanceof NumberControllerSlider) {
  36323. var box = new NumberControllerBox(controller.object, controller.property, {
  36324. min: controller.__min,
  36325. max: controller.__max,
  36326. step: controller.__step
  36327. });
  36328. Common.each(['updateDisplay', 'onChange', 'onFinishChange', 'step', 'min', 'max'], function (method) {
  36329. var pc = controller[method];
  36330. var pb = box[method];
  36331. controller[method] = box[method] = function () {
  36332. var args = Array.prototype.slice.call(arguments);
  36333. pb.apply(box, args);
  36334. return pc.apply(controller, args);
  36335. };
  36336. });
  36337. dom.addClass(li, 'has-slider');
  36338. controller.domElement.insertBefore(box.domElement, controller.domElement.firstElementChild);
  36339. } else if (controller instanceof NumberControllerBox) {
  36340. var r = function r(returned) {
  36341. if (Common.isNumber(controller.__min) && Common.isNumber(controller.__max)) {
  36342. var oldName = controller.__li.firstElementChild.firstElementChild.innerHTML;
  36343. var wasListening = controller.__gui.__listening.indexOf(controller) > -1;
  36344. controller.remove();
  36345. var newController = _add(gui, controller.object, controller.property, {
  36346. before: controller.__li.nextElementSibling,
  36347. factoryArgs: [controller.__min, controller.__max, controller.__step]
  36348. });
  36349. newController.name(oldName);
  36350. if (wasListening) newController.listen();
  36351. return newController;
  36352. }
  36353. return returned;
  36354. };
  36355. controller.min = Common.compose(r, controller.min);
  36356. controller.max = Common.compose(r, controller.max);
  36357. } else if (controller instanceof BooleanController) {
  36358. dom.bind(li, 'click', function () {
  36359. dom.fakeEvent(controller.__checkbox, 'click');
  36360. });
  36361. dom.bind(controller.__checkbox, 'click', function (e) {
  36362. e.stopPropagation();
  36363. });
  36364. } else if (controller instanceof FunctionController) {
  36365. dom.bind(li, 'click', function () {
  36366. dom.fakeEvent(controller.__button, 'click');
  36367. });
  36368. dom.bind(li, 'mouseover', function () {
  36369. dom.addClass(controller.__button, 'hover');
  36370. });
  36371. dom.bind(li, 'mouseout', function () {
  36372. dom.removeClass(controller.__button, 'hover');
  36373. });
  36374. } else if (controller instanceof ColorController) {
  36375. dom.addClass(li, 'color');
  36376. controller.updateDisplay = Common.compose(function (val) {
  36377. li.style.borderLeftColor = controller.__color.toString();
  36378. return val;
  36379. }, controller.updateDisplay);
  36380. controller.updateDisplay();
  36381. }
  36382. controller.setValue = Common.compose(function (val) {
  36383. if (gui.getRoot().__preset_select && controller.isModified()) {
  36384. markPresetModified(gui.getRoot(), true);
  36385. }
  36386. return val;
  36387. }, controller.setValue);
  36388. }
  36389. function recallSavedValue(gui, controller) {
  36390. var root = gui.getRoot();
  36391. var matchedIndex = root.__rememberedObjects.indexOf(controller.object);
  36392. if (matchedIndex !== -1) {
  36393. var controllerMap = root.__rememberedObjectIndecesToControllers[matchedIndex];
  36394. if (controllerMap === undefined) {
  36395. controllerMap = {};
  36396. root.__rememberedObjectIndecesToControllers[matchedIndex] = controllerMap;
  36397. }
  36398. controllerMap[controller.property] = controller;
  36399. if (root.load && root.load.remembered) {
  36400. var presetMap = root.load.remembered;
  36401. var preset = void 0;
  36402. if (presetMap[gui.preset]) {
  36403. preset = presetMap[gui.preset];
  36404. } else if (presetMap[DEFAULT_DEFAULT_PRESET_NAME]) {
  36405. preset = presetMap[DEFAULT_DEFAULT_PRESET_NAME];
  36406. } else {
  36407. return;
  36408. }
  36409. if (preset[matchedIndex] && preset[matchedIndex][controller.property] !== undefined) {
  36410. var value = preset[matchedIndex][controller.property];
  36411. controller.initialValue = value;
  36412. controller.setValue(value);
  36413. }
  36414. }
  36415. }
  36416. }
  36417. function _add(gui, object, property, params) {
  36418. if (object[property] === undefined) {
  36419. throw new Error('Object "' + object + '" has no property "' + property + '"');
  36420. }
  36421. var controller = void 0;
  36422. if (params.color) {
  36423. controller = new ColorController(object, property);
  36424. } else {
  36425. var factoryArgs = [object, property].concat(params.factoryArgs);
  36426. controller = ControllerFactory.apply(gui, factoryArgs);
  36427. }
  36428. if (params.before instanceof Controller) {
  36429. params.before = params.before.__li;
  36430. }
  36431. recallSavedValue(gui, controller);
  36432. dom.addClass(controller.domElement, 'c');
  36433. var name = document.createElement('span');
  36434. dom.addClass(name, 'property-name');
  36435. name.innerHTML = controller.property;
  36436. var container = document.createElement('div');
  36437. container.appendChild(name);
  36438. container.appendChild(controller.domElement);
  36439. var li = addRow(gui, container, params.before);
  36440. dom.addClass(li, GUI.CLASS_CONTROLLER_ROW);
  36441. if (controller instanceof ColorController) {
  36442. dom.addClass(li, 'color');
  36443. } else {
  36444. dom.addClass(li, _typeof(controller.getValue()));
  36445. }
  36446. augmentController(gui, li, controller);
  36447. gui.__controllers.push(controller);
  36448. return controller;
  36449. }
  36450. function getLocalStorageHash(gui, key) {
  36451. return document.location.href + '.' + key;
  36452. }
  36453. function addPresetOption(gui, name, setSelected) {
  36454. var opt = document.createElement('option');
  36455. opt.innerHTML = name;
  36456. opt.value = name;
  36457. gui.__preset_select.appendChild(opt);
  36458. if (setSelected) {
  36459. gui.__preset_select.selectedIndex = gui.__preset_select.length - 1;
  36460. }
  36461. }
  36462. function showHideExplain(gui, explain) {
  36463. explain.style.display = gui.useLocalStorage ? 'block' : 'none';
  36464. }
  36465. function addSaveMenu(gui) {
  36466. var div = gui.__save_row = document.createElement('li');
  36467. dom.addClass(gui.domElement, 'has-save');
  36468. gui.__ul.insertBefore(div, gui.__ul.firstChild);
  36469. dom.addClass(div, 'save-row');
  36470. var gears = document.createElement('span');
  36471. gears.innerHTML = '&nbsp;';
  36472. dom.addClass(gears, 'button gears');
  36473. var button = document.createElement('span');
  36474. button.innerHTML = 'Save';
  36475. dom.addClass(button, 'button');
  36476. dom.addClass(button, 'save');
  36477. var button2 = document.createElement('span');
  36478. button2.innerHTML = 'New';
  36479. dom.addClass(button2, 'button');
  36480. dom.addClass(button2, 'save-as');
  36481. var button3 = document.createElement('span');
  36482. button3.innerHTML = 'Revert';
  36483. dom.addClass(button3, 'button');
  36484. dom.addClass(button3, 'revert');
  36485. var select = gui.__preset_select = document.createElement('select');
  36486. if (gui.load && gui.load.remembered) {
  36487. Common.each(gui.load.remembered, function (value, key) {
  36488. addPresetOption(gui, key, key === gui.preset);
  36489. });
  36490. } else {
  36491. addPresetOption(gui, DEFAULT_DEFAULT_PRESET_NAME, false);
  36492. }
  36493. dom.bind(select, 'change', function () {
  36494. for (var index = 0; index < gui.__preset_select.length; index++) {
  36495. gui.__preset_select[index].innerHTML = gui.__preset_select[index].value;
  36496. }
  36497. gui.preset = this.value;
  36498. });
  36499. div.appendChild(select);
  36500. div.appendChild(gears);
  36501. div.appendChild(button);
  36502. div.appendChild(button2);
  36503. div.appendChild(button3);
  36504. if (SUPPORTS_LOCAL_STORAGE) {
  36505. var explain = document.getElementById('dg-local-explain');
  36506. var localStorageCheckBox = document.getElementById('dg-local-storage');
  36507. var saveLocally = document.getElementById('dg-save-locally');
  36508. saveLocally.style.display = 'block';
  36509. if (localStorage.getItem(getLocalStorageHash(gui, 'isLocal')) === 'true') {
  36510. localStorageCheckBox.setAttribute('checked', 'checked');
  36511. }
  36512. showHideExplain(gui, explain);
  36513. dom.bind(localStorageCheckBox, 'change', function () {
  36514. gui.useLocalStorage = !gui.useLocalStorage;
  36515. showHideExplain(gui, explain);
  36516. });
  36517. }
  36518. var newConstructorTextArea = document.getElementById('dg-new-constructor');
  36519. dom.bind(newConstructorTextArea, 'keydown', function (e) {
  36520. if (e.metaKey && (e.which === 67 || e.keyCode === 67)) {
  36521. SAVE_DIALOGUE.hide();
  36522. }
  36523. });
  36524. dom.bind(gears, 'click', function () {
  36525. newConstructorTextArea.innerHTML = JSON.stringify(gui.getSaveObject(), undefined, 2);
  36526. SAVE_DIALOGUE.show();
  36527. newConstructorTextArea.focus();
  36528. newConstructorTextArea.select();
  36529. });
  36530. dom.bind(button, 'click', function () {
  36531. gui.save();
  36532. });
  36533. dom.bind(button2, 'click', function () {
  36534. var presetName = prompt('Enter a new preset name.');
  36535. if (presetName) {
  36536. gui.saveAs(presetName);
  36537. }
  36538. });
  36539. dom.bind(button3, 'click', function () {
  36540. gui.revert();
  36541. });
  36542. }
  36543. function addResizeHandle(gui) {
  36544. var pmouseX = void 0;
  36545. gui.__resize_handle = document.createElement('div');
  36546. Common.extend(gui.__resize_handle.style, {
  36547. width: '6px',
  36548. marginLeft: '-3px',
  36549. height: '200px',
  36550. cursor: 'ew-resize',
  36551. position: 'absolute'
  36552. });
  36553. function drag(e) {
  36554. e.preventDefault();
  36555. gui.width += pmouseX - e.clientX;
  36556. gui.onResize();
  36557. pmouseX = e.clientX;
  36558. return false;
  36559. }
  36560. function dragStop() {
  36561. dom.removeClass(gui.__closeButton, GUI.CLASS_DRAG);
  36562. dom.unbind(window, 'mousemove', drag);
  36563. dom.unbind(window, 'mouseup', dragStop);
  36564. }
  36565. function dragStart(e) {
  36566. e.preventDefault();
  36567. pmouseX = e.clientX;
  36568. dom.addClass(gui.__closeButton, GUI.CLASS_DRAG);
  36569. dom.bind(window, 'mousemove', drag);
  36570. dom.bind(window, 'mouseup', dragStop);
  36571. return false;
  36572. }
  36573. dom.bind(gui.__resize_handle, 'mousedown', dragStart);
  36574. dom.bind(gui.__closeButton, 'mousedown', dragStart);
  36575. gui.domElement.insertBefore(gui.__resize_handle, gui.domElement.firstElementChild);
  36576. }
  36577. function setWidth(gui, w) {
  36578. gui.domElement.style.width = w + 'px';
  36579. if (gui.__save_row && gui.autoPlace) {
  36580. gui.__save_row.style.width = w + 'px';
  36581. }
  36582. if (gui.__closeButton) {
  36583. gui.__closeButton.style.width = w + 'px';
  36584. }
  36585. }
  36586. function getCurrentPreset(gui, useInitialValues) {
  36587. var toReturn = {};
  36588. Common.each(gui.__rememberedObjects, function (val, index) {
  36589. var savedValues = {};
  36590. var controllerMap = gui.__rememberedObjectIndecesToControllers[index];
  36591. Common.each(controllerMap, function (controller, property) {
  36592. savedValues[property] = useInitialValues ? controller.initialValue : controller.getValue();
  36593. });
  36594. toReturn[index] = savedValues;
  36595. });
  36596. return toReturn;
  36597. }
  36598. function setPresetSelectIndex(gui) {
  36599. for (var index = 0; index < gui.__preset_select.length; index++) {
  36600. if (gui.__preset_select[index].value === gui.preset) {
  36601. gui.__preset_select.selectedIndex = index;
  36602. }
  36603. }
  36604. }
  36605. function updateDisplays(controllerArray) {
  36606. if (controllerArray.length !== 0) {
  36607. requestAnimationFrame$1.call(window, function () {
  36608. updateDisplays(controllerArray);
  36609. });
  36610. }
  36611. Common.each(controllerArray, function (c) {
  36612. c.updateDisplay();
  36613. });
  36614. }
  36615. var color = {
  36616. Color: Color,
  36617. math: ColorMath,
  36618. interpret: interpret
  36619. };
  36620. exports.color = color;
  36621. var controllers = {
  36622. Controller: Controller,
  36623. BooleanController: BooleanController,
  36624. OptionController: OptionController,
  36625. StringController: StringController,
  36626. NumberController: NumberController,
  36627. NumberControllerBox: NumberControllerBox,
  36628. NumberControllerSlider: NumberControllerSlider,
  36629. FunctionController: FunctionController,
  36630. ColorController: ColorController
  36631. };
  36632. exports.controllers = controllers;
  36633. var dom$1 = {
  36634. dom: dom
  36635. };
  36636. exports.dom = dom$1;
  36637. var gui = {
  36638. GUI: GUI
  36639. };
  36640. exports.gui = gui;
  36641. var GUI$1 = GUI;
  36642. exports.GUI = GUI$1;
  36643. var index = {
  36644. color: color,
  36645. controllers: controllers,
  36646. dom: dom$1,
  36647. gui: gui,
  36648. GUI: GUI$1
  36649. };
  36650. var _default = index;
  36651. exports.default = _default;
  36652. },{}],"../node_modules/three/examples/jsm/libs/stats.module.js":[function(require,module,exports) {
  36653. "use strict";
  36654. Object.defineProperty(exports, "__esModule", {
  36655. value: true
  36656. });
  36657. exports.default = void 0;
  36658. /**
  36659. * @author mrdoob / http://mrdoob.com/
  36660. */
  36661. var Stats = function () {
  36662. var mode = 0;
  36663. var container = document.createElement('div');
  36664. container.style.cssText = 'position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000';
  36665. container.addEventListener('click', function (event) {
  36666. event.preventDefault();
  36667. showPanel(++mode % container.children.length);
  36668. }, false); //
  36669. function addPanel(panel) {
  36670. container.appendChild(panel.dom);
  36671. return panel;
  36672. }
  36673. function showPanel(id) {
  36674. for (var i = 0; i < container.children.length; i++) {
  36675. container.children[i].style.display = i === id ? 'block' : 'none';
  36676. }
  36677. mode = id;
  36678. } //
  36679. var beginTime = (performance || Date).now(),
  36680. prevTime = beginTime,
  36681. frames = 0;
  36682. var fpsPanel = addPanel(new Stats.Panel('FPS', '#0ff', '#002'));
  36683. var msPanel = addPanel(new Stats.Panel('MS', '#0f0', '#020'));
  36684. if (self.performance && self.performance.memory) {
  36685. var memPanel = addPanel(new Stats.Panel('MB', '#f08', '#201'));
  36686. }
  36687. showPanel(0);
  36688. return {
  36689. REVISION: 16,
  36690. dom: container,
  36691. addPanel: addPanel,
  36692. showPanel: showPanel,
  36693. begin: function () {
  36694. beginTime = (performance || Date).now();
  36695. },
  36696. end: function () {
  36697. frames++;
  36698. var time = (performance || Date).now();
  36699. msPanel.update(time - beginTime, 200);
  36700. if (time >= prevTime + 1000) {
  36701. fpsPanel.update(frames * 1000 / (time - prevTime), 100);
  36702. prevTime = time;
  36703. frames = 0;
  36704. if (memPanel) {
  36705. var memory = performance.memory;
  36706. memPanel.update(memory.usedJSHeapSize / 1048576, memory.jsHeapSizeLimit / 1048576);
  36707. }
  36708. }
  36709. return time;
  36710. },
  36711. update: function () {
  36712. beginTime = this.end();
  36713. },
  36714. // Backwards Compatibility
  36715. domElement: container,
  36716. setMode: showPanel
  36717. };
  36718. };
  36719. Stats.Panel = function (name, fg, bg) {
  36720. var min = Infinity,
  36721. max = 0,
  36722. round = Math.round;
  36723. var PR = round(window.devicePixelRatio || 1);
  36724. var WIDTH = 80 * PR,
  36725. HEIGHT = 48 * PR,
  36726. TEXT_X = 3 * PR,
  36727. TEXT_Y = 2 * PR,
  36728. GRAPH_X = 3 * PR,
  36729. GRAPH_Y = 15 * PR,
  36730. GRAPH_WIDTH = 74 * PR,
  36731. GRAPH_HEIGHT = 30 * PR;
  36732. var canvas = document.createElement('canvas');
  36733. canvas.width = WIDTH;
  36734. canvas.height = HEIGHT;
  36735. canvas.style.cssText = 'width:80px;height:48px';
  36736. var context = canvas.getContext('2d');
  36737. context.font = 'bold ' + 9 * PR + 'px Helvetica,Arial,sans-serif';
  36738. context.textBaseline = 'top';
  36739. context.fillStyle = bg;
  36740. context.fillRect(0, 0, WIDTH, HEIGHT);
  36741. context.fillStyle = fg;
  36742. context.fillText(name, TEXT_X, TEXT_Y);
  36743. context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
  36744. context.fillStyle = bg;
  36745. context.globalAlpha = 0.9;
  36746. context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
  36747. return {
  36748. dom: canvas,
  36749. update: function (value, maxValue) {
  36750. min = Math.min(min, value);
  36751. max = Math.max(max, value);
  36752. context.fillStyle = bg;
  36753. context.globalAlpha = 1;
  36754. context.fillRect(0, 0, WIDTH, GRAPH_Y);
  36755. context.fillStyle = fg;
  36756. context.fillText(round(value) + ' ' + name + ' (' + round(min) + '-' + round(max) + ')', TEXT_X, TEXT_Y);
  36757. context.drawImage(canvas, GRAPH_X + PR, GRAPH_Y, GRAPH_WIDTH - PR, GRAPH_HEIGHT, GRAPH_X, GRAPH_Y, GRAPH_WIDTH - PR, GRAPH_HEIGHT);
  36758. context.fillRect(GRAPH_X + GRAPH_WIDTH - PR, GRAPH_Y, PR, GRAPH_HEIGHT);
  36759. context.fillStyle = bg;
  36760. context.globalAlpha = 0.9;
  36761. context.fillRect(GRAPH_X + GRAPH_WIDTH - PR, GRAPH_Y, PR, round((1 - value / maxValue) * GRAPH_HEIGHT));
  36762. }
  36763. };
  36764. };
  36765. var _default = Stats;
  36766. exports.default = _default;
  36767. },{}],"index.js":[function(require,module,exports) {
  36768. "use strict";
  36769. var _index = require("../src/index.js");
  36770. var _three = require("three");
  36771. var _OrbitControls = require("three/examples/jsm/controls/OrbitControls.js");
  36772. var _BufferGeometryUtils = require("three/examples/jsm/utils/BufferGeometryUtils.js");
  36773. var dat = _interopRequireWildcard(require("three/examples/jsm/libs/dat.gui.module.js"));
  36774. var _statsModule = _interopRequireDefault(require("three/examples/jsm/libs/stats.module.js"));
  36775. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  36776. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
  36777. 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; }
  36778. let camera, controls, scene, renderer, tiles, cameraHelper;
  36779. let thirdPersonCamera, thirdPersonRenderer, thirdPersonControls;
  36780. let orthoCamera, orthoCameraHelper;
  36781. let box;
  36782. let raycaster, mouse, rayIntersect;
  36783. let offsetParent;
  36784. let statsContainer, stats;
  36785. let params = {
  36786. 'orthographic': false,
  36787. 'errorTarget': 6,
  36788. 'errorThreshold': 60,
  36789. 'maxDepth': 15,
  36790. 'loadSiblings': true,
  36791. 'up': '+Y',
  36792. 'displayBoxBounds': false,
  36793. 'colorMode': 0,
  36794. 'showThirdPerson': true,
  36795. 'reload': reinstantiateTiles
  36796. };
  36797. init();
  36798. animate();
  36799. function reinstantiateTiles() {
  36800. const url = window.location.hash.replace(/^#/, '') || '../data/tileset.json';
  36801. if (tiles) {
  36802. offsetParent.remove(tiles.group);
  36803. }
  36804. tiles = new _index.DebugTilesRenderer(url);
  36805. tiles.camera = camera;
  36806. tiles.setResolutionFromRenderer(renderer);
  36807. offsetParent.add(tiles.group);
  36808. }
  36809. function init() {
  36810. // Third person camera view
  36811. thirdPersonCamera = new _three.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 3000);
  36812. thirdPersonCamera.position.set(50, 40, 40);
  36813. thirdPersonCamera.lookAt(0, 0, 0);
  36814. thirdPersonRenderer = new _three.WebGLRenderer({
  36815. antialias: true
  36816. });
  36817. thirdPersonRenderer.setPixelRatio(window.devicePixelRatio);
  36818. thirdPersonRenderer.setSize(window.innerWidth, window.innerHeight);
  36819. thirdPersonRenderer.setClearColor(0x0f1416);
  36820. document.body.appendChild(thirdPersonRenderer.domElement);
  36821. thirdPersonRenderer.domElement.style.position = 'fixed';
  36822. thirdPersonRenderer.domElement.style.left = '5px';
  36823. thirdPersonRenderer.domElement.style.bottom = '5px';
  36824. thirdPersonControls = new _OrbitControls.OrbitControls(thirdPersonCamera, thirdPersonRenderer.domElement);
  36825. thirdPersonControls.screenSpacePanning = false;
  36826. thirdPersonControls.minDistance = 1;
  36827. thirdPersonControls.maxDistance = 2000; // primary camera view
  36828. scene = new _three.Scene();
  36829. renderer = new _three.WebGLRenderer({
  36830. antialias: true
  36831. });
  36832. renderer.setPixelRatio(window.devicePixelRatio);
  36833. renderer.setSize(window.innerWidth, window.innerHeight);
  36834. renderer.setClearColor(0x151c1f);
  36835. renderer.gammaInput = true;
  36836. renderer.gameOutput = true;
  36837. document.body.appendChild(renderer.domElement);
  36838. camera = new _three.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 2000);
  36839. camera.position.set(400, 400, 400);
  36840. cameraHelper = new _three.CameraHelper(camera);
  36841. scene.add(cameraHelper);
  36842. orthoCamera = new _three.OrthographicCamera();
  36843. orthoCameraHelper = new _three.CameraHelper(orthoCamera);
  36844. scene.add(orthoCameraHelper); // controls
  36845. controls = new _OrbitControls.OrbitControls(camera, renderer.domElement);
  36846. controls.screenSpacePanning = false;
  36847. controls.minDistance = 1;
  36848. controls.maxDistance = 2000; // lights
  36849. var dirLight = new _three.DirectionalLight(0xffffff);
  36850. dirLight.position.set(1, 2, 3);
  36851. scene.add(dirLight);
  36852. var ambLight = new _three.AmbientLight(0xffffff, 0.2);
  36853. scene.add(ambLight);
  36854. box = new _three.Box3();
  36855. offsetParent = new _three.Group();
  36856. scene.add(offsetParent); // Raycasting init
  36857. raycaster = new _three.Raycaster();
  36858. mouse = new _three.Vector2();
  36859. rayIntersect = new _three.Group();
  36860. const rayIntersectMat = new _three.MeshBasicMaterial({
  36861. color: 0xe91e63
  36862. });
  36863. const rayMesh = new _three.Mesh(new _three.CylinderBufferGeometry(0.25, 0.25, 6), rayIntersectMat);
  36864. rayMesh.rotation.x = Math.PI / 2;
  36865. rayMesh.position.z += 3;
  36866. rayIntersect.add(rayMesh);
  36867. const rayRing = new _three.Mesh(new _three.TorusBufferGeometry(1.5, 0.2, 16, 100), rayIntersectMat);
  36868. rayIntersect.add(rayRing);
  36869. scene.add(rayIntersect);
  36870. rayIntersect.visible = false;
  36871. reinstantiateTiles();
  36872. onWindowResize();
  36873. window.addEventListener('resize', onWindowResize, false);
  36874. window.addEventListener('mousemove', onMouseMove, false);
  36875. window.addEventListener('mousedown', onMouseDown, false);
  36876. window.addEventListener('mouseup', onMouseUp, false); // GUI
  36877. const gui = new dat.GUI();
  36878. gui.width = 300;
  36879. const tileOptions = gui.addFolder('Tiles Options');
  36880. tileOptions.add(params, 'orthographic');
  36881. tileOptions.add(params, 'loadSiblings');
  36882. tileOptions.add(params, 'errorTarget').min(0).max(50);
  36883. tileOptions.add(params, 'errorThreshold').min(0).max(1000);
  36884. tileOptions.add(params, 'maxDepth').min(1).max(100);
  36885. tileOptions.add(params, 'up', ['+Y', '-Z']);
  36886. tileOptions.open();
  36887. const debug = gui.addFolder('Debug Options');
  36888. debug.add(params, 'displayBoxBounds');
  36889. debug.add(params, 'colorMode', {
  36890. DEFAULT: 0,
  36891. SCREEN_ERROR: 1,
  36892. GEOMETRIC_ERROR: 2,
  36893. DISTANCE: 3,
  36894. DEPTH: 4,
  36895. IS_LEAF: 5.
  36896. }).onChange(function (v) {
  36897. tiles.colorMode = parseFloat(v);
  36898. });
  36899. debug.open();
  36900. gui.add(params, 'showThirdPerson');
  36901. gui.add(params, 'reload');
  36902. gui.open();
  36903. statsContainer = document.createElement('div');
  36904. statsContainer.style.position = 'absolute';
  36905. statsContainer.style.top = 0;
  36906. statsContainer.style.left = 0;
  36907. statsContainer.style.color = 'white';
  36908. statsContainer.style.width = '100%';
  36909. statsContainer.style.textAlign = 'center';
  36910. statsContainer.style.padding = '5px';
  36911. statsContainer.style.pointerEvents = 'none';
  36912. statsContainer.style.lineHeight = '1.5em';
  36913. document.body.appendChild(statsContainer); // Stats
  36914. stats = new _statsModule.default();
  36915. stats.showPanel(0);
  36916. document.body.appendChild(stats.dom);
  36917. }
  36918. function onWindowResize() {
  36919. thirdPersonCamera.aspect = window.innerWidth / window.innerHeight;
  36920. thirdPersonCamera.updateProjectionMatrix();
  36921. thirdPersonRenderer.setSize(Math.floor(window.innerWidth / 3), Math.floor(window.innerHeight / 3));
  36922. camera.aspect = window.innerWidth / window.innerHeight;
  36923. camera.updateProjectionMatrix();
  36924. renderer.setSize(window.innerWidth, window.innerHeight);
  36925. updateOrthoCamera();
  36926. }
  36927. function onMouseMove(e) {
  36928. mouse.x = e.clientX / window.innerWidth * 2 - 1;
  36929. mouse.y = -(e.clientY / window.innerHeight) * 2 + 1;
  36930. }
  36931. const startPos = new _three.Vector2();
  36932. const endPos = new _three.Vector2();
  36933. function onMouseDown(e) {
  36934. startPos.set(e.clientX, e.clientY);
  36935. }
  36936. function onMouseUp(e) {
  36937. endPos.set(e.clientX, e.clientY);
  36938. if (startPos.distanceTo(endPos) > 2) {
  36939. return;
  36940. }
  36941. raycaster.setFromCamera(mouse, params.orthographic ? orthoCamera : camera);
  36942. raycaster.firstHitOnly = true;
  36943. const results = raycaster.intersectObject(tiles.group, true);
  36944. if (results.length) {
  36945. const object = results[0].object;
  36946. const info = tiles.getTileInformationFromActiveObject(object);
  36947. let str = '';
  36948. for (const key in info) {
  36949. let val = info[key];
  36950. if (typeof val === 'number') {
  36951. val = Math.floor(val * 1e5) / 1e5;
  36952. }
  36953. let name = key;
  36954. while (name.length < 20) {
  36955. name += ' ';
  36956. }
  36957. str += `${name} : ${val}\n`;
  36958. }
  36959. console.log(str);
  36960. }
  36961. }
  36962. function updateOrthoCamera() {
  36963. orthoCamera.position.copy(camera.position);
  36964. orthoCamera.rotation.copy(camera.rotation);
  36965. const scale = camera.position.distanceTo(controls.target) / 2.0;
  36966. const aspect = window.innerWidth / window.innerHeight;
  36967. orthoCamera.left = -aspect * scale;
  36968. orthoCamera.right = aspect * scale;
  36969. orthoCamera.bottom = -scale;
  36970. orthoCamera.top = scale;
  36971. orthoCamera.near = camera.near;
  36972. orthoCamera.far = camera.far;
  36973. orthoCamera.updateProjectionMatrix();
  36974. }
  36975. function animate() {
  36976. // update options
  36977. tiles.errorTarget = params.errorTarget;
  36978. tiles.errorThreshold = params.errorThreshold;
  36979. tiles.loadSiblings = params.loadSiblings;
  36980. tiles.maxDepth = params.maxDepth;
  36981. tiles.camera = params.orthographic ? orthoCamera : camera;
  36982. tiles.displayBoxBounds = params.displayBoxBounds;
  36983. tiles.setResolutionFromRenderer(renderer); // update tiles
  36984. tiles.update();
  36985. window.tiles = tiles;
  36986. offsetParent.rotation.set(0, 0, 0);
  36987. if (params.up === '-Z') {
  36988. offsetParent.rotation.x = Math.PI / 2;
  36989. } // update tiles center
  36990. if (tiles.getBounds(box)) {
  36991. box.getCenter(tiles.group.position);
  36992. tiles.group.position.multiplyScalar(-1);
  36993. }
  36994. raycaster.setFromCamera(mouse, params.orthographic ? orthoCamera : camera);
  36995. raycaster.firstHitOnly = true;
  36996. const results = raycaster.intersectObject(tiles.group, true);
  36997. if (results.length) {
  36998. const closestHit = results[0];
  36999. const point = closestHit.point;
  37000. rayIntersect.position.copy(point); // If the display bounds are visible they get intersected
  37001. if (closestHit.face) {
  37002. const normal = closestHit.face.normal;
  37003. normal.transformDirection(closestHit.object.matrixWorld);
  37004. rayIntersect.lookAt(point.x + normal.x, point.y + normal.y, point.z + normal.z);
  37005. }
  37006. if (params.orthographic) {
  37007. rayIntersect.scale.setScalar(closestHit.distance / 150);
  37008. } else {
  37009. rayIntersect.scale.setScalar(closestHit.distance * camera.fov / 6000);
  37010. }
  37011. rayIntersect.visible = true;
  37012. } else {
  37013. rayIntersect.visible = false;
  37014. }
  37015. stats.begin();
  37016. render();
  37017. stats.end();
  37018. requestAnimationFrame(animate);
  37019. }
  37020. function render() {
  37021. updateOrthoCamera(); // render primary view
  37022. cameraHelper.visible = false;
  37023. orthoCameraHelper.visible = false;
  37024. renderer.render(scene, params.orthographic ? orthoCamera : camera); // render third person view
  37025. thirdPersonRenderer.domElement.style.visibility = params.showThirdPerson ? 'visible' : 'hidden';
  37026. if (params.showThirdPerson) {
  37027. cameraHelper.update();
  37028. cameraHelper.visible = !params.orthographic;
  37029. orthoCameraHelper.update();
  37030. orthoCameraHelper.visible = params.orthographic;
  37031. thirdPersonRenderer.render(scene, thirdPersonCamera);
  37032. }
  37033. const geomSet = new Set();
  37034. tiles.traverse(tile => {
  37035. const scene = tile.cached.scene;
  37036. if (scene) {
  37037. scene.traverse(c => {
  37038. if (c.geometry) {
  37039. geomSet.add(c.geometry);
  37040. }
  37041. });
  37042. }
  37043. });
  37044. let count = 0;
  37045. geomSet.forEach(g => {
  37046. count += _BufferGeometryUtils.BufferGeometryUtils.estimateBytesUsed(g);
  37047. });
  37048. const cacheFullness = tiles.lruCache.itemList.length / tiles.lruCache.minSize;
  37049. statsContainer.innerHTML = `
  37050. Downloading: ${tiles.stats.downloading} Parsing: ${tiles.stats.parsing} Visible: ${tiles.group.children.length - 2}
  37051. <br/>
  37052. Cache: ${(100 * cacheFullness).toFixed(2)}% ~${(count / 1000 / 1000).toFixed(2)}mb
  37053. `;
  37054. }
  37055. },{"../src/index.js":"../src/index.js","three":"../node_modules/three/build/three.module.js","three/examples/jsm/controls/OrbitControls.js":"../node_modules/three/examples/jsm/controls/OrbitControls.js","three/examples/jsm/utils/BufferGeometryUtils.js":"../node_modules/three/examples/jsm/utils/BufferGeometryUtils.js","three/examples/jsm/libs/dat.gui.module.js":"../node_modules/three/examples/jsm/libs/dat.gui.module.js","three/examples/jsm/libs/stats.module.js":"../node_modules/three/examples/jsm/libs/stats.module.js"}],"../node_modules/parcel-bundler/src/builtins/hmr-runtime.js":[function(require,module,exports) {
  37056. var global = arguments[3];
  37057. var OVERLAY_ID = '__parcel__error__overlay__';
  37058. var OldModule = module.bundle.Module;
  37059. function Module(moduleName) {
  37060. OldModule.call(this, moduleName);
  37061. this.hot = {
  37062. data: module.bundle.hotData,
  37063. _acceptCallbacks: [],
  37064. _disposeCallbacks: [],
  37065. accept: function (fn) {
  37066. this._acceptCallbacks.push(fn || function () {});
  37067. },
  37068. dispose: function (fn) {
  37069. this._disposeCallbacks.push(fn);
  37070. }
  37071. };
  37072. module.bundle.hotData = null;
  37073. }
  37074. module.bundle.Module = Module;
  37075. var checkedAssets, assetsToAccept;
  37076. var parent = module.bundle.parent;
  37077. if ((!parent || !parent.isParcelRequire) && typeof WebSocket !== 'undefined') {
  37078. var hostname = "" || location.hostname;
  37079. var protocol = location.protocol === 'https:' ? 'wss' : 'ws';
  37080. var ws = new WebSocket(protocol + '://' + hostname + ':' + "55631" + '/');
  37081. ws.onmessage = function (event) {
  37082. checkedAssets = {};
  37083. assetsToAccept = [];
  37084. var data = JSON.parse(event.data);
  37085. if (data.type === 'update') {
  37086. var handled = false;
  37087. data.assets.forEach(function (asset) {
  37088. if (!asset.isNew) {
  37089. var didAccept = hmrAcceptCheck(global.parcelRequire, asset.id);
  37090. if (didAccept) {
  37091. handled = true;
  37092. }
  37093. }
  37094. }); // Enable HMR for CSS by default.
  37095. handled = handled || data.assets.every(function (asset) {
  37096. return asset.type === 'css' && asset.generated.js;
  37097. });
  37098. if (handled) {
  37099. console.clear();
  37100. data.assets.forEach(function (asset) {
  37101. hmrApply(global.parcelRequire, asset);
  37102. });
  37103. assetsToAccept.forEach(function (v) {
  37104. hmrAcceptRun(v[0], v[1]);
  37105. });
  37106. } else if (location.reload) {
  37107. // `location` global exists in a web worker context but lacks `.reload()` function.
  37108. location.reload();
  37109. }
  37110. }
  37111. if (data.type === 'reload') {
  37112. ws.close();
  37113. ws.onclose = function () {
  37114. location.reload();
  37115. };
  37116. }
  37117. if (data.type === 'error-resolved') {
  37118. console.log('[parcel] ✨ Error resolved');
  37119. removeErrorOverlay();
  37120. }
  37121. if (data.type === 'error') {
  37122. console.error('[parcel] 🚨 ' + data.error.message + '\n' + data.error.stack);
  37123. removeErrorOverlay();
  37124. var overlay = createErrorOverlay(data);
  37125. document.body.appendChild(overlay);
  37126. }
  37127. };
  37128. }
  37129. function removeErrorOverlay() {
  37130. var overlay = document.getElementById(OVERLAY_ID);
  37131. if (overlay) {
  37132. overlay.remove();
  37133. }
  37134. }
  37135. function createErrorOverlay(data) {
  37136. var overlay = document.createElement('div');
  37137. overlay.id = OVERLAY_ID; // html encode message and stack trace
  37138. var message = document.createElement('div');
  37139. var stackTrace = document.createElement('pre');
  37140. message.innerText = data.error.message;
  37141. stackTrace.innerText = data.error.stack;
  37142. 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>';
  37143. return overlay;
  37144. }
  37145. function getParents(bundle, id) {
  37146. var modules = bundle.modules;
  37147. if (!modules) {
  37148. return [];
  37149. }
  37150. var parents = [];
  37151. var k, d, dep;
  37152. for (k in modules) {
  37153. for (d in modules[k][1]) {
  37154. dep = modules[k][1][d];
  37155. if (dep === id || Array.isArray(dep) && dep[dep.length - 1] === id) {
  37156. parents.push(k);
  37157. }
  37158. }
  37159. }
  37160. if (bundle.parent) {
  37161. parents = parents.concat(getParents(bundle.parent, id));
  37162. }
  37163. return parents;
  37164. }
  37165. function hmrApply(bundle, asset) {
  37166. var modules = bundle.modules;
  37167. if (!modules) {
  37168. return;
  37169. }
  37170. if (modules[asset.id] || !bundle.parent) {
  37171. var fn = new Function('require', 'module', 'exports', asset.generated.js);
  37172. asset.isNew = !modules[asset.id];
  37173. modules[asset.id] = [fn, asset.deps];
  37174. } else if (bundle.parent) {
  37175. hmrApply(bundle.parent, asset);
  37176. }
  37177. }
  37178. function hmrAcceptCheck(bundle, id) {
  37179. var modules = bundle.modules;
  37180. if (!modules) {
  37181. return;
  37182. }
  37183. if (!modules[id] && bundle.parent) {
  37184. return hmrAcceptCheck(bundle.parent, id);
  37185. }
  37186. if (checkedAssets[id]) {
  37187. return;
  37188. }
  37189. checkedAssets[id] = true;
  37190. var cached = bundle.cache[id];
  37191. assetsToAccept.push([bundle, id]);
  37192. if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
  37193. return true;
  37194. }
  37195. return getParents(global.parcelRequire, id).some(function (id) {
  37196. return hmrAcceptCheck(global.parcelRequire, id);
  37197. });
  37198. }
  37199. function hmrAcceptRun(bundle, id) {
  37200. var cached = bundle.cache[id];
  37201. bundle.hotData = {};
  37202. if (cached) {
  37203. cached.hot.data = bundle.hotData;
  37204. }
  37205. if (cached && cached.hot && cached.hot._disposeCallbacks.length) {
  37206. cached.hot._disposeCallbacks.forEach(function (cb) {
  37207. cb(bundle.hotData);
  37208. });
  37209. }
  37210. delete bundle.cache[id];
  37211. bundle(id);
  37212. cached = bundle.cache[id];
  37213. if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
  37214. cached.hot._acceptCallbacks.forEach(function (cb) {
  37215. cb();
  37216. });
  37217. return true;
  37218. }
  37219. }
  37220. },{}]},{},["../node_modules/parcel-bundler/src/builtins/hmr-runtime.js","index.js"], null)
  37221. //# sourceMappingURL=example.e31bb0bc.js.map