example.e31bb0bc.js 1.6 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934
  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.AudioLoader = AudioLoader;
  114. exports.AxisHelper = AxisHelper;
  115. exports.BinaryTextureLoader = BinaryTextureLoader;
  116. exports.Bone = Bone;
  117. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  118. exports.BoundingBoxHelper = BoundingBoxHelper;
  119. exports.BufferAttribute = BufferAttribute;
  120. exports.BufferGeometry = BufferGeometry;
  121. exports.BufferGeometryLoader = BufferGeometryLoader;
  122. exports.Camera = Camera;
  123. exports.CanvasRenderer = CanvasRenderer;
  124. exports.CanvasTexture = CanvasTexture;
  125. exports.CatmullRomCurve3 = CatmullRomCurve3;
  126. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  127. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  128. exports.CompressedTexture = CompressedTexture;
  129. exports.CompressedTextureLoader = CompressedTextureLoader;
  130. exports.CubeCamera = CubeCamera;
  131. exports.CubeTexture = CubeTexture;
  132. exports.CubeTextureLoader = CubeTextureLoader;
  133. exports.CubicBezierCurve = CubicBezierCurve;
  134. exports.CubicBezierCurve3 = CubicBezierCurve3;
  135. exports.CubicInterpolant = CubicInterpolant;
  136. exports.Curve = Curve;
  137. exports.CurvePath = CurvePath;
  138. exports.DataTexture = DataTexture;
  139. exports.DataTexture2DArray = DataTexture2DArray;
  140. exports.DataTexture3D = DataTexture3D;
  141. exports.DataTextureLoader = DataTextureLoader;
  142. exports.DepthTexture = DepthTexture;
  143. exports.DirectionalLight = DirectionalLight;
  144. exports.DiscreteInterpolant = DiscreteInterpolant;
  145. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  146. exports.EdgesHelper = EdgesHelper;
  147. exports.EllipseCurve = EllipseCurve;
  148. exports.EventDispatcher = EventDispatcher;
  149. exports.Face4 = Face4;
  150. exports.FileLoader = FileLoader;
  151. exports.Float16BufferAttribute = Float16BufferAttribute;
  152. exports.Float32Attribute = Float32Attribute;
  153. exports.Float32BufferAttribute = Float32BufferAttribute;
  154. exports.Float64Attribute = Float64Attribute;
  155. exports.Float64BufferAttribute = Float64BufferAttribute;
  156. exports.Font = Font;
  157. exports.FontLoader = FontLoader;
  158. exports.GLBufferAttribute = GLBufferAttribute;
  159. exports.Geometry = Geometry;
  160. exports.Group = Group;
  161. exports.HemisphereLight = HemisphereLight;
  162. exports.HemisphereLightProbe = HemisphereLightProbe;
  163. exports.ImageBitmapLoader = ImageBitmapLoader;
  164. exports.ImageLoader = ImageLoader;
  165. exports.ImmediateRenderObject = ImmediateRenderObject;
  166. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  167. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  168. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  169. exports.InstancedMesh = InstancedMesh;
  170. exports.Int16Attribute = Int16Attribute;
  171. exports.Int16BufferAttribute = Int16BufferAttribute;
  172. exports.Int32Attribute = Int32Attribute;
  173. exports.Int32BufferAttribute = Int32BufferAttribute;
  174. exports.Int8Attribute = Int8Attribute;
  175. exports.Int8BufferAttribute = Int8BufferAttribute;
  176. exports.InterleavedBuffer = InterleavedBuffer;
  177. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  178. exports.Interpolant = Interpolant;
  179. exports.JSONLoader = JSONLoader;
  180. exports.KeyframeTrack = KeyframeTrack;
  181. exports.LOD = LOD;
  182. exports.LensFlare = LensFlare;
  183. exports.Light = Light;
  184. exports.LightProbe = LightProbe;
  185. exports.Line = Line;
  186. exports.LineBasicMaterial = LineBasicMaterial;
  187. exports.LineCurve = LineCurve;
  188. exports.LineCurve3 = LineCurve3;
  189. exports.LineDashedMaterial = LineDashedMaterial;
  190. exports.LineLoop = LineLoop;
  191. exports.LineSegments = LineSegments;
  192. exports.LinearInterpolant = LinearInterpolant;
  193. exports.Loader = Loader;
  194. exports.LoadingManager = LoadingManager;
  195. exports.Material = Material;
  196. exports.MaterialLoader = MaterialLoader;
  197. exports.Mesh = Mesh;
  198. exports.MeshBasicMaterial = MeshBasicMaterial;
  199. exports.MeshDepthMaterial = MeshDepthMaterial;
  200. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  201. exports.MeshFaceMaterial = MeshFaceMaterial;
  202. exports.MeshLambertMaterial = MeshLambertMaterial;
  203. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  204. exports.MeshNormalMaterial = MeshNormalMaterial;
  205. exports.MeshPhongMaterial = MeshPhongMaterial;
  206. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  207. exports.MeshStandardMaterial = MeshStandardMaterial;
  208. exports.MeshToonMaterial = MeshToonMaterial;
  209. exports.MultiMaterial = MultiMaterial;
  210. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  211. exports.Object3D = Object3D;
  212. exports.OrthographicCamera = OrthographicCamera;
  213. exports.ParametricBufferGeometry = ParametricBufferGeometry;
  214. exports.ParametricGeometry = ParametricGeometry;
  215. exports.Particle = Particle;
  216. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  217. exports.ParticleSystem = ParticleSystem;
  218. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  219. exports.Path = Path;
  220. exports.PerspectiveCamera = PerspectiveCamera;
  221. exports.PointCloud = PointCloud;
  222. exports.PointCloudMaterial = PointCloudMaterial;
  223. exports.PointLight = PointLight;
  224. exports.Points = Points;
  225. exports.PointsMaterial = PointsMaterial;
  226. exports.PropertyBinding = PropertyBinding;
  227. exports.PropertyMixer = PropertyMixer;
  228. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  229. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  230. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  231. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  232. exports.RawShaderMaterial = RawShaderMaterial;
  233. exports.Raycaster = Raycaster;
  234. exports.RectAreaLight = RectAreaLight;
  235. exports.ShaderMaterial = ShaderMaterial;
  236. exports.ShadowMaterial = ShadowMaterial;
  237. exports.Shape = Shape;
  238. exports.ShapePath = ShapePath;
  239. exports.Skeleton = Skeleton;
  240. exports.SkinnedMesh = SkinnedMesh;
  241. exports.Spline = Spline;
  242. exports.SplineCurve = SplineCurve;
  243. exports.SplineCurve3 = SplineCurve3;
  244. exports.SpotLight = SpotLight;
  245. exports.Sprite = Sprite;
  246. exports.SpriteMaterial = SpriteMaterial;
  247. exports.StereoCamera = StereoCamera;
  248. exports.StringKeyframeTrack = StringKeyframeTrack;
  249. exports.Texture = Texture;
  250. exports.TextureLoader = TextureLoader;
  251. exports.Uint16Attribute = Uint16Attribute;
  252. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  253. exports.Uint32Attribute = Uint32Attribute;
  254. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  255. exports.Uint8Attribute = Uint8Attribute;
  256. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  257. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  258. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  259. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  260. exports.Vertex = Vertex;
  261. exports.VideoTexture = VideoTexture;
  262. exports.WebGL1Renderer = WebGL1Renderer;
  263. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  264. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  265. exports.WebGLRenderTarget = WebGLRenderTarget;
  266. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  267. exports.WebGLRenderer = WebGLRenderer;
  268. exports.WebGLUtils = WebGLUtils;
  269. exports.WireframeHelper = WireframeHelper;
  270. exports.XHRLoader = XHRLoader;
  271. exports.InterpolateSmooth = exports.InterpolateLinear = exports.InterpolateDiscrete = exports.IntType = exports.IncrementWrapStencilOp = exports.IncrementStencilOp = exports.ImageUtils = exports.IcosahedronGeometry = exports.IcosahedronBufferGeometry = exports.HemisphereLightHelper = exports.HalfFloatType = exports.GridHelper = exports.GreaterStencilFunc = exports.GreaterEqualStencilFunc = exports.GreaterEqualDepth = exports.GreaterDepth = exports.GeometryUtils = exports.GammaEncoding = exports.GLSL3 = exports.GLSL1 = exports.Frustum = exports.FrontSide = exports.FogExp2 = exports.Fog = exports.FloatType = exports.FlatShading = exports.FaceColors = exports.Face3 = exports.ExtrudeGeometry = exports.ExtrudeBufferGeometry = exports.Euler = exports.EquirectangularRefractionMapping = exports.EquirectangularReflectionMapping = exports.EqualStencilFunc = exports.EqualDepth = exports.EdgesGeometry = exports.DynamicReadUsage = exports.DynamicDrawUsage = exports.DynamicCopyUsage = exports.DstColorFactor = exports.DstAlphaFactor = exports.DoubleSide = exports.DodecahedronGeometry = exports.DodecahedronBufferGeometry = exports.DirectionalLightHelper = exports.DepthStencilFormat = exports.DepthFormat = exports.DefaultLoadingManager = exports.DecrementWrapStencilOp = exports.DecrementStencilOp = exports.DataUtils = exports.Cylindrical = exports.CylinderGeometry = exports.CylinderBufferGeometry = exports.CustomToneMapping = exports.CustomBlending = exports.CullFaceNone = exports.CullFaceFrontBack = exports.CullFaceFront = exports.CullFaceBack = exports.CubeUVRefractionMapping = exports.CubeUVReflectionMapping = exports.CubeRefractionMapping = exports.CubeReflectionMapping = exports.ConeGeometry = exports.ConeBufferGeometry = exports.Color = exports.Clock = exports.ClampToEdgeWrapping = exports.CircleGeometry = exports.CircleBufferGeometry = exports.CineonToneMapping = exports.CameraHelper = exports.Cache = exports.ByteType = exports.BoxHelper = exports.CubeGeometry = exports.BoxGeometry = exports.BoxBufferGeometry = exports.Box3Helper = exports.Box3 = exports.Box2 = exports.BasicShadowMap = exports.BasicDepthPacking = exports.BackSide = exports.AxesHelper = exports.AudioListener = exports.AudioContext = exports.AudioAnalyser = exports.Audio = exports.ArrowHelper = exports.AnimationUtils = exports.AlwaysStencilFunc = exports.AlwaysDepth = exports.AlphaFormat = exports.AdditiveBlending = exports.AdditiveAnimationBlendMode = exports.AddOperation = exports.AddEquation = exports.ACESFilmicToneMapping = void 0;
  272. exports.RGBEEncoding = exports.RGBDEncoding = exports.RGBA_S3TC_DXT5_Format = exports.RGBA_S3TC_DXT3_Format = exports.RGBA_S3TC_DXT1_Format = exports.RGBA_PVRTC_4BPPV1_Format = exports.RGBA_PVRTC_2BPPV1_Format = exports.RGBA_ETC2_EAC_Format = exports.RGBA_BPTC_Format = exports.RGBA_ASTC_8x8_Format = exports.RGBA_ASTC_8x6_Format = exports.RGBA_ASTC_8x5_Format = exports.RGBA_ASTC_6x6_Format = exports.RGBA_ASTC_6x5_Format = exports.RGBA_ASTC_5x5_Format = exports.RGBA_ASTC_5x4_Format = exports.RGBA_ASTC_4x4_Format = exports.RGBA_ASTC_12x12_Format = exports.RGBA_ASTC_12x10_Format = exports.RGBA_ASTC_10x8_Format = exports.RGBA_ASTC_10x6_Format = exports.RGBA_ASTC_10x5_Format = exports.RGBA_ASTC_10x10_Format = exports.RGBAIntegerFormat = exports.RGBAFormat = exports.RGBADepthPacking = exports.REVISION = exports.Quaternion = exports.PositionalAudio = exports.PolyhedronGeometry = exports.PolyhedronBufferGeometry = exports.PolarGridHelper = exports.PointLightHelper = exports.PlaneHelper = exports.PlaneGeometry = exports.PlaneBufferGeometry = exports.Plane = exports.PMREMGenerator = exports.PCFSoftShadowMap = exports.PCFShadowMap = exports.OneMinusSrcColorFactor = exports.OneMinusSrcAlphaFactor = exports.OneMinusDstColorFactor = exports.OneMinusDstAlphaFactor = exports.OneFactor = exports.OctahedronGeometry = exports.OctahedronBufferGeometry = exports.ObjectSpaceNormalMap = exports.ObjectLoader = exports.NotEqualStencilFunc = exports.NotEqualDepth = exports.NormalBlending = exports.NormalAnimationBlendMode = 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.Matrix4 = exports.Matrix3 = exports.MathUtils = exports.Math = exports.MOUSE = exports.LuminanceFormat = exports.LuminanceAlphaFormat = exports.LoopRepeat = exports.LoopPingPong = exports.LoopOnce = exports.LogLuvEncoding = exports.LoaderUtils = exports.LinearToneMapping = exports.LinearMipmapNearestFilter = exports.LinearMipmapLinearFilter = exports.LinearMipMapNearestFilter = exports.LinearMipMapLinearFilter = exports.LinearFilter = exports.LinearEncoding = exports.LineStrip = exports.LinePieces = exports.Line3 = exports.LessStencilFunc = exports.LessEqualStencilFunc = exports.LessEqualDepth = exports.LessDepth = exports.Layers = exports.LatheGeometry = exports.LatheBufferGeometry = exports.KeepStencilOp = exports.InvertStencilOp = void 0;
  273. exports.ZeroStencilOp = exports.ZeroSlopeEnding = exports.ZeroFactor = exports.ZeroCurvatureEnding = exports.WrapAroundEnding = exports.WireframeGeometry = exports.VertexColors = exports.Vector4 = exports.Vector3 = exports.Vector2 = exports.VSMShadowMap = exports.UnsignedShortType = exports.UnsignedShort565Type = exports.UnsignedShort5551Type = exports.UnsignedShort4444Type = exports.UnsignedIntType = exports.UnsignedInt248Type = exports.UnsignedByteType = exports.UniformsUtils = exports.UniformsLib = exports.Uniform = exports.UVMapping = exports.TubeGeometry = exports.TubeBufferGeometry = exports.TrianglesDrawMode = exports.TriangleStripDrawMode = exports.TriangleFanDrawMode = exports.Triangle = exports.TorusKnotGeometry = exports.TorusKnotBufferGeometry = exports.TorusGeometry = exports.TorusBufferGeometry = exports.TextGeometry = exports.TextBufferGeometry = exports.TetrahedronGeometry = exports.TetrahedronBufferGeometry = exports.TangentSpaceNormalMap = exports.TOUCH = exports.SubtractiveBlending = exports.SubtractEquation = exports.StreamReadUsage = exports.StreamDrawUsage = exports.StreamCopyUsage = exports.StaticReadUsage = exports.StaticDrawUsage = exports.StaticCopyUsage = exports.SrcColorFactor = exports.SrcAlphaSaturateFactor = exports.SrcAlphaFactor = exports.SpotLightHelper = exports.SphericalHarmonics3 = exports.Spherical = exports.SphereGeometry = exports.SphereBufferGeometry = exports.Sphere = exports.SmoothShading = exports.SkeletonHelper = exports.ShortType = exports.ShapeUtils = exports.ShapeGeometry = exports.ShapeBufferGeometry = exports.ShaderLib = exports.ShaderChunk = exports.SceneUtils = exports.Scene = exports.SRGB8_ALPHA8_ASTC_8x8_Format = exports.SRGB8_ALPHA8_ASTC_8x6_Format = exports.SRGB8_ALPHA8_ASTC_8x5_Format = exports.SRGB8_ALPHA8_ASTC_6x6_Format = exports.SRGB8_ALPHA8_ASTC_6x5_Format = exports.SRGB8_ALPHA8_ASTC_5x5_Format = exports.SRGB8_ALPHA8_ASTC_5x4_Format = exports.SRGB8_ALPHA8_ASTC_4x4_Format = exports.SRGB8_ALPHA8_ASTC_12x12_Format = exports.SRGB8_ALPHA8_ASTC_12x10_Format = exports.SRGB8_ALPHA8_ASTC_10x8_Format = exports.SRGB8_ALPHA8_ASTC_10x6_Format = exports.SRGB8_ALPHA8_ASTC_10x5_Format = exports.SRGB8_ALPHA8_ASTC_10x10_Format = exports.RingGeometry = exports.RingBufferGeometry = exports.ReverseSubtractEquation = exports.ReplaceStencilOp = exports.RepeatWrapping = exports.ReinhardToneMapping = exports.RedIntegerFormat = exports.RedFormat = exports.Ray = exports.RGIntegerFormat = exports.RGFormat = exports.RGB_S3TC_DXT1_Format = exports.RGB_PVRTC_4BPPV1_Format = exports.RGB_PVRTC_2BPPV1_Format = exports.RGB_ETC2_Format = exports.RGB_ETC1_Format = exports.RGBM7Encoding = exports.RGBM16Encoding = exports.RGBIntegerFormat = exports.RGBFormat = exports.RGBEFormat = void 0;
  274. exports.sRGBEncoding = void 0;
  275. // threejs.org/license
  276. const REVISION = '123';
  277. exports.REVISION = REVISION;
  278. const MOUSE = {
  279. LEFT: 0,
  280. MIDDLE: 1,
  281. RIGHT: 2,
  282. ROTATE: 0,
  283. DOLLY: 1,
  284. PAN: 2
  285. };
  286. exports.MOUSE = MOUSE;
  287. const TOUCH = {
  288. ROTATE: 0,
  289. PAN: 1,
  290. DOLLY_PAN: 2,
  291. DOLLY_ROTATE: 3
  292. };
  293. exports.TOUCH = TOUCH;
  294. const CullFaceNone = 0;
  295. exports.CullFaceNone = CullFaceNone;
  296. const CullFaceBack = 1;
  297. exports.CullFaceBack = CullFaceBack;
  298. const CullFaceFront = 2;
  299. exports.CullFaceFront = CullFaceFront;
  300. const CullFaceFrontBack = 3;
  301. exports.CullFaceFrontBack = CullFaceFrontBack;
  302. const BasicShadowMap = 0;
  303. exports.BasicShadowMap = BasicShadowMap;
  304. const PCFShadowMap = 1;
  305. exports.PCFShadowMap = PCFShadowMap;
  306. const PCFSoftShadowMap = 2;
  307. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  308. const VSMShadowMap = 3;
  309. exports.VSMShadowMap = VSMShadowMap;
  310. const FrontSide = 0;
  311. exports.FrontSide = FrontSide;
  312. const BackSide = 1;
  313. exports.BackSide = BackSide;
  314. const DoubleSide = 2;
  315. exports.DoubleSide = DoubleSide;
  316. const FlatShading = 1;
  317. exports.FlatShading = FlatShading;
  318. const SmoothShading = 2;
  319. exports.SmoothShading = SmoothShading;
  320. const NoBlending = 0;
  321. exports.NoBlending = NoBlending;
  322. const NormalBlending = 1;
  323. exports.NormalBlending = NormalBlending;
  324. const AdditiveBlending = 2;
  325. exports.AdditiveBlending = AdditiveBlending;
  326. const SubtractiveBlending = 3;
  327. exports.SubtractiveBlending = SubtractiveBlending;
  328. const MultiplyBlending = 4;
  329. exports.MultiplyBlending = MultiplyBlending;
  330. const CustomBlending = 5;
  331. exports.CustomBlending = CustomBlending;
  332. const AddEquation = 100;
  333. exports.AddEquation = AddEquation;
  334. const SubtractEquation = 101;
  335. exports.SubtractEquation = SubtractEquation;
  336. const ReverseSubtractEquation = 102;
  337. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  338. const MinEquation = 103;
  339. exports.MinEquation = MinEquation;
  340. const MaxEquation = 104;
  341. exports.MaxEquation = MaxEquation;
  342. const ZeroFactor = 200;
  343. exports.ZeroFactor = ZeroFactor;
  344. const OneFactor = 201;
  345. exports.OneFactor = OneFactor;
  346. const SrcColorFactor = 202;
  347. exports.SrcColorFactor = SrcColorFactor;
  348. const OneMinusSrcColorFactor = 203;
  349. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  350. const SrcAlphaFactor = 204;
  351. exports.SrcAlphaFactor = SrcAlphaFactor;
  352. const OneMinusSrcAlphaFactor = 205;
  353. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  354. const DstAlphaFactor = 206;
  355. exports.DstAlphaFactor = DstAlphaFactor;
  356. const OneMinusDstAlphaFactor = 207;
  357. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  358. const DstColorFactor = 208;
  359. exports.DstColorFactor = DstColorFactor;
  360. const OneMinusDstColorFactor = 209;
  361. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  362. const SrcAlphaSaturateFactor = 210;
  363. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  364. const NeverDepth = 0;
  365. exports.NeverDepth = NeverDepth;
  366. const AlwaysDepth = 1;
  367. exports.AlwaysDepth = AlwaysDepth;
  368. const LessDepth = 2;
  369. exports.LessDepth = LessDepth;
  370. const LessEqualDepth = 3;
  371. exports.LessEqualDepth = LessEqualDepth;
  372. const EqualDepth = 4;
  373. exports.EqualDepth = EqualDepth;
  374. const GreaterEqualDepth = 5;
  375. exports.GreaterEqualDepth = GreaterEqualDepth;
  376. const GreaterDepth = 6;
  377. exports.GreaterDepth = GreaterDepth;
  378. const NotEqualDepth = 7;
  379. exports.NotEqualDepth = NotEqualDepth;
  380. const MultiplyOperation = 0;
  381. exports.MultiplyOperation = MultiplyOperation;
  382. const MixOperation = 1;
  383. exports.MixOperation = MixOperation;
  384. const AddOperation = 2;
  385. exports.AddOperation = AddOperation;
  386. const NoToneMapping = 0;
  387. exports.NoToneMapping = NoToneMapping;
  388. const LinearToneMapping = 1;
  389. exports.LinearToneMapping = LinearToneMapping;
  390. const ReinhardToneMapping = 2;
  391. exports.ReinhardToneMapping = ReinhardToneMapping;
  392. const CineonToneMapping = 3;
  393. exports.CineonToneMapping = CineonToneMapping;
  394. const ACESFilmicToneMapping = 4;
  395. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  396. const CustomToneMapping = 5;
  397. exports.CustomToneMapping = CustomToneMapping;
  398. const UVMapping = 300;
  399. exports.UVMapping = UVMapping;
  400. const CubeReflectionMapping = 301;
  401. exports.CubeReflectionMapping = CubeReflectionMapping;
  402. const CubeRefractionMapping = 302;
  403. exports.CubeRefractionMapping = CubeRefractionMapping;
  404. const EquirectangularReflectionMapping = 303;
  405. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  406. const EquirectangularRefractionMapping = 304;
  407. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  408. const CubeUVReflectionMapping = 306;
  409. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  410. const CubeUVRefractionMapping = 307;
  411. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  412. const RepeatWrapping = 1000;
  413. exports.RepeatWrapping = RepeatWrapping;
  414. const ClampToEdgeWrapping = 1001;
  415. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  416. const MirroredRepeatWrapping = 1002;
  417. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  418. const NearestFilter = 1003;
  419. exports.NearestFilter = NearestFilter;
  420. const NearestMipmapNearestFilter = 1004;
  421. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  422. const NearestMipMapNearestFilter = 1004;
  423. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  424. const NearestMipmapLinearFilter = 1005;
  425. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  426. const NearestMipMapLinearFilter = 1005;
  427. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  428. const LinearFilter = 1006;
  429. exports.LinearFilter = LinearFilter;
  430. const LinearMipmapNearestFilter = 1007;
  431. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  432. const LinearMipMapNearestFilter = 1007;
  433. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  434. const LinearMipmapLinearFilter = 1008;
  435. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  436. const LinearMipMapLinearFilter = 1008;
  437. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  438. const UnsignedByteType = 1009;
  439. exports.UnsignedByteType = UnsignedByteType;
  440. const ByteType = 1010;
  441. exports.ByteType = ByteType;
  442. const ShortType = 1011;
  443. exports.ShortType = ShortType;
  444. const UnsignedShortType = 1012;
  445. exports.UnsignedShortType = UnsignedShortType;
  446. const IntType = 1013;
  447. exports.IntType = IntType;
  448. const UnsignedIntType = 1014;
  449. exports.UnsignedIntType = UnsignedIntType;
  450. const FloatType = 1015;
  451. exports.FloatType = FloatType;
  452. const HalfFloatType = 1016;
  453. exports.HalfFloatType = HalfFloatType;
  454. const UnsignedShort4444Type = 1017;
  455. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  456. const UnsignedShort5551Type = 1018;
  457. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  458. const UnsignedShort565Type = 1019;
  459. exports.UnsignedShort565Type = UnsignedShort565Type;
  460. const UnsignedInt248Type = 1020;
  461. exports.UnsignedInt248Type = UnsignedInt248Type;
  462. const AlphaFormat = 1021;
  463. exports.AlphaFormat = AlphaFormat;
  464. const RGBFormat = 1022;
  465. exports.RGBFormat = RGBFormat;
  466. const RGBAFormat = 1023;
  467. exports.RGBAFormat = RGBAFormat;
  468. const LuminanceFormat = 1024;
  469. exports.LuminanceFormat = LuminanceFormat;
  470. const LuminanceAlphaFormat = 1025;
  471. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  472. const RGBEFormat = RGBAFormat;
  473. exports.RGBEFormat = RGBEFormat;
  474. const DepthFormat = 1026;
  475. exports.DepthFormat = DepthFormat;
  476. const DepthStencilFormat = 1027;
  477. exports.DepthStencilFormat = DepthStencilFormat;
  478. const RedFormat = 1028;
  479. exports.RedFormat = RedFormat;
  480. const RedIntegerFormat = 1029;
  481. exports.RedIntegerFormat = RedIntegerFormat;
  482. const RGFormat = 1030;
  483. exports.RGFormat = RGFormat;
  484. const RGIntegerFormat = 1031;
  485. exports.RGIntegerFormat = RGIntegerFormat;
  486. const RGBIntegerFormat = 1032;
  487. exports.RGBIntegerFormat = RGBIntegerFormat;
  488. const RGBAIntegerFormat = 1033;
  489. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  490. const RGB_S3TC_DXT1_Format = 33776;
  491. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  492. const RGBA_S3TC_DXT1_Format = 33777;
  493. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  494. const RGBA_S3TC_DXT3_Format = 33778;
  495. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  496. const RGBA_S3TC_DXT5_Format = 33779;
  497. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  498. const RGB_PVRTC_4BPPV1_Format = 35840;
  499. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  500. const RGB_PVRTC_2BPPV1_Format = 35841;
  501. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  502. const RGBA_PVRTC_4BPPV1_Format = 35842;
  503. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  504. const RGBA_PVRTC_2BPPV1_Format = 35843;
  505. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  506. const RGB_ETC1_Format = 36196;
  507. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  508. const RGB_ETC2_Format = 37492;
  509. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  510. const RGBA_ETC2_EAC_Format = 37496;
  511. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  512. const RGBA_ASTC_4x4_Format = 37808;
  513. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  514. const RGBA_ASTC_5x4_Format = 37809;
  515. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  516. const RGBA_ASTC_5x5_Format = 37810;
  517. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  518. const RGBA_ASTC_6x5_Format = 37811;
  519. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  520. const RGBA_ASTC_6x6_Format = 37812;
  521. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  522. const RGBA_ASTC_8x5_Format = 37813;
  523. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  524. const RGBA_ASTC_8x6_Format = 37814;
  525. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  526. const RGBA_ASTC_8x8_Format = 37815;
  527. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  528. const RGBA_ASTC_10x5_Format = 37816;
  529. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  530. const RGBA_ASTC_10x6_Format = 37817;
  531. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  532. const RGBA_ASTC_10x8_Format = 37818;
  533. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  534. const RGBA_ASTC_10x10_Format = 37819;
  535. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  536. const RGBA_ASTC_12x10_Format = 37820;
  537. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  538. const RGBA_ASTC_12x12_Format = 37821;
  539. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  540. const RGBA_BPTC_Format = 36492;
  541. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  542. const SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
  543. exports.SRGB8_ALPHA8_ASTC_4x4_Format = SRGB8_ALPHA8_ASTC_4x4_Format;
  544. const SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
  545. exports.SRGB8_ALPHA8_ASTC_5x4_Format = SRGB8_ALPHA8_ASTC_5x4_Format;
  546. const SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
  547. exports.SRGB8_ALPHA8_ASTC_5x5_Format = SRGB8_ALPHA8_ASTC_5x5_Format;
  548. const SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
  549. exports.SRGB8_ALPHA8_ASTC_6x5_Format = SRGB8_ALPHA8_ASTC_6x5_Format;
  550. const SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
  551. exports.SRGB8_ALPHA8_ASTC_6x6_Format = SRGB8_ALPHA8_ASTC_6x6_Format;
  552. const SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
  553. exports.SRGB8_ALPHA8_ASTC_8x5_Format = SRGB8_ALPHA8_ASTC_8x5_Format;
  554. const SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
  555. exports.SRGB8_ALPHA8_ASTC_8x6_Format = SRGB8_ALPHA8_ASTC_8x6_Format;
  556. const SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
  557. exports.SRGB8_ALPHA8_ASTC_8x8_Format = SRGB8_ALPHA8_ASTC_8x8_Format;
  558. const SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
  559. exports.SRGB8_ALPHA8_ASTC_10x5_Format = SRGB8_ALPHA8_ASTC_10x5_Format;
  560. const SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
  561. exports.SRGB8_ALPHA8_ASTC_10x6_Format = SRGB8_ALPHA8_ASTC_10x6_Format;
  562. const SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
  563. exports.SRGB8_ALPHA8_ASTC_10x8_Format = SRGB8_ALPHA8_ASTC_10x8_Format;
  564. const SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
  565. exports.SRGB8_ALPHA8_ASTC_10x10_Format = SRGB8_ALPHA8_ASTC_10x10_Format;
  566. const SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
  567. exports.SRGB8_ALPHA8_ASTC_12x10_Format = SRGB8_ALPHA8_ASTC_12x10_Format;
  568. const SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
  569. exports.SRGB8_ALPHA8_ASTC_12x12_Format = SRGB8_ALPHA8_ASTC_12x12_Format;
  570. const LoopOnce = 2200;
  571. exports.LoopOnce = LoopOnce;
  572. const LoopRepeat = 2201;
  573. exports.LoopRepeat = LoopRepeat;
  574. const LoopPingPong = 2202;
  575. exports.LoopPingPong = LoopPingPong;
  576. const InterpolateDiscrete = 2300;
  577. exports.InterpolateDiscrete = InterpolateDiscrete;
  578. const InterpolateLinear = 2301;
  579. exports.InterpolateLinear = InterpolateLinear;
  580. const InterpolateSmooth = 2302;
  581. exports.InterpolateSmooth = InterpolateSmooth;
  582. const ZeroCurvatureEnding = 2400;
  583. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  584. const ZeroSlopeEnding = 2401;
  585. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  586. const WrapAroundEnding = 2402;
  587. exports.WrapAroundEnding = WrapAroundEnding;
  588. const NormalAnimationBlendMode = 2500;
  589. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  590. const AdditiveAnimationBlendMode = 2501;
  591. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  592. const TrianglesDrawMode = 0;
  593. exports.TrianglesDrawMode = TrianglesDrawMode;
  594. const TriangleStripDrawMode = 1;
  595. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  596. const TriangleFanDrawMode = 2;
  597. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  598. const LinearEncoding = 3000;
  599. exports.LinearEncoding = LinearEncoding;
  600. const sRGBEncoding = 3001;
  601. exports.sRGBEncoding = sRGBEncoding;
  602. const GammaEncoding = 3007;
  603. exports.GammaEncoding = GammaEncoding;
  604. const RGBEEncoding = 3002;
  605. exports.RGBEEncoding = RGBEEncoding;
  606. const LogLuvEncoding = 3003;
  607. exports.LogLuvEncoding = LogLuvEncoding;
  608. const RGBM7Encoding = 3004;
  609. exports.RGBM7Encoding = RGBM7Encoding;
  610. const RGBM16Encoding = 3005;
  611. exports.RGBM16Encoding = RGBM16Encoding;
  612. const RGBDEncoding = 3006;
  613. exports.RGBDEncoding = RGBDEncoding;
  614. const BasicDepthPacking = 3200;
  615. exports.BasicDepthPacking = BasicDepthPacking;
  616. const RGBADepthPacking = 3201;
  617. exports.RGBADepthPacking = RGBADepthPacking;
  618. const TangentSpaceNormalMap = 0;
  619. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  620. const ObjectSpaceNormalMap = 1;
  621. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  622. const ZeroStencilOp = 0;
  623. exports.ZeroStencilOp = ZeroStencilOp;
  624. const KeepStencilOp = 7680;
  625. exports.KeepStencilOp = KeepStencilOp;
  626. const ReplaceStencilOp = 7681;
  627. exports.ReplaceStencilOp = ReplaceStencilOp;
  628. const IncrementStencilOp = 7682;
  629. exports.IncrementStencilOp = IncrementStencilOp;
  630. const DecrementStencilOp = 7683;
  631. exports.DecrementStencilOp = DecrementStencilOp;
  632. const IncrementWrapStencilOp = 34055;
  633. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  634. const DecrementWrapStencilOp = 34056;
  635. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  636. const InvertStencilOp = 5386;
  637. exports.InvertStencilOp = InvertStencilOp;
  638. const NeverStencilFunc = 512;
  639. exports.NeverStencilFunc = NeverStencilFunc;
  640. const LessStencilFunc = 513;
  641. exports.LessStencilFunc = LessStencilFunc;
  642. const EqualStencilFunc = 514;
  643. exports.EqualStencilFunc = EqualStencilFunc;
  644. const LessEqualStencilFunc = 515;
  645. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  646. const GreaterStencilFunc = 516;
  647. exports.GreaterStencilFunc = GreaterStencilFunc;
  648. const NotEqualStencilFunc = 517;
  649. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  650. const GreaterEqualStencilFunc = 518;
  651. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  652. const AlwaysStencilFunc = 519;
  653. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  654. const StaticDrawUsage = 35044;
  655. exports.StaticDrawUsage = StaticDrawUsage;
  656. const DynamicDrawUsage = 35048;
  657. exports.DynamicDrawUsage = DynamicDrawUsage;
  658. const StreamDrawUsage = 35040;
  659. exports.StreamDrawUsage = StreamDrawUsage;
  660. const StaticReadUsage = 35045;
  661. exports.StaticReadUsage = StaticReadUsage;
  662. const DynamicReadUsage = 35049;
  663. exports.DynamicReadUsage = DynamicReadUsage;
  664. const StreamReadUsage = 35041;
  665. exports.StreamReadUsage = StreamReadUsage;
  666. const StaticCopyUsage = 35046;
  667. exports.StaticCopyUsage = StaticCopyUsage;
  668. const DynamicCopyUsage = 35050;
  669. exports.DynamicCopyUsage = DynamicCopyUsage;
  670. const StreamCopyUsage = 35042;
  671. exports.StreamCopyUsage = StreamCopyUsage;
  672. const GLSL1 = "100";
  673. exports.GLSL1 = GLSL1;
  674. const GLSL3 = "300 es";
  675. /**
  676. * https://github.com/mrdoob/eventdispatcher.js/
  677. */
  678. exports.GLSL3 = GLSL3;
  679. function EventDispatcher() {}
  680. Object.assign(EventDispatcher.prototype, {
  681. addEventListener: function (type, listener) {
  682. if (this._listeners === undefined) this._listeners = {};
  683. const listeners = this._listeners;
  684. if (listeners[type] === undefined) {
  685. listeners[type] = [];
  686. }
  687. if (listeners[type].indexOf(listener) === -1) {
  688. listeners[type].push(listener);
  689. }
  690. },
  691. hasEventListener: function (type, listener) {
  692. if (this._listeners === undefined) return false;
  693. const listeners = this._listeners;
  694. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  695. },
  696. removeEventListener: function (type, listener) {
  697. if (this._listeners === undefined) return;
  698. const listeners = this._listeners;
  699. const listenerArray = listeners[type];
  700. if (listenerArray !== undefined) {
  701. const index = listenerArray.indexOf(listener);
  702. if (index !== -1) {
  703. listenerArray.splice(index, 1);
  704. }
  705. }
  706. },
  707. dispatchEvent: function (event) {
  708. if (this._listeners === undefined) return;
  709. const listeners = this._listeners;
  710. const listenerArray = listeners[event.type];
  711. if (listenerArray !== undefined) {
  712. event.target = this; // Make a copy, in case listeners are removed while iterating.
  713. const array = listenerArray.slice(0);
  714. for (let i = 0, l = array.length; i < l; i++) {
  715. array[i].call(this, event);
  716. }
  717. }
  718. }
  719. });
  720. const _lut = [];
  721. for (let i = 0; i < 256; i++) {
  722. _lut[i] = (i < 16 ? '0' : '') + i.toString(16);
  723. }
  724. let _seed = 1234567;
  725. const MathUtils = {
  726. DEG2RAD: Math.PI / 180,
  727. RAD2DEG: 180 / Math.PI,
  728. generateUUID: function () {
  729. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  730. const d0 = Math.random() * 0xffffffff | 0;
  731. const d1 = Math.random() * 0xffffffff | 0;
  732. const d2 = Math.random() * 0xffffffff | 0;
  733. const d3 = Math.random() * 0xffffffff | 0;
  734. const 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.
  735. return uuid.toUpperCase();
  736. },
  737. clamp: function (value, min, max) {
  738. return Math.max(min, Math.min(max, value));
  739. },
  740. // compute euclidian modulo of m % n
  741. // https://en.wikipedia.org/wiki/Modulo_operation
  742. euclideanModulo: function (n, m) {
  743. return (n % m + m) % m;
  744. },
  745. // Linear mapping from range <a1, a2> to range <b1, b2>
  746. mapLinear: function (x, a1, a2, b1, b2) {
  747. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  748. },
  749. // https://en.wikipedia.org/wiki/Linear_interpolation
  750. lerp: function (x, y, t) {
  751. return (1 - t) * x + t * y;
  752. },
  753. // http://en.wikipedia.org/wiki/Smoothstep
  754. smoothstep: function (x, min, max) {
  755. if (x <= min) return 0;
  756. if (x >= max) return 1;
  757. x = (x - min) / (max - min);
  758. return x * x * (3 - 2 * x);
  759. },
  760. smootherstep: function (x, min, max) {
  761. if (x <= min) return 0;
  762. if (x >= max) return 1;
  763. x = (x - min) / (max - min);
  764. return x * x * x * (x * (x * 6 - 15) + 10);
  765. },
  766. // Random integer from <low, high> interval
  767. randInt: function (low, high) {
  768. return low + Math.floor(Math.random() * (high - low + 1));
  769. },
  770. // Random float from <low, high> interval
  771. randFloat: function (low, high) {
  772. return low + Math.random() * (high - low);
  773. },
  774. // Random float from <-range/2, range/2> interval
  775. randFloatSpread: function (range) {
  776. return range * (0.5 - Math.random());
  777. },
  778. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  779. seededRandom: function (s) {
  780. if (s !== undefined) _seed = s % 2147483647; // Park-Miller algorithm
  781. _seed = _seed * 16807 % 2147483647;
  782. return (_seed - 1) / 2147483646;
  783. },
  784. degToRad: function (degrees) {
  785. return degrees * MathUtils.DEG2RAD;
  786. },
  787. radToDeg: function (radians) {
  788. return radians * MathUtils.RAD2DEG;
  789. },
  790. isPowerOfTwo: function (value) {
  791. return (value & value - 1) === 0 && value !== 0;
  792. },
  793. ceilPowerOfTwo: function (value) {
  794. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  795. },
  796. floorPowerOfTwo: function (value) {
  797. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  798. },
  799. setQuaternionFromProperEuler: function (q, a, b, c, order) {
  800. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  801. // rotations are applied to the axes in the order specified by 'order'
  802. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  803. // angles are in radians
  804. const cos = Math.cos;
  805. const sin = Math.sin;
  806. const c2 = cos(b / 2);
  807. const s2 = sin(b / 2);
  808. const c13 = cos((a + c) / 2);
  809. const s13 = sin((a + c) / 2);
  810. const c1_3 = cos((a - c) / 2);
  811. const s1_3 = sin((a - c) / 2);
  812. const c3_1 = cos((c - a) / 2);
  813. const s3_1 = sin((c - a) / 2);
  814. switch (order) {
  815. case 'XYX':
  816. q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13);
  817. break;
  818. case 'YZY':
  819. q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13);
  820. break;
  821. case 'ZXZ':
  822. q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13);
  823. break;
  824. case 'XZX':
  825. q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13);
  826. break;
  827. case 'YXY':
  828. q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13);
  829. break;
  830. case 'ZYZ':
  831. q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13);
  832. break;
  833. default:
  834. console.warn('THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order);
  835. }
  836. }
  837. };
  838. exports.MathUtils = exports.Math = MathUtils;
  839. class Vector2 {
  840. constructor(x = 0, y = 0) {
  841. Object.defineProperty(this, 'isVector2', {
  842. value: true
  843. });
  844. this.x = x;
  845. this.y = y;
  846. }
  847. get width() {
  848. return this.x;
  849. }
  850. set width(value) {
  851. this.x = value;
  852. }
  853. get height() {
  854. return this.y;
  855. }
  856. set height(value) {
  857. this.y = value;
  858. }
  859. set(x, y) {
  860. this.x = x;
  861. this.y = y;
  862. return this;
  863. }
  864. setScalar(scalar) {
  865. this.x = scalar;
  866. this.y = scalar;
  867. return this;
  868. }
  869. setX(x) {
  870. this.x = x;
  871. return this;
  872. }
  873. setY(y) {
  874. this.y = y;
  875. return this;
  876. }
  877. setComponent(index, value) {
  878. switch (index) {
  879. case 0:
  880. this.x = value;
  881. break;
  882. case 1:
  883. this.y = value;
  884. break;
  885. default:
  886. throw new Error('index is out of range: ' + index);
  887. }
  888. return this;
  889. }
  890. getComponent(index) {
  891. switch (index) {
  892. case 0:
  893. return this.x;
  894. case 1:
  895. return this.y;
  896. default:
  897. throw new Error('index is out of range: ' + index);
  898. }
  899. }
  900. clone() {
  901. return new this.constructor(this.x, this.y);
  902. }
  903. copy(v) {
  904. this.x = v.x;
  905. this.y = v.y;
  906. return this;
  907. }
  908. add(v, w) {
  909. if (w !== undefined) {
  910. console.warn('THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  911. return this.addVectors(v, w);
  912. }
  913. this.x += v.x;
  914. this.y += v.y;
  915. return this;
  916. }
  917. addScalar(s) {
  918. this.x += s;
  919. this.y += s;
  920. return this;
  921. }
  922. addVectors(a, b) {
  923. this.x = a.x + b.x;
  924. this.y = a.y + b.y;
  925. return this;
  926. }
  927. addScaledVector(v, s) {
  928. this.x += v.x * s;
  929. this.y += v.y * s;
  930. return this;
  931. }
  932. sub(v, w) {
  933. if (w !== undefined) {
  934. console.warn('THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  935. return this.subVectors(v, w);
  936. }
  937. this.x -= v.x;
  938. this.y -= v.y;
  939. return this;
  940. }
  941. subScalar(s) {
  942. this.x -= s;
  943. this.y -= s;
  944. return this;
  945. }
  946. subVectors(a, b) {
  947. this.x = a.x - b.x;
  948. this.y = a.y - b.y;
  949. return this;
  950. }
  951. multiply(v) {
  952. this.x *= v.x;
  953. this.y *= v.y;
  954. return this;
  955. }
  956. multiplyScalar(scalar) {
  957. this.x *= scalar;
  958. this.y *= scalar;
  959. return this;
  960. }
  961. divide(v) {
  962. this.x /= v.x;
  963. this.y /= v.y;
  964. return this;
  965. }
  966. divideScalar(scalar) {
  967. return this.multiplyScalar(1 / scalar);
  968. }
  969. applyMatrix3(m) {
  970. const x = this.x,
  971. y = this.y;
  972. const e = m.elements;
  973. this.x = e[0] * x + e[3] * y + e[6];
  974. this.y = e[1] * x + e[4] * y + e[7];
  975. return this;
  976. }
  977. min(v) {
  978. this.x = Math.min(this.x, v.x);
  979. this.y = Math.min(this.y, v.y);
  980. return this;
  981. }
  982. max(v) {
  983. this.x = Math.max(this.x, v.x);
  984. this.y = Math.max(this.y, v.y);
  985. return this;
  986. }
  987. clamp(min, max) {
  988. // assumes min < max, componentwise
  989. this.x = Math.max(min.x, Math.min(max.x, this.x));
  990. this.y = Math.max(min.y, Math.min(max.y, this.y));
  991. return this;
  992. }
  993. clampScalar(minVal, maxVal) {
  994. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  995. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  996. return this;
  997. }
  998. clampLength(min, max) {
  999. const length = this.length();
  1000. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  1001. }
  1002. floor() {
  1003. this.x = Math.floor(this.x);
  1004. this.y = Math.floor(this.y);
  1005. return this;
  1006. }
  1007. ceil() {
  1008. this.x = Math.ceil(this.x);
  1009. this.y = Math.ceil(this.y);
  1010. return this;
  1011. }
  1012. round() {
  1013. this.x = Math.round(this.x);
  1014. this.y = Math.round(this.y);
  1015. return this;
  1016. }
  1017. roundToZero() {
  1018. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  1019. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  1020. return this;
  1021. }
  1022. negate() {
  1023. this.x = -this.x;
  1024. this.y = -this.y;
  1025. return this;
  1026. }
  1027. dot(v) {
  1028. return this.x * v.x + this.y * v.y;
  1029. }
  1030. cross(v) {
  1031. return this.x * v.y - this.y * v.x;
  1032. }
  1033. lengthSq() {
  1034. return this.x * this.x + this.y * this.y;
  1035. }
  1036. length() {
  1037. return Math.sqrt(this.x * this.x + this.y * this.y);
  1038. }
  1039. manhattanLength() {
  1040. return Math.abs(this.x) + Math.abs(this.y);
  1041. }
  1042. normalize() {
  1043. return this.divideScalar(this.length() || 1);
  1044. }
  1045. angle() {
  1046. // computes the angle in radians with respect to the positive x-axis
  1047. const angle = Math.atan2(-this.y, -this.x) + Math.PI;
  1048. return angle;
  1049. }
  1050. distanceTo(v) {
  1051. return Math.sqrt(this.distanceToSquared(v));
  1052. }
  1053. distanceToSquared(v) {
  1054. const dx = this.x - v.x,
  1055. dy = this.y - v.y;
  1056. return dx * dx + dy * dy;
  1057. }
  1058. manhattanDistanceTo(v) {
  1059. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  1060. }
  1061. setLength(length) {
  1062. return this.normalize().multiplyScalar(length);
  1063. }
  1064. lerp(v, alpha) {
  1065. this.x += (v.x - this.x) * alpha;
  1066. this.y += (v.y - this.y) * alpha;
  1067. return this;
  1068. }
  1069. lerpVectors(v1, v2, alpha) {
  1070. this.x = v1.x + (v2.x - v1.x) * alpha;
  1071. this.y = v1.y + (v2.y - v1.y) * alpha;
  1072. return this;
  1073. }
  1074. equals(v) {
  1075. return v.x === this.x && v.y === this.y;
  1076. }
  1077. fromArray(array, offset = 0) {
  1078. this.x = array[offset];
  1079. this.y = array[offset + 1];
  1080. return this;
  1081. }
  1082. toArray(array = [], offset = 0) {
  1083. array[offset] = this.x;
  1084. array[offset + 1] = this.y;
  1085. return array;
  1086. }
  1087. fromBufferAttribute(attribute, index, offset) {
  1088. if (offset !== undefined) {
  1089. console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');
  1090. }
  1091. this.x = attribute.getX(index);
  1092. this.y = attribute.getY(index);
  1093. return this;
  1094. }
  1095. rotateAround(center, angle) {
  1096. const c = Math.cos(angle),
  1097. s = Math.sin(angle);
  1098. const x = this.x - center.x;
  1099. const y = this.y - center.y;
  1100. this.x = x * c - y * s + center.x;
  1101. this.y = x * s + y * c + center.y;
  1102. return this;
  1103. }
  1104. random() {
  1105. this.x = Math.random();
  1106. this.y = Math.random();
  1107. return this;
  1108. }
  1109. }
  1110. exports.Vector2 = Vector2;
  1111. class Matrix3 {
  1112. constructor() {
  1113. Object.defineProperty(this, 'isMatrix3', {
  1114. value: true
  1115. });
  1116. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  1117. if (arguments.length > 0) {
  1118. console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');
  1119. }
  1120. }
  1121. set(n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  1122. const te = this.elements;
  1123. te[0] = n11;
  1124. te[1] = n21;
  1125. te[2] = n31;
  1126. te[3] = n12;
  1127. te[4] = n22;
  1128. te[5] = n32;
  1129. te[6] = n13;
  1130. te[7] = n23;
  1131. te[8] = n33;
  1132. return this;
  1133. }
  1134. identity() {
  1135. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  1136. return this;
  1137. }
  1138. clone() {
  1139. return new this.constructor().fromArray(this.elements);
  1140. }
  1141. copy(m) {
  1142. const te = this.elements;
  1143. const me = m.elements;
  1144. te[0] = me[0];
  1145. te[1] = me[1];
  1146. te[2] = me[2];
  1147. te[3] = me[3];
  1148. te[4] = me[4];
  1149. te[5] = me[5];
  1150. te[6] = me[6];
  1151. te[7] = me[7];
  1152. te[8] = me[8];
  1153. return this;
  1154. }
  1155. extractBasis(xAxis, yAxis, zAxis) {
  1156. xAxis.setFromMatrix3Column(this, 0);
  1157. yAxis.setFromMatrix3Column(this, 1);
  1158. zAxis.setFromMatrix3Column(this, 2);
  1159. return this;
  1160. }
  1161. setFromMatrix4(m) {
  1162. const me = m.elements;
  1163. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  1164. return this;
  1165. }
  1166. multiply(m) {
  1167. return this.multiplyMatrices(this, m);
  1168. }
  1169. premultiply(m) {
  1170. return this.multiplyMatrices(m, this);
  1171. }
  1172. multiplyMatrices(a, b) {
  1173. const ae = a.elements;
  1174. const be = b.elements;
  1175. const te = this.elements;
  1176. const a11 = ae[0],
  1177. a12 = ae[3],
  1178. a13 = ae[6];
  1179. const a21 = ae[1],
  1180. a22 = ae[4],
  1181. a23 = ae[7];
  1182. const a31 = ae[2],
  1183. a32 = ae[5],
  1184. a33 = ae[8];
  1185. const b11 = be[0],
  1186. b12 = be[3],
  1187. b13 = be[6];
  1188. const b21 = be[1],
  1189. b22 = be[4],
  1190. b23 = be[7];
  1191. const b31 = be[2],
  1192. b32 = be[5],
  1193. b33 = be[8];
  1194. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  1195. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  1196. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  1197. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  1198. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  1199. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  1200. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  1201. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  1202. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  1203. return this;
  1204. }
  1205. multiplyScalar(s) {
  1206. const te = this.elements;
  1207. te[0] *= s;
  1208. te[3] *= s;
  1209. te[6] *= s;
  1210. te[1] *= s;
  1211. te[4] *= s;
  1212. te[7] *= s;
  1213. te[2] *= s;
  1214. te[5] *= s;
  1215. te[8] *= s;
  1216. return this;
  1217. }
  1218. determinant() {
  1219. const te = this.elements;
  1220. const a = te[0],
  1221. b = te[1],
  1222. c = te[2],
  1223. d = te[3],
  1224. e = te[4],
  1225. f = te[5],
  1226. g = te[6],
  1227. h = te[7],
  1228. i = te[8];
  1229. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  1230. }
  1231. invert() {
  1232. const te = this.elements,
  1233. n11 = te[0],
  1234. n21 = te[1],
  1235. n31 = te[2],
  1236. n12 = te[3],
  1237. n22 = te[4],
  1238. n32 = te[5],
  1239. n13 = te[6],
  1240. n23 = te[7],
  1241. n33 = te[8],
  1242. t11 = n33 * n22 - n32 * n23,
  1243. t12 = n32 * n13 - n33 * n12,
  1244. t13 = n23 * n12 - n22 * n13,
  1245. det = n11 * t11 + n21 * t12 + n31 * t13;
  1246. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  1247. const detInv = 1 / det;
  1248. te[0] = t11 * detInv;
  1249. te[1] = (n31 * n23 - n33 * n21) * detInv;
  1250. te[2] = (n32 * n21 - n31 * n22) * detInv;
  1251. te[3] = t12 * detInv;
  1252. te[4] = (n33 * n11 - n31 * n13) * detInv;
  1253. te[5] = (n31 * n12 - n32 * n11) * detInv;
  1254. te[6] = t13 * detInv;
  1255. te[7] = (n21 * n13 - n23 * n11) * detInv;
  1256. te[8] = (n22 * n11 - n21 * n12) * detInv;
  1257. return this;
  1258. }
  1259. transpose() {
  1260. let tmp;
  1261. const m = this.elements;
  1262. tmp = m[1];
  1263. m[1] = m[3];
  1264. m[3] = tmp;
  1265. tmp = m[2];
  1266. m[2] = m[6];
  1267. m[6] = tmp;
  1268. tmp = m[5];
  1269. m[5] = m[7];
  1270. m[7] = tmp;
  1271. return this;
  1272. }
  1273. getNormalMatrix(matrix4) {
  1274. return this.setFromMatrix4(matrix4).copy(this).invert().transpose();
  1275. }
  1276. transposeIntoArray(r) {
  1277. const m = this.elements;
  1278. r[0] = m[0];
  1279. r[1] = m[3];
  1280. r[2] = m[6];
  1281. r[3] = m[1];
  1282. r[4] = m[4];
  1283. r[5] = m[7];
  1284. r[6] = m[2];
  1285. r[7] = m[5];
  1286. r[8] = m[8];
  1287. return this;
  1288. }
  1289. setUvTransform(tx, ty, sx, sy, rotation, cx, cy) {
  1290. const c = Math.cos(rotation);
  1291. const s = Math.sin(rotation);
  1292. 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);
  1293. }
  1294. scale(sx, sy) {
  1295. const te = this.elements;
  1296. te[0] *= sx;
  1297. te[3] *= sx;
  1298. te[6] *= sx;
  1299. te[1] *= sy;
  1300. te[4] *= sy;
  1301. te[7] *= sy;
  1302. return this;
  1303. }
  1304. rotate(theta) {
  1305. const c = Math.cos(theta);
  1306. const s = Math.sin(theta);
  1307. const te = this.elements;
  1308. const a11 = te[0],
  1309. a12 = te[3],
  1310. a13 = te[6];
  1311. const a21 = te[1],
  1312. a22 = te[4],
  1313. a23 = te[7];
  1314. te[0] = c * a11 + s * a21;
  1315. te[3] = c * a12 + s * a22;
  1316. te[6] = c * a13 + s * a23;
  1317. te[1] = -s * a11 + c * a21;
  1318. te[4] = -s * a12 + c * a22;
  1319. te[7] = -s * a13 + c * a23;
  1320. return this;
  1321. }
  1322. translate(tx, ty) {
  1323. const te = this.elements;
  1324. te[0] += tx * te[2];
  1325. te[3] += tx * te[5];
  1326. te[6] += tx * te[8];
  1327. te[1] += ty * te[2];
  1328. te[4] += ty * te[5];
  1329. te[7] += ty * te[8];
  1330. return this;
  1331. }
  1332. equals(matrix) {
  1333. const te = this.elements;
  1334. const me = matrix.elements;
  1335. for (let i = 0; i < 9; i++) {
  1336. if (te[i] !== me[i]) return false;
  1337. }
  1338. return true;
  1339. }
  1340. fromArray(array, offset = 0) {
  1341. for (let i = 0; i < 9; i++) {
  1342. this.elements[i] = array[i + offset];
  1343. }
  1344. return this;
  1345. }
  1346. toArray(array = [], offset = 0) {
  1347. const te = this.elements;
  1348. array[offset] = te[0];
  1349. array[offset + 1] = te[1];
  1350. array[offset + 2] = te[2];
  1351. array[offset + 3] = te[3];
  1352. array[offset + 4] = te[4];
  1353. array[offset + 5] = te[5];
  1354. array[offset + 6] = te[6];
  1355. array[offset + 7] = te[7];
  1356. array[offset + 8] = te[8];
  1357. return array;
  1358. }
  1359. }
  1360. exports.Matrix3 = Matrix3;
  1361. let _canvas;
  1362. const ImageUtils = {
  1363. getDataURL: function (image) {
  1364. if (/^data:/i.test(image.src)) {
  1365. return image.src;
  1366. }
  1367. if (typeof HTMLCanvasElement == 'undefined') {
  1368. return image.src;
  1369. }
  1370. let canvas;
  1371. if (image instanceof HTMLCanvasElement) {
  1372. canvas = image;
  1373. } else {
  1374. if (_canvas === undefined) _canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  1375. _canvas.width = image.width;
  1376. _canvas.height = image.height;
  1377. const context = _canvas.getContext('2d');
  1378. if (image instanceof ImageData) {
  1379. context.putImageData(image, 0, 0);
  1380. } else {
  1381. context.drawImage(image, 0, 0, image.width, image.height);
  1382. }
  1383. canvas = _canvas;
  1384. }
  1385. if (canvas.width > 2048 || canvas.height > 2048) {
  1386. return canvas.toDataURL('image/jpeg', 0.6);
  1387. } else {
  1388. return canvas.toDataURL('image/png');
  1389. }
  1390. }
  1391. };
  1392. exports.ImageUtils = ImageUtils;
  1393. let textureId = 0;
  1394. function Texture(image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = 1, encoding = LinearEncoding) {
  1395. Object.defineProperty(this, 'id', {
  1396. value: textureId++
  1397. });
  1398. this.uuid = MathUtils.generateUUID();
  1399. this.name = '';
  1400. this.image = image;
  1401. this.mipmaps = [];
  1402. this.mapping = mapping;
  1403. this.wrapS = wrapS;
  1404. this.wrapT = wrapT;
  1405. this.magFilter = magFilter;
  1406. this.minFilter = minFilter;
  1407. this.anisotropy = anisotropy;
  1408. this.format = format;
  1409. this.internalFormat = null;
  1410. this.type = type;
  1411. this.offset = new Vector2(0, 0);
  1412. this.repeat = new Vector2(1, 1);
  1413. this.center = new Vector2(0, 0);
  1414. this.rotation = 0;
  1415. this.matrixAutoUpdate = true;
  1416. this.matrix = new Matrix3();
  1417. this.generateMipmaps = true;
  1418. this.premultiplyAlpha = false;
  1419. this.flipY = true;
  1420. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1421. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  1422. //
  1423. // Also changing the encoding after already used by a Material will not automatically make the Material
  1424. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  1425. this.encoding = encoding;
  1426. this.version = 0;
  1427. this.onUpdate = null;
  1428. }
  1429. Texture.DEFAULT_IMAGE = undefined;
  1430. Texture.DEFAULT_MAPPING = UVMapping;
  1431. Texture.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  1432. constructor: Texture,
  1433. isTexture: true,
  1434. updateMatrix: function () {
  1435. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  1436. },
  1437. clone: function () {
  1438. return new this.constructor().copy(this);
  1439. },
  1440. copy: function (source) {
  1441. this.name = source.name;
  1442. this.image = source.image;
  1443. this.mipmaps = source.mipmaps.slice(0);
  1444. this.mapping = source.mapping;
  1445. this.wrapS = source.wrapS;
  1446. this.wrapT = source.wrapT;
  1447. this.magFilter = source.magFilter;
  1448. this.minFilter = source.minFilter;
  1449. this.anisotropy = source.anisotropy;
  1450. this.format = source.format;
  1451. this.internalFormat = source.internalFormat;
  1452. this.type = source.type;
  1453. this.offset.copy(source.offset);
  1454. this.repeat.copy(source.repeat);
  1455. this.center.copy(source.center);
  1456. this.rotation = source.rotation;
  1457. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1458. this.matrix.copy(source.matrix);
  1459. this.generateMipmaps = source.generateMipmaps;
  1460. this.premultiplyAlpha = source.premultiplyAlpha;
  1461. this.flipY = source.flipY;
  1462. this.unpackAlignment = source.unpackAlignment;
  1463. this.encoding = source.encoding;
  1464. return this;
  1465. },
  1466. toJSON: function (meta) {
  1467. const isRootObject = meta === undefined || typeof meta === 'string';
  1468. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  1469. return meta.textures[this.uuid];
  1470. }
  1471. const output = {
  1472. metadata: {
  1473. version: 4.5,
  1474. type: 'Texture',
  1475. generator: 'Texture.toJSON'
  1476. },
  1477. uuid: this.uuid,
  1478. name: this.name,
  1479. mapping: this.mapping,
  1480. repeat: [this.repeat.x, this.repeat.y],
  1481. offset: [this.offset.x, this.offset.y],
  1482. center: [this.center.x, this.center.y],
  1483. rotation: this.rotation,
  1484. wrap: [this.wrapS, this.wrapT],
  1485. format: this.format,
  1486. type: this.type,
  1487. encoding: this.encoding,
  1488. minFilter: this.minFilter,
  1489. magFilter: this.magFilter,
  1490. anisotropy: this.anisotropy,
  1491. flipY: this.flipY,
  1492. premultiplyAlpha: this.premultiplyAlpha,
  1493. unpackAlignment: this.unpackAlignment
  1494. };
  1495. if (this.image !== undefined) {
  1496. // TODO: Move to THREE.Image
  1497. const image = this.image;
  1498. if (image.uuid === undefined) {
  1499. image.uuid = MathUtils.generateUUID(); // UGH
  1500. }
  1501. if (!isRootObject && meta.images[image.uuid] === undefined) {
  1502. let url;
  1503. if (Array.isArray(image)) {
  1504. // process array of images e.g. CubeTexture
  1505. url = [];
  1506. for (let i = 0, l = image.length; i < l; i++) {
  1507. // check cube texture with data textures
  1508. if (image[i].isDataTexture) {
  1509. url.push(serializeImage(image[i].image));
  1510. } else {
  1511. url.push(serializeImage(image[i]));
  1512. }
  1513. }
  1514. } else {
  1515. // process single image
  1516. url = serializeImage(image);
  1517. }
  1518. meta.images[image.uuid] = {
  1519. uuid: image.uuid,
  1520. url: url
  1521. };
  1522. }
  1523. output.image = image.uuid;
  1524. }
  1525. if (!isRootObject) {
  1526. meta.textures[this.uuid] = output;
  1527. }
  1528. return output;
  1529. },
  1530. dispose: function () {
  1531. this.dispatchEvent({
  1532. type: 'dispose'
  1533. });
  1534. },
  1535. transformUv: function (uv) {
  1536. if (this.mapping !== UVMapping) return uv;
  1537. uv.applyMatrix3(this.matrix);
  1538. if (uv.x < 0 || uv.x > 1) {
  1539. switch (this.wrapS) {
  1540. case RepeatWrapping:
  1541. uv.x = uv.x - Math.floor(uv.x);
  1542. break;
  1543. case ClampToEdgeWrapping:
  1544. uv.x = uv.x < 0 ? 0 : 1;
  1545. break;
  1546. case MirroredRepeatWrapping:
  1547. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  1548. uv.x = Math.ceil(uv.x) - uv.x;
  1549. } else {
  1550. uv.x = uv.x - Math.floor(uv.x);
  1551. }
  1552. break;
  1553. }
  1554. }
  1555. if (uv.y < 0 || uv.y > 1) {
  1556. switch (this.wrapT) {
  1557. case RepeatWrapping:
  1558. uv.y = uv.y - Math.floor(uv.y);
  1559. break;
  1560. case ClampToEdgeWrapping:
  1561. uv.y = uv.y < 0 ? 0 : 1;
  1562. break;
  1563. case MirroredRepeatWrapping:
  1564. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  1565. uv.y = Math.ceil(uv.y) - uv.y;
  1566. } else {
  1567. uv.y = uv.y - Math.floor(uv.y);
  1568. }
  1569. break;
  1570. }
  1571. }
  1572. if (this.flipY) {
  1573. uv.y = 1 - uv.y;
  1574. }
  1575. return uv;
  1576. }
  1577. });
  1578. Object.defineProperty(Texture.prototype, "needsUpdate", {
  1579. set: function (value) {
  1580. if (value === true) this.version++;
  1581. }
  1582. });
  1583. function serializeImage(image) {
  1584. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  1585. // default images
  1586. return ImageUtils.getDataURL(image);
  1587. } else {
  1588. if (image.data) {
  1589. // images of DataTexture
  1590. return {
  1591. data: Array.prototype.slice.call(image.data),
  1592. width: image.width,
  1593. height: image.height,
  1594. type: image.data.constructor.name
  1595. };
  1596. } else {
  1597. console.warn('THREE.Texture: Unable to serialize Texture.');
  1598. return {};
  1599. }
  1600. }
  1601. }
  1602. class Vector4 {
  1603. constructor(x = 0, y = 0, z = 0, w = 1) {
  1604. Object.defineProperty(this, 'isVector4', {
  1605. value: true
  1606. });
  1607. this.x = x;
  1608. this.y = y;
  1609. this.z = z;
  1610. this.w = w;
  1611. }
  1612. get width() {
  1613. return this.z;
  1614. }
  1615. set width(value) {
  1616. this.z = value;
  1617. }
  1618. get height() {
  1619. return this.w;
  1620. }
  1621. set height(value) {
  1622. this.w = value;
  1623. }
  1624. set(x, y, z, w) {
  1625. this.x = x;
  1626. this.y = y;
  1627. this.z = z;
  1628. this.w = w;
  1629. return this;
  1630. }
  1631. setScalar(scalar) {
  1632. this.x = scalar;
  1633. this.y = scalar;
  1634. this.z = scalar;
  1635. this.w = scalar;
  1636. return this;
  1637. }
  1638. setX(x) {
  1639. this.x = x;
  1640. return this;
  1641. }
  1642. setY(y) {
  1643. this.y = y;
  1644. return this;
  1645. }
  1646. setZ(z) {
  1647. this.z = z;
  1648. return this;
  1649. }
  1650. setW(w) {
  1651. this.w = w;
  1652. return this;
  1653. }
  1654. setComponent(index, value) {
  1655. switch (index) {
  1656. case 0:
  1657. this.x = value;
  1658. break;
  1659. case 1:
  1660. this.y = value;
  1661. break;
  1662. case 2:
  1663. this.z = value;
  1664. break;
  1665. case 3:
  1666. this.w = value;
  1667. break;
  1668. default:
  1669. throw new Error('index is out of range: ' + index);
  1670. }
  1671. return this;
  1672. }
  1673. getComponent(index) {
  1674. switch (index) {
  1675. case 0:
  1676. return this.x;
  1677. case 1:
  1678. return this.y;
  1679. case 2:
  1680. return this.z;
  1681. case 3:
  1682. return this.w;
  1683. default:
  1684. throw new Error('index is out of range: ' + index);
  1685. }
  1686. }
  1687. clone() {
  1688. return new this.constructor(this.x, this.y, this.z, this.w);
  1689. }
  1690. copy(v) {
  1691. this.x = v.x;
  1692. this.y = v.y;
  1693. this.z = v.z;
  1694. this.w = v.w !== undefined ? v.w : 1;
  1695. return this;
  1696. }
  1697. add(v, w) {
  1698. if (w !== undefined) {
  1699. console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  1700. return this.addVectors(v, w);
  1701. }
  1702. this.x += v.x;
  1703. this.y += v.y;
  1704. this.z += v.z;
  1705. this.w += v.w;
  1706. return this;
  1707. }
  1708. addScalar(s) {
  1709. this.x += s;
  1710. this.y += s;
  1711. this.z += s;
  1712. this.w += s;
  1713. return this;
  1714. }
  1715. addVectors(a, b) {
  1716. this.x = a.x + b.x;
  1717. this.y = a.y + b.y;
  1718. this.z = a.z + b.z;
  1719. this.w = a.w + b.w;
  1720. return this;
  1721. }
  1722. addScaledVector(v, s) {
  1723. this.x += v.x * s;
  1724. this.y += v.y * s;
  1725. this.z += v.z * s;
  1726. this.w += v.w * s;
  1727. return this;
  1728. }
  1729. sub(v, w) {
  1730. if (w !== undefined) {
  1731. console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  1732. return this.subVectors(v, w);
  1733. }
  1734. this.x -= v.x;
  1735. this.y -= v.y;
  1736. this.z -= v.z;
  1737. this.w -= v.w;
  1738. return this;
  1739. }
  1740. subScalar(s) {
  1741. this.x -= s;
  1742. this.y -= s;
  1743. this.z -= s;
  1744. this.w -= s;
  1745. return this;
  1746. }
  1747. subVectors(a, b) {
  1748. this.x = a.x - b.x;
  1749. this.y = a.y - b.y;
  1750. this.z = a.z - b.z;
  1751. this.w = a.w - b.w;
  1752. return this;
  1753. }
  1754. multiplyScalar(scalar) {
  1755. this.x *= scalar;
  1756. this.y *= scalar;
  1757. this.z *= scalar;
  1758. this.w *= scalar;
  1759. return this;
  1760. }
  1761. applyMatrix4(m) {
  1762. const x = this.x,
  1763. y = this.y,
  1764. z = this.z,
  1765. w = this.w;
  1766. const e = m.elements;
  1767. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1768. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1769. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1770. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1771. return this;
  1772. }
  1773. divideScalar(scalar) {
  1774. return this.multiplyScalar(1 / scalar);
  1775. }
  1776. setAxisAngleFromQuaternion(q) {
  1777. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1778. // q is assumed to be normalized
  1779. this.w = 2 * Math.acos(q.w);
  1780. const s = Math.sqrt(1 - q.w * q.w);
  1781. if (s < 0.0001) {
  1782. this.x = 1;
  1783. this.y = 0;
  1784. this.z = 0;
  1785. } else {
  1786. this.x = q.x / s;
  1787. this.y = q.y / s;
  1788. this.z = q.z / s;
  1789. }
  1790. return this;
  1791. }
  1792. setAxisAngleFromRotationMatrix(m) {
  1793. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1794. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1795. let angle, x, y, z; // variables for result
  1796. const epsilon = 0.01,
  1797. // margin to allow for rounding errors
  1798. epsilon2 = 0.1,
  1799. // margin to distinguish between 0 and 180 degrees
  1800. te = m.elements,
  1801. m11 = te[0],
  1802. m12 = te[4],
  1803. m13 = te[8],
  1804. m21 = te[1],
  1805. m22 = te[5],
  1806. m23 = te[9],
  1807. m31 = te[2],
  1808. m32 = te[6],
  1809. m33 = te[10];
  1810. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  1811. // singularity found
  1812. // first check for identity matrix which must have +1 for all terms
  1813. // in leading diagonal and zero in other terms
  1814. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  1815. // this singularity is identity matrix so angle = 0
  1816. this.set(1, 0, 0, 0);
  1817. return this; // zero angle, arbitrary axis
  1818. } // otherwise this singularity is angle = 180
  1819. angle = Math.PI;
  1820. const xx = (m11 + 1) / 2;
  1821. const yy = (m22 + 1) / 2;
  1822. const zz = (m33 + 1) / 2;
  1823. const xy = (m12 + m21) / 4;
  1824. const xz = (m13 + m31) / 4;
  1825. const yz = (m23 + m32) / 4;
  1826. if (xx > yy && xx > zz) {
  1827. // m11 is the largest diagonal term
  1828. if (xx < epsilon) {
  1829. x = 0;
  1830. y = 0.707106781;
  1831. z = 0.707106781;
  1832. } else {
  1833. x = Math.sqrt(xx);
  1834. y = xy / x;
  1835. z = xz / x;
  1836. }
  1837. } else if (yy > zz) {
  1838. // m22 is the largest diagonal term
  1839. if (yy < epsilon) {
  1840. x = 0.707106781;
  1841. y = 0;
  1842. z = 0.707106781;
  1843. } else {
  1844. y = Math.sqrt(yy);
  1845. x = xy / y;
  1846. z = yz / y;
  1847. }
  1848. } else {
  1849. // m33 is the largest diagonal term so base result on this
  1850. if (zz < epsilon) {
  1851. x = 0.707106781;
  1852. y = 0.707106781;
  1853. z = 0;
  1854. } else {
  1855. z = Math.sqrt(zz);
  1856. x = xz / z;
  1857. y = yz / z;
  1858. }
  1859. }
  1860. this.set(x, y, z, angle);
  1861. return this; // return 180 deg rotation
  1862. } // as we have reached here there are no singularities so we can handle normally
  1863. let s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  1864. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1865. // caught by singularity test above, but I've left it in just in case
  1866. this.x = (m32 - m23) / s;
  1867. this.y = (m13 - m31) / s;
  1868. this.z = (m21 - m12) / s;
  1869. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  1870. return this;
  1871. }
  1872. min(v) {
  1873. this.x = Math.min(this.x, v.x);
  1874. this.y = Math.min(this.y, v.y);
  1875. this.z = Math.min(this.z, v.z);
  1876. this.w = Math.min(this.w, v.w);
  1877. return this;
  1878. }
  1879. max(v) {
  1880. this.x = Math.max(this.x, v.x);
  1881. this.y = Math.max(this.y, v.y);
  1882. this.z = Math.max(this.z, v.z);
  1883. this.w = Math.max(this.w, v.w);
  1884. return this;
  1885. }
  1886. clamp(min, max) {
  1887. // assumes min < max, componentwise
  1888. this.x = Math.max(min.x, Math.min(max.x, this.x));
  1889. this.y = Math.max(min.y, Math.min(max.y, this.y));
  1890. this.z = Math.max(min.z, Math.min(max.z, this.z));
  1891. this.w = Math.max(min.w, Math.min(max.w, this.w));
  1892. return this;
  1893. }
  1894. clampScalar(minVal, maxVal) {
  1895. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  1896. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  1897. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  1898. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  1899. return this;
  1900. }
  1901. clampLength(min, max) {
  1902. const length = this.length();
  1903. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  1904. }
  1905. floor() {
  1906. this.x = Math.floor(this.x);
  1907. this.y = Math.floor(this.y);
  1908. this.z = Math.floor(this.z);
  1909. this.w = Math.floor(this.w);
  1910. return this;
  1911. }
  1912. ceil() {
  1913. this.x = Math.ceil(this.x);
  1914. this.y = Math.ceil(this.y);
  1915. this.z = Math.ceil(this.z);
  1916. this.w = Math.ceil(this.w);
  1917. return this;
  1918. }
  1919. round() {
  1920. this.x = Math.round(this.x);
  1921. this.y = Math.round(this.y);
  1922. this.z = Math.round(this.z);
  1923. this.w = Math.round(this.w);
  1924. return this;
  1925. }
  1926. roundToZero() {
  1927. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  1928. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  1929. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  1930. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  1931. return this;
  1932. }
  1933. negate() {
  1934. this.x = -this.x;
  1935. this.y = -this.y;
  1936. this.z = -this.z;
  1937. this.w = -this.w;
  1938. return this;
  1939. }
  1940. dot(v) {
  1941. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1942. }
  1943. lengthSq() {
  1944. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1945. }
  1946. length() {
  1947. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1948. }
  1949. manhattanLength() {
  1950. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  1951. }
  1952. normalize() {
  1953. return this.divideScalar(this.length() || 1);
  1954. }
  1955. setLength(length) {
  1956. return this.normalize().multiplyScalar(length);
  1957. }
  1958. lerp(v, alpha) {
  1959. this.x += (v.x - this.x) * alpha;
  1960. this.y += (v.y - this.y) * alpha;
  1961. this.z += (v.z - this.z) * alpha;
  1962. this.w += (v.w - this.w) * alpha;
  1963. return this;
  1964. }
  1965. lerpVectors(v1, v2, alpha) {
  1966. this.x = v1.x + (v2.x - v1.x) * alpha;
  1967. this.y = v1.y + (v2.y - v1.y) * alpha;
  1968. this.z = v1.z + (v2.z - v1.z) * alpha;
  1969. this.w = v1.w + (v2.w - v1.w) * alpha;
  1970. return this;
  1971. }
  1972. equals(v) {
  1973. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  1974. }
  1975. fromArray(array, offset = 0) {
  1976. this.x = array[offset];
  1977. this.y = array[offset + 1];
  1978. this.z = array[offset + 2];
  1979. this.w = array[offset + 3];
  1980. return this;
  1981. }
  1982. toArray(array = [], offset = 0) {
  1983. array[offset] = this.x;
  1984. array[offset + 1] = this.y;
  1985. array[offset + 2] = this.z;
  1986. array[offset + 3] = this.w;
  1987. return array;
  1988. }
  1989. fromBufferAttribute(attribute, index, offset) {
  1990. if (offset !== undefined) {
  1991. console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');
  1992. }
  1993. this.x = attribute.getX(index);
  1994. this.y = attribute.getY(index);
  1995. this.z = attribute.getZ(index);
  1996. this.w = attribute.getW(index);
  1997. return this;
  1998. }
  1999. random() {
  2000. this.x = Math.random();
  2001. this.y = Math.random();
  2002. this.z = Math.random();
  2003. this.w = Math.random();
  2004. return this;
  2005. }
  2006. }
  2007. /*
  2008. In options, we can specify:
  2009. * Texture parameters for an auto-generated target texture
  2010. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  2011. */
  2012. exports.Vector4 = Vector4;
  2013. function WebGLRenderTarget(width, height, options) {
  2014. this.width = width;
  2015. this.height = height;
  2016. this.scissor = new Vector4(0, 0, width, height);
  2017. this.scissorTest = false;
  2018. this.viewport = new Vector4(0, 0, width, height);
  2019. options = options || {};
  2020. this.texture = new Texture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  2021. this.texture.image = {};
  2022. this.texture.image.width = width;
  2023. this.texture.image.height = height;
  2024. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  2025. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  2026. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  2027. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  2028. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  2029. }
  2030. WebGLRenderTarget.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  2031. constructor: WebGLRenderTarget,
  2032. isWebGLRenderTarget: true,
  2033. setSize: function (width, height) {
  2034. if (this.width !== width || this.height !== height) {
  2035. this.width = width;
  2036. this.height = height;
  2037. this.texture.image.width = width;
  2038. this.texture.image.height = height;
  2039. this.dispose();
  2040. }
  2041. this.viewport.set(0, 0, width, height);
  2042. this.scissor.set(0, 0, width, height);
  2043. },
  2044. clone: function () {
  2045. return new this.constructor().copy(this);
  2046. },
  2047. copy: function (source) {
  2048. this.width = source.width;
  2049. this.height = source.height;
  2050. this.viewport.copy(source.viewport);
  2051. this.texture = source.texture.clone();
  2052. this.depthBuffer = source.depthBuffer;
  2053. this.stencilBuffer = source.stencilBuffer;
  2054. this.depthTexture = source.depthTexture;
  2055. return this;
  2056. },
  2057. dispose: function () {
  2058. this.dispatchEvent({
  2059. type: 'dispose'
  2060. });
  2061. }
  2062. });
  2063. function WebGLMultisampleRenderTarget(width, height, options) {
  2064. WebGLRenderTarget.call(this, width, height, options);
  2065. this.samples = 4;
  2066. }
  2067. WebGLMultisampleRenderTarget.prototype = Object.assign(Object.create(WebGLRenderTarget.prototype), {
  2068. constructor: WebGLMultisampleRenderTarget,
  2069. isWebGLMultisampleRenderTarget: true,
  2070. copy: function (source) {
  2071. WebGLRenderTarget.prototype.copy.call(this, source);
  2072. this.samples = source.samples;
  2073. return this;
  2074. }
  2075. });
  2076. class Quaternion {
  2077. constructor(x = 0, y = 0, z = 0, w = 1) {
  2078. Object.defineProperty(this, 'isQuaternion', {
  2079. value: true
  2080. });
  2081. this._x = x;
  2082. this._y = y;
  2083. this._z = z;
  2084. this._w = w;
  2085. }
  2086. static slerp(qa, qb, qm, t) {
  2087. return qm.copy(qa).slerp(qb, t);
  2088. }
  2089. static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  2090. // fuzz-free, array-based Quaternion SLERP operation
  2091. let x0 = src0[srcOffset0 + 0],
  2092. y0 = src0[srcOffset0 + 1],
  2093. z0 = src0[srcOffset0 + 2],
  2094. w0 = src0[srcOffset0 + 3];
  2095. const x1 = src1[srcOffset1 + 0],
  2096. y1 = src1[srcOffset1 + 1],
  2097. z1 = src1[srcOffset1 + 2],
  2098. w1 = src1[srcOffset1 + 3];
  2099. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  2100. let s = 1 - t;
  2101. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2102. dir = cos >= 0 ? 1 : -1,
  2103. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  2104. if (sqrSin > Number.EPSILON) {
  2105. const sin = Math.sqrt(sqrSin),
  2106. len = Math.atan2(sin, cos * dir);
  2107. s = Math.sin(s * len) / sin;
  2108. t = Math.sin(t * len) / sin;
  2109. }
  2110. const tDir = t * dir;
  2111. x0 = x0 * s + x1 * tDir;
  2112. y0 = y0 * s + y1 * tDir;
  2113. z0 = z0 * s + z1 * tDir;
  2114. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  2115. if (s === 1 - t) {
  2116. const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  2117. x0 *= f;
  2118. y0 *= f;
  2119. z0 *= f;
  2120. w0 *= f;
  2121. }
  2122. }
  2123. dst[dstOffset] = x0;
  2124. dst[dstOffset + 1] = y0;
  2125. dst[dstOffset + 2] = z0;
  2126. dst[dstOffset + 3] = w0;
  2127. }
  2128. static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) {
  2129. const x0 = src0[srcOffset0];
  2130. const y0 = src0[srcOffset0 + 1];
  2131. const z0 = src0[srcOffset0 + 2];
  2132. const w0 = src0[srcOffset0 + 3];
  2133. const x1 = src1[srcOffset1];
  2134. const y1 = src1[srcOffset1 + 1];
  2135. const z1 = src1[srcOffset1 + 2];
  2136. const w1 = src1[srcOffset1 + 3];
  2137. dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2138. dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2139. dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2140. dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2141. return dst;
  2142. }
  2143. get x() {
  2144. return this._x;
  2145. }
  2146. set x(value) {
  2147. this._x = value;
  2148. this._onChangeCallback();
  2149. }
  2150. get y() {
  2151. return this._y;
  2152. }
  2153. set y(value) {
  2154. this._y = value;
  2155. this._onChangeCallback();
  2156. }
  2157. get z() {
  2158. return this._z;
  2159. }
  2160. set z(value) {
  2161. this._z = value;
  2162. this._onChangeCallback();
  2163. }
  2164. get w() {
  2165. return this._w;
  2166. }
  2167. set w(value) {
  2168. this._w = value;
  2169. this._onChangeCallback();
  2170. }
  2171. set(x, y, z, w) {
  2172. this._x = x;
  2173. this._y = y;
  2174. this._z = z;
  2175. this._w = w;
  2176. this._onChangeCallback();
  2177. return this;
  2178. }
  2179. clone() {
  2180. return new this.constructor(this._x, this._y, this._z, this._w);
  2181. }
  2182. copy(quaternion) {
  2183. this._x = quaternion.x;
  2184. this._y = quaternion.y;
  2185. this._z = quaternion.z;
  2186. this._w = quaternion.w;
  2187. this._onChangeCallback();
  2188. return this;
  2189. }
  2190. setFromEuler(euler, update) {
  2191. if (!(euler && euler.isEuler)) {
  2192. throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2193. }
  2194. const x = euler._x,
  2195. y = euler._y,
  2196. z = euler._z,
  2197. order = euler._order; // http://www.mathworks.com/matlabcentral/fileexchange/
  2198. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2199. // content/SpinCalc.m
  2200. const cos = Math.cos;
  2201. const sin = Math.sin;
  2202. const c1 = cos(x / 2);
  2203. const c2 = cos(y / 2);
  2204. const c3 = cos(z / 2);
  2205. const s1 = sin(x / 2);
  2206. const s2 = sin(y / 2);
  2207. const s3 = sin(z / 2);
  2208. switch (order) {
  2209. case 'XYZ':
  2210. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2211. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2212. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2213. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2214. break;
  2215. case 'YXZ':
  2216. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2217. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2218. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2219. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2220. break;
  2221. case 'ZXY':
  2222. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2223. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2224. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2225. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2226. break;
  2227. case 'ZYX':
  2228. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2229. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2230. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2231. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2232. break;
  2233. case 'YZX':
  2234. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2235. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2236. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2237. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2238. break;
  2239. case 'XZY':
  2240. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2241. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2242. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2243. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2244. break;
  2245. default:
  2246. console.warn('THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order);
  2247. }
  2248. if (update !== false) this._onChangeCallback();
  2249. return this;
  2250. }
  2251. setFromAxisAngle(axis, angle) {
  2252. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2253. // assumes axis is normalized
  2254. const halfAngle = angle / 2,
  2255. s = Math.sin(halfAngle);
  2256. this._x = axis.x * s;
  2257. this._y = axis.y * s;
  2258. this._z = axis.z * s;
  2259. this._w = Math.cos(halfAngle);
  2260. this._onChangeCallback();
  2261. return this;
  2262. }
  2263. setFromRotationMatrix(m) {
  2264. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2265. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2266. const te = m.elements,
  2267. m11 = te[0],
  2268. m12 = te[4],
  2269. m13 = te[8],
  2270. m21 = te[1],
  2271. m22 = te[5],
  2272. m23 = te[9],
  2273. m31 = te[2],
  2274. m32 = te[6],
  2275. m33 = te[10],
  2276. trace = m11 + m22 + m33;
  2277. if (trace > 0) {
  2278. const s = 0.5 / Math.sqrt(trace + 1.0);
  2279. this._w = 0.25 / s;
  2280. this._x = (m32 - m23) * s;
  2281. this._y = (m13 - m31) * s;
  2282. this._z = (m21 - m12) * s;
  2283. } else if (m11 > m22 && m11 > m33) {
  2284. const s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2285. this._w = (m32 - m23) / s;
  2286. this._x = 0.25 * s;
  2287. this._y = (m12 + m21) / s;
  2288. this._z = (m13 + m31) / s;
  2289. } else if (m22 > m33) {
  2290. const s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2291. this._w = (m13 - m31) / s;
  2292. this._x = (m12 + m21) / s;
  2293. this._y = 0.25 * s;
  2294. this._z = (m23 + m32) / s;
  2295. } else {
  2296. const s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2297. this._w = (m21 - m12) / s;
  2298. this._x = (m13 + m31) / s;
  2299. this._y = (m23 + m32) / s;
  2300. this._z = 0.25 * s;
  2301. }
  2302. this._onChangeCallback();
  2303. return this;
  2304. }
  2305. setFromUnitVectors(vFrom, vTo) {
  2306. // assumes direction vectors vFrom and vTo are normalized
  2307. const EPS = 0.000001;
  2308. let r = vFrom.dot(vTo) + 1;
  2309. if (r < EPS) {
  2310. r = 0;
  2311. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  2312. this._x = -vFrom.y;
  2313. this._y = vFrom.x;
  2314. this._z = 0;
  2315. this._w = r;
  2316. } else {
  2317. this._x = 0;
  2318. this._y = -vFrom.z;
  2319. this._z = vFrom.y;
  2320. this._w = r;
  2321. }
  2322. } else {
  2323. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2324. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2325. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2326. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2327. this._w = r;
  2328. }
  2329. return this.normalize();
  2330. }
  2331. angleTo(q) {
  2332. return 2 * Math.acos(Math.abs(MathUtils.clamp(this.dot(q), -1, 1)));
  2333. }
  2334. rotateTowards(q, step) {
  2335. const angle = this.angleTo(q);
  2336. if (angle === 0) return this;
  2337. const t = Math.min(1, step / angle);
  2338. this.slerp(q, t);
  2339. return this;
  2340. }
  2341. identity() {
  2342. return this.set(0, 0, 0, 1);
  2343. }
  2344. invert() {
  2345. // quaternion is assumed to have unit length
  2346. return this.conjugate();
  2347. }
  2348. conjugate() {
  2349. this._x *= -1;
  2350. this._y *= -1;
  2351. this._z *= -1;
  2352. this._onChangeCallback();
  2353. return this;
  2354. }
  2355. dot(v) {
  2356. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2357. }
  2358. lengthSq() {
  2359. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2360. }
  2361. length() {
  2362. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  2363. }
  2364. normalize() {
  2365. let l = this.length();
  2366. if (l === 0) {
  2367. this._x = 0;
  2368. this._y = 0;
  2369. this._z = 0;
  2370. this._w = 1;
  2371. } else {
  2372. l = 1 / l;
  2373. this._x = this._x * l;
  2374. this._y = this._y * l;
  2375. this._z = this._z * l;
  2376. this._w = this._w * l;
  2377. }
  2378. this._onChangeCallback();
  2379. return this;
  2380. }
  2381. multiply(q, p) {
  2382. if (p !== undefined) {
  2383. console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
  2384. return this.multiplyQuaternions(q, p);
  2385. }
  2386. return this.multiplyQuaternions(this, q);
  2387. }
  2388. premultiply(q) {
  2389. return this.multiplyQuaternions(q, this);
  2390. }
  2391. multiplyQuaternions(a, b) {
  2392. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2393. const qax = a._x,
  2394. qay = a._y,
  2395. qaz = a._z,
  2396. qaw = a._w;
  2397. const qbx = b._x,
  2398. qby = b._y,
  2399. qbz = b._z,
  2400. qbw = b._w;
  2401. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2402. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2403. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2404. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2405. this._onChangeCallback();
  2406. return this;
  2407. }
  2408. slerp(qb, t) {
  2409. if (t === 0) return this;
  2410. if (t === 1) return this.copy(qb);
  2411. const x = this._x,
  2412. y = this._y,
  2413. z = this._z,
  2414. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2415. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2416. if (cosHalfTheta < 0) {
  2417. this._w = -qb._w;
  2418. this._x = -qb._x;
  2419. this._y = -qb._y;
  2420. this._z = -qb._z;
  2421. cosHalfTheta = -cosHalfTheta;
  2422. } else {
  2423. this.copy(qb);
  2424. }
  2425. if (cosHalfTheta >= 1.0) {
  2426. this._w = w;
  2427. this._x = x;
  2428. this._y = y;
  2429. this._z = z;
  2430. return this;
  2431. }
  2432. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2433. if (sqrSinHalfTheta <= Number.EPSILON) {
  2434. const s = 1 - t;
  2435. this._w = s * w + t * this._w;
  2436. this._x = s * x + t * this._x;
  2437. this._y = s * y + t * this._y;
  2438. this._z = s * z + t * this._z;
  2439. this.normalize();
  2440. this._onChangeCallback();
  2441. return this;
  2442. }
  2443. const sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  2444. const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  2445. const ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  2446. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  2447. this._w = w * ratioA + this._w * ratioB;
  2448. this._x = x * ratioA + this._x * ratioB;
  2449. this._y = y * ratioA + this._y * ratioB;
  2450. this._z = z * ratioA + this._z * ratioB;
  2451. this._onChangeCallback();
  2452. return this;
  2453. }
  2454. equals(quaternion) {
  2455. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  2456. }
  2457. fromArray(array, offset = 0) {
  2458. this._x = array[offset];
  2459. this._y = array[offset + 1];
  2460. this._z = array[offset + 2];
  2461. this._w = array[offset + 3];
  2462. this._onChangeCallback();
  2463. return this;
  2464. }
  2465. toArray(array = [], offset = 0) {
  2466. array[offset] = this._x;
  2467. array[offset + 1] = this._y;
  2468. array[offset + 2] = this._z;
  2469. array[offset + 3] = this._w;
  2470. return array;
  2471. }
  2472. fromBufferAttribute(attribute, index) {
  2473. this._x = attribute.getX(index);
  2474. this._y = attribute.getY(index);
  2475. this._z = attribute.getZ(index);
  2476. this._w = attribute.getW(index);
  2477. return this;
  2478. }
  2479. _onChange(callback) {
  2480. this._onChangeCallback = callback;
  2481. return this;
  2482. }
  2483. _onChangeCallback() {}
  2484. }
  2485. exports.Quaternion = Quaternion;
  2486. class Vector3 {
  2487. constructor(x = 0, y = 0, z = 0) {
  2488. Object.defineProperty(this, 'isVector3', {
  2489. value: true
  2490. });
  2491. this.x = x;
  2492. this.y = y;
  2493. this.z = z;
  2494. }
  2495. set(x, y, z) {
  2496. if (z === undefined) z = this.z; // sprite.scale.set(x,y)
  2497. this.x = x;
  2498. this.y = y;
  2499. this.z = z;
  2500. return this;
  2501. }
  2502. setScalar(scalar) {
  2503. this.x = scalar;
  2504. this.y = scalar;
  2505. this.z = scalar;
  2506. return this;
  2507. }
  2508. setX(x) {
  2509. this.x = x;
  2510. return this;
  2511. }
  2512. setY(y) {
  2513. this.y = y;
  2514. return this;
  2515. }
  2516. setZ(z) {
  2517. this.z = z;
  2518. return this;
  2519. }
  2520. setComponent(index, value) {
  2521. switch (index) {
  2522. case 0:
  2523. this.x = value;
  2524. break;
  2525. case 1:
  2526. this.y = value;
  2527. break;
  2528. case 2:
  2529. this.z = value;
  2530. break;
  2531. default:
  2532. throw new Error('index is out of range: ' + index);
  2533. }
  2534. return this;
  2535. }
  2536. getComponent(index) {
  2537. switch (index) {
  2538. case 0:
  2539. return this.x;
  2540. case 1:
  2541. return this.y;
  2542. case 2:
  2543. return this.z;
  2544. default:
  2545. throw new Error('index is out of range: ' + index);
  2546. }
  2547. }
  2548. clone() {
  2549. return new this.constructor(this.x, this.y, this.z);
  2550. }
  2551. copy(v) {
  2552. this.x = v.x;
  2553. this.y = v.y;
  2554. this.z = v.z;
  2555. return this;
  2556. }
  2557. add(v, w) {
  2558. if (w !== undefined) {
  2559. console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  2560. return this.addVectors(v, w);
  2561. }
  2562. this.x += v.x;
  2563. this.y += v.y;
  2564. this.z += v.z;
  2565. return this;
  2566. }
  2567. addScalar(s) {
  2568. this.x += s;
  2569. this.y += s;
  2570. this.z += s;
  2571. return this;
  2572. }
  2573. addVectors(a, b) {
  2574. this.x = a.x + b.x;
  2575. this.y = a.y + b.y;
  2576. this.z = a.z + b.z;
  2577. return this;
  2578. }
  2579. addScaledVector(v, s) {
  2580. this.x += v.x * s;
  2581. this.y += v.y * s;
  2582. this.z += v.z * s;
  2583. return this;
  2584. }
  2585. sub(v, w) {
  2586. if (w !== undefined) {
  2587. console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  2588. return this.subVectors(v, w);
  2589. }
  2590. this.x -= v.x;
  2591. this.y -= v.y;
  2592. this.z -= v.z;
  2593. return this;
  2594. }
  2595. subScalar(s) {
  2596. this.x -= s;
  2597. this.y -= s;
  2598. this.z -= s;
  2599. return this;
  2600. }
  2601. subVectors(a, b) {
  2602. this.x = a.x - b.x;
  2603. this.y = a.y - b.y;
  2604. this.z = a.z - b.z;
  2605. return this;
  2606. }
  2607. multiply(v, w) {
  2608. if (w !== undefined) {
  2609. console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');
  2610. return this.multiplyVectors(v, w);
  2611. }
  2612. this.x *= v.x;
  2613. this.y *= v.y;
  2614. this.z *= v.z;
  2615. return this;
  2616. }
  2617. multiplyScalar(scalar) {
  2618. this.x *= scalar;
  2619. this.y *= scalar;
  2620. this.z *= scalar;
  2621. return this;
  2622. }
  2623. multiplyVectors(a, b) {
  2624. this.x = a.x * b.x;
  2625. this.y = a.y * b.y;
  2626. this.z = a.z * b.z;
  2627. return this;
  2628. }
  2629. applyEuler(euler) {
  2630. if (!(euler && euler.isEuler)) {
  2631. console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2632. }
  2633. return this.applyQuaternion(_quaternion.setFromEuler(euler));
  2634. }
  2635. applyAxisAngle(axis, angle) {
  2636. return this.applyQuaternion(_quaternion.setFromAxisAngle(axis, angle));
  2637. }
  2638. applyMatrix3(m) {
  2639. const x = this.x,
  2640. y = this.y,
  2641. z = this.z;
  2642. const e = m.elements;
  2643. this.x = e[0] * x + e[3] * y + e[6] * z;
  2644. this.y = e[1] * x + e[4] * y + e[7] * z;
  2645. this.z = e[2] * x + e[5] * y + e[8] * z;
  2646. return this;
  2647. }
  2648. applyNormalMatrix(m) {
  2649. return this.applyMatrix3(m).normalize();
  2650. }
  2651. applyMatrix4(m) {
  2652. const x = this.x,
  2653. y = this.y,
  2654. z = this.z;
  2655. const e = m.elements;
  2656. const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  2657. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  2658. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  2659. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  2660. return this;
  2661. }
  2662. applyQuaternion(q) {
  2663. const x = this.x,
  2664. y = this.y,
  2665. z = this.z;
  2666. const qx = q.x,
  2667. qy = q.y,
  2668. qz = q.z,
  2669. qw = q.w; // calculate quat * vector
  2670. const ix = qw * x + qy * z - qz * y;
  2671. const iy = qw * y + qz * x - qx * z;
  2672. const iz = qw * z + qx * y - qy * x;
  2673. const iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  2674. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2675. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2676. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2677. return this;
  2678. }
  2679. project(camera) {
  2680. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  2681. }
  2682. unproject(camera) {
  2683. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  2684. }
  2685. transformDirection(m) {
  2686. // input: THREE.Matrix4 affine matrix
  2687. // vector interpreted as a direction
  2688. const x = this.x,
  2689. y = this.y,
  2690. z = this.z;
  2691. const e = m.elements;
  2692. this.x = e[0] * x + e[4] * y + e[8] * z;
  2693. this.y = e[1] * x + e[5] * y + e[9] * z;
  2694. this.z = e[2] * x + e[6] * y + e[10] * z;
  2695. return this.normalize();
  2696. }
  2697. divide(v) {
  2698. this.x /= v.x;
  2699. this.y /= v.y;
  2700. this.z /= v.z;
  2701. return this;
  2702. }
  2703. divideScalar(scalar) {
  2704. return this.multiplyScalar(1 / scalar);
  2705. }
  2706. min(v) {
  2707. this.x = Math.min(this.x, v.x);
  2708. this.y = Math.min(this.y, v.y);
  2709. this.z = Math.min(this.z, v.z);
  2710. return this;
  2711. }
  2712. max(v) {
  2713. this.x = Math.max(this.x, v.x);
  2714. this.y = Math.max(this.y, v.y);
  2715. this.z = Math.max(this.z, v.z);
  2716. return this;
  2717. }
  2718. clamp(min, max) {
  2719. // assumes min < max, componentwise
  2720. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2721. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2722. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2723. return this;
  2724. }
  2725. clampScalar(minVal, maxVal) {
  2726. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2727. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2728. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2729. return this;
  2730. }
  2731. clampLength(min, max) {
  2732. const length = this.length();
  2733. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2734. }
  2735. floor() {
  2736. this.x = Math.floor(this.x);
  2737. this.y = Math.floor(this.y);
  2738. this.z = Math.floor(this.z);
  2739. return this;
  2740. }
  2741. ceil() {
  2742. this.x = Math.ceil(this.x);
  2743. this.y = Math.ceil(this.y);
  2744. this.z = Math.ceil(this.z);
  2745. return this;
  2746. }
  2747. round() {
  2748. this.x = Math.round(this.x);
  2749. this.y = Math.round(this.y);
  2750. this.z = Math.round(this.z);
  2751. return this;
  2752. }
  2753. roundToZero() {
  2754. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2755. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2756. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2757. return this;
  2758. }
  2759. negate() {
  2760. this.x = -this.x;
  2761. this.y = -this.y;
  2762. this.z = -this.z;
  2763. return this;
  2764. }
  2765. dot(v) {
  2766. return this.x * v.x + this.y * v.y + this.z * v.z;
  2767. } // TODO lengthSquared?
  2768. lengthSq() {
  2769. return this.x * this.x + this.y * this.y + this.z * this.z;
  2770. }
  2771. length() {
  2772. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2773. }
  2774. manhattanLength() {
  2775. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  2776. }
  2777. normalize() {
  2778. return this.divideScalar(this.length() || 1);
  2779. }
  2780. setLength(length) {
  2781. return this.normalize().multiplyScalar(length);
  2782. }
  2783. lerp(v, alpha) {
  2784. this.x += (v.x - this.x) * alpha;
  2785. this.y += (v.y - this.y) * alpha;
  2786. this.z += (v.z - this.z) * alpha;
  2787. return this;
  2788. }
  2789. lerpVectors(v1, v2, alpha) {
  2790. this.x = v1.x + (v2.x - v1.x) * alpha;
  2791. this.y = v1.y + (v2.y - v1.y) * alpha;
  2792. this.z = v1.z + (v2.z - v1.z) * alpha;
  2793. return this;
  2794. }
  2795. cross(v, w) {
  2796. if (w !== undefined) {
  2797. console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
  2798. return this.crossVectors(v, w);
  2799. }
  2800. return this.crossVectors(this, v);
  2801. }
  2802. crossVectors(a, b) {
  2803. const ax = a.x,
  2804. ay = a.y,
  2805. az = a.z;
  2806. const bx = b.x,
  2807. by = b.y,
  2808. bz = b.z;
  2809. this.x = ay * bz - az * by;
  2810. this.y = az * bx - ax * bz;
  2811. this.z = ax * by - ay * bx;
  2812. return this;
  2813. }
  2814. projectOnVector(v) {
  2815. const denominator = v.lengthSq();
  2816. if (denominator === 0) return this.set(0, 0, 0);
  2817. const scalar = v.dot(this) / denominator;
  2818. return this.copy(v).multiplyScalar(scalar);
  2819. }
  2820. projectOnPlane(planeNormal) {
  2821. _vector.copy(this).projectOnVector(planeNormal);
  2822. return this.sub(_vector);
  2823. }
  2824. reflect(normal) {
  2825. // reflect incident vector off plane orthogonal to normal
  2826. // normal is assumed to have unit length
  2827. return this.sub(_vector.copy(normal).multiplyScalar(2 * this.dot(normal)));
  2828. }
  2829. angleTo(v) {
  2830. const denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  2831. if (denominator === 0) return Math.PI / 2;
  2832. const theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  2833. return Math.acos(MathUtils.clamp(theta, -1, 1));
  2834. }
  2835. distanceTo(v) {
  2836. return Math.sqrt(this.distanceToSquared(v));
  2837. }
  2838. distanceToSquared(v) {
  2839. const dx = this.x - v.x,
  2840. dy = this.y - v.y,
  2841. dz = this.z - v.z;
  2842. return dx * dx + dy * dy + dz * dz;
  2843. }
  2844. manhattanDistanceTo(v) {
  2845. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  2846. }
  2847. setFromSpherical(s) {
  2848. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  2849. }
  2850. setFromSphericalCoords(radius, phi, theta) {
  2851. const sinPhiRadius = Math.sin(phi) * radius;
  2852. this.x = sinPhiRadius * Math.sin(theta);
  2853. this.y = Math.cos(phi) * radius;
  2854. this.z = sinPhiRadius * Math.cos(theta);
  2855. return this;
  2856. }
  2857. setFromCylindrical(c) {
  2858. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  2859. }
  2860. setFromCylindricalCoords(radius, theta, y) {
  2861. this.x = radius * Math.sin(theta);
  2862. this.y = y;
  2863. this.z = radius * Math.cos(theta);
  2864. return this;
  2865. }
  2866. setFromMatrixPosition(m) {
  2867. const e = m.elements;
  2868. this.x = e[12];
  2869. this.y = e[13];
  2870. this.z = e[14];
  2871. return this;
  2872. }
  2873. setFromMatrixScale(m) {
  2874. const sx = this.setFromMatrixColumn(m, 0).length();
  2875. const sy = this.setFromMatrixColumn(m, 1).length();
  2876. const sz = this.setFromMatrixColumn(m, 2).length();
  2877. this.x = sx;
  2878. this.y = sy;
  2879. this.z = sz;
  2880. return this;
  2881. }
  2882. setFromMatrixColumn(m, index) {
  2883. return this.fromArray(m.elements, index * 4);
  2884. }
  2885. setFromMatrix3Column(m, index) {
  2886. return this.fromArray(m.elements, index * 3);
  2887. }
  2888. equals(v) {
  2889. return v.x === this.x && v.y === this.y && v.z === this.z;
  2890. }
  2891. fromArray(array, offset = 0) {
  2892. this.x = array[offset];
  2893. this.y = array[offset + 1];
  2894. this.z = array[offset + 2];
  2895. return this;
  2896. }
  2897. toArray(array = [], offset = 0) {
  2898. array[offset] = this.x;
  2899. array[offset + 1] = this.y;
  2900. array[offset + 2] = this.z;
  2901. return array;
  2902. }
  2903. fromBufferAttribute(attribute, index, offset) {
  2904. if (offset !== undefined) {
  2905. console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
  2906. }
  2907. this.x = attribute.getX(index);
  2908. this.y = attribute.getY(index);
  2909. this.z = attribute.getZ(index);
  2910. return this;
  2911. }
  2912. random() {
  2913. this.x = Math.random();
  2914. this.y = Math.random();
  2915. this.z = Math.random();
  2916. return this;
  2917. }
  2918. }
  2919. exports.Vector3 = Vector3;
  2920. const _vector =
  2921. /*@__PURE__*/
  2922. new Vector3();
  2923. const _quaternion =
  2924. /*@__PURE__*/
  2925. new Quaternion();
  2926. class Box3 {
  2927. constructor(min, max) {
  2928. Object.defineProperty(this, 'isBox3', {
  2929. value: true
  2930. });
  2931. this.min = min !== undefined ? min : new Vector3(+Infinity, +Infinity, +Infinity);
  2932. this.max = max !== undefined ? max : new Vector3(-Infinity, -Infinity, -Infinity);
  2933. }
  2934. set(min, max) {
  2935. this.min.copy(min);
  2936. this.max.copy(max);
  2937. return this;
  2938. }
  2939. setFromArray(array) {
  2940. let minX = +Infinity;
  2941. let minY = +Infinity;
  2942. let minZ = +Infinity;
  2943. let maxX = -Infinity;
  2944. let maxY = -Infinity;
  2945. let maxZ = -Infinity;
  2946. for (let i = 0, l = array.length; i < l; i += 3) {
  2947. const x = array[i];
  2948. const y = array[i + 1];
  2949. const z = array[i + 2];
  2950. if (x < minX) minX = x;
  2951. if (y < minY) minY = y;
  2952. if (z < minZ) minZ = z;
  2953. if (x > maxX) maxX = x;
  2954. if (y > maxY) maxY = y;
  2955. if (z > maxZ) maxZ = z;
  2956. }
  2957. this.min.set(minX, minY, minZ);
  2958. this.max.set(maxX, maxY, maxZ);
  2959. return this;
  2960. }
  2961. setFromBufferAttribute(attribute) {
  2962. let minX = +Infinity;
  2963. let minY = +Infinity;
  2964. let minZ = +Infinity;
  2965. let maxX = -Infinity;
  2966. let maxY = -Infinity;
  2967. let maxZ = -Infinity;
  2968. for (let i = 0, l = attribute.count; i < l; i++) {
  2969. const x = attribute.getX(i);
  2970. const y = attribute.getY(i);
  2971. const z = attribute.getZ(i);
  2972. if (x < minX) minX = x;
  2973. if (y < minY) minY = y;
  2974. if (z < minZ) minZ = z;
  2975. if (x > maxX) maxX = x;
  2976. if (y > maxY) maxY = y;
  2977. if (z > maxZ) maxZ = z;
  2978. }
  2979. this.min.set(minX, minY, minZ);
  2980. this.max.set(maxX, maxY, maxZ);
  2981. return this;
  2982. }
  2983. setFromPoints(points) {
  2984. this.makeEmpty();
  2985. for (let i = 0, il = points.length; i < il; i++) {
  2986. this.expandByPoint(points[i]);
  2987. }
  2988. return this;
  2989. }
  2990. setFromCenterAndSize(center, size) {
  2991. const halfSize = _vector$1.copy(size).multiplyScalar(0.5);
  2992. this.min.copy(center).sub(halfSize);
  2993. this.max.copy(center).add(halfSize);
  2994. return this;
  2995. }
  2996. setFromObject(object) {
  2997. this.makeEmpty();
  2998. return this.expandByObject(object);
  2999. }
  3000. clone() {
  3001. return new this.constructor().copy(this);
  3002. }
  3003. copy(box) {
  3004. this.min.copy(box.min);
  3005. this.max.copy(box.max);
  3006. return this;
  3007. }
  3008. makeEmpty() {
  3009. this.min.x = this.min.y = this.min.z = +Infinity;
  3010. this.max.x = this.max.y = this.max.z = -Infinity;
  3011. return this;
  3012. }
  3013. isEmpty() {
  3014. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3015. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  3016. }
  3017. getCenter(target) {
  3018. if (target === undefined) {
  3019. console.warn('THREE.Box3: .getCenter() target is now required');
  3020. target = new Vector3();
  3021. }
  3022. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  3023. }
  3024. getSize(target) {
  3025. if (target === undefined) {
  3026. console.warn('THREE.Box3: .getSize() target is now required');
  3027. target = new Vector3();
  3028. }
  3029. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  3030. }
  3031. expandByPoint(point) {
  3032. this.min.min(point);
  3033. this.max.max(point);
  3034. return this;
  3035. }
  3036. expandByVector(vector) {
  3037. this.min.sub(vector);
  3038. this.max.add(vector);
  3039. return this;
  3040. }
  3041. expandByScalar(scalar) {
  3042. this.min.addScalar(-scalar);
  3043. this.max.addScalar(scalar);
  3044. return this;
  3045. }
  3046. expandByObject(object) {
  3047. // Computes the world-axis-aligned bounding box of an object (including its children),
  3048. // accounting for both the object's, and children's, world transforms
  3049. object.updateWorldMatrix(false, false);
  3050. const geometry = object.geometry;
  3051. if (geometry !== undefined) {
  3052. if (geometry.boundingBox === null) {
  3053. geometry.computeBoundingBox();
  3054. }
  3055. _box.copy(geometry.boundingBox);
  3056. _box.applyMatrix4(object.matrixWorld);
  3057. this.union(_box);
  3058. }
  3059. const children = object.children;
  3060. for (let i = 0, l = children.length; i < l; i++) {
  3061. this.expandByObject(children[i]);
  3062. }
  3063. return this;
  3064. }
  3065. containsPoint(point) {
  3066. 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;
  3067. }
  3068. containsBox(box) {
  3069. 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;
  3070. }
  3071. getParameter(point, target) {
  3072. // This can potentially have a divide by zero if the box
  3073. // has a size dimension of 0.
  3074. if (target === undefined) {
  3075. console.warn('THREE.Box3: .getParameter() target is now required');
  3076. target = new Vector3();
  3077. }
  3078. 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));
  3079. }
  3080. intersectsBox(box) {
  3081. // using 6 splitting planes to rule out intersections.
  3082. 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;
  3083. }
  3084. intersectsSphere(sphere) {
  3085. // Find the point on the AABB closest to the sphere center.
  3086. this.clampPoint(sphere.center, _vector$1); // If that point is inside the sphere, the AABB and sphere intersect.
  3087. return _vector$1.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  3088. }
  3089. intersectsPlane(plane) {
  3090. // We compute the minimum and maximum dot product values. If those values
  3091. // are on the same side (back or front) of the plane, then there is no intersection.
  3092. let min, max;
  3093. if (plane.normal.x > 0) {
  3094. min = plane.normal.x * this.min.x;
  3095. max = plane.normal.x * this.max.x;
  3096. } else {
  3097. min = plane.normal.x * this.max.x;
  3098. max = plane.normal.x * this.min.x;
  3099. }
  3100. if (plane.normal.y > 0) {
  3101. min += plane.normal.y * this.min.y;
  3102. max += plane.normal.y * this.max.y;
  3103. } else {
  3104. min += plane.normal.y * this.max.y;
  3105. max += plane.normal.y * this.min.y;
  3106. }
  3107. if (plane.normal.z > 0) {
  3108. min += plane.normal.z * this.min.z;
  3109. max += plane.normal.z * this.max.z;
  3110. } else {
  3111. min += plane.normal.z * this.max.z;
  3112. max += plane.normal.z * this.min.z;
  3113. }
  3114. return min <= -plane.constant && max >= -plane.constant;
  3115. }
  3116. intersectsTriangle(triangle) {
  3117. if (this.isEmpty()) {
  3118. return false;
  3119. } // compute box center and extents
  3120. this.getCenter(_center);
  3121. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  3122. _v0.subVectors(triangle.a, _center);
  3123. _v1.subVectors(triangle.b, _center);
  3124. _v2.subVectors(triangle.c, _center); // compute edge vectors for triangle
  3125. _f0.subVectors(_v1, _v0);
  3126. _f1.subVectors(_v2, _v1);
  3127. _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
  3128. // 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
  3129. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  3130. let 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];
  3131. if (!satForAxes(axes, _v0, _v1, _v2, _extents)) {
  3132. return false;
  3133. } // test 3 face normals from the aabb
  3134. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  3135. if (!satForAxes(axes, _v0, _v1, _v2, _extents)) {
  3136. return false;
  3137. } // finally testing the face normal of the triangle
  3138. // use already existing triangle edge vectors here
  3139. _triangleNormal.crossVectors(_f0, _f1);
  3140. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  3141. return satForAxes(axes, _v0, _v1, _v2, _extents);
  3142. }
  3143. clampPoint(point, target) {
  3144. if (target === undefined) {
  3145. console.warn('THREE.Box3: .clampPoint() target is now required');
  3146. target = new Vector3();
  3147. }
  3148. return target.copy(point).clamp(this.min, this.max);
  3149. }
  3150. distanceToPoint(point) {
  3151. const clampedPoint = _vector$1.copy(point).clamp(this.min, this.max);
  3152. return clampedPoint.sub(point).length();
  3153. }
  3154. getBoundingSphere(target) {
  3155. if (target === undefined) {
  3156. console.error('THREE.Box3: .getBoundingSphere() target is now required'); //target = new Sphere(); // removed to avoid cyclic dependency
  3157. }
  3158. this.getCenter(target.center);
  3159. target.radius = this.getSize(_vector$1).length() * 0.5;
  3160. return target;
  3161. }
  3162. intersect(box) {
  3163. this.min.max(box.min);
  3164. 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.
  3165. if (this.isEmpty()) this.makeEmpty();
  3166. return this;
  3167. }
  3168. union(box) {
  3169. this.min.min(box.min);
  3170. this.max.max(box.max);
  3171. return this;
  3172. }
  3173. applyMatrix4(matrix) {
  3174. // transform of empty box is an empty box.
  3175. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3176. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  3177. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  3178. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  3179. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  3180. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  3181. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  3182. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  3183. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  3184. this.setFromPoints(_points);
  3185. return this;
  3186. }
  3187. translate(offset) {
  3188. this.min.add(offset);
  3189. this.max.add(offset);
  3190. return this;
  3191. }
  3192. equals(box) {
  3193. return box.min.equals(this.min) && box.max.equals(this.max);
  3194. }
  3195. }
  3196. exports.Box3 = Box3;
  3197. function satForAxes(axes, v0, v1, v2, extents) {
  3198. for (let i = 0, j = axes.length - 3; i <= j; i += 3) {
  3199. _testAxis.fromArray(axes, i); // project the aabb onto the seperating axis
  3200. const 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
  3201. const p0 = v0.dot(_testAxis);
  3202. const p1 = v1.dot(_testAxis);
  3203. const p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  3204. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  3205. // points of the projected triangle are outside the projected half-length of the aabb
  3206. // the axis is seperating and we can exit
  3207. return false;
  3208. }
  3209. }
  3210. return true;
  3211. }
  3212. const _points = [
  3213. /*@__PURE__*/
  3214. new Vector3(),
  3215. /*@__PURE__*/
  3216. new Vector3(),
  3217. /*@__PURE__*/
  3218. new Vector3(),
  3219. /*@__PURE__*/
  3220. new Vector3(),
  3221. /*@__PURE__*/
  3222. new Vector3(),
  3223. /*@__PURE__*/
  3224. new Vector3(),
  3225. /*@__PURE__*/
  3226. new Vector3(),
  3227. /*@__PURE__*/
  3228. new Vector3()];
  3229. const _vector$1 =
  3230. /*@__PURE__*/
  3231. new Vector3();
  3232. const _box =
  3233. /*@__PURE__*/
  3234. new Box3(); // triangle centered vertices
  3235. const _v0 =
  3236. /*@__PURE__*/
  3237. new Vector3();
  3238. const _v1 =
  3239. /*@__PURE__*/
  3240. new Vector3();
  3241. const _v2 =
  3242. /*@__PURE__*/
  3243. new Vector3(); // triangle edge vectors
  3244. const _f0 =
  3245. /*@__PURE__*/
  3246. new Vector3();
  3247. const _f1 =
  3248. /*@__PURE__*/
  3249. new Vector3();
  3250. const _f2 =
  3251. /*@__PURE__*/
  3252. new Vector3();
  3253. const _center =
  3254. /*@__PURE__*/
  3255. new Vector3();
  3256. const _extents =
  3257. /*@__PURE__*/
  3258. new Vector3();
  3259. const _triangleNormal =
  3260. /*@__PURE__*/
  3261. new Vector3();
  3262. const _testAxis =
  3263. /*@__PURE__*/
  3264. new Vector3();
  3265. const _box$1 =
  3266. /*@__PURE__*/
  3267. new Box3();
  3268. class Sphere {
  3269. constructor(center, radius) {
  3270. this.center = center !== undefined ? center : new Vector3();
  3271. this.radius = radius !== undefined ? radius : -1;
  3272. }
  3273. set(center, radius) {
  3274. this.center.copy(center);
  3275. this.radius = radius;
  3276. return this;
  3277. }
  3278. setFromPoints(points, optionalCenter) {
  3279. const center = this.center;
  3280. if (optionalCenter !== undefined) {
  3281. center.copy(optionalCenter);
  3282. } else {
  3283. _box$1.setFromPoints(points).getCenter(center);
  3284. }
  3285. let maxRadiusSq = 0;
  3286. for (let i = 0, il = points.length; i < il; i++) {
  3287. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  3288. }
  3289. this.radius = Math.sqrt(maxRadiusSq);
  3290. return this;
  3291. }
  3292. clone() {
  3293. return new this.constructor().copy(this);
  3294. }
  3295. copy(sphere) {
  3296. this.center.copy(sphere.center);
  3297. this.radius = sphere.radius;
  3298. return this;
  3299. }
  3300. isEmpty() {
  3301. return this.radius < 0;
  3302. }
  3303. makeEmpty() {
  3304. this.center.set(0, 0, 0);
  3305. this.radius = -1;
  3306. return this;
  3307. }
  3308. containsPoint(point) {
  3309. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  3310. }
  3311. distanceToPoint(point) {
  3312. return point.distanceTo(this.center) - this.radius;
  3313. }
  3314. intersectsSphere(sphere) {
  3315. const radiusSum = this.radius + sphere.radius;
  3316. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  3317. }
  3318. intersectsBox(box) {
  3319. return box.intersectsSphere(this);
  3320. }
  3321. intersectsPlane(plane) {
  3322. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  3323. }
  3324. clampPoint(point, target) {
  3325. const deltaLengthSq = this.center.distanceToSquared(point);
  3326. if (target === undefined) {
  3327. console.warn('THREE.Sphere: .clampPoint() target is now required');
  3328. target = new Vector3();
  3329. }
  3330. target.copy(point);
  3331. if (deltaLengthSq > this.radius * this.radius) {
  3332. target.sub(this.center).normalize();
  3333. target.multiplyScalar(this.radius).add(this.center);
  3334. }
  3335. return target;
  3336. }
  3337. getBoundingBox(target) {
  3338. if (target === undefined) {
  3339. console.warn('THREE.Sphere: .getBoundingBox() target is now required');
  3340. target = new Box3();
  3341. }
  3342. if (this.isEmpty()) {
  3343. // Empty sphere produces empty bounding box
  3344. target.makeEmpty();
  3345. return target;
  3346. }
  3347. target.set(this.center, this.center);
  3348. target.expandByScalar(this.radius);
  3349. return target;
  3350. }
  3351. applyMatrix4(matrix) {
  3352. this.center.applyMatrix4(matrix);
  3353. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3354. return this;
  3355. }
  3356. translate(offset) {
  3357. this.center.add(offset);
  3358. return this;
  3359. }
  3360. equals(sphere) {
  3361. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  3362. }
  3363. }
  3364. exports.Sphere = Sphere;
  3365. const _vector$2 =
  3366. /*@__PURE__*/
  3367. new Vector3();
  3368. const _segCenter =
  3369. /*@__PURE__*/
  3370. new Vector3();
  3371. const _segDir =
  3372. /*@__PURE__*/
  3373. new Vector3();
  3374. const _diff =
  3375. /*@__PURE__*/
  3376. new Vector3();
  3377. const _edge1 =
  3378. /*@__PURE__*/
  3379. new Vector3();
  3380. const _edge2 =
  3381. /*@__PURE__*/
  3382. new Vector3();
  3383. const _normal =
  3384. /*@__PURE__*/
  3385. new Vector3();
  3386. class Ray {
  3387. constructor(origin, direction) {
  3388. this.origin = origin !== undefined ? origin : new Vector3();
  3389. this.direction = direction !== undefined ? direction : new Vector3(0, 0, -1);
  3390. }
  3391. set(origin, direction) {
  3392. this.origin.copy(origin);
  3393. this.direction.copy(direction);
  3394. return this;
  3395. }
  3396. clone() {
  3397. return new this.constructor().copy(this);
  3398. }
  3399. copy(ray) {
  3400. this.origin.copy(ray.origin);
  3401. this.direction.copy(ray.direction);
  3402. return this;
  3403. }
  3404. at(t, target) {
  3405. if (target === undefined) {
  3406. console.warn('THREE.Ray: .at() target is now required');
  3407. target = new Vector3();
  3408. }
  3409. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  3410. }
  3411. lookAt(v) {
  3412. this.direction.copy(v).sub(this.origin).normalize();
  3413. return this;
  3414. }
  3415. recast(t) {
  3416. this.origin.copy(this.at(t, _vector$2));
  3417. return this;
  3418. }
  3419. closestPointToPoint(point, target) {
  3420. if (target === undefined) {
  3421. console.warn('THREE.Ray: .closestPointToPoint() target is now required');
  3422. target = new Vector3();
  3423. }
  3424. target.subVectors(point, this.origin);
  3425. const directionDistance = target.dot(this.direction);
  3426. if (directionDistance < 0) {
  3427. return target.copy(this.origin);
  3428. }
  3429. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3430. }
  3431. distanceToPoint(point) {
  3432. return Math.sqrt(this.distanceSqToPoint(point));
  3433. }
  3434. distanceSqToPoint(point) {
  3435. const directionDistance = _vector$2.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  3436. if (directionDistance < 0) {
  3437. return this.origin.distanceToSquared(point);
  3438. }
  3439. _vector$2.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3440. return _vector$2.distanceToSquared(point);
  3441. }
  3442. distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  3443. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3444. // It returns the min distance between the ray and the segment
  3445. // defined by v0 and v1
  3446. // It can also set two optional targets :
  3447. // - The closest point on the ray
  3448. // - The closest point on the segment
  3449. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  3450. _segDir.copy(v1).sub(v0).normalize();
  3451. _diff.copy(this.origin).sub(_segCenter);
  3452. const segExtent = v0.distanceTo(v1) * 0.5;
  3453. const a01 = -this.direction.dot(_segDir);
  3454. const b0 = _diff.dot(this.direction);
  3455. const b1 = -_diff.dot(_segDir);
  3456. const c = _diff.lengthSq();
  3457. const det = Math.abs(1 - a01 * a01);
  3458. let s0, s1, sqrDist, extDet;
  3459. if (det > 0) {
  3460. // The ray and segment are not parallel.
  3461. s0 = a01 * b1 - b0;
  3462. s1 = a01 * b0 - b1;
  3463. extDet = segExtent * det;
  3464. if (s0 >= 0) {
  3465. if (s1 >= -extDet) {
  3466. if (s1 <= extDet) {
  3467. // region 0
  3468. // Minimum at interior points of ray and segment.
  3469. const invDet = 1 / det;
  3470. s0 *= invDet;
  3471. s1 *= invDet;
  3472. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  3473. } else {
  3474. // region 1
  3475. s1 = segExtent;
  3476. s0 = Math.max(0, -(a01 * s1 + b0));
  3477. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3478. }
  3479. } else {
  3480. // region 5
  3481. s1 = -segExtent;
  3482. s0 = Math.max(0, -(a01 * s1 + b0));
  3483. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3484. }
  3485. } else {
  3486. if (s1 <= -extDet) {
  3487. // region 4
  3488. s0 = Math.max(0, -(-a01 * segExtent + b0));
  3489. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3490. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3491. } else if (s1 <= extDet) {
  3492. // region 3
  3493. s0 = 0;
  3494. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  3495. sqrDist = s1 * (s1 + 2 * b1) + c;
  3496. } else {
  3497. // region 2
  3498. s0 = Math.max(0, -(a01 * segExtent + b0));
  3499. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3500. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3501. }
  3502. }
  3503. } else {
  3504. // Ray and segment are parallel.
  3505. s1 = a01 > 0 ? -segExtent : segExtent;
  3506. s0 = Math.max(0, -(a01 * s1 + b0));
  3507. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3508. }
  3509. if (optionalPointOnRay) {
  3510. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  3511. }
  3512. if (optionalPointOnSegment) {
  3513. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  3514. }
  3515. return sqrDist;
  3516. }
  3517. intersectSphere(sphere, target) {
  3518. _vector$2.subVectors(sphere.center, this.origin);
  3519. const tca = _vector$2.dot(this.direction);
  3520. const d2 = _vector$2.dot(_vector$2) - tca * tca;
  3521. const radius2 = sphere.radius * sphere.radius;
  3522. if (d2 > radius2) return null;
  3523. const thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  3524. const t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  3525. const t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  3526. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  3527. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3528. // in order to always return an intersect point that is in front of the ray.
  3529. 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
  3530. return this.at(t0, target);
  3531. }
  3532. intersectsSphere(sphere) {
  3533. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  3534. }
  3535. distanceToPlane(plane) {
  3536. const denominator = plane.normal.dot(this.direction);
  3537. if (denominator === 0) {
  3538. // line is coplanar, return origin
  3539. if (plane.distanceToPoint(this.origin) === 0) {
  3540. return 0;
  3541. } // Null is preferable to undefined since undefined means.... it is undefined
  3542. return null;
  3543. }
  3544. const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  3545. return t >= 0 ? t : null;
  3546. }
  3547. intersectPlane(plane, target) {
  3548. const t = this.distanceToPlane(plane);
  3549. if (t === null) {
  3550. return null;
  3551. }
  3552. return this.at(t, target);
  3553. }
  3554. intersectsPlane(plane) {
  3555. // check if the ray lies on the plane first
  3556. const distToPoint = plane.distanceToPoint(this.origin);
  3557. if (distToPoint === 0) {
  3558. return true;
  3559. }
  3560. const denominator = plane.normal.dot(this.direction);
  3561. if (denominator * distToPoint < 0) {
  3562. return true;
  3563. } // ray origin is behind the plane (and is pointing behind it)
  3564. return false;
  3565. }
  3566. intersectBox(box, target) {
  3567. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3568. const invdirx = 1 / this.direction.x,
  3569. invdiry = 1 / this.direction.y,
  3570. invdirz = 1 / this.direction.z;
  3571. const origin = this.origin;
  3572. if (invdirx >= 0) {
  3573. tmin = (box.min.x - origin.x) * invdirx;
  3574. tmax = (box.max.x - origin.x) * invdirx;
  3575. } else {
  3576. tmin = (box.max.x - origin.x) * invdirx;
  3577. tmax = (box.min.x - origin.x) * invdirx;
  3578. }
  3579. if (invdiry >= 0) {
  3580. tymin = (box.min.y - origin.y) * invdiry;
  3581. tymax = (box.max.y - origin.y) * invdiry;
  3582. } else {
  3583. tymin = (box.max.y - origin.y) * invdiry;
  3584. tymax = (box.min.y - origin.y) * invdiry;
  3585. }
  3586. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  3587. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3588. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  3589. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  3590. if (invdirz >= 0) {
  3591. tzmin = (box.min.z - origin.z) * invdirz;
  3592. tzmax = (box.max.z - origin.z) * invdirz;
  3593. } else {
  3594. tzmin = (box.max.z - origin.z) * invdirz;
  3595. tzmax = (box.min.z - origin.z) * invdirz;
  3596. }
  3597. if (tmin > tzmax || tzmin > tmax) return null;
  3598. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  3599. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  3600. if (tmax < 0) return null;
  3601. return this.at(tmin >= 0 ? tmin : tmax, target);
  3602. }
  3603. intersectsBox(box) {
  3604. return this.intersectBox(box, _vector$2) !== null;
  3605. }
  3606. intersectTriangle(a, b, c, backfaceCulling, target) {
  3607. // Compute the offset origin, edges, and normal.
  3608. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3609. _edge1.subVectors(b, a);
  3610. _edge2.subVectors(c, a);
  3611. _normal.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3612. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3613. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3614. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3615. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3616. let DdN = this.direction.dot(_normal);
  3617. let sign;
  3618. if (DdN > 0) {
  3619. if (backfaceCulling) return null;
  3620. sign = 1;
  3621. } else if (DdN < 0) {
  3622. sign = -1;
  3623. DdN = -DdN;
  3624. } else {
  3625. return null;
  3626. }
  3627. _diff.subVectors(this.origin, a);
  3628. const DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  3629. if (DdQxE2 < 0) {
  3630. return null;
  3631. }
  3632. const DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  3633. if (DdE1xQ < 0) {
  3634. return null;
  3635. } // b1+b2 > 1, no intersection
  3636. if (DdQxE2 + DdE1xQ > DdN) {
  3637. return null;
  3638. } // Line intersects triangle, check if ray does.
  3639. const QdN = -sign * _diff.dot(_normal); // t < 0, no intersection
  3640. if (QdN < 0) {
  3641. return null;
  3642. } // Ray intersects triangle.
  3643. return this.at(QdN / DdN, target);
  3644. }
  3645. applyMatrix4(matrix4) {
  3646. this.origin.applyMatrix4(matrix4);
  3647. this.direction.transformDirection(matrix4);
  3648. return this;
  3649. }
  3650. equals(ray) {
  3651. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  3652. }
  3653. }
  3654. exports.Ray = Ray;
  3655. class Matrix4 {
  3656. constructor() {
  3657. Object.defineProperty(this, 'isMatrix4', {
  3658. value: true
  3659. });
  3660. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  3661. if (arguments.length > 0) {
  3662. console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
  3663. }
  3664. }
  3665. set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  3666. const te = this.elements;
  3667. te[0] = n11;
  3668. te[4] = n12;
  3669. te[8] = n13;
  3670. te[12] = n14;
  3671. te[1] = n21;
  3672. te[5] = n22;
  3673. te[9] = n23;
  3674. te[13] = n24;
  3675. te[2] = n31;
  3676. te[6] = n32;
  3677. te[10] = n33;
  3678. te[14] = n34;
  3679. te[3] = n41;
  3680. te[7] = n42;
  3681. te[11] = n43;
  3682. te[15] = n44;
  3683. return this;
  3684. }
  3685. identity() {
  3686. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3687. return this;
  3688. }
  3689. clone() {
  3690. return new Matrix4().fromArray(this.elements);
  3691. }
  3692. copy(m) {
  3693. const te = this.elements;
  3694. const me = m.elements;
  3695. te[0] = me[0];
  3696. te[1] = me[1];
  3697. te[2] = me[2];
  3698. te[3] = me[3];
  3699. te[4] = me[4];
  3700. te[5] = me[5];
  3701. te[6] = me[6];
  3702. te[7] = me[7];
  3703. te[8] = me[8];
  3704. te[9] = me[9];
  3705. te[10] = me[10];
  3706. te[11] = me[11];
  3707. te[12] = me[12];
  3708. te[13] = me[13];
  3709. te[14] = me[14];
  3710. te[15] = me[15];
  3711. return this;
  3712. }
  3713. copyPosition(m) {
  3714. const te = this.elements,
  3715. me = m.elements;
  3716. te[12] = me[12];
  3717. te[13] = me[13];
  3718. te[14] = me[14];
  3719. return this;
  3720. }
  3721. extractBasis(xAxis, yAxis, zAxis) {
  3722. xAxis.setFromMatrixColumn(this, 0);
  3723. yAxis.setFromMatrixColumn(this, 1);
  3724. zAxis.setFromMatrixColumn(this, 2);
  3725. return this;
  3726. }
  3727. makeBasis(xAxis, yAxis, zAxis) {
  3728. 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);
  3729. return this;
  3730. }
  3731. extractRotation(m) {
  3732. // this method does not support reflection matrices
  3733. const te = this.elements;
  3734. const me = m.elements;
  3735. const scaleX = 1 / _v1$1.setFromMatrixColumn(m, 0).length();
  3736. const scaleY = 1 / _v1$1.setFromMatrixColumn(m, 1).length();
  3737. const scaleZ = 1 / _v1$1.setFromMatrixColumn(m, 2).length();
  3738. te[0] = me[0] * scaleX;
  3739. te[1] = me[1] * scaleX;
  3740. te[2] = me[2] * scaleX;
  3741. te[3] = 0;
  3742. te[4] = me[4] * scaleY;
  3743. te[5] = me[5] * scaleY;
  3744. te[6] = me[6] * scaleY;
  3745. te[7] = 0;
  3746. te[8] = me[8] * scaleZ;
  3747. te[9] = me[9] * scaleZ;
  3748. te[10] = me[10] * scaleZ;
  3749. te[11] = 0;
  3750. te[12] = 0;
  3751. te[13] = 0;
  3752. te[14] = 0;
  3753. te[15] = 1;
  3754. return this;
  3755. }
  3756. makeRotationFromEuler(euler) {
  3757. if (!(euler && euler.isEuler)) {
  3758. console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
  3759. }
  3760. const te = this.elements;
  3761. const x = euler.x,
  3762. y = euler.y,
  3763. z = euler.z;
  3764. const a = Math.cos(x),
  3765. b = Math.sin(x);
  3766. const c = Math.cos(y),
  3767. d = Math.sin(y);
  3768. const e = Math.cos(z),
  3769. f = Math.sin(z);
  3770. if (euler.order === 'XYZ') {
  3771. const ae = a * e,
  3772. af = a * f,
  3773. be = b * e,
  3774. bf = b * f;
  3775. te[0] = c * e;
  3776. te[4] = -c * f;
  3777. te[8] = d;
  3778. te[1] = af + be * d;
  3779. te[5] = ae - bf * d;
  3780. te[9] = -b * c;
  3781. te[2] = bf - ae * d;
  3782. te[6] = be + af * d;
  3783. te[10] = a * c;
  3784. } else if (euler.order === 'YXZ') {
  3785. const ce = c * e,
  3786. cf = c * f,
  3787. de = d * e,
  3788. df = d * f;
  3789. te[0] = ce + df * b;
  3790. te[4] = de * b - cf;
  3791. te[8] = a * d;
  3792. te[1] = a * f;
  3793. te[5] = a * e;
  3794. te[9] = -b;
  3795. te[2] = cf * b - de;
  3796. te[6] = df + ce * b;
  3797. te[10] = a * c;
  3798. } else if (euler.order === 'ZXY') {
  3799. const ce = c * e,
  3800. cf = c * f,
  3801. de = d * e,
  3802. df = d * f;
  3803. te[0] = ce - df * b;
  3804. te[4] = -a * f;
  3805. te[8] = de + cf * b;
  3806. te[1] = cf + de * b;
  3807. te[5] = a * e;
  3808. te[9] = df - ce * b;
  3809. te[2] = -a * d;
  3810. te[6] = b;
  3811. te[10] = a * c;
  3812. } else if (euler.order === 'ZYX') {
  3813. const ae = a * e,
  3814. af = a * f,
  3815. be = b * e,
  3816. bf = b * f;
  3817. te[0] = c * e;
  3818. te[4] = be * d - af;
  3819. te[8] = ae * d + bf;
  3820. te[1] = c * f;
  3821. te[5] = bf * d + ae;
  3822. te[9] = af * d - be;
  3823. te[2] = -d;
  3824. te[6] = b * c;
  3825. te[10] = a * c;
  3826. } else if (euler.order === 'YZX') {
  3827. const ac = a * c,
  3828. ad = a * d,
  3829. bc = b * c,
  3830. bd = b * d;
  3831. te[0] = c * e;
  3832. te[4] = bd - ac * f;
  3833. te[8] = bc * f + ad;
  3834. te[1] = f;
  3835. te[5] = a * e;
  3836. te[9] = -b * e;
  3837. te[2] = -d * e;
  3838. te[6] = ad * f + bc;
  3839. te[10] = ac - bd * f;
  3840. } else if (euler.order === 'XZY') {
  3841. const ac = a * c,
  3842. ad = a * d,
  3843. bc = b * c,
  3844. bd = b * d;
  3845. te[0] = c * e;
  3846. te[4] = -f;
  3847. te[8] = d * e;
  3848. te[1] = ac * f + bd;
  3849. te[5] = a * e;
  3850. te[9] = ad * f - bc;
  3851. te[2] = bc * f - ad;
  3852. te[6] = b * e;
  3853. te[10] = bd * f + ac;
  3854. } // bottom row
  3855. te[3] = 0;
  3856. te[7] = 0;
  3857. te[11] = 0; // last column
  3858. te[12] = 0;
  3859. te[13] = 0;
  3860. te[14] = 0;
  3861. te[15] = 1;
  3862. return this;
  3863. }
  3864. makeRotationFromQuaternion(q) {
  3865. return this.compose(_zero, q, _one);
  3866. }
  3867. lookAt(eye, target, up) {
  3868. const te = this.elements;
  3869. _z.subVectors(eye, target);
  3870. if (_z.lengthSq() === 0) {
  3871. // eye and target are in the same position
  3872. _z.z = 1;
  3873. }
  3874. _z.normalize();
  3875. _x.crossVectors(up, _z);
  3876. if (_x.lengthSq() === 0) {
  3877. // up and z are parallel
  3878. if (Math.abs(up.z) === 1) {
  3879. _z.x += 0.0001;
  3880. } else {
  3881. _z.z += 0.0001;
  3882. }
  3883. _z.normalize();
  3884. _x.crossVectors(up, _z);
  3885. }
  3886. _x.normalize();
  3887. _y.crossVectors(_z, _x);
  3888. te[0] = _x.x;
  3889. te[4] = _y.x;
  3890. te[8] = _z.x;
  3891. te[1] = _x.y;
  3892. te[5] = _y.y;
  3893. te[9] = _z.y;
  3894. te[2] = _x.z;
  3895. te[6] = _y.z;
  3896. te[10] = _z.z;
  3897. return this;
  3898. }
  3899. multiply(m, n) {
  3900. if (n !== undefined) {
  3901. console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
  3902. return this.multiplyMatrices(m, n);
  3903. }
  3904. return this.multiplyMatrices(this, m);
  3905. }
  3906. premultiply(m) {
  3907. return this.multiplyMatrices(m, this);
  3908. }
  3909. multiplyMatrices(a, b) {
  3910. const ae = a.elements;
  3911. const be = b.elements;
  3912. const te = this.elements;
  3913. const a11 = ae[0],
  3914. a12 = ae[4],
  3915. a13 = ae[8],
  3916. a14 = ae[12];
  3917. const a21 = ae[1],
  3918. a22 = ae[5],
  3919. a23 = ae[9],
  3920. a24 = ae[13];
  3921. const a31 = ae[2],
  3922. a32 = ae[6],
  3923. a33 = ae[10],
  3924. a34 = ae[14];
  3925. const a41 = ae[3],
  3926. a42 = ae[7],
  3927. a43 = ae[11],
  3928. a44 = ae[15];
  3929. const b11 = be[0],
  3930. b12 = be[4],
  3931. b13 = be[8],
  3932. b14 = be[12];
  3933. const b21 = be[1],
  3934. b22 = be[5],
  3935. b23 = be[9],
  3936. b24 = be[13];
  3937. const b31 = be[2],
  3938. b32 = be[6],
  3939. b33 = be[10],
  3940. b34 = be[14];
  3941. const b41 = be[3],
  3942. b42 = be[7],
  3943. b43 = be[11],
  3944. b44 = be[15];
  3945. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3946. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3947. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3948. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3949. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3950. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3951. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3952. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3953. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3954. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3955. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3956. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3957. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3958. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3959. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3960. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3961. return this;
  3962. }
  3963. multiplyScalar(s) {
  3964. const te = this.elements;
  3965. te[0] *= s;
  3966. te[4] *= s;
  3967. te[8] *= s;
  3968. te[12] *= s;
  3969. te[1] *= s;
  3970. te[5] *= s;
  3971. te[9] *= s;
  3972. te[13] *= s;
  3973. te[2] *= s;
  3974. te[6] *= s;
  3975. te[10] *= s;
  3976. te[14] *= s;
  3977. te[3] *= s;
  3978. te[7] *= s;
  3979. te[11] *= s;
  3980. te[15] *= s;
  3981. return this;
  3982. }
  3983. determinant() {
  3984. const te = this.elements;
  3985. const n11 = te[0],
  3986. n12 = te[4],
  3987. n13 = te[8],
  3988. n14 = te[12];
  3989. const n21 = te[1],
  3990. n22 = te[5],
  3991. n23 = te[9],
  3992. n24 = te[13];
  3993. const n31 = te[2],
  3994. n32 = te[6],
  3995. n33 = te[10],
  3996. n34 = te[14];
  3997. const n41 = te[3],
  3998. n42 = te[7],
  3999. n43 = te[11],
  4000. n44 = te[15]; //TODO: make this more efficient
  4001. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  4002. 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);
  4003. }
  4004. transpose() {
  4005. const te = this.elements;
  4006. let tmp;
  4007. tmp = te[1];
  4008. te[1] = te[4];
  4009. te[4] = tmp;
  4010. tmp = te[2];
  4011. te[2] = te[8];
  4012. te[8] = tmp;
  4013. tmp = te[6];
  4014. te[6] = te[9];
  4015. te[9] = tmp;
  4016. tmp = te[3];
  4017. te[3] = te[12];
  4018. te[12] = tmp;
  4019. tmp = te[7];
  4020. te[7] = te[13];
  4021. te[13] = tmp;
  4022. tmp = te[11];
  4023. te[11] = te[14];
  4024. te[14] = tmp;
  4025. return this;
  4026. }
  4027. setPosition(x, y, z) {
  4028. const te = this.elements;
  4029. if (x.isVector3) {
  4030. te[12] = x.x;
  4031. te[13] = x.y;
  4032. te[14] = x.z;
  4033. } else {
  4034. te[12] = x;
  4035. te[13] = y;
  4036. te[14] = z;
  4037. }
  4038. return this;
  4039. }
  4040. invert() {
  4041. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  4042. const te = this.elements,
  4043. n11 = te[0],
  4044. n21 = te[1],
  4045. n31 = te[2],
  4046. n41 = te[3],
  4047. n12 = te[4],
  4048. n22 = te[5],
  4049. n32 = te[6],
  4050. n42 = te[7],
  4051. n13 = te[8],
  4052. n23 = te[9],
  4053. n33 = te[10],
  4054. n43 = te[11],
  4055. n14 = te[12],
  4056. n24 = te[13],
  4057. n34 = te[14],
  4058. n44 = te[15],
  4059. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  4060. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  4061. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  4062. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  4063. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  4064. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  4065. const detInv = 1 / det;
  4066. te[0] = t11 * detInv;
  4067. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  4068. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  4069. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  4070. te[4] = t12 * detInv;
  4071. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  4072. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  4073. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  4074. te[8] = t13 * detInv;
  4075. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  4076. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  4077. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  4078. te[12] = t14 * detInv;
  4079. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  4080. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  4081. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  4082. return this;
  4083. }
  4084. scale(v) {
  4085. const te = this.elements;
  4086. const x = v.x,
  4087. y = v.y,
  4088. z = v.z;
  4089. te[0] *= x;
  4090. te[4] *= y;
  4091. te[8] *= z;
  4092. te[1] *= x;
  4093. te[5] *= y;
  4094. te[9] *= z;
  4095. te[2] *= x;
  4096. te[6] *= y;
  4097. te[10] *= z;
  4098. te[3] *= x;
  4099. te[7] *= y;
  4100. te[11] *= z;
  4101. return this;
  4102. }
  4103. getMaxScaleOnAxis() {
  4104. const te = this.elements;
  4105. const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  4106. const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  4107. const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  4108. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  4109. }
  4110. makeTranslation(x, y, z) {
  4111. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  4112. return this;
  4113. }
  4114. makeRotationX(theta) {
  4115. const c = Math.cos(theta),
  4116. s = Math.sin(theta);
  4117. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  4118. return this;
  4119. }
  4120. makeRotationY(theta) {
  4121. const c = Math.cos(theta),
  4122. s = Math.sin(theta);
  4123. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  4124. return this;
  4125. }
  4126. makeRotationZ(theta) {
  4127. const c = Math.cos(theta),
  4128. s = Math.sin(theta);
  4129. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  4130. return this;
  4131. }
  4132. makeRotationAxis(axis, angle) {
  4133. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4134. const c = Math.cos(angle);
  4135. const s = Math.sin(angle);
  4136. const t = 1 - c;
  4137. const x = axis.x,
  4138. y = axis.y,
  4139. z = axis.z;
  4140. const tx = t * x,
  4141. ty = t * y;
  4142. 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);
  4143. return this;
  4144. }
  4145. makeScale(x, y, z) {
  4146. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  4147. return this;
  4148. }
  4149. makeShear(x, y, z) {
  4150. this.set(1, y, z, 0, x, 1, z, 0, x, y, 1, 0, 0, 0, 0, 1);
  4151. return this;
  4152. }
  4153. compose(position, quaternion, scale) {
  4154. const te = this.elements;
  4155. const x = quaternion._x,
  4156. y = quaternion._y,
  4157. z = quaternion._z,
  4158. w = quaternion._w;
  4159. const x2 = x + x,
  4160. y2 = y + y,
  4161. z2 = z + z;
  4162. const xx = x * x2,
  4163. xy = x * y2,
  4164. xz = x * z2;
  4165. const yy = y * y2,
  4166. yz = y * z2,
  4167. zz = z * z2;
  4168. const wx = w * x2,
  4169. wy = w * y2,
  4170. wz = w * z2;
  4171. const sx = scale.x,
  4172. sy = scale.y,
  4173. sz = scale.z;
  4174. te[0] = (1 - (yy + zz)) * sx;
  4175. te[1] = (xy + wz) * sx;
  4176. te[2] = (xz - wy) * sx;
  4177. te[3] = 0;
  4178. te[4] = (xy - wz) * sy;
  4179. te[5] = (1 - (xx + zz)) * sy;
  4180. te[6] = (yz + wx) * sy;
  4181. te[7] = 0;
  4182. te[8] = (xz + wy) * sz;
  4183. te[9] = (yz - wx) * sz;
  4184. te[10] = (1 - (xx + yy)) * sz;
  4185. te[11] = 0;
  4186. te[12] = position.x;
  4187. te[13] = position.y;
  4188. te[14] = position.z;
  4189. te[15] = 1;
  4190. return this;
  4191. }
  4192. decompose(position, quaternion, scale) {
  4193. const te = this.elements;
  4194. let sx = _v1$1.set(te[0], te[1], te[2]).length();
  4195. const sy = _v1$1.set(te[4], te[5], te[6]).length();
  4196. const sz = _v1$1.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  4197. const det = this.determinant();
  4198. if (det < 0) sx = -sx;
  4199. position.x = te[12];
  4200. position.y = te[13];
  4201. position.z = te[14]; // scale the rotation part
  4202. _m1.copy(this);
  4203. const invSX = 1 / sx;
  4204. const invSY = 1 / sy;
  4205. const invSZ = 1 / sz;
  4206. _m1.elements[0] *= invSX;
  4207. _m1.elements[1] *= invSX;
  4208. _m1.elements[2] *= invSX;
  4209. _m1.elements[4] *= invSY;
  4210. _m1.elements[5] *= invSY;
  4211. _m1.elements[6] *= invSY;
  4212. _m1.elements[8] *= invSZ;
  4213. _m1.elements[9] *= invSZ;
  4214. _m1.elements[10] *= invSZ;
  4215. quaternion.setFromRotationMatrix(_m1);
  4216. scale.x = sx;
  4217. scale.y = sy;
  4218. scale.z = sz;
  4219. return this;
  4220. }
  4221. makePerspective(left, right, top, bottom, near, far) {
  4222. if (far === undefined) {
  4223. console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
  4224. }
  4225. const te = this.elements;
  4226. const x = 2 * near / (right - left);
  4227. const y = 2 * near / (top - bottom);
  4228. const a = (right + left) / (right - left);
  4229. const b = (top + bottom) / (top - bottom);
  4230. const c = -(far + near) / (far - near);
  4231. const d = -2 * far * near / (far - near);
  4232. te[0] = x;
  4233. te[4] = 0;
  4234. te[8] = a;
  4235. te[12] = 0;
  4236. te[1] = 0;
  4237. te[5] = y;
  4238. te[9] = b;
  4239. te[13] = 0;
  4240. te[2] = 0;
  4241. te[6] = 0;
  4242. te[10] = c;
  4243. te[14] = d;
  4244. te[3] = 0;
  4245. te[7] = 0;
  4246. te[11] = -1;
  4247. te[15] = 0;
  4248. return this;
  4249. }
  4250. makeOrthographic(left, right, top, bottom, near, far) {
  4251. const te = this.elements;
  4252. const w = 1.0 / (right - left);
  4253. const h = 1.0 / (top - bottom);
  4254. const p = 1.0 / (far - near);
  4255. const x = (right + left) * w;
  4256. const y = (top + bottom) * h;
  4257. const z = (far + near) * p;
  4258. te[0] = 2 * w;
  4259. te[4] = 0;
  4260. te[8] = 0;
  4261. te[12] = -x;
  4262. te[1] = 0;
  4263. te[5] = 2 * h;
  4264. te[9] = 0;
  4265. te[13] = -y;
  4266. te[2] = 0;
  4267. te[6] = 0;
  4268. te[10] = -2 * p;
  4269. te[14] = -z;
  4270. te[3] = 0;
  4271. te[7] = 0;
  4272. te[11] = 0;
  4273. te[15] = 1;
  4274. return this;
  4275. }
  4276. equals(matrix) {
  4277. const te = this.elements;
  4278. const me = matrix.elements;
  4279. for (let i = 0; i < 16; i++) {
  4280. if (te[i] !== me[i]) return false;
  4281. }
  4282. return true;
  4283. }
  4284. fromArray(array, offset = 0) {
  4285. for (let i = 0; i < 16; i++) {
  4286. this.elements[i] = array[i + offset];
  4287. }
  4288. return this;
  4289. }
  4290. toArray(array = [], offset = 0) {
  4291. const te = this.elements;
  4292. array[offset] = te[0];
  4293. array[offset + 1] = te[1];
  4294. array[offset + 2] = te[2];
  4295. array[offset + 3] = te[3];
  4296. array[offset + 4] = te[4];
  4297. array[offset + 5] = te[5];
  4298. array[offset + 6] = te[6];
  4299. array[offset + 7] = te[7];
  4300. array[offset + 8] = te[8];
  4301. array[offset + 9] = te[9];
  4302. array[offset + 10] = te[10];
  4303. array[offset + 11] = te[11];
  4304. array[offset + 12] = te[12];
  4305. array[offset + 13] = te[13];
  4306. array[offset + 14] = te[14];
  4307. array[offset + 15] = te[15];
  4308. return array;
  4309. }
  4310. }
  4311. exports.Matrix4 = Matrix4;
  4312. const _v1$1 =
  4313. /*@__PURE__*/
  4314. new Vector3();
  4315. const _m1 =
  4316. /*@__PURE__*/
  4317. new Matrix4();
  4318. const _zero =
  4319. /*@__PURE__*/
  4320. new Vector3(0, 0, 0);
  4321. const _one =
  4322. /*@__PURE__*/
  4323. new Vector3(1, 1, 1);
  4324. const _x =
  4325. /*@__PURE__*/
  4326. new Vector3();
  4327. const _y =
  4328. /*@__PURE__*/
  4329. new Vector3();
  4330. const _z =
  4331. /*@__PURE__*/
  4332. new Vector3();
  4333. class Euler {
  4334. constructor(x = 0, y = 0, z = 0, order = Euler.DefaultOrder) {
  4335. Object.defineProperty(this, 'isEuler', {
  4336. value: true
  4337. });
  4338. this._x = x;
  4339. this._y = y;
  4340. this._z = z;
  4341. this._order = order;
  4342. }
  4343. get x() {
  4344. return this._x;
  4345. }
  4346. set x(value) {
  4347. this._x = value;
  4348. this._onChangeCallback();
  4349. }
  4350. get y() {
  4351. return this._y;
  4352. }
  4353. set y(value) {
  4354. this._y = value;
  4355. this._onChangeCallback();
  4356. }
  4357. get z() {
  4358. return this._z;
  4359. }
  4360. set z(value) {
  4361. this._z = value;
  4362. this._onChangeCallback();
  4363. }
  4364. get order() {
  4365. return this._order;
  4366. }
  4367. set order(value) {
  4368. this._order = value;
  4369. this._onChangeCallback();
  4370. }
  4371. set(x, y, z, order) {
  4372. this._x = x;
  4373. this._y = y;
  4374. this._z = z;
  4375. this._order = order || this._order;
  4376. this._onChangeCallback();
  4377. return this;
  4378. }
  4379. clone() {
  4380. return new this.constructor(this._x, this._y, this._z, this._order);
  4381. }
  4382. copy(euler) {
  4383. this._x = euler._x;
  4384. this._y = euler._y;
  4385. this._z = euler._z;
  4386. this._order = euler._order;
  4387. this._onChangeCallback();
  4388. return this;
  4389. }
  4390. setFromRotationMatrix(m, order, update) {
  4391. const clamp = MathUtils.clamp; // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4392. const te = m.elements;
  4393. const m11 = te[0],
  4394. m12 = te[4],
  4395. m13 = te[8];
  4396. const m21 = te[1],
  4397. m22 = te[5],
  4398. m23 = te[9];
  4399. const m31 = te[2],
  4400. m32 = te[6],
  4401. m33 = te[10];
  4402. order = order || this._order;
  4403. switch (order) {
  4404. case 'XYZ':
  4405. this._y = Math.asin(clamp(m13, -1, 1));
  4406. if (Math.abs(m13) < 0.9999999) {
  4407. this._x = Math.atan2(-m23, m33);
  4408. this._z = Math.atan2(-m12, m11);
  4409. } else {
  4410. this._x = Math.atan2(m32, m22);
  4411. this._z = 0;
  4412. }
  4413. break;
  4414. case 'YXZ':
  4415. this._x = Math.asin(-clamp(m23, -1, 1));
  4416. if (Math.abs(m23) < 0.9999999) {
  4417. this._y = Math.atan2(m13, m33);
  4418. this._z = Math.atan2(m21, m22);
  4419. } else {
  4420. this._y = Math.atan2(-m31, m11);
  4421. this._z = 0;
  4422. }
  4423. break;
  4424. case 'ZXY':
  4425. this._x = Math.asin(clamp(m32, -1, 1));
  4426. if (Math.abs(m32) < 0.9999999) {
  4427. this._y = Math.atan2(-m31, m33);
  4428. this._z = Math.atan2(-m12, m22);
  4429. } else {
  4430. this._y = 0;
  4431. this._z = Math.atan2(m21, m11);
  4432. }
  4433. break;
  4434. case 'ZYX':
  4435. this._y = Math.asin(-clamp(m31, -1, 1));
  4436. if (Math.abs(m31) < 0.9999999) {
  4437. this._x = Math.atan2(m32, m33);
  4438. this._z = Math.atan2(m21, m11);
  4439. } else {
  4440. this._x = 0;
  4441. this._z = Math.atan2(-m12, m22);
  4442. }
  4443. break;
  4444. case 'YZX':
  4445. this._z = Math.asin(clamp(m21, -1, 1));
  4446. if (Math.abs(m21) < 0.9999999) {
  4447. this._x = Math.atan2(-m23, m22);
  4448. this._y = Math.atan2(-m31, m11);
  4449. } else {
  4450. this._x = 0;
  4451. this._y = Math.atan2(m13, m33);
  4452. }
  4453. break;
  4454. case 'XZY':
  4455. this._z = Math.asin(-clamp(m12, -1, 1));
  4456. if (Math.abs(m12) < 0.9999999) {
  4457. this._x = Math.atan2(m32, m22);
  4458. this._y = Math.atan2(m13, m11);
  4459. } else {
  4460. this._x = Math.atan2(-m23, m33);
  4461. this._y = 0;
  4462. }
  4463. break;
  4464. default:
  4465. console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order);
  4466. }
  4467. this._order = order;
  4468. if (update !== false) this._onChangeCallback();
  4469. return this;
  4470. }
  4471. setFromQuaternion(q, order, update) {
  4472. _matrix.makeRotationFromQuaternion(q);
  4473. return this.setFromRotationMatrix(_matrix, order, update);
  4474. }
  4475. setFromVector3(v, order) {
  4476. return this.set(v.x, v.y, v.z, order || this._order);
  4477. }
  4478. reorder(newOrder) {
  4479. // WARNING: this discards revolution information -bhouston
  4480. _quaternion$1.setFromEuler(this);
  4481. return this.setFromQuaternion(_quaternion$1, newOrder);
  4482. }
  4483. equals(euler) {
  4484. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  4485. }
  4486. fromArray(array) {
  4487. this._x = array[0];
  4488. this._y = array[1];
  4489. this._z = array[2];
  4490. if (array[3] !== undefined) this._order = array[3];
  4491. this._onChangeCallback();
  4492. return this;
  4493. }
  4494. toArray(array = [], offset = 0) {
  4495. array[offset] = this._x;
  4496. array[offset + 1] = this._y;
  4497. array[offset + 2] = this._z;
  4498. array[offset + 3] = this._order;
  4499. return array;
  4500. }
  4501. toVector3(optionalResult) {
  4502. if (optionalResult) {
  4503. return optionalResult.set(this._x, this._y, this._z);
  4504. } else {
  4505. return new Vector3(this._x, this._y, this._z);
  4506. }
  4507. }
  4508. _onChange(callback) {
  4509. this._onChangeCallback = callback;
  4510. return this;
  4511. }
  4512. _onChangeCallback() {}
  4513. }
  4514. exports.Euler = Euler;
  4515. Euler.DefaultOrder = 'XYZ';
  4516. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  4517. const _matrix =
  4518. /*@__PURE__*/
  4519. new Matrix4();
  4520. const _quaternion$1 =
  4521. /*@__PURE__*/
  4522. new Quaternion();
  4523. class Layers {
  4524. constructor() {
  4525. this.mask = 1 | 0;
  4526. }
  4527. set(channel) {
  4528. this.mask = 1 << channel | 0;
  4529. }
  4530. enable(channel) {
  4531. this.mask |= 1 << channel | 0;
  4532. }
  4533. enableAll() {
  4534. this.mask = 0xffffffff | 0;
  4535. }
  4536. toggle(channel) {
  4537. this.mask ^= 1 << channel | 0;
  4538. }
  4539. disable(channel) {
  4540. this.mask &= ~(1 << channel | 0);
  4541. }
  4542. disableAll() {
  4543. this.mask = 0;
  4544. }
  4545. test(layers) {
  4546. return (this.mask & layers.mask) !== 0;
  4547. }
  4548. }
  4549. exports.Layers = Layers;
  4550. let _object3DId = 0;
  4551. const _v1$2 = new Vector3();
  4552. const _q1 = new Quaternion();
  4553. const _m1$1 = new Matrix4();
  4554. const _target = new Vector3();
  4555. const _position = new Vector3();
  4556. const _scale = new Vector3();
  4557. const _quaternion$2 = new Quaternion();
  4558. const _xAxis = new Vector3(1, 0, 0);
  4559. const _yAxis = new Vector3(0, 1, 0);
  4560. const _zAxis = new Vector3(0, 0, 1);
  4561. const _addedEvent = {
  4562. type: 'added'
  4563. };
  4564. const _removedEvent = {
  4565. type: 'removed'
  4566. };
  4567. function Object3D() {
  4568. Object.defineProperty(this, 'id', {
  4569. value: _object3DId++
  4570. });
  4571. this.uuid = MathUtils.generateUUID();
  4572. this.name = '';
  4573. this.type = 'Object3D';
  4574. this.parent = null;
  4575. this.children = [];
  4576. this.up = Object3D.DefaultUp.clone();
  4577. const position = new Vector3();
  4578. const rotation = new Euler();
  4579. const quaternion = new Quaternion();
  4580. const scale = new Vector3(1, 1, 1);
  4581. function onRotationChange() {
  4582. quaternion.setFromEuler(rotation, false);
  4583. }
  4584. function onQuaternionChange() {
  4585. rotation.setFromQuaternion(quaternion, undefined, false);
  4586. }
  4587. rotation._onChange(onRotationChange);
  4588. quaternion._onChange(onQuaternionChange);
  4589. Object.defineProperties(this, {
  4590. position: {
  4591. configurable: true,
  4592. enumerable: true,
  4593. value: position
  4594. },
  4595. rotation: {
  4596. configurable: true,
  4597. enumerable: true,
  4598. value: rotation
  4599. },
  4600. quaternion: {
  4601. configurable: true,
  4602. enumerable: true,
  4603. value: quaternion
  4604. },
  4605. scale: {
  4606. configurable: true,
  4607. enumerable: true,
  4608. value: scale
  4609. },
  4610. modelViewMatrix: {
  4611. value: new Matrix4()
  4612. },
  4613. normalMatrix: {
  4614. value: new Matrix3()
  4615. }
  4616. });
  4617. this.matrix = new Matrix4();
  4618. this.matrixWorld = new Matrix4();
  4619. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4620. this.matrixWorldNeedsUpdate = false;
  4621. this.layers = new Layers();
  4622. this.visible = true;
  4623. this.castShadow = false;
  4624. this.receiveShadow = false;
  4625. this.frustumCulled = true;
  4626. this.renderOrder = 0;
  4627. this.animations = [];
  4628. this.userData = {};
  4629. }
  4630. Object3D.DefaultUp = new Vector3(0, 1, 0);
  4631. Object3D.DefaultMatrixAutoUpdate = true;
  4632. Object3D.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  4633. constructor: Object3D,
  4634. isObject3D: true,
  4635. onBeforeRender: function () {},
  4636. onAfterRender: function () {},
  4637. applyMatrix4: function (matrix) {
  4638. if (this.matrixAutoUpdate) this.updateMatrix();
  4639. this.matrix.premultiply(matrix);
  4640. this.matrix.decompose(this.position, this.quaternion, this.scale);
  4641. },
  4642. applyQuaternion: function (q) {
  4643. this.quaternion.premultiply(q);
  4644. return this;
  4645. },
  4646. setRotationFromAxisAngle: function (axis, angle) {
  4647. // assumes axis is normalized
  4648. this.quaternion.setFromAxisAngle(axis, angle);
  4649. },
  4650. setRotationFromEuler: function (euler) {
  4651. this.quaternion.setFromEuler(euler, true);
  4652. },
  4653. setRotationFromMatrix: function (m) {
  4654. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4655. this.quaternion.setFromRotationMatrix(m);
  4656. },
  4657. setRotationFromQuaternion: function (q) {
  4658. // assumes q is normalized
  4659. this.quaternion.copy(q);
  4660. },
  4661. rotateOnAxis: function (axis, angle) {
  4662. // rotate object on axis in object space
  4663. // axis is assumed to be normalized
  4664. _q1.setFromAxisAngle(axis, angle);
  4665. this.quaternion.multiply(_q1);
  4666. return this;
  4667. },
  4668. rotateOnWorldAxis: function (axis, angle) {
  4669. // rotate object on axis in world space
  4670. // axis is assumed to be normalized
  4671. // method assumes no rotated parent
  4672. _q1.setFromAxisAngle(axis, angle);
  4673. this.quaternion.premultiply(_q1);
  4674. return this;
  4675. },
  4676. rotateX: function (angle) {
  4677. return this.rotateOnAxis(_xAxis, angle);
  4678. },
  4679. rotateY: function (angle) {
  4680. return this.rotateOnAxis(_yAxis, angle);
  4681. },
  4682. rotateZ: function (angle) {
  4683. return this.rotateOnAxis(_zAxis, angle);
  4684. },
  4685. translateOnAxis: function (axis, distance) {
  4686. // translate object by distance along axis in object space
  4687. // axis is assumed to be normalized
  4688. _v1$2.copy(axis).applyQuaternion(this.quaternion);
  4689. this.position.add(_v1$2.multiplyScalar(distance));
  4690. return this;
  4691. },
  4692. translateX: function (distance) {
  4693. return this.translateOnAxis(_xAxis, distance);
  4694. },
  4695. translateY: function (distance) {
  4696. return this.translateOnAxis(_yAxis, distance);
  4697. },
  4698. translateZ: function (distance) {
  4699. return this.translateOnAxis(_zAxis, distance);
  4700. },
  4701. localToWorld: function (vector) {
  4702. return vector.applyMatrix4(this.matrixWorld);
  4703. },
  4704. worldToLocal: function (vector) {
  4705. return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert());
  4706. },
  4707. lookAt: function (x, y, z) {
  4708. // This method does not support objects having non-uniformly-scaled parent(s)
  4709. if (x.isVector3) {
  4710. _target.copy(x);
  4711. } else {
  4712. _target.set(x, y, z);
  4713. }
  4714. const parent = this.parent;
  4715. this.updateWorldMatrix(true, false);
  4716. _position.setFromMatrixPosition(this.matrixWorld);
  4717. if (this.isCamera || this.isLight) {
  4718. _m1$1.lookAt(_position, _target, this.up);
  4719. } else {
  4720. _m1$1.lookAt(_target, _position, this.up);
  4721. }
  4722. this.quaternion.setFromRotationMatrix(_m1$1);
  4723. if (parent) {
  4724. _m1$1.extractRotation(parent.matrixWorld);
  4725. _q1.setFromRotationMatrix(_m1$1);
  4726. this.quaternion.premultiply(_q1.invert());
  4727. }
  4728. },
  4729. add: function (object) {
  4730. if (arguments.length > 1) {
  4731. for (let i = 0; i < arguments.length; i++) {
  4732. this.add(arguments[i]);
  4733. }
  4734. return this;
  4735. }
  4736. if (object === this) {
  4737. console.error("THREE.Object3D.add: object can't be added as a child of itself.", object);
  4738. return this;
  4739. }
  4740. if (object && object.isObject3D) {
  4741. if (object.parent !== null) {
  4742. object.parent.remove(object);
  4743. }
  4744. object.parent = this;
  4745. this.children.push(object);
  4746. object.dispatchEvent(_addedEvent);
  4747. } else {
  4748. console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.", object);
  4749. }
  4750. return this;
  4751. },
  4752. remove: function (object) {
  4753. if (arguments.length > 1) {
  4754. for (let i = 0; i < arguments.length; i++) {
  4755. this.remove(arguments[i]);
  4756. }
  4757. return this;
  4758. }
  4759. const index = this.children.indexOf(object);
  4760. if (index !== -1) {
  4761. object.parent = null;
  4762. this.children.splice(index, 1);
  4763. object.dispatchEvent(_removedEvent);
  4764. }
  4765. return this;
  4766. },
  4767. clear: function () {
  4768. for (let i = 0; i < this.children.length; i++) {
  4769. const object = this.children[i];
  4770. object.parent = null;
  4771. object.dispatchEvent(_removedEvent);
  4772. }
  4773. this.children.length = 0;
  4774. return this;
  4775. },
  4776. attach: function (object) {
  4777. // adds object as a child of this, while maintaining the object's world transform
  4778. this.updateWorldMatrix(true, false);
  4779. _m1$1.copy(this.matrixWorld).invert();
  4780. if (object.parent !== null) {
  4781. object.parent.updateWorldMatrix(true, false);
  4782. _m1$1.multiply(object.parent.matrixWorld);
  4783. }
  4784. object.applyMatrix4(_m1$1);
  4785. object.updateWorldMatrix(false, false);
  4786. this.add(object);
  4787. return this;
  4788. },
  4789. getObjectById: function (id) {
  4790. return this.getObjectByProperty('id', id);
  4791. },
  4792. getObjectByName: function (name) {
  4793. return this.getObjectByProperty('name', name);
  4794. },
  4795. getObjectByProperty: function (name, value) {
  4796. if (this[name] === value) return this;
  4797. for (let i = 0, l = this.children.length; i < l; i++) {
  4798. const child = this.children[i];
  4799. const object = child.getObjectByProperty(name, value);
  4800. if (object !== undefined) {
  4801. return object;
  4802. }
  4803. }
  4804. return undefined;
  4805. },
  4806. getWorldPosition: function (target) {
  4807. if (target === undefined) {
  4808. console.warn('THREE.Object3D: .getWorldPosition() target is now required');
  4809. target = new Vector3();
  4810. }
  4811. this.updateWorldMatrix(true, false);
  4812. return target.setFromMatrixPosition(this.matrixWorld);
  4813. },
  4814. getWorldQuaternion: function (target) {
  4815. if (target === undefined) {
  4816. console.warn('THREE.Object3D: .getWorldQuaternion() target is now required');
  4817. target = new Quaternion();
  4818. }
  4819. this.updateWorldMatrix(true, false);
  4820. this.matrixWorld.decompose(_position, target, _scale);
  4821. return target;
  4822. },
  4823. getWorldScale: function (target) {
  4824. if (target === undefined) {
  4825. console.warn('THREE.Object3D: .getWorldScale() target is now required');
  4826. target = new Vector3();
  4827. }
  4828. this.updateWorldMatrix(true, false);
  4829. this.matrixWorld.decompose(_position, _quaternion$2, target);
  4830. return target;
  4831. },
  4832. getWorldDirection: function (target) {
  4833. if (target === undefined) {
  4834. console.warn('THREE.Object3D: .getWorldDirection() target is now required');
  4835. target = new Vector3();
  4836. }
  4837. this.updateWorldMatrix(true, false);
  4838. const e = this.matrixWorld.elements;
  4839. return target.set(e[8], e[9], e[10]).normalize();
  4840. },
  4841. raycast: function () {},
  4842. traverse: function (callback) {
  4843. callback(this);
  4844. const children = this.children;
  4845. for (let i = 0, l = children.length; i < l; i++) {
  4846. children[i].traverse(callback);
  4847. }
  4848. },
  4849. traverseVisible: function (callback) {
  4850. if (this.visible === false) return;
  4851. callback(this);
  4852. const children = this.children;
  4853. for (let i = 0, l = children.length; i < l; i++) {
  4854. children[i].traverseVisible(callback);
  4855. }
  4856. },
  4857. traverseAncestors: function (callback) {
  4858. const parent = this.parent;
  4859. if (parent !== null) {
  4860. callback(parent);
  4861. parent.traverseAncestors(callback);
  4862. }
  4863. },
  4864. updateMatrix: function () {
  4865. this.matrix.compose(this.position, this.quaternion, this.scale);
  4866. this.matrixWorldNeedsUpdate = true;
  4867. },
  4868. updateMatrixWorld: function (force) {
  4869. if (this.matrixAutoUpdate) this.updateMatrix();
  4870. if (this.matrixWorldNeedsUpdate || force) {
  4871. if (this.parent === null) {
  4872. this.matrixWorld.copy(this.matrix);
  4873. } else {
  4874. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4875. }
  4876. this.matrixWorldNeedsUpdate = false;
  4877. force = true;
  4878. } // update children
  4879. const children = this.children;
  4880. for (let i = 0, l = children.length; i < l; i++) {
  4881. children[i].updateMatrixWorld(force);
  4882. }
  4883. },
  4884. updateWorldMatrix: function (updateParents, updateChildren) {
  4885. const parent = this.parent;
  4886. if (updateParents === true && parent !== null) {
  4887. parent.updateWorldMatrix(true, false);
  4888. }
  4889. if (this.matrixAutoUpdate) this.updateMatrix();
  4890. if (this.parent === null) {
  4891. this.matrixWorld.copy(this.matrix);
  4892. } else {
  4893. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4894. } // update children
  4895. if (updateChildren === true) {
  4896. const children = this.children;
  4897. for (let i = 0, l = children.length; i < l; i++) {
  4898. children[i].updateWorldMatrix(false, true);
  4899. }
  4900. }
  4901. },
  4902. toJSON: function (meta) {
  4903. // meta is a string when called from JSON.stringify
  4904. const isRootObject = meta === undefined || typeof meta === 'string';
  4905. const output = {}; // meta is a hash used to collect geometries, materials.
  4906. // not providing it implies that this is the root object
  4907. // being serialized.
  4908. if (isRootObject) {
  4909. // initialize meta obj
  4910. meta = {
  4911. geometries: {},
  4912. materials: {},
  4913. textures: {},
  4914. images: {},
  4915. shapes: {},
  4916. skeletons: {},
  4917. animations: {}
  4918. };
  4919. output.metadata = {
  4920. version: 4.5,
  4921. type: 'Object',
  4922. generator: 'Object3D.toJSON'
  4923. };
  4924. } // standard Object3D serialization
  4925. const object = {};
  4926. object.uuid = this.uuid;
  4927. object.type = this.type;
  4928. if (this.name !== '') object.name = this.name;
  4929. if (this.castShadow === true) object.castShadow = true;
  4930. if (this.receiveShadow === true) object.receiveShadow = true;
  4931. if (this.visible === false) object.visible = false;
  4932. if (this.frustumCulled === false) object.frustumCulled = false;
  4933. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  4934. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  4935. object.layers = this.layers.mask;
  4936. object.matrix = this.matrix.toArray();
  4937. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  4938. if (this.isInstancedMesh) {
  4939. object.type = 'InstancedMesh';
  4940. object.count = this.count;
  4941. object.instanceMatrix = this.instanceMatrix.toJSON();
  4942. } //
  4943. function serialize(library, element) {
  4944. if (library[element.uuid] === undefined) {
  4945. library[element.uuid] = element.toJSON(meta);
  4946. }
  4947. return element.uuid;
  4948. }
  4949. if (this.isMesh || this.isLine || this.isPoints) {
  4950. object.geometry = serialize(meta.geometries, this.geometry);
  4951. const parameters = this.geometry.parameters;
  4952. if (parameters !== undefined && parameters.shapes !== undefined) {
  4953. const shapes = parameters.shapes;
  4954. if (Array.isArray(shapes)) {
  4955. for (let i = 0, l = shapes.length; i < l; i++) {
  4956. const shape = shapes[i];
  4957. serialize(meta.shapes, shape);
  4958. }
  4959. } else {
  4960. serialize(meta.shapes, shapes);
  4961. }
  4962. }
  4963. }
  4964. if (this.isSkinnedMesh) {
  4965. object.bindMode = this.bindMode;
  4966. object.bindMatrix = this.bindMatrix.toArray();
  4967. if (this.skeleton !== undefined) {
  4968. serialize(meta.skeletons, this.skeleton);
  4969. object.skeleton = this.skeleton.uuid;
  4970. }
  4971. }
  4972. if (this.material !== undefined) {
  4973. if (Array.isArray(this.material)) {
  4974. const uuids = [];
  4975. for (let i = 0, l = this.material.length; i < l; i++) {
  4976. uuids.push(serialize(meta.materials, this.material[i]));
  4977. }
  4978. object.material = uuids;
  4979. } else {
  4980. object.material = serialize(meta.materials, this.material);
  4981. }
  4982. } //
  4983. if (this.children.length > 0) {
  4984. object.children = [];
  4985. for (let i = 0; i < this.children.length; i++) {
  4986. object.children.push(this.children[i].toJSON(meta).object);
  4987. }
  4988. } //
  4989. if (this.animations.length > 0) {
  4990. object.animations = [];
  4991. for (let i = 0; i < this.animations.length; i++) {
  4992. const animation = this.animations[i];
  4993. object.animations.push(serialize(meta.animations, animation));
  4994. }
  4995. }
  4996. if (isRootObject) {
  4997. const geometries = extractFromCache(meta.geometries);
  4998. const materials = extractFromCache(meta.materials);
  4999. const textures = extractFromCache(meta.textures);
  5000. const images = extractFromCache(meta.images);
  5001. const shapes = extractFromCache(meta.shapes);
  5002. const skeletons = extractFromCache(meta.skeletons);
  5003. const animations = extractFromCache(meta.animations);
  5004. if (geometries.length > 0) output.geometries = geometries;
  5005. if (materials.length > 0) output.materials = materials;
  5006. if (textures.length > 0) output.textures = textures;
  5007. if (images.length > 0) output.images = images;
  5008. if (shapes.length > 0) output.shapes = shapes;
  5009. if (skeletons.length > 0) output.skeletons = skeletons;
  5010. if (animations.length > 0) output.animations = animations;
  5011. }
  5012. output.object = object;
  5013. return output; // extract data from the cache hash
  5014. // remove metadata on each item
  5015. // and return as array
  5016. function extractFromCache(cache) {
  5017. const values = [];
  5018. for (const key in cache) {
  5019. const data = cache[key];
  5020. delete data.metadata;
  5021. values.push(data);
  5022. }
  5023. return values;
  5024. }
  5025. },
  5026. clone: function (recursive) {
  5027. return new this.constructor().copy(this, recursive);
  5028. },
  5029. copy: function (source, recursive = true) {
  5030. this.name = source.name;
  5031. this.up.copy(source.up);
  5032. this.position.copy(source.position);
  5033. this.rotation.order = source.rotation.order;
  5034. this.quaternion.copy(source.quaternion);
  5035. this.scale.copy(source.scale);
  5036. this.matrix.copy(source.matrix);
  5037. this.matrixWorld.copy(source.matrixWorld);
  5038. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5039. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  5040. this.layers.mask = source.layers.mask;
  5041. this.visible = source.visible;
  5042. this.castShadow = source.castShadow;
  5043. this.receiveShadow = source.receiveShadow;
  5044. this.frustumCulled = source.frustumCulled;
  5045. this.renderOrder = source.renderOrder;
  5046. this.userData = JSON.parse(JSON.stringify(source.userData));
  5047. if (recursive === true) {
  5048. for (let i = 0; i < source.children.length; i++) {
  5049. const child = source.children[i];
  5050. this.add(child.clone());
  5051. }
  5052. }
  5053. return this;
  5054. }
  5055. });
  5056. const _vector1 =
  5057. /*@__PURE__*/
  5058. new Vector3();
  5059. const _vector2 =
  5060. /*@__PURE__*/
  5061. new Vector3();
  5062. const _normalMatrix =
  5063. /*@__PURE__*/
  5064. new Matrix3();
  5065. class Plane {
  5066. constructor(normal, constant) {
  5067. Object.defineProperty(this, 'isPlane', {
  5068. value: true
  5069. }); // normal is assumed to be normalized
  5070. this.normal = normal !== undefined ? normal : new Vector3(1, 0, 0);
  5071. this.constant = constant !== undefined ? constant : 0;
  5072. }
  5073. set(normal, constant) {
  5074. this.normal.copy(normal);
  5075. this.constant = constant;
  5076. return this;
  5077. }
  5078. setComponents(x, y, z, w) {
  5079. this.normal.set(x, y, z);
  5080. this.constant = w;
  5081. return this;
  5082. }
  5083. setFromNormalAndCoplanarPoint(normal, point) {
  5084. this.normal.copy(normal);
  5085. this.constant = -point.dot(this.normal);
  5086. return this;
  5087. }
  5088. setFromCoplanarPoints(a, b, c) {
  5089. const 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)?
  5090. this.setFromNormalAndCoplanarPoint(normal, a);
  5091. return this;
  5092. }
  5093. clone() {
  5094. return new this.constructor().copy(this);
  5095. }
  5096. copy(plane) {
  5097. this.normal.copy(plane.normal);
  5098. this.constant = plane.constant;
  5099. return this;
  5100. }
  5101. normalize() {
  5102. // Note: will lead to a divide by zero if the plane is invalid.
  5103. const inverseNormalLength = 1.0 / this.normal.length();
  5104. this.normal.multiplyScalar(inverseNormalLength);
  5105. this.constant *= inverseNormalLength;
  5106. return this;
  5107. }
  5108. negate() {
  5109. this.constant *= -1;
  5110. this.normal.negate();
  5111. return this;
  5112. }
  5113. distanceToPoint(point) {
  5114. return this.normal.dot(point) + this.constant;
  5115. }
  5116. distanceToSphere(sphere) {
  5117. return this.distanceToPoint(sphere.center) - sphere.radius;
  5118. }
  5119. projectPoint(point, target) {
  5120. if (target === undefined) {
  5121. console.warn('THREE.Plane: .projectPoint() target is now required');
  5122. target = new Vector3();
  5123. }
  5124. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  5125. }
  5126. intersectLine(line, target) {
  5127. if (target === undefined) {
  5128. console.warn('THREE.Plane: .intersectLine() target is now required');
  5129. target = new Vector3();
  5130. }
  5131. const direction = line.delta(_vector1);
  5132. const denominator = this.normal.dot(direction);
  5133. if (denominator === 0) {
  5134. // line is coplanar, return origin
  5135. if (this.distanceToPoint(line.start) === 0) {
  5136. return target.copy(line.start);
  5137. } // Unsure if this is the correct method to handle this case.
  5138. return undefined;
  5139. }
  5140. const t = -(line.start.dot(this.normal) + this.constant) / denominator;
  5141. if (t < 0 || t > 1) {
  5142. return undefined;
  5143. }
  5144. return target.copy(direction).multiplyScalar(t).add(line.start);
  5145. }
  5146. intersectsLine(line) {
  5147. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  5148. const startSign = this.distanceToPoint(line.start);
  5149. const endSign = this.distanceToPoint(line.end);
  5150. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  5151. }
  5152. intersectsBox(box) {
  5153. return box.intersectsPlane(this);
  5154. }
  5155. intersectsSphere(sphere) {
  5156. return sphere.intersectsPlane(this);
  5157. }
  5158. coplanarPoint(target) {
  5159. if (target === undefined) {
  5160. console.warn('THREE.Plane: .coplanarPoint() target is now required');
  5161. target = new Vector3();
  5162. }
  5163. return target.copy(this.normal).multiplyScalar(-this.constant);
  5164. }
  5165. applyMatrix4(matrix, optionalNormalMatrix) {
  5166. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  5167. const referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  5168. const normal = this.normal.applyMatrix3(normalMatrix).normalize();
  5169. this.constant = -referencePoint.dot(normal);
  5170. return this;
  5171. }
  5172. translate(offset) {
  5173. this.constant -= offset.dot(this.normal);
  5174. return this;
  5175. }
  5176. equals(plane) {
  5177. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  5178. }
  5179. }
  5180. exports.Plane = Plane;
  5181. const _v0$1 =
  5182. /*@__PURE__*/
  5183. new Vector3();
  5184. const _v1$3 =
  5185. /*@__PURE__*/
  5186. new Vector3();
  5187. const _v2$1 =
  5188. /*@__PURE__*/
  5189. new Vector3();
  5190. const _v3 =
  5191. /*@__PURE__*/
  5192. new Vector3();
  5193. const _vab =
  5194. /*@__PURE__*/
  5195. new Vector3();
  5196. const _vac =
  5197. /*@__PURE__*/
  5198. new Vector3();
  5199. const _vbc =
  5200. /*@__PURE__*/
  5201. new Vector3();
  5202. const _vap =
  5203. /*@__PURE__*/
  5204. new Vector3();
  5205. const _vbp =
  5206. /*@__PURE__*/
  5207. new Vector3();
  5208. const _vcp =
  5209. /*@__PURE__*/
  5210. new Vector3();
  5211. class Triangle {
  5212. constructor(a, b, c) {
  5213. this.a = a !== undefined ? a : new Vector3();
  5214. this.b = b !== undefined ? b : new Vector3();
  5215. this.c = c !== undefined ? c : new Vector3();
  5216. }
  5217. static getNormal(a, b, c, target) {
  5218. if (target === undefined) {
  5219. console.warn('THREE.Triangle: .getNormal() target is now required');
  5220. target = new Vector3();
  5221. }
  5222. target.subVectors(c, b);
  5223. _v0$1.subVectors(a, b);
  5224. target.cross(_v0$1);
  5225. const targetLengthSq = target.lengthSq();
  5226. if (targetLengthSq > 0) {
  5227. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  5228. }
  5229. return target.set(0, 0, 0);
  5230. } // static/instance method to calculate barycentric coordinates
  5231. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  5232. static getBarycoord(point, a, b, c, target) {
  5233. _v0$1.subVectors(c, a);
  5234. _v1$3.subVectors(b, a);
  5235. _v2$1.subVectors(point, a);
  5236. const dot00 = _v0$1.dot(_v0$1);
  5237. const dot01 = _v0$1.dot(_v1$3);
  5238. const dot02 = _v0$1.dot(_v2$1);
  5239. const dot11 = _v1$3.dot(_v1$3);
  5240. const dot12 = _v1$3.dot(_v2$1);
  5241. const denom = dot00 * dot11 - dot01 * dot01;
  5242. if (target === undefined) {
  5243. console.warn('THREE.Triangle: .getBarycoord() target is now required');
  5244. target = new Vector3();
  5245. } // collinear or singular triangle
  5246. if (denom === 0) {
  5247. // arbitrary location outside of triangle?
  5248. // not sure if this is the best idea, maybe should be returning undefined
  5249. return target.set(-2, -1, -1);
  5250. }
  5251. const invDenom = 1 / denom;
  5252. const u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  5253. const v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  5254. return target.set(1 - u - v, v, u);
  5255. }
  5256. static containsPoint(point, a, b, c) {
  5257. this.getBarycoord(point, a, b, c, _v3);
  5258. return _v3.x >= 0 && _v3.y >= 0 && _v3.x + _v3.y <= 1;
  5259. }
  5260. static getUV(point, p1, p2, p3, uv1, uv2, uv3, target) {
  5261. this.getBarycoord(point, p1, p2, p3, _v3);
  5262. target.set(0, 0);
  5263. target.addScaledVector(uv1, _v3.x);
  5264. target.addScaledVector(uv2, _v3.y);
  5265. target.addScaledVector(uv3, _v3.z);
  5266. return target;
  5267. }
  5268. static isFrontFacing(a, b, c, direction) {
  5269. _v0$1.subVectors(c, b);
  5270. _v1$3.subVectors(a, b); // strictly front facing
  5271. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  5272. }
  5273. set(a, b, c) {
  5274. this.a.copy(a);
  5275. this.b.copy(b);
  5276. this.c.copy(c);
  5277. return this;
  5278. }
  5279. setFromPointsAndIndices(points, i0, i1, i2) {
  5280. this.a.copy(points[i0]);
  5281. this.b.copy(points[i1]);
  5282. this.c.copy(points[i2]);
  5283. return this;
  5284. }
  5285. clone() {
  5286. return new this.constructor().copy(this);
  5287. }
  5288. copy(triangle) {
  5289. this.a.copy(triangle.a);
  5290. this.b.copy(triangle.b);
  5291. this.c.copy(triangle.c);
  5292. return this;
  5293. }
  5294. getArea() {
  5295. _v0$1.subVectors(this.c, this.b);
  5296. _v1$3.subVectors(this.a, this.b);
  5297. return _v0$1.cross(_v1$3).length() * 0.5;
  5298. }
  5299. getMidpoint(target) {
  5300. if (target === undefined) {
  5301. console.warn('THREE.Triangle: .getMidpoint() target is now required');
  5302. target = new Vector3();
  5303. }
  5304. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  5305. }
  5306. getNormal(target) {
  5307. return Triangle.getNormal(this.a, this.b, this.c, target);
  5308. }
  5309. getPlane(target) {
  5310. if (target === undefined) {
  5311. console.warn('THREE.Triangle: .getPlane() target is now required');
  5312. target = new Plane();
  5313. }
  5314. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  5315. }
  5316. getBarycoord(point, target) {
  5317. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  5318. }
  5319. getUV(point, uv1, uv2, uv3, target) {
  5320. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  5321. }
  5322. containsPoint(point) {
  5323. return Triangle.containsPoint(point, this.a, this.b, this.c);
  5324. }
  5325. isFrontFacing(direction) {
  5326. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  5327. }
  5328. intersectsBox(box) {
  5329. return box.intersectsTriangle(this);
  5330. }
  5331. closestPointToPoint(p, target) {
  5332. if (target === undefined) {
  5333. console.warn('THREE.Triangle: .closestPointToPoint() target is now required');
  5334. target = new Vector3();
  5335. }
  5336. const a = this.a,
  5337. b = this.b,
  5338. c = this.c;
  5339. let v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5340. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5341. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5342. // basically, we're distinguishing which of the voronoi regions of the triangle
  5343. // the point lies in with the minimum amount of redundant computation.
  5344. _vab.subVectors(b, a);
  5345. _vac.subVectors(c, a);
  5346. _vap.subVectors(p, a);
  5347. const d1 = _vab.dot(_vap);
  5348. const d2 = _vac.dot(_vap);
  5349. if (d1 <= 0 && d2 <= 0) {
  5350. // vertex region of A; barycentric coords (1, 0, 0)
  5351. return target.copy(a);
  5352. }
  5353. _vbp.subVectors(p, b);
  5354. const d3 = _vab.dot(_vbp);
  5355. const d4 = _vac.dot(_vbp);
  5356. if (d3 >= 0 && d4 <= d3) {
  5357. // vertex region of B; barycentric coords (0, 1, 0)
  5358. return target.copy(b);
  5359. }
  5360. const vc = d1 * d4 - d3 * d2;
  5361. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  5362. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  5363. return target.copy(a).addScaledVector(_vab, v);
  5364. }
  5365. _vcp.subVectors(p, c);
  5366. const d5 = _vab.dot(_vcp);
  5367. const d6 = _vac.dot(_vcp);
  5368. if (d6 >= 0 && d5 <= d6) {
  5369. // vertex region of C; barycentric coords (0, 0, 1)
  5370. return target.copy(c);
  5371. }
  5372. const vb = d5 * d2 - d1 * d6;
  5373. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  5374. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  5375. return target.copy(a).addScaledVector(_vac, w);
  5376. }
  5377. const va = d3 * d6 - d5 * d4;
  5378. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  5379. _vbc.subVectors(c, b);
  5380. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  5381. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  5382. } // face region
  5383. const denom = 1 / (va + vb + vc); // u = va * denom
  5384. v = vb * denom;
  5385. w = vc * denom;
  5386. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  5387. }
  5388. equals(triangle) {
  5389. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  5390. }
  5391. }
  5392. exports.Triangle = Triangle;
  5393. const _colorKeywords = {
  5394. 'aliceblue': 0xF0F8FF,
  5395. 'antiquewhite': 0xFAEBD7,
  5396. 'aqua': 0x00FFFF,
  5397. 'aquamarine': 0x7FFFD4,
  5398. 'azure': 0xF0FFFF,
  5399. 'beige': 0xF5F5DC,
  5400. 'bisque': 0xFFE4C4,
  5401. 'black': 0x000000,
  5402. 'blanchedalmond': 0xFFEBCD,
  5403. 'blue': 0x0000FF,
  5404. 'blueviolet': 0x8A2BE2,
  5405. 'brown': 0xA52A2A,
  5406. 'burlywood': 0xDEB887,
  5407. 'cadetblue': 0x5F9EA0,
  5408. 'chartreuse': 0x7FFF00,
  5409. 'chocolate': 0xD2691E,
  5410. 'coral': 0xFF7F50,
  5411. 'cornflowerblue': 0x6495ED,
  5412. 'cornsilk': 0xFFF8DC,
  5413. 'crimson': 0xDC143C,
  5414. 'cyan': 0x00FFFF,
  5415. 'darkblue': 0x00008B,
  5416. 'darkcyan': 0x008B8B,
  5417. 'darkgoldenrod': 0xB8860B,
  5418. 'darkgray': 0xA9A9A9,
  5419. 'darkgreen': 0x006400,
  5420. 'darkgrey': 0xA9A9A9,
  5421. 'darkkhaki': 0xBDB76B,
  5422. 'darkmagenta': 0x8B008B,
  5423. 'darkolivegreen': 0x556B2F,
  5424. 'darkorange': 0xFF8C00,
  5425. 'darkorchid': 0x9932CC,
  5426. 'darkred': 0x8B0000,
  5427. 'darksalmon': 0xE9967A,
  5428. 'darkseagreen': 0x8FBC8F,
  5429. 'darkslateblue': 0x483D8B,
  5430. 'darkslategray': 0x2F4F4F,
  5431. 'darkslategrey': 0x2F4F4F,
  5432. 'darkturquoise': 0x00CED1,
  5433. 'darkviolet': 0x9400D3,
  5434. 'deeppink': 0xFF1493,
  5435. 'deepskyblue': 0x00BFFF,
  5436. 'dimgray': 0x696969,
  5437. 'dimgrey': 0x696969,
  5438. 'dodgerblue': 0x1E90FF,
  5439. 'firebrick': 0xB22222,
  5440. 'floralwhite': 0xFFFAF0,
  5441. 'forestgreen': 0x228B22,
  5442. 'fuchsia': 0xFF00FF,
  5443. 'gainsboro': 0xDCDCDC,
  5444. 'ghostwhite': 0xF8F8FF,
  5445. 'gold': 0xFFD700,
  5446. 'goldenrod': 0xDAA520,
  5447. 'gray': 0x808080,
  5448. 'green': 0x008000,
  5449. 'greenyellow': 0xADFF2F,
  5450. 'grey': 0x808080,
  5451. 'honeydew': 0xF0FFF0,
  5452. 'hotpink': 0xFF69B4,
  5453. 'indianred': 0xCD5C5C,
  5454. 'indigo': 0x4B0082,
  5455. 'ivory': 0xFFFFF0,
  5456. 'khaki': 0xF0E68C,
  5457. 'lavender': 0xE6E6FA,
  5458. 'lavenderblush': 0xFFF0F5,
  5459. 'lawngreen': 0x7CFC00,
  5460. 'lemonchiffon': 0xFFFACD,
  5461. 'lightblue': 0xADD8E6,
  5462. 'lightcoral': 0xF08080,
  5463. 'lightcyan': 0xE0FFFF,
  5464. 'lightgoldenrodyellow': 0xFAFAD2,
  5465. 'lightgray': 0xD3D3D3,
  5466. 'lightgreen': 0x90EE90,
  5467. 'lightgrey': 0xD3D3D3,
  5468. 'lightpink': 0xFFB6C1,
  5469. 'lightsalmon': 0xFFA07A,
  5470. 'lightseagreen': 0x20B2AA,
  5471. 'lightskyblue': 0x87CEFA,
  5472. 'lightslategray': 0x778899,
  5473. 'lightslategrey': 0x778899,
  5474. 'lightsteelblue': 0xB0C4DE,
  5475. 'lightyellow': 0xFFFFE0,
  5476. 'lime': 0x00FF00,
  5477. 'limegreen': 0x32CD32,
  5478. 'linen': 0xFAF0E6,
  5479. 'magenta': 0xFF00FF,
  5480. 'maroon': 0x800000,
  5481. 'mediumaquamarine': 0x66CDAA,
  5482. 'mediumblue': 0x0000CD,
  5483. 'mediumorchid': 0xBA55D3,
  5484. 'mediumpurple': 0x9370DB,
  5485. 'mediumseagreen': 0x3CB371,
  5486. 'mediumslateblue': 0x7B68EE,
  5487. 'mediumspringgreen': 0x00FA9A,
  5488. 'mediumturquoise': 0x48D1CC,
  5489. 'mediumvioletred': 0xC71585,
  5490. 'midnightblue': 0x191970,
  5491. 'mintcream': 0xF5FFFA,
  5492. 'mistyrose': 0xFFE4E1,
  5493. 'moccasin': 0xFFE4B5,
  5494. 'navajowhite': 0xFFDEAD,
  5495. 'navy': 0x000080,
  5496. 'oldlace': 0xFDF5E6,
  5497. 'olive': 0x808000,
  5498. 'olivedrab': 0x6B8E23,
  5499. 'orange': 0xFFA500,
  5500. 'orangered': 0xFF4500,
  5501. 'orchid': 0xDA70D6,
  5502. 'palegoldenrod': 0xEEE8AA,
  5503. 'palegreen': 0x98FB98,
  5504. 'paleturquoise': 0xAFEEEE,
  5505. 'palevioletred': 0xDB7093,
  5506. 'papayawhip': 0xFFEFD5,
  5507. 'peachpuff': 0xFFDAB9,
  5508. 'peru': 0xCD853F,
  5509. 'pink': 0xFFC0CB,
  5510. 'plum': 0xDDA0DD,
  5511. 'powderblue': 0xB0E0E6,
  5512. 'purple': 0x800080,
  5513. 'rebeccapurple': 0x663399,
  5514. 'red': 0xFF0000,
  5515. 'rosybrown': 0xBC8F8F,
  5516. 'royalblue': 0x4169E1,
  5517. 'saddlebrown': 0x8B4513,
  5518. 'salmon': 0xFA8072,
  5519. 'sandybrown': 0xF4A460,
  5520. 'seagreen': 0x2E8B57,
  5521. 'seashell': 0xFFF5EE,
  5522. 'sienna': 0xA0522D,
  5523. 'silver': 0xC0C0C0,
  5524. 'skyblue': 0x87CEEB,
  5525. 'slateblue': 0x6A5ACD,
  5526. 'slategray': 0x708090,
  5527. 'slategrey': 0x708090,
  5528. 'snow': 0xFFFAFA,
  5529. 'springgreen': 0x00FF7F,
  5530. 'steelblue': 0x4682B4,
  5531. 'tan': 0xD2B48C,
  5532. 'teal': 0x008080,
  5533. 'thistle': 0xD8BFD8,
  5534. 'tomato': 0xFF6347,
  5535. 'turquoise': 0x40E0D0,
  5536. 'violet': 0xEE82EE,
  5537. 'wheat': 0xF5DEB3,
  5538. 'white': 0xFFFFFF,
  5539. 'whitesmoke': 0xF5F5F5,
  5540. 'yellow': 0xFFFF00,
  5541. 'yellowgreen': 0x9ACD32
  5542. };
  5543. const _hslA = {
  5544. h: 0,
  5545. s: 0,
  5546. l: 0
  5547. };
  5548. const _hslB = {
  5549. h: 0,
  5550. s: 0,
  5551. l: 0
  5552. };
  5553. function hue2rgb(p, q, t) {
  5554. if (t < 0) t += 1;
  5555. if (t > 1) t -= 1;
  5556. if (t < 1 / 6) return p + (q - p) * 6 * t;
  5557. if (t < 1 / 2) return q;
  5558. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  5559. return p;
  5560. }
  5561. function SRGBToLinear(c) {
  5562. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  5563. }
  5564. function LinearToSRGB(c) {
  5565. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  5566. }
  5567. class Color {
  5568. constructor(r, g, b) {
  5569. Object.defineProperty(this, 'isColor', {
  5570. value: true
  5571. });
  5572. if (g === undefined && b === undefined) {
  5573. // r is THREE.Color, hex or string
  5574. return this.set(r);
  5575. }
  5576. return this.setRGB(r, g, b);
  5577. }
  5578. set(value) {
  5579. if (value && value.isColor) {
  5580. this.copy(value);
  5581. } else if (typeof value === 'number') {
  5582. this.setHex(value);
  5583. } else if (typeof value === 'string') {
  5584. this.setStyle(value);
  5585. }
  5586. return this;
  5587. }
  5588. setScalar(scalar) {
  5589. this.r = scalar;
  5590. this.g = scalar;
  5591. this.b = scalar;
  5592. return this;
  5593. }
  5594. setHex(hex) {
  5595. hex = Math.floor(hex);
  5596. this.r = (hex >> 16 & 255) / 255;
  5597. this.g = (hex >> 8 & 255) / 255;
  5598. this.b = (hex & 255) / 255;
  5599. return this;
  5600. }
  5601. setRGB(r, g, b) {
  5602. this.r = r;
  5603. this.g = g;
  5604. this.b = b;
  5605. return this;
  5606. }
  5607. setHSL(h, s, l) {
  5608. // h,s,l ranges are in 0.0 - 1.0
  5609. h = MathUtils.euclideanModulo(h, 1);
  5610. s = MathUtils.clamp(s, 0, 1);
  5611. l = MathUtils.clamp(l, 0, 1);
  5612. if (s === 0) {
  5613. this.r = this.g = this.b = l;
  5614. } else {
  5615. const p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  5616. const q = 2 * l - p;
  5617. this.r = hue2rgb(q, p, h + 1 / 3);
  5618. this.g = hue2rgb(q, p, h);
  5619. this.b = hue2rgb(q, p, h - 1 / 3);
  5620. }
  5621. return this;
  5622. }
  5623. setStyle(style) {
  5624. function handleAlpha(string) {
  5625. if (string === undefined) return;
  5626. if (parseFloat(string) < 1) {
  5627. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  5628. }
  5629. }
  5630. let m;
  5631. if (m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(style)) {
  5632. // rgb / hsl
  5633. let color;
  5634. const name = m[1];
  5635. const components = m[2];
  5636. switch (name) {
  5637. case 'rgb':
  5638. case 'rgba':
  5639. if (color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  5640. // rgb(255,0,0) rgba(255,0,0,0.5)
  5641. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  5642. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  5643. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  5644. handleAlpha(color[5]);
  5645. return this;
  5646. }
  5647. if (color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  5648. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5649. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  5650. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  5651. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  5652. handleAlpha(color[5]);
  5653. return this;
  5654. }
  5655. break;
  5656. case 'hsl':
  5657. case 'hsla':
  5658. if (color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  5659. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5660. const h = parseFloat(color[1]) / 360;
  5661. const s = parseInt(color[2], 10) / 100;
  5662. const l = parseInt(color[3], 10) / 100;
  5663. handleAlpha(color[5]);
  5664. return this.setHSL(h, s, l);
  5665. }
  5666. break;
  5667. }
  5668. } else if (m = /^\#([A-Fa-f0-9]+)$/.exec(style)) {
  5669. // hex color
  5670. const hex = m[1];
  5671. const size = hex.length;
  5672. if (size === 3) {
  5673. // #ff0
  5674. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  5675. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  5676. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  5677. return this;
  5678. } else if (size === 6) {
  5679. // #ff0000
  5680. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  5681. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  5682. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  5683. return this;
  5684. }
  5685. }
  5686. if (style && style.length > 0) {
  5687. return this.setColorName(style);
  5688. }
  5689. return this;
  5690. }
  5691. setColorName(style) {
  5692. // color keywords
  5693. const hex = _colorKeywords[style];
  5694. if (hex !== undefined) {
  5695. // red
  5696. this.setHex(hex);
  5697. } else {
  5698. // unknown color
  5699. console.warn('THREE.Color: Unknown color ' + style);
  5700. }
  5701. return this;
  5702. }
  5703. clone() {
  5704. return new this.constructor(this.r, this.g, this.b);
  5705. }
  5706. copy(color) {
  5707. this.r = color.r;
  5708. this.g = color.g;
  5709. this.b = color.b;
  5710. return this;
  5711. }
  5712. copyGammaToLinear(color, gammaFactor = 2.0) {
  5713. this.r = Math.pow(color.r, gammaFactor);
  5714. this.g = Math.pow(color.g, gammaFactor);
  5715. this.b = Math.pow(color.b, gammaFactor);
  5716. return this;
  5717. }
  5718. copyLinearToGamma(color, gammaFactor = 2.0) {
  5719. const safeInverse = gammaFactor > 0 ? 1.0 / gammaFactor : 1.0;
  5720. this.r = Math.pow(color.r, safeInverse);
  5721. this.g = Math.pow(color.g, safeInverse);
  5722. this.b = Math.pow(color.b, safeInverse);
  5723. return this;
  5724. }
  5725. convertGammaToLinear(gammaFactor) {
  5726. this.copyGammaToLinear(this, gammaFactor);
  5727. return this;
  5728. }
  5729. convertLinearToGamma(gammaFactor) {
  5730. this.copyLinearToGamma(this, gammaFactor);
  5731. return this;
  5732. }
  5733. copySRGBToLinear(color) {
  5734. this.r = SRGBToLinear(color.r);
  5735. this.g = SRGBToLinear(color.g);
  5736. this.b = SRGBToLinear(color.b);
  5737. return this;
  5738. }
  5739. copyLinearToSRGB(color) {
  5740. this.r = LinearToSRGB(color.r);
  5741. this.g = LinearToSRGB(color.g);
  5742. this.b = LinearToSRGB(color.b);
  5743. return this;
  5744. }
  5745. convertSRGBToLinear() {
  5746. this.copySRGBToLinear(this);
  5747. return this;
  5748. }
  5749. convertLinearToSRGB() {
  5750. this.copyLinearToSRGB(this);
  5751. return this;
  5752. }
  5753. getHex() {
  5754. return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
  5755. }
  5756. getHexString() {
  5757. return ('000000' + this.getHex().toString(16)).slice(-6);
  5758. }
  5759. getHSL(target) {
  5760. // h,s,l ranges are in 0.0 - 1.0
  5761. if (target === undefined) {
  5762. console.warn('THREE.Color: .getHSL() target is now required');
  5763. target = {
  5764. h: 0,
  5765. s: 0,
  5766. l: 0
  5767. };
  5768. }
  5769. const r = this.r,
  5770. g = this.g,
  5771. b = this.b;
  5772. const max = Math.max(r, g, b);
  5773. const min = Math.min(r, g, b);
  5774. let hue, saturation;
  5775. const lightness = (min + max) / 2.0;
  5776. if (min === max) {
  5777. hue = 0;
  5778. saturation = 0;
  5779. } else {
  5780. const delta = max - min;
  5781. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  5782. switch (max) {
  5783. case r:
  5784. hue = (g - b) / delta + (g < b ? 6 : 0);
  5785. break;
  5786. case g:
  5787. hue = (b - r) / delta + 2;
  5788. break;
  5789. case b:
  5790. hue = (r - g) / delta + 4;
  5791. break;
  5792. }
  5793. hue /= 6;
  5794. }
  5795. target.h = hue;
  5796. target.s = saturation;
  5797. target.l = lightness;
  5798. return target;
  5799. }
  5800. getStyle() {
  5801. return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
  5802. }
  5803. offsetHSL(h, s, l) {
  5804. this.getHSL(_hslA);
  5805. _hslA.h += h;
  5806. _hslA.s += s;
  5807. _hslA.l += l;
  5808. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  5809. return this;
  5810. }
  5811. add(color) {
  5812. this.r += color.r;
  5813. this.g += color.g;
  5814. this.b += color.b;
  5815. return this;
  5816. }
  5817. addColors(color1, color2) {
  5818. this.r = color1.r + color2.r;
  5819. this.g = color1.g + color2.g;
  5820. this.b = color1.b + color2.b;
  5821. return this;
  5822. }
  5823. addScalar(s) {
  5824. this.r += s;
  5825. this.g += s;
  5826. this.b += s;
  5827. return this;
  5828. }
  5829. sub(color) {
  5830. this.r = Math.max(0, this.r - color.r);
  5831. this.g = Math.max(0, this.g - color.g);
  5832. this.b = Math.max(0, this.b - color.b);
  5833. return this;
  5834. }
  5835. multiply(color) {
  5836. this.r *= color.r;
  5837. this.g *= color.g;
  5838. this.b *= color.b;
  5839. return this;
  5840. }
  5841. multiplyScalar(s) {
  5842. this.r *= s;
  5843. this.g *= s;
  5844. this.b *= s;
  5845. return this;
  5846. }
  5847. lerp(color, alpha) {
  5848. this.r += (color.r - this.r) * alpha;
  5849. this.g += (color.g - this.g) * alpha;
  5850. this.b += (color.b - this.b) * alpha;
  5851. return this;
  5852. }
  5853. lerpHSL(color, alpha) {
  5854. this.getHSL(_hslA);
  5855. color.getHSL(_hslB);
  5856. const h = MathUtils.lerp(_hslA.h, _hslB.h, alpha);
  5857. const s = MathUtils.lerp(_hslA.s, _hslB.s, alpha);
  5858. const l = MathUtils.lerp(_hslA.l, _hslB.l, alpha);
  5859. this.setHSL(h, s, l);
  5860. return this;
  5861. }
  5862. equals(c) {
  5863. return c.r === this.r && c.g === this.g && c.b === this.b;
  5864. }
  5865. fromArray(array, offset = 0) {
  5866. this.r = array[offset];
  5867. this.g = array[offset + 1];
  5868. this.b = array[offset + 2];
  5869. return this;
  5870. }
  5871. toArray(array = [], offset = 0) {
  5872. array[offset] = this.r;
  5873. array[offset + 1] = this.g;
  5874. array[offset + 2] = this.b;
  5875. return array;
  5876. }
  5877. fromBufferAttribute(attribute, index) {
  5878. this.r = attribute.getX(index);
  5879. this.g = attribute.getY(index);
  5880. this.b = attribute.getZ(index);
  5881. if (attribute.normalized === true) {
  5882. // assuming Uint8Array
  5883. this.r /= 255;
  5884. this.g /= 255;
  5885. this.b /= 255;
  5886. }
  5887. return this;
  5888. }
  5889. toJSON() {
  5890. return this.getHex();
  5891. }
  5892. }
  5893. exports.Color = Color;
  5894. Color.NAMES = _colorKeywords;
  5895. Color.prototype.r = 1;
  5896. Color.prototype.g = 1;
  5897. Color.prototype.b = 1;
  5898. class Face3 {
  5899. constructor(a, b, c, normal, color, materialIndex = 0) {
  5900. this.a = a;
  5901. this.b = b;
  5902. this.c = c;
  5903. this.normal = normal && normal.isVector3 ? normal : new Vector3();
  5904. this.vertexNormals = Array.isArray(normal) ? normal : [];
  5905. this.color = color && color.isColor ? color : new Color();
  5906. this.vertexColors = Array.isArray(color) ? color : [];
  5907. this.materialIndex = materialIndex;
  5908. }
  5909. clone() {
  5910. return new this.constructor().copy(this);
  5911. }
  5912. copy(source) {
  5913. this.a = source.a;
  5914. this.b = source.b;
  5915. this.c = source.c;
  5916. this.normal.copy(source.normal);
  5917. this.color.copy(source.color);
  5918. this.materialIndex = source.materialIndex;
  5919. for (let i = 0, il = source.vertexNormals.length; i < il; i++) {
  5920. this.vertexNormals[i] = source.vertexNormals[i].clone();
  5921. }
  5922. for (let i = 0, il = source.vertexColors.length; i < il; i++) {
  5923. this.vertexColors[i] = source.vertexColors[i].clone();
  5924. }
  5925. return this;
  5926. }
  5927. }
  5928. exports.Face3 = Face3;
  5929. let materialId = 0;
  5930. function Material() {
  5931. Object.defineProperty(this, 'id', {
  5932. value: materialId++
  5933. });
  5934. this.uuid = MathUtils.generateUUID();
  5935. this.name = '';
  5936. this.type = 'Material';
  5937. this.fog = true;
  5938. this.blending = NormalBlending;
  5939. this.side = FrontSide;
  5940. this.flatShading = false;
  5941. this.vertexColors = false;
  5942. this.opacity = 1;
  5943. this.transparent = false;
  5944. this.blendSrc = SrcAlphaFactor;
  5945. this.blendDst = OneMinusSrcAlphaFactor;
  5946. this.blendEquation = AddEquation;
  5947. this.blendSrcAlpha = null;
  5948. this.blendDstAlpha = null;
  5949. this.blendEquationAlpha = null;
  5950. this.depthFunc = LessEqualDepth;
  5951. this.depthTest = true;
  5952. this.depthWrite = true;
  5953. this.stencilWriteMask = 0xff;
  5954. this.stencilFunc = AlwaysStencilFunc;
  5955. this.stencilRef = 0;
  5956. this.stencilFuncMask = 0xff;
  5957. this.stencilFail = KeepStencilOp;
  5958. this.stencilZFail = KeepStencilOp;
  5959. this.stencilZPass = KeepStencilOp;
  5960. this.stencilWrite = false;
  5961. this.clippingPlanes = null;
  5962. this.clipIntersection = false;
  5963. this.clipShadows = false;
  5964. this.shadowSide = null;
  5965. this.colorWrite = true;
  5966. this.precision = null; // override the renderer's default precision for this material
  5967. this.polygonOffset = false;
  5968. this.polygonOffsetFactor = 0;
  5969. this.polygonOffsetUnits = 0;
  5970. this.dithering = false;
  5971. this.alphaTest = 0;
  5972. this.premultipliedAlpha = false;
  5973. this.visible = true;
  5974. this.toneMapped = true;
  5975. this.userData = {};
  5976. this.version = 0;
  5977. }
  5978. Material.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  5979. constructor: Material,
  5980. isMaterial: true,
  5981. onBeforeCompile: function ()
  5982. /* shaderobject, renderer */
  5983. {},
  5984. customProgramCacheKey: function () {
  5985. return this.onBeforeCompile.toString();
  5986. },
  5987. setValues: function (values) {
  5988. if (values === undefined) return;
  5989. for (const key in values) {
  5990. const newValue = values[key];
  5991. if (newValue === undefined) {
  5992. console.warn("THREE.Material: '" + key + "' parameter is undefined.");
  5993. continue;
  5994. } // for backward compatability if shading is set in the constructor
  5995. if (key === 'shading') {
  5996. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  5997. this.flatShading = newValue === FlatShading ? true : false;
  5998. continue;
  5999. }
  6000. const currentValue = this[key];
  6001. if (currentValue === undefined) {
  6002. console.warn("THREE." + this.type + ": '" + key + "' is not a property of this material.");
  6003. continue;
  6004. }
  6005. if (currentValue && currentValue.isColor) {
  6006. currentValue.set(newValue);
  6007. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  6008. currentValue.copy(newValue);
  6009. } else {
  6010. this[key] = newValue;
  6011. }
  6012. }
  6013. },
  6014. toJSON: function (meta) {
  6015. const isRoot = meta === undefined || typeof meta === 'string';
  6016. if (isRoot) {
  6017. meta = {
  6018. textures: {},
  6019. images: {}
  6020. };
  6021. }
  6022. const data = {
  6023. metadata: {
  6024. version: 4.5,
  6025. type: 'Material',
  6026. generator: 'Material.toJSON'
  6027. }
  6028. }; // standard Material serialization
  6029. data.uuid = this.uuid;
  6030. data.type = this.type;
  6031. if (this.name !== '') data.name = this.name;
  6032. if (this.color && this.color.isColor) data.color = this.color.getHex();
  6033. if (this.roughness !== undefined) data.roughness = this.roughness;
  6034. if (this.metalness !== undefined) data.metalness = this.metalness;
  6035. if (this.sheen && this.sheen.isColor) data.sheen = this.sheen.getHex();
  6036. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  6037. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  6038. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  6039. if (this.shininess !== undefined) data.shininess = this.shininess;
  6040. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  6041. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  6042. if (this.clearcoatMap && this.clearcoatMap.isTexture) {
  6043. data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid;
  6044. }
  6045. if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) {
  6046. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid;
  6047. }
  6048. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  6049. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  6050. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  6051. }
  6052. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  6053. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  6054. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  6055. if (this.lightMap && this.lightMap.isTexture) data.lightMap = this.lightMap.toJSON(meta).uuid;
  6056. if (this.aoMap && this.aoMap.isTexture) {
  6057. data.aoMap = this.aoMap.toJSON(meta).uuid;
  6058. data.aoMapIntensity = this.aoMapIntensity;
  6059. }
  6060. if (this.bumpMap && this.bumpMap.isTexture) {
  6061. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  6062. data.bumpScale = this.bumpScale;
  6063. }
  6064. if (this.normalMap && this.normalMap.isTexture) {
  6065. data.normalMap = this.normalMap.toJSON(meta).uuid;
  6066. data.normalMapType = this.normalMapType;
  6067. data.normalScale = this.normalScale.toArray();
  6068. }
  6069. if (this.displacementMap && this.displacementMap.isTexture) {
  6070. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  6071. data.displacementScale = this.displacementScale;
  6072. data.displacementBias = this.displacementBias;
  6073. }
  6074. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  6075. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  6076. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  6077. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  6078. if (this.envMap && this.envMap.isTexture) {
  6079. data.envMap = this.envMap.toJSON(meta).uuid;
  6080. data.reflectivity = this.reflectivity; // Scale behind envMap
  6081. data.refractionRatio = this.refractionRatio;
  6082. if (this.combine !== undefined) data.combine = this.combine;
  6083. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  6084. }
  6085. if (this.gradientMap && this.gradientMap.isTexture) {
  6086. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  6087. }
  6088. if (this.size !== undefined) data.size = this.size;
  6089. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  6090. if (this.blending !== NormalBlending) data.blending = this.blending;
  6091. if (this.flatShading === true) data.flatShading = this.flatShading;
  6092. if (this.side !== FrontSide) data.side = this.side;
  6093. if (this.vertexColors) data.vertexColors = true;
  6094. if (this.opacity < 1) data.opacity = this.opacity;
  6095. if (this.transparent === true) data.transparent = this.transparent;
  6096. data.depthFunc = this.depthFunc;
  6097. data.depthTest = this.depthTest;
  6098. data.depthWrite = this.depthWrite;
  6099. data.stencilWrite = this.stencilWrite;
  6100. data.stencilWriteMask = this.stencilWriteMask;
  6101. data.stencilFunc = this.stencilFunc;
  6102. data.stencilRef = this.stencilRef;
  6103. data.stencilFuncMask = this.stencilFuncMask;
  6104. data.stencilFail = this.stencilFail;
  6105. data.stencilZFail = this.stencilZFail;
  6106. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  6107. if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;
  6108. if (this.polygonOffset === true) data.polygonOffset = true;
  6109. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  6110. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  6111. if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;
  6112. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  6113. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  6114. if (this.scale !== undefined) data.scale = this.scale;
  6115. if (this.dithering === true) data.dithering = true;
  6116. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  6117. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  6118. if (this.wireframe === true) data.wireframe = this.wireframe;
  6119. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  6120. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  6121. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  6122. if (this.morphTargets === true) data.morphTargets = true;
  6123. if (this.morphNormals === true) data.morphNormals = true;
  6124. if (this.skinning === true) data.skinning = true;
  6125. if (this.visible === false) data.visible = false;
  6126. if (this.toneMapped === false) data.toneMapped = false;
  6127. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  6128. function extractFromCache(cache) {
  6129. const values = [];
  6130. for (const key in cache) {
  6131. const data = cache[key];
  6132. delete data.metadata;
  6133. values.push(data);
  6134. }
  6135. return values;
  6136. }
  6137. if (isRoot) {
  6138. const textures = extractFromCache(meta.textures);
  6139. const images = extractFromCache(meta.images);
  6140. if (textures.length > 0) data.textures = textures;
  6141. if (images.length > 0) data.images = images;
  6142. }
  6143. return data;
  6144. },
  6145. clone: function () {
  6146. return new this.constructor().copy(this);
  6147. },
  6148. copy: function (source) {
  6149. this.name = source.name;
  6150. this.fog = source.fog;
  6151. this.blending = source.blending;
  6152. this.side = source.side;
  6153. this.flatShading = source.flatShading;
  6154. this.vertexColors = source.vertexColors;
  6155. this.opacity = source.opacity;
  6156. this.transparent = source.transparent;
  6157. this.blendSrc = source.blendSrc;
  6158. this.blendDst = source.blendDst;
  6159. this.blendEquation = source.blendEquation;
  6160. this.blendSrcAlpha = source.blendSrcAlpha;
  6161. this.blendDstAlpha = source.blendDstAlpha;
  6162. this.blendEquationAlpha = source.blendEquationAlpha;
  6163. this.depthFunc = source.depthFunc;
  6164. this.depthTest = source.depthTest;
  6165. this.depthWrite = source.depthWrite;
  6166. this.stencilWriteMask = source.stencilWriteMask;
  6167. this.stencilFunc = source.stencilFunc;
  6168. this.stencilRef = source.stencilRef;
  6169. this.stencilFuncMask = source.stencilFuncMask;
  6170. this.stencilFail = source.stencilFail;
  6171. this.stencilZFail = source.stencilZFail;
  6172. this.stencilZPass = source.stencilZPass;
  6173. this.stencilWrite = source.stencilWrite;
  6174. const srcPlanes = source.clippingPlanes;
  6175. let dstPlanes = null;
  6176. if (srcPlanes !== null) {
  6177. const n = srcPlanes.length;
  6178. dstPlanes = new Array(n);
  6179. for (let i = 0; i !== n; ++i) {
  6180. dstPlanes[i] = srcPlanes[i].clone();
  6181. }
  6182. }
  6183. this.clippingPlanes = dstPlanes;
  6184. this.clipIntersection = source.clipIntersection;
  6185. this.clipShadows = source.clipShadows;
  6186. this.shadowSide = source.shadowSide;
  6187. this.colorWrite = source.colorWrite;
  6188. this.precision = source.precision;
  6189. this.polygonOffset = source.polygonOffset;
  6190. this.polygonOffsetFactor = source.polygonOffsetFactor;
  6191. this.polygonOffsetUnits = source.polygonOffsetUnits;
  6192. this.dithering = source.dithering;
  6193. this.alphaTest = source.alphaTest;
  6194. this.premultipliedAlpha = source.premultipliedAlpha;
  6195. this.visible = source.visible;
  6196. this.toneMapped = source.toneMapped;
  6197. this.userData = JSON.parse(JSON.stringify(source.userData));
  6198. return this;
  6199. },
  6200. dispose: function () {
  6201. this.dispatchEvent({
  6202. type: 'dispose'
  6203. });
  6204. }
  6205. });
  6206. Object.defineProperty(Material.prototype, 'needsUpdate', {
  6207. set: function (value) {
  6208. if (value === true) this.version++;
  6209. }
  6210. });
  6211. /**
  6212. * parameters = {
  6213. * color: <hex>,
  6214. * opacity: <float>,
  6215. * map: new THREE.Texture( <Image> ),
  6216. *
  6217. * lightMap: new THREE.Texture( <Image> ),
  6218. * lightMapIntensity: <float>
  6219. *
  6220. * aoMap: new THREE.Texture( <Image> ),
  6221. * aoMapIntensity: <float>
  6222. *
  6223. * specularMap: new THREE.Texture( <Image> ),
  6224. *
  6225. * alphaMap: new THREE.Texture( <Image> ),
  6226. *
  6227. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  6228. * combine: THREE.Multiply,
  6229. * reflectivity: <float>,
  6230. * refractionRatio: <float>,
  6231. *
  6232. * depthTest: <bool>,
  6233. * depthWrite: <bool>,
  6234. *
  6235. * wireframe: <boolean>,
  6236. * wireframeLinewidth: <float>,
  6237. *
  6238. * skinning: <bool>,
  6239. * morphTargets: <bool>
  6240. * }
  6241. */
  6242. function MeshBasicMaterial(parameters) {
  6243. Material.call(this);
  6244. this.type = 'MeshBasicMaterial';
  6245. this.color = new Color(0xffffff); // emissive
  6246. this.map = null;
  6247. this.lightMap = null;
  6248. this.lightMapIntensity = 1.0;
  6249. this.aoMap = null;
  6250. this.aoMapIntensity = 1.0;
  6251. this.specularMap = null;
  6252. this.alphaMap = null;
  6253. this.envMap = null;
  6254. this.combine = MultiplyOperation;
  6255. this.reflectivity = 1;
  6256. this.refractionRatio = 0.98;
  6257. this.wireframe = false;
  6258. this.wireframeLinewidth = 1;
  6259. this.wireframeLinecap = 'round';
  6260. this.wireframeLinejoin = 'round';
  6261. this.skinning = false;
  6262. this.morphTargets = false;
  6263. this.setValues(parameters);
  6264. }
  6265. MeshBasicMaterial.prototype = Object.create(Material.prototype);
  6266. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  6267. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  6268. MeshBasicMaterial.prototype.copy = function (source) {
  6269. Material.prototype.copy.call(this, source);
  6270. this.color.copy(source.color);
  6271. this.map = source.map;
  6272. this.lightMap = source.lightMap;
  6273. this.lightMapIntensity = source.lightMapIntensity;
  6274. this.aoMap = source.aoMap;
  6275. this.aoMapIntensity = source.aoMapIntensity;
  6276. this.specularMap = source.specularMap;
  6277. this.alphaMap = source.alphaMap;
  6278. this.envMap = source.envMap;
  6279. this.combine = source.combine;
  6280. this.reflectivity = source.reflectivity;
  6281. this.refractionRatio = source.refractionRatio;
  6282. this.wireframe = source.wireframe;
  6283. this.wireframeLinewidth = source.wireframeLinewidth;
  6284. this.wireframeLinecap = source.wireframeLinecap;
  6285. this.wireframeLinejoin = source.wireframeLinejoin;
  6286. this.skinning = source.skinning;
  6287. this.morphTargets = source.morphTargets;
  6288. return this;
  6289. };
  6290. const _vector$3 = new Vector3();
  6291. const _vector2$1 = new Vector2();
  6292. function BufferAttribute(array, itemSize, normalized) {
  6293. if (Array.isArray(array)) {
  6294. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  6295. }
  6296. this.name = '';
  6297. this.array = array;
  6298. this.itemSize = itemSize;
  6299. this.count = array !== undefined ? array.length / itemSize : 0;
  6300. this.normalized = normalized === true;
  6301. this.usage = StaticDrawUsage;
  6302. this.updateRange = {
  6303. offset: 0,
  6304. count: -1
  6305. };
  6306. this.version = 0;
  6307. }
  6308. Object.defineProperty(BufferAttribute.prototype, 'needsUpdate', {
  6309. set: function (value) {
  6310. if (value === true) this.version++;
  6311. }
  6312. });
  6313. Object.assign(BufferAttribute.prototype, {
  6314. isBufferAttribute: true,
  6315. onUploadCallback: function () {},
  6316. setUsage: function (value) {
  6317. this.usage = value;
  6318. return this;
  6319. },
  6320. copy: function (source) {
  6321. this.name = source.name;
  6322. this.array = new source.array.constructor(source.array);
  6323. this.itemSize = source.itemSize;
  6324. this.count = source.count;
  6325. this.normalized = source.normalized;
  6326. this.usage = source.usage;
  6327. return this;
  6328. },
  6329. copyAt: function (index1, attribute, index2) {
  6330. index1 *= this.itemSize;
  6331. index2 *= attribute.itemSize;
  6332. for (let i = 0, l = this.itemSize; i < l; i++) {
  6333. this.array[index1 + i] = attribute.array[index2 + i];
  6334. }
  6335. return this;
  6336. },
  6337. copyArray: function (array) {
  6338. this.array.set(array);
  6339. return this;
  6340. },
  6341. copyColorsArray: function (colors) {
  6342. const array = this.array;
  6343. let offset = 0;
  6344. for (let i = 0, l = colors.length; i < l; i++) {
  6345. let color = colors[i];
  6346. if (color === undefined) {
  6347. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  6348. color = new Color();
  6349. }
  6350. array[offset++] = color.r;
  6351. array[offset++] = color.g;
  6352. array[offset++] = color.b;
  6353. }
  6354. return this;
  6355. },
  6356. copyVector2sArray: function (vectors) {
  6357. const array = this.array;
  6358. let offset = 0;
  6359. for (let i = 0, l = vectors.length; i < l; i++) {
  6360. let vector = vectors[i];
  6361. if (vector === undefined) {
  6362. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  6363. vector = new Vector2();
  6364. }
  6365. array[offset++] = vector.x;
  6366. array[offset++] = vector.y;
  6367. }
  6368. return this;
  6369. },
  6370. copyVector3sArray: function (vectors) {
  6371. const array = this.array;
  6372. let offset = 0;
  6373. for (let i = 0, l = vectors.length; i < l; i++) {
  6374. let vector = vectors[i];
  6375. if (vector === undefined) {
  6376. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  6377. vector = new Vector3();
  6378. }
  6379. array[offset++] = vector.x;
  6380. array[offset++] = vector.y;
  6381. array[offset++] = vector.z;
  6382. }
  6383. return this;
  6384. },
  6385. copyVector4sArray: function (vectors) {
  6386. const array = this.array;
  6387. let offset = 0;
  6388. for (let i = 0, l = vectors.length; i < l; i++) {
  6389. let vector = vectors[i];
  6390. if (vector === undefined) {
  6391. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  6392. vector = new Vector4();
  6393. }
  6394. array[offset++] = vector.x;
  6395. array[offset++] = vector.y;
  6396. array[offset++] = vector.z;
  6397. array[offset++] = vector.w;
  6398. }
  6399. return this;
  6400. },
  6401. applyMatrix3: function (m) {
  6402. if (this.itemSize === 2) {
  6403. for (let i = 0, l = this.count; i < l; i++) {
  6404. _vector2$1.fromBufferAttribute(this, i);
  6405. _vector2$1.applyMatrix3(m);
  6406. this.setXY(i, _vector2$1.x, _vector2$1.y);
  6407. }
  6408. } else if (this.itemSize === 3) {
  6409. for (let i = 0, l = this.count; i < l; i++) {
  6410. _vector$3.fromBufferAttribute(this, i);
  6411. _vector$3.applyMatrix3(m);
  6412. this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
  6413. }
  6414. }
  6415. return this;
  6416. },
  6417. applyMatrix4: function (m) {
  6418. for (let i = 0, l = this.count; i < l; i++) {
  6419. _vector$3.x = this.getX(i);
  6420. _vector$3.y = this.getY(i);
  6421. _vector$3.z = this.getZ(i);
  6422. _vector$3.applyMatrix4(m);
  6423. this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
  6424. }
  6425. return this;
  6426. },
  6427. applyNormalMatrix: function (m) {
  6428. for (let i = 0, l = this.count; i < l; i++) {
  6429. _vector$3.x = this.getX(i);
  6430. _vector$3.y = this.getY(i);
  6431. _vector$3.z = this.getZ(i);
  6432. _vector$3.applyNormalMatrix(m);
  6433. this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
  6434. }
  6435. return this;
  6436. },
  6437. transformDirection: function (m) {
  6438. for (let i = 0, l = this.count; i < l; i++) {
  6439. _vector$3.x = this.getX(i);
  6440. _vector$3.y = this.getY(i);
  6441. _vector$3.z = this.getZ(i);
  6442. _vector$3.transformDirection(m);
  6443. this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
  6444. }
  6445. return this;
  6446. },
  6447. set: function (value, offset = 0) {
  6448. this.array.set(value, offset);
  6449. return this;
  6450. },
  6451. getX: function (index) {
  6452. return this.array[index * this.itemSize];
  6453. },
  6454. setX: function (index, x) {
  6455. this.array[index * this.itemSize] = x;
  6456. return this;
  6457. },
  6458. getY: function (index) {
  6459. return this.array[index * this.itemSize + 1];
  6460. },
  6461. setY: function (index, y) {
  6462. this.array[index * this.itemSize + 1] = y;
  6463. return this;
  6464. },
  6465. getZ: function (index) {
  6466. return this.array[index * this.itemSize + 2];
  6467. },
  6468. setZ: function (index, z) {
  6469. this.array[index * this.itemSize + 2] = z;
  6470. return this;
  6471. },
  6472. getW: function (index) {
  6473. return this.array[index * this.itemSize + 3];
  6474. },
  6475. setW: function (index, w) {
  6476. this.array[index * this.itemSize + 3] = w;
  6477. return this;
  6478. },
  6479. setXY: function (index, x, y) {
  6480. index *= this.itemSize;
  6481. this.array[index + 0] = x;
  6482. this.array[index + 1] = y;
  6483. return this;
  6484. },
  6485. setXYZ: function (index, x, y, z) {
  6486. index *= this.itemSize;
  6487. this.array[index + 0] = x;
  6488. this.array[index + 1] = y;
  6489. this.array[index + 2] = z;
  6490. return this;
  6491. },
  6492. setXYZW: function (index, x, y, z, w) {
  6493. index *= this.itemSize;
  6494. this.array[index + 0] = x;
  6495. this.array[index + 1] = y;
  6496. this.array[index + 2] = z;
  6497. this.array[index + 3] = w;
  6498. return this;
  6499. },
  6500. onUpload: function (callback) {
  6501. this.onUploadCallback = callback;
  6502. return this;
  6503. },
  6504. clone: function () {
  6505. return new this.constructor(this.array, this.itemSize).copy(this);
  6506. },
  6507. toJSON: function () {
  6508. return {
  6509. itemSize: this.itemSize,
  6510. type: this.array.constructor.name,
  6511. array: Array.prototype.slice.call(this.array),
  6512. normalized: this.normalized
  6513. };
  6514. }
  6515. }); //
  6516. function Int8BufferAttribute(array, itemSize, normalized) {
  6517. BufferAttribute.call(this, new Int8Array(array), itemSize, normalized);
  6518. }
  6519. Int8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6520. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  6521. function Uint8BufferAttribute(array, itemSize, normalized) {
  6522. BufferAttribute.call(this, new Uint8Array(array), itemSize, normalized);
  6523. }
  6524. Uint8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6525. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  6526. function Uint8ClampedBufferAttribute(array, itemSize, normalized) {
  6527. BufferAttribute.call(this, new Uint8ClampedArray(array), itemSize, normalized);
  6528. }
  6529. Uint8ClampedBufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6530. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  6531. function Int16BufferAttribute(array, itemSize, normalized) {
  6532. BufferAttribute.call(this, new Int16Array(array), itemSize, normalized);
  6533. }
  6534. Int16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6535. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  6536. function Uint16BufferAttribute(array, itemSize, normalized) {
  6537. BufferAttribute.call(this, new Uint16Array(array), itemSize, normalized);
  6538. }
  6539. Uint16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6540. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  6541. function Int32BufferAttribute(array, itemSize, normalized) {
  6542. BufferAttribute.call(this, new Int32Array(array), itemSize, normalized);
  6543. }
  6544. Int32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6545. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  6546. function Uint32BufferAttribute(array, itemSize, normalized) {
  6547. BufferAttribute.call(this, new Uint32Array(array), itemSize, normalized);
  6548. }
  6549. Uint32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6550. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  6551. function Float16BufferAttribute(array, itemSize, normalized) {
  6552. BufferAttribute.call(this, new Uint16Array(array), itemSize, normalized);
  6553. }
  6554. Float16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6555. Float16BufferAttribute.prototype.constructor = Float16BufferAttribute;
  6556. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  6557. function Float32BufferAttribute(array, itemSize, normalized) {
  6558. BufferAttribute.call(this, new Float32Array(array), itemSize, normalized);
  6559. }
  6560. Float32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6561. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  6562. function Float64BufferAttribute(array, itemSize, normalized) {
  6563. BufferAttribute.call(this, new Float64Array(array), itemSize, normalized);
  6564. }
  6565. Float64BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6566. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  6567. class DirectGeometry {
  6568. constructor() {
  6569. this.vertices = [];
  6570. this.normals = [];
  6571. this.colors = [];
  6572. this.uvs = [];
  6573. this.uvs2 = [];
  6574. this.groups = [];
  6575. this.morphTargets = {};
  6576. this.skinWeights = [];
  6577. this.skinIndices = []; // this.lineDistances = [];
  6578. this.boundingBox = null;
  6579. this.boundingSphere = null; // update flags
  6580. this.verticesNeedUpdate = false;
  6581. this.normalsNeedUpdate = false;
  6582. this.colorsNeedUpdate = false;
  6583. this.uvsNeedUpdate = false;
  6584. this.groupsNeedUpdate = false;
  6585. }
  6586. computeGroups(geometry) {
  6587. const groups = [];
  6588. let group, i;
  6589. let materialIndex = undefined;
  6590. const faces = geometry.faces;
  6591. for (i = 0; i < faces.length; i++) {
  6592. const face = faces[i]; // materials
  6593. if (face.materialIndex !== materialIndex) {
  6594. materialIndex = face.materialIndex;
  6595. if (group !== undefined) {
  6596. group.count = i * 3 - group.start;
  6597. groups.push(group);
  6598. }
  6599. group = {
  6600. start: i * 3,
  6601. materialIndex: materialIndex
  6602. };
  6603. }
  6604. }
  6605. if (group !== undefined) {
  6606. group.count = i * 3 - group.start;
  6607. groups.push(group);
  6608. }
  6609. this.groups = groups;
  6610. }
  6611. fromGeometry(geometry) {
  6612. const faces = geometry.faces;
  6613. const vertices = geometry.vertices;
  6614. const faceVertexUvs = geometry.faceVertexUvs;
  6615. const hasFaceVertexUv = faceVertexUvs[0] && faceVertexUvs[0].length > 0;
  6616. const hasFaceVertexUv2 = faceVertexUvs[1] && faceVertexUvs[1].length > 0; // morphs
  6617. const morphTargets = geometry.morphTargets;
  6618. const morphTargetsLength = morphTargets.length;
  6619. let morphTargetsPosition;
  6620. if (morphTargetsLength > 0) {
  6621. morphTargetsPosition = [];
  6622. for (let i = 0; i < morphTargetsLength; i++) {
  6623. morphTargetsPosition[i] = {
  6624. name: morphTargets[i].name,
  6625. data: []
  6626. };
  6627. }
  6628. this.morphTargets.position = morphTargetsPosition;
  6629. }
  6630. const morphNormals = geometry.morphNormals;
  6631. const morphNormalsLength = morphNormals.length;
  6632. let morphTargetsNormal;
  6633. if (morphNormalsLength > 0) {
  6634. morphTargetsNormal = [];
  6635. for (let i = 0; i < morphNormalsLength; i++) {
  6636. morphTargetsNormal[i] = {
  6637. name: morphNormals[i].name,
  6638. data: []
  6639. };
  6640. }
  6641. this.morphTargets.normal = morphTargetsNormal;
  6642. } // skins
  6643. const skinIndices = geometry.skinIndices;
  6644. const skinWeights = geometry.skinWeights;
  6645. const hasSkinIndices = skinIndices.length === vertices.length;
  6646. const hasSkinWeights = skinWeights.length === vertices.length; //
  6647. if (vertices.length > 0 && faces.length === 0) {
  6648. console.error('THREE.DirectGeometry: Faceless geometries are not supported.');
  6649. }
  6650. for (let i = 0; i < faces.length; i++) {
  6651. const face = faces[i];
  6652. this.vertices.push(vertices[face.a], vertices[face.b], vertices[face.c]);
  6653. const vertexNormals = face.vertexNormals;
  6654. if (vertexNormals.length === 3) {
  6655. this.normals.push(vertexNormals[0], vertexNormals[1], vertexNormals[2]);
  6656. } else {
  6657. const normal = face.normal;
  6658. this.normals.push(normal, normal, normal);
  6659. }
  6660. const vertexColors = face.vertexColors;
  6661. if (vertexColors.length === 3) {
  6662. this.colors.push(vertexColors[0], vertexColors[1], vertexColors[2]);
  6663. } else {
  6664. const color = face.color;
  6665. this.colors.push(color, color, color);
  6666. }
  6667. if (hasFaceVertexUv === true) {
  6668. const vertexUvs = faceVertexUvs[0][i];
  6669. if (vertexUvs !== undefined) {
  6670. this.uvs.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]);
  6671. } else {
  6672. console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i);
  6673. this.uvs.push(new Vector2(), new Vector2(), new Vector2());
  6674. }
  6675. }
  6676. if (hasFaceVertexUv2 === true) {
  6677. const vertexUvs = faceVertexUvs[1][i];
  6678. if (vertexUvs !== undefined) {
  6679. this.uvs2.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]);
  6680. } else {
  6681. console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i);
  6682. this.uvs2.push(new Vector2(), new Vector2(), new Vector2());
  6683. }
  6684. } // morphs
  6685. for (let j = 0; j < morphTargetsLength; j++) {
  6686. const morphTarget = morphTargets[j].vertices;
  6687. morphTargetsPosition[j].data.push(morphTarget[face.a], morphTarget[face.b], morphTarget[face.c]);
  6688. }
  6689. for (let j = 0; j < morphNormalsLength; j++) {
  6690. const morphNormal = morphNormals[j].vertexNormals[i];
  6691. morphTargetsNormal[j].data.push(morphNormal.a, morphNormal.b, morphNormal.c);
  6692. } // skins
  6693. if (hasSkinIndices) {
  6694. this.skinIndices.push(skinIndices[face.a], skinIndices[face.b], skinIndices[face.c]);
  6695. }
  6696. if (hasSkinWeights) {
  6697. this.skinWeights.push(skinWeights[face.a], skinWeights[face.b], skinWeights[face.c]);
  6698. }
  6699. }
  6700. this.computeGroups(geometry);
  6701. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6702. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6703. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6704. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6705. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6706. if (geometry.boundingSphere !== null) {
  6707. this.boundingSphere = geometry.boundingSphere.clone();
  6708. }
  6709. if (geometry.boundingBox !== null) {
  6710. this.boundingBox = geometry.boundingBox.clone();
  6711. }
  6712. return this;
  6713. }
  6714. }
  6715. function arrayMax(array) {
  6716. if (array.length === 0) return -Infinity;
  6717. let max = array[0];
  6718. for (let i = 1, l = array.length; i < l; ++i) {
  6719. if (array[i] > max) max = array[i];
  6720. }
  6721. return max;
  6722. }
  6723. const TYPED_ARRAYS = {
  6724. Int8Array: Int8Array,
  6725. Uint8Array: Uint8Array,
  6726. // Workaround for IE11 pre KB2929437. See #11440
  6727. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  6728. Int16Array: Int16Array,
  6729. Uint16Array: Uint16Array,
  6730. Int32Array: Int32Array,
  6731. Uint32Array: Uint32Array,
  6732. Float32Array: Float32Array,
  6733. Float64Array: Float64Array
  6734. };
  6735. function getTypedArray(type, buffer) {
  6736. return new TYPED_ARRAYS[type](buffer);
  6737. }
  6738. let _bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id
  6739. const _m1$2 = new Matrix4();
  6740. const _obj = new Object3D();
  6741. const _offset = new Vector3();
  6742. const _box$2 = new Box3();
  6743. const _boxMorphTargets = new Box3();
  6744. const _vector$4 = new Vector3();
  6745. function BufferGeometry() {
  6746. Object.defineProperty(this, 'id', {
  6747. value: _bufferGeometryId += 2
  6748. });
  6749. this.uuid = MathUtils.generateUUID();
  6750. this.name = '';
  6751. this.type = 'BufferGeometry';
  6752. this.index = null;
  6753. this.attributes = {};
  6754. this.morphAttributes = {};
  6755. this.morphTargetsRelative = false;
  6756. this.groups = [];
  6757. this.boundingBox = null;
  6758. this.boundingSphere = null;
  6759. this.drawRange = {
  6760. start: 0,
  6761. count: Infinity
  6762. };
  6763. this.userData = {};
  6764. }
  6765. BufferGeometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  6766. constructor: BufferGeometry,
  6767. isBufferGeometry: true,
  6768. getIndex: function () {
  6769. return this.index;
  6770. },
  6771. setIndex: function (index) {
  6772. if (Array.isArray(index)) {
  6773. this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  6774. } else {
  6775. this.index = index;
  6776. }
  6777. return this;
  6778. },
  6779. getAttribute: function (name) {
  6780. return this.attributes[name];
  6781. },
  6782. setAttribute: function (name, attribute) {
  6783. this.attributes[name] = attribute;
  6784. return this;
  6785. },
  6786. deleteAttribute: function (name) {
  6787. delete this.attributes[name];
  6788. return this;
  6789. },
  6790. hasAttribute: function (name) {
  6791. return this.attributes[name] !== undefined;
  6792. },
  6793. addGroup: function (start, count, materialIndex = 0) {
  6794. this.groups.push({
  6795. start: start,
  6796. count: count,
  6797. materialIndex: materialIndex
  6798. });
  6799. },
  6800. clearGroups: function () {
  6801. this.groups = [];
  6802. },
  6803. setDrawRange: function (start, count) {
  6804. this.drawRange.start = start;
  6805. this.drawRange.count = count;
  6806. },
  6807. applyMatrix4: function (matrix) {
  6808. const position = this.attributes.position;
  6809. if (position !== undefined) {
  6810. position.applyMatrix4(matrix);
  6811. position.needsUpdate = true;
  6812. }
  6813. const normal = this.attributes.normal;
  6814. if (normal !== undefined) {
  6815. const normalMatrix = new Matrix3().getNormalMatrix(matrix);
  6816. normal.applyNormalMatrix(normalMatrix);
  6817. normal.needsUpdate = true;
  6818. }
  6819. const tangent = this.attributes.tangent;
  6820. if (tangent !== undefined) {
  6821. tangent.transformDirection(matrix);
  6822. tangent.needsUpdate = true;
  6823. }
  6824. if (this.boundingBox !== null) {
  6825. this.computeBoundingBox();
  6826. }
  6827. if (this.boundingSphere !== null) {
  6828. this.computeBoundingSphere();
  6829. }
  6830. return this;
  6831. },
  6832. rotateX: function (angle) {
  6833. // rotate geometry around world x-axis
  6834. _m1$2.makeRotationX(angle);
  6835. this.applyMatrix4(_m1$2);
  6836. return this;
  6837. },
  6838. rotateY: function (angle) {
  6839. // rotate geometry around world y-axis
  6840. _m1$2.makeRotationY(angle);
  6841. this.applyMatrix4(_m1$2);
  6842. return this;
  6843. },
  6844. rotateZ: function (angle) {
  6845. // rotate geometry around world z-axis
  6846. _m1$2.makeRotationZ(angle);
  6847. this.applyMatrix4(_m1$2);
  6848. return this;
  6849. },
  6850. translate: function (x, y, z) {
  6851. // translate geometry
  6852. _m1$2.makeTranslation(x, y, z);
  6853. this.applyMatrix4(_m1$2);
  6854. return this;
  6855. },
  6856. scale: function (x, y, z) {
  6857. // scale geometry
  6858. _m1$2.makeScale(x, y, z);
  6859. this.applyMatrix4(_m1$2);
  6860. return this;
  6861. },
  6862. lookAt: function (vector) {
  6863. _obj.lookAt(vector);
  6864. _obj.updateMatrix();
  6865. this.applyMatrix4(_obj.matrix);
  6866. return this;
  6867. },
  6868. center: function () {
  6869. this.computeBoundingBox();
  6870. this.boundingBox.getCenter(_offset).negate();
  6871. this.translate(_offset.x, _offset.y, _offset.z);
  6872. return this;
  6873. },
  6874. setFromObject: function (object) {
  6875. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  6876. const geometry = object.geometry;
  6877. if (object.isPoints || object.isLine) {
  6878. const positions = new Float32BufferAttribute(geometry.vertices.length * 3, 3);
  6879. const colors = new Float32BufferAttribute(geometry.colors.length * 3, 3);
  6880. this.setAttribute('position', positions.copyVector3sArray(geometry.vertices));
  6881. this.setAttribute('color', colors.copyColorsArray(geometry.colors));
  6882. if (geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length) {
  6883. const lineDistances = new Float32BufferAttribute(geometry.lineDistances.length, 1);
  6884. this.setAttribute('lineDistance', lineDistances.copyArray(geometry.lineDistances));
  6885. }
  6886. if (geometry.boundingSphere !== null) {
  6887. this.boundingSphere = geometry.boundingSphere.clone();
  6888. }
  6889. if (geometry.boundingBox !== null) {
  6890. this.boundingBox = geometry.boundingBox.clone();
  6891. }
  6892. } else if (object.isMesh) {
  6893. if (geometry && geometry.isGeometry) {
  6894. this.fromGeometry(geometry);
  6895. }
  6896. }
  6897. return this;
  6898. },
  6899. setFromPoints: function (points) {
  6900. const position = [];
  6901. for (let i = 0, l = points.length; i < l; i++) {
  6902. const point = points[i];
  6903. position.push(point.x, point.y, point.z || 0);
  6904. }
  6905. this.setAttribute('position', new Float32BufferAttribute(position, 3));
  6906. return this;
  6907. },
  6908. updateFromObject: function (object) {
  6909. let geometry = object.geometry;
  6910. if (object.isMesh) {
  6911. let direct = geometry.__directGeometry;
  6912. if (geometry.elementsNeedUpdate === true) {
  6913. direct = undefined;
  6914. geometry.elementsNeedUpdate = false;
  6915. }
  6916. if (direct === undefined) {
  6917. return this.fromGeometry(geometry);
  6918. }
  6919. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6920. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6921. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6922. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6923. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6924. geometry.verticesNeedUpdate = false;
  6925. geometry.normalsNeedUpdate = false;
  6926. geometry.colorsNeedUpdate = false;
  6927. geometry.uvsNeedUpdate = false;
  6928. geometry.groupsNeedUpdate = false;
  6929. geometry = direct;
  6930. }
  6931. if (geometry.verticesNeedUpdate === true) {
  6932. const attribute = this.attributes.position;
  6933. if (attribute !== undefined) {
  6934. attribute.copyVector3sArray(geometry.vertices);
  6935. attribute.needsUpdate = true;
  6936. }
  6937. geometry.verticesNeedUpdate = false;
  6938. }
  6939. if (geometry.normalsNeedUpdate === true) {
  6940. const attribute = this.attributes.normal;
  6941. if (attribute !== undefined) {
  6942. attribute.copyVector3sArray(geometry.normals);
  6943. attribute.needsUpdate = true;
  6944. }
  6945. geometry.normalsNeedUpdate = false;
  6946. }
  6947. if (geometry.colorsNeedUpdate === true) {
  6948. const attribute = this.attributes.color;
  6949. if (attribute !== undefined) {
  6950. attribute.copyColorsArray(geometry.colors);
  6951. attribute.needsUpdate = true;
  6952. }
  6953. geometry.colorsNeedUpdate = false;
  6954. }
  6955. if (geometry.uvsNeedUpdate) {
  6956. const attribute = this.attributes.uv;
  6957. if (attribute !== undefined) {
  6958. attribute.copyVector2sArray(geometry.uvs);
  6959. attribute.needsUpdate = true;
  6960. }
  6961. geometry.uvsNeedUpdate = false;
  6962. }
  6963. if (geometry.lineDistancesNeedUpdate) {
  6964. const attribute = this.attributes.lineDistance;
  6965. if (attribute !== undefined) {
  6966. attribute.copyArray(geometry.lineDistances);
  6967. attribute.needsUpdate = true;
  6968. }
  6969. geometry.lineDistancesNeedUpdate = false;
  6970. }
  6971. if (geometry.groupsNeedUpdate) {
  6972. geometry.computeGroups(object.geometry);
  6973. this.groups = geometry.groups;
  6974. geometry.groupsNeedUpdate = false;
  6975. }
  6976. return this;
  6977. },
  6978. fromGeometry: function (geometry) {
  6979. geometry.__directGeometry = new DirectGeometry().fromGeometry(geometry);
  6980. return this.fromDirectGeometry(geometry.__directGeometry);
  6981. },
  6982. fromDirectGeometry: function (geometry) {
  6983. const positions = new Float32Array(geometry.vertices.length * 3);
  6984. this.setAttribute('position', new BufferAttribute(positions, 3).copyVector3sArray(geometry.vertices));
  6985. if (geometry.normals.length > 0) {
  6986. const normals = new Float32Array(geometry.normals.length * 3);
  6987. this.setAttribute('normal', new BufferAttribute(normals, 3).copyVector3sArray(geometry.normals));
  6988. }
  6989. if (geometry.colors.length > 0) {
  6990. const colors = new Float32Array(geometry.colors.length * 3);
  6991. this.setAttribute('color', new BufferAttribute(colors, 3).copyColorsArray(geometry.colors));
  6992. }
  6993. if (geometry.uvs.length > 0) {
  6994. const uvs = new Float32Array(geometry.uvs.length * 2);
  6995. this.setAttribute('uv', new BufferAttribute(uvs, 2).copyVector2sArray(geometry.uvs));
  6996. }
  6997. if (geometry.uvs2.length > 0) {
  6998. const uvs2 = new Float32Array(geometry.uvs2.length * 2);
  6999. this.setAttribute('uv2', new BufferAttribute(uvs2, 2).copyVector2sArray(geometry.uvs2));
  7000. } // groups
  7001. this.groups = geometry.groups; // morphs
  7002. for (const name in geometry.morphTargets) {
  7003. const array = [];
  7004. const morphTargets = geometry.morphTargets[name];
  7005. for (let i = 0, l = morphTargets.length; i < l; i++) {
  7006. const morphTarget = morphTargets[i];
  7007. const attribute = new Float32BufferAttribute(morphTarget.data.length * 3, 3);
  7008. attribute.name = morphTarget.name;
  7009. array.push(attribute.copyVector3sArray(morphTarget.data));
  7010. }
  7011. this.morphAttributes[name] = array;
  7012. } // skinning
  7013. if (geometry.skinIndices.length > 0) {
  7014. const skinIndices = new Float32BufferAttribute(geometry.skinIndices.length * 4, 4);
  7015. this.setAttribute('skinIndex', skinIndices.copyVector4sArray(geometry.skinIndices));
  7016. }
  7017. if (geometry.skinWeights.length > 0) {
  7018. const skinWeights = new Float32BufferAttribute(geometry.skinWeights.length * 4, 4);
  7019. this.setAttribute('skinWeight', skinWeights.copyVector4sArray(geometry.skinWeights));
  7020. } //
  7021. if (geometry.boundingSphere !== null) {
  7022. this.boundingSphere = geometry.boundingSphere.clone();
  7023. }
  7024. if (geometry.boundingBox !== null) {
  7025. this.boundingBox = geometry.boundingBox.clone();
  7026. }
  7027. return this;
  7028. },
  7029. computeBoundingBox: function () {
  7030. if (this.boundingBox === null) {
  7031. this.boundingBox = new Box3();
  7032. }
  7033. const position = this.attributes.position;
  7034. const morphAttributesPosition = this.morphAttributes.position;
  7035. if (position && position.isGLBufferAttribute) {
  7036. console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this);
  7037. this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(+Infinity, +Infinity, +Infinity));
  7038. return;
  7039. }
  7040. if (position !== undefined) {
  7041. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  7042. if (morphAttributesPosition) {
  7043. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7044. const morphAttribute = morphAttributesPosition[i];
  7045. _box$2.setFromBufferAttribute(morphAttribute);
  7046. if (this.morphTargetsRelative) {
  7047. _vector$4.addVectors(this.boundingBox.min, _box$2.min);
  7048. this.boundingBox.expandByPoint(_vector$4);
  7049. _vector$4.addVectors(this.boundingBox.max, _box$2.max);
  7050. this.boundingBox.expandByPoint(_vector$4);
  7051. } else {
  7052. this.boundingBox.expandByPoint(_box$2.min);
  7053. this.boundingBox.expandByPoint(_box$2.max);
  7054. }
  7055. }
  7056. }
  7057. } else {
  7058. this.boundingBox.makeEmpty();
  7059. }
  7060. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  7061. console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  7062. }
  7063. },
  7064. computeBoundingSphere: function () {
  7065. if (this.boundingSphere === null) {
  7066. this.boundingSphere = new Sphere();
  7067. }
  7068. const position = this.attributes.position;
  7069. const morphAttributesPosition = this.morphAttributes.position;
  7070. if (position && position.isGLBufferAttribute) {
  7071. console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this);
  7072. this.boundingSphere.set(new Vector3(), Infinity);
  7073. return;
  7074. }
  7075. if (position) {
  7076. // first, find the center of the bounding sphere
  7077. const center = this.boundingSphere.center;
  7078. _box$2.setFromBufferAttribute(position); // process morph attributes if present
  7079. if (morphAttributesPosition) {
  7080. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7081. const morphAttribute = morphAttributesPosition[i];
  7082. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  7083. if (this.morphTargetsRelative) {
  7084. _vector$4.addVectors(_box$2.min, _boxMorphTargets.min);
  7085. _box$2.expandByPoint(_vector$4);
  7086. _vector$4.addVectors(_box$2.max, _boxMorphTargets.max);
  7087. _box$2.expandByPoint(_vector$4);
  7088. } else {
  7089. _box$2.expandByPoint(_boxMorphTargets.min);
  7090. _box$2.expandByPoint(_boxMorphTargets.max);
  7091. }
  7092. }
  7093. }
  7094. _box$2.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  7095. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  7096. let maxRadiusSq = 0;
  7097. for (let i = 0, il = position.count; i < il; i++) {
  7098. _vector$4.fromBufferAttribute(position, i);
  7099. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
  7100. } // process morph attributes if present
  7101. if (morphAttributesPosition) {
  7102. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7103. const morphAttribute = morphAttributesPosition[i];
  7104. const morphTargetsRelative = this.morphTargetsRelative;
  7105. for (let j = 0, jl = morphAttribute.count; j < jl; j++) {
  7106. _vector$4.fromBufferAttribute(morphAttribute, j);
  7107. if (morphTargetsRelative) {
  7108. _offset.fromBufferAttribute(position, j);
  7109. _vector$4.add(_offset);
  7110. }
  7111. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
  7112. }
  7113. }
  7114. }
  7115. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  7116. if (isNaN(this.boundingSphere.radius)) {
  7117. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  7118. }
  7119. }
  7120. },
  7121. computeFaceNormals: function () {// backwards compatibility
  7122. },
  7123. computeVertexNormals: function () {
  7124. const index = this.index;
  7125. const positionAttribute = this.getAttribute('position');
  7126. if (positionAttribute !== undefined) {
  7127. let normalAttribute = this.getAttribute('normal');
  7128. if (normalAttribute === undefined) {
  7129. normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3);
  7130. this.setAttribute('normal', normalAttribute);
  7131. } else {
  7132. // reset existing normals to zero
  7133. for (let i = 0, il = normalAttribute.count; i < il; i++) {
  7134. normalAttribute.setXYZ(i, 0, 0, 0);
  7135. }
  7136. }
  7137. const pA = new Vector3(),
  7138. pB = new Vector3(),
  7139. pC = new Vector3();
  7140. const nA = new Vector3(),
  7141. nB = new Vector3(),
  7142. nC = new Vector3();
  7143. const cb = new Vector3(),
  7144. ab = new Vector3(); // indexed elements
  7145. if (index) {
  7146. for (let i = 0, il = index.count; i < il; i += 3) {
  7147. const vA = index.getX(i + 0);
  7148. const vB = index.getX(i + 1);
  7149. const vC = index.getX(i + 2);
  7150. pA.fromBufferAttribute(positionAttribute, vA);
  7151. pB.fromBufferAttribute(positionAttribute, vB);
  7152. pC.fromBufferAttribute(positionAttribute, vC);
  7153. cb.subVectors(pC, pB);
  7154. ab.subVectors(pA, pB);
  7155. cb.cross(ab);
  7156. nA.fromBufferAttribute(normalAttribute, vA);
  7157. nB.fromBufferAttribute(normalAttribute, vB);
  7158. nC.fromBufferAttribute(normalAttribute, vC);
  7159. nA.add(cb);
  7160. nB.add(cb);
  7161. nC.add(cb);
  7162. normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z);
  7163. normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z);
  7164. normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z);
  7165. }
  7166. } else {
  7167. // non-indexed elements (unconnected triangle soup)
  7168. for (let i = 0, il = positionAttribute.count; i < il; i += 3) {
  7169. pA.fromBufferAttribute(positionAttribute, i + 0);
  7170. pB.fromBufferAttribute(positionAttribute, i + 1);
  7171. pC.fromBufferAttribute(positionAttribute, i + 2);
  7172. cb.subVectors(pC, pB);
  7173. ab.subVectors(pA, pB);
  7174. cb.cross(ab);
  7175. normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z);
  7176. normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z);
  7177. normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z);
  7178. }
  7179. }
  7180. this.normalizeNormals();
  7181. normalAttribute.needsUpdate = true;
  7182. }
  7183. },
  7184. merge: function (geometry, offset) {
  7185. if (!(geometry && geometry.isBufferGeometry)) {
  7186. console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
  7187. return;
  7188. }
  7189. if (offset === undefined) {
  7190. offset = 0;
  7191. console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
  7192. }
  7193. const attributes = this.attributes;
  7194. for (const key in attributes) {
  7195. if (geometry.attributes[key] === undefined) continue;
  7196. const attribute1 = attributes[key];
  7197. const attributeArray1 = attribute1.array;
  7198. const attribute2 = geometry.attributes[key];
  7199. const attributeArray2 = attribute2.array;
  7200. const attributeOffset = attribute2.itemSize * offset;
  7201. const length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
  7202. for (let i = 0, j = attributeOffset; i < length; i++, j++) {
  7203. attributeArray1[j] = attributeArray2[i];
  7204. }
  7205. }
  7206. return this;
  7207. },
  7208. normalizeNormals: function () {
  7209. const normals = this.attributes.normal;
  7210. for (let i = 0, il = normals.count; i < il; i++) {
  7211. _vector$4.fromBufferAttribute(normals, i);
  7212. _vector$4.normalize();
  7213. normals.setXYZ(i, _vector$4.x, _vector$4.y, _vector$4.z);
  7214. }
  7215. },
  7216. toNonIndexed: function () {
  7217. function convertBufferAttribute(attribute, indices) {
  7218. const array = attribute.array;
  7219. const itemSize = attribute.itemSize;
  7220. const normalized = attribute.normalized;
  7221. const array2 = new array.constructor(indices.length * itemSize);
  7222. let index = 0,
  7223. index2 = 0;
  7224. for (let i = 0, l = indices.length; i < l; i++) {
  7225. index = indices[i] * itemSize;
  7226. for (let j = 0; j < itemSize; j++) {
  7227. array2[index2++] = array[index++];
  7228. }
  7229. }
  7230. return new BufferAttribute(array2, itemSize, normalized);
  7231. } //
  7232. if (this.index === null) {
  7233. console.warn('THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.');
  7234. return this;
  7235. }
  7236. const geometry2 = new BufferGeometry();
  7237. const indices = this.index.array;
  7238. const attributes = this.attributes; // attributes
  7239. for (const name in attributes) {
  7240. const attribute = attributes[name];
  7241. const newAttribute = convertBufferAttribute(attribute, indices);
  7242. geometry2.setAttribute(name, newAttribute);
  7243. } // morph attributes
  7244. const morphAttributes = this.morphAttributes;
  7245. for (const name in morphAttributes) {
  7246. const morphArray = [];
  7247. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  7248. for (let i = 0, il = morphAttribute.length; i < il; i++) {
  7249. const attribute = morphAttribute[i];
  7250. const newAttribute = convertBufferAttribute(attribute, indices);
  7251. morphArray.push(newAttribute);
  7252. }
  7253. geometry2.morphAttributes[name] = morphArray;
  7254. }
  7255. geometry2.morphTargetsRelative = this.morphTargetsRelative; // groups
  7256. const groups = this.groups;
  7257. for (let i = 0, l = groups.length; i < l; i++) {
  7258. const group = groups[i];
  7259. geometry2.addGroup(group.start, group.count, group.materialIndex);
  7260. }
  7261. return geometry2;
  7262. },
  7263. toJSON: function () {
  7264. const data = {
  7265. metadata: {
  7266. version: 4.5,
  7267. type: 'BufferGeometry',
  7268. generator: 'BufferGeometry.toJSON'
  7269. }
  7270. }; // standard BufferGeometry serialization
  7271. data.uuid = this.uuid;
  7272. data.type = this.type;
  7273. if (this.name !== '') data.name = this.name;
  7274. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  7275. if (this.parameters !== undefined) {
  7276. const parameters = this.parameters;
  7277. for (const key in parameters) {
  7278. if (parameters[key] !== undefined) data[key] = parameters[key];
  7279. }
  7280. return data;
  7281. }
  7282. data.data = {
  7283. attributes: {}
  7284. };
  7285. const index = this.index;
  7286. if (index !== null) {
  7287. data.data.index = {
  7288. type: index.array.constructor.name,
  7289. array: Array.prototype.slice.call(index.array)
  7290. };
  7291. }
  7292. const attributes = this.attributes;
  7293. for (const key in attributes) {
  7294. const attribute = attributes[key];
  7295. const attributeData = attribute.toJSON(data.data);
  7296. if (attribute.name !== '') attributeData.name = attribute.name;
  7297. data.data.attributes[key] = attributeData;
  7298. }
  7299. const morphAttributes = {};
  7300. let hasMorphAttributes = false;
  7301. for (const key in this.morphAttributes) {
  7302. const attributeArray = this.morphAttributes[key];
  7303. const array = [];
  7304. for (let i = 0, il = attributeArray.length; i < il; i++) {
  7305. const attribute = attributeArray[i];
  7306. const attributeData = attribute.toJSON(data.data);
  7307. if (attribute.name !== '') attributeData.name = attribute.name;
  7308. array.push(attributeData);
  7309. }
  7310. if (array.length > 0) {
  7311. morphAttributes[key] = array;
  7312. hasMorphAttributes = true;
  7313. }
  7314. }
  7315. if (hasMorphAttributes) {
  7316. data.data.morphAttributes = morphAttributes;
  7317. data.data.morphTargetsRelative = this.morphTargetsRelative;
  7318. }
  7319. const groups = this.groups;
  7320. if (groups.length > 0) {
  7321. data.data.groups = JSON.parse(JSON.stringify(groups));
  7322. }
  7323. const boundingSphere = this.boundingSphere;
  7324. if (boundingSphere !== null) {
  7325. data.data.boundingSphere = {
  7326. center: boundingSphere.center.toArray(),
  7327. radius: boundingSphere.radius
  7328. };
  7329. }
  7330. return data;
  7331. },
  7332. clone: function () {
  7333. /*
  7334. // Handle primitives
  7335. const parameters = this.parameters;
  7336. if ( parameters !== undefined ) {
  7337. const values = [];
  7338. for ( const key in parameters ) {
  7339. values.push( parameters[ key ] );
  7340. }
  7341. const geometry = Object.create( this.constructor.prototype );
  7342. this.constructor.apply( geometry, values );
  7343. return geometry;
  7344. }
  7345. return new this.constructor().copy( this );
  7346. */
  7347. return new BufferGeometry().copy(this);
  7348. },
  7349. copy: function (source) {
  7350. // reset
  7351. this.index = null;
  7352. this.attributes = {};
  7353. this.morphAttributes = {};
  7354. this.groups = [];
  7355. this.boundingBox = null;
  7356. this.boundingSphere = null; // used for storing cloned, shared data
  7357. const data = {}; // name
  7358. this.name = source.name; // index
  7359. const index = source.index;
  7360. if (index !== null) {
  7361. this.setIndex(index.clone(data));
  7362. } // attributes
  7363. const attributes = source.attributes;
  7364. for (const name in attributes) {
  7365. const attribute = attributes[name];
  7366. this.setAttribute(name, attribute.clone(data));
  7367. } // morph attributes
  7368. const morphAttributes = source.morphAttributes;
  7369. for (const name in morphAttributes) {
  7370. const array = [];
  7371. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  7372. for (let i = 0, l = morphAttribute.length; i < l; i++) {
  7373. array.push(morphAttribute[i].clone(data));
  7374. }
  7375. this.morphAttributes[name] = array;
  7376. }
  7377. this.morphTargetsRelative = source.morphTargetsRelative; // groups
  7378. const groups = source.groups;
  7379. for (let i = 0, l = groups.length; i < l; i++) {
  7380. const group = groups[i];
  7381. this.addGroup(group.start, group.count, group.materialIndex);
  7382. } // bounding box
  7383. const boundingBox = source.boundingBox;
  7384. if (boundingBox !== null) {
  7385. this.boundingBox = boundingBox.clone();
  7386. } // bounding sphere
  7387. const boundingSphere = source.boundingSphere;
  7388. if (boundingSphere !== null) {
  7389. this.boundingSphere = boundingSphere.clone();
  7390. } // draw range
  7391. this.drawRange.start = source.drawRange.start;
  7392. this.drawRange.count = source.drawRange.count; // user data
  7393. this.userData = source.userData;
  7394. return this;
  7395. },
  7396. dispose: function () {
  7397. this.dispatchEvent({
  7398. type: 'dispose'
  7399. });
  7400. }
  7401. });
  7402. const _inverseMatrix = new Matrix4();
  7403. const _ray = new Ray();
  7404. const _sphere = new Sphere();
  7405. const _vA = new Vector3();
  7406. const _vB = new Vector3();
  7407. const _vC = new Vector3();
  7408. const _tempA = new Vector3();
  7409. const _tempB = new Vector3();
  7410. const _tempC = new Vector3();
  7411. const _morphA = new Vector3();
  7412. const _morphB = new Vector3();
  7413. const _morphC = new Vector3();
  7414. const _uvA = new Vector2();
  7415. const _uvB = new Vector2();
  7416. const _uvC = new Vector2();
  7417. const _intersectionPoint = new Vector3();
  7418. const _intersectionPointWorld = new Vector3();
  7419. function Mesh(geometry, material) {
  7420. Object3D.call(this);
  7421. this.type = 'Mesh';
  7422. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  7423. this.material = material !== undefined ? material : new MeshBasicMaterial();
  7424. this.updateMorphTargets();
  7425. }
  7426. Mesh.prototype = Object.assign(Object.create(Object3D.prototype), {
  7427. constructor: Mesh,
  7428. isMesh: true,
  7429. copy: function (source) {
  7430. Object3D.prototype.copy.call(this, source);
  7431. if (source.morphTargetInfluences !== undefined) {
  7432. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  7433. }
  7434. if (source.morphTargetDictionary !== undefined) {
  7435. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  7436. }
  7437. this.material = source.material;
  7438. this.geometry = source.geometry;
  7439. return this;
  7440. },
  7441. updateMorphTargets: function () {
  7442. const geometry = this.geometry;
  7443. if (geometry.isBufferGeometry) {
  7444. const morphAttributes = geometry.morphAttributes;
  7445. const keys = Object.keys(morphAttributes);
  7446. if (keys.length > 0) {
  7447. const morphAttribute = morphAttributes[keys[0]];
  7448. if (morphAttribute !== undefined) {
  7449. this.morphTargetInfluences = [];
  7450. this.morphTargetDictionary = {};
  7451. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  7452. const name = morphAttribute[m].name || String(m);
  7453. this.morphTargetInfluences.push(0);
  7454. this.morphTargetDictionary[name] = m;
  7455. }
  7456. }
  7457. }
  7458. } else {
  7459. const morphTargets = geometry.morphTargets;
  7460. if (morphTargets !== undefined && morphTargets.length > 0) {
  7461. console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  7462. }
  7463. }
  7464. },
  7465. raycast: function (raycaster, intersects) {
  7466. const geometry = this.geometry;
  7467. const material = this.material;
  7468. const matrixWorld = this.matrixWorld;
  7469. if (material === undefined) return; // Checking boundingSphere distance to ray
  7470. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  7471. _sphere.copy(geometry.boundingSphere);
  7472. _sphere.applyMatrix4(matrixWorld);
  7473. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  7474. _inverseMatrix.copy(matrixWorld).invert();
  7475. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix); // Check boundingBox before continuing
  7476. if (geometry.boundingBox !== null) {
  7477. if (_ray.intersectsBox(geometry.boundingBox) === false) return;
  7478. }
  7479. let intersection;
  7480. if (geometry.isBufferGeometry) {
  7481. const index = geometry.index;
  7482. const position = geometry.attributes.position;
  7483. const morphPosition = geometry.morphAttributes.position;
  7484. const morphTargetsRelative = geometry.morphTargetsRelative;
  7485. const uv = geometry.attributes.uv;
  7486. const uv2 = geometry.attributes.uv2;
  7487. const groups = geometry.groups;
  7488. const drawRange = geometry.drawRange;
  7489. if (index !== null) {
  7490. // indexed buffer geometry
  7491. if (Array.isArray(material)) {
  7492. for (let i = 0, il = groups.length; i < il; i++) {
  7493. const group = groups[i];
  7494. const groupMaterial = material[group.materialIndex];
  7495. const start = Math.max(group.start, drawRange.start);
  7496. const end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  7497. for (let j = start, jl = end; j < jl; j += 3) {
  7498. const a = index.getX(j);
  7499. const b = index.getX(j + 1);
  7500. const c = index.getX(j + 2);
  7501. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  7502. if (intersection) {
  7503. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  7504. intersection.face.materialIndex = group.materialIndex;
  7505. intersects.push(intersection);
  7506. }
  7507. }
  7508. }
  7509. } else {
  7510. const start = Math.max(0, drawRange.start);
  7511. const end = Math.min(index.count, drawRange.start + drawRange.count);
  7512. for (let i = start, il = end; i < il; i += 3) {
  7513. const a = index.getX(i);
  7514. const b = index.getX(i + 1);
  7515. const c = index.getX(i + 2);
  7516. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  7517. if (intersection) {
  7518. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  7519. intersects.push(intersection);
  7520. }
  7521. }
  7522. }
  7523. } else if (position !== undefined) {
  7524. // non-indexed buffer geometry
  7525. if (Array.isArray(material)) {
  7526. for (let i = 0, il = groups.length; i < il; i++) {
  7527. const group = groups[i];
  7528. const groupMaterial = material[group.materialIndex];
  7529. const start = Math.max(group.start, drawRange.start);
  7530. const end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  7531. for (let j = start, jl = end; j < jl; j += 3) {
  7532. const a = j;
  7533. const b = j + 1;
  7534. const c = j + 2;
  7535. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  7536. if (intersection) {
  7537. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  7538. intersection.face.materialIndex = group.materialIndex;
  7539. intersects.push(intersection);
  7540. }
  7541. }
  7542. }
  7543. } else {
  7544. const start = Math.max(0, drawRange.start);
  7545. const end = Math.min(position.count, drawRange.start + drawRange.count);
  7546. for (let i = start, il = end; i < il; i += 3) {
  7547. const a = i;
  7548. const b = i + 1;
  7549. const c = i + 2;
  7550. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  7551. if (intersection) {
  7552. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  7553. intersects.push(intersection);
  7554. }
  7555. }
  7556. }
  7557. }
  7558. } else if (geometry.isGeometry) {
  7559. const isMultiMaterial = Array.isArray(material);
  7560. const vertices = geometry.vertices;
  7561. const faces = geometry.faces;
  7562. let uvs;
  7563. const faceVertexUvs = geometry.faceVertexUvs[0];
  7564. if (faceVertexUvs.length > 0) uvs = faceVertexUvs;
  7565. for (let f = 0, fl = faces.length; f < fl; f++) {
  7566. const face = faces[f];
  7567. const faceMaterial = isMultiMaterial ? material[face.materialIndex] : material;
  7568. if (faceMaterial === undefined) continue;
  7569. const fvA = vertices[face.a];
  7570. const fvB = vertices[face.b];
  7571. const fvC = vertices[face.c];
  7572. intersection = checkIntersection(this, faceMaterial, raycaster, _ray, fvA, fvB, fvC, _intersectionPoint);
  7573. if (intersection) {
  7574. if (uvs && uvs[f]) {
  7575. const uvs_f = uvs[f];
  7576. _uvA.copy(uvs_f[0]);
  7577. _uvB.copy(uvs_f[1]);
  7578. _uvC.copy(uvs_f[2]);
  7579. intersection.uv = Triangle.getUV(_intersectionPoint, fvA, fvB, fvC, _uvA, _uvB, _uvC, new Vector2());
  7580. }
  7581. intersection.face = face;
  7582. intersection.faceIndex = f;
  7583. intersects.push(intersection);
  7584. }
  7585. }
  7586. }
  7587. }
  7588. });
  7589. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  7590. let intersect;
  7591. if (material.side === BackSide) {
  7592. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  7593. } else {
  7594. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  7595. }
  7596. if (intersect === null) return null;
  7597. _intersectionPointWorld.copy(point);
  7598. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  7599. const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  7600. if (distance < raycaster.near || distance > raycaster.far) return null;
  7601. return {
  7602. distance: distance,
  7603. point: _intersectionPointWorld.clone(),
  7604. object: object
  7605. };
  7606. }
  7607. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) {
  7608. _vA.fromBufferAttribute(position, a);
  7609. _vB.fromBufferAttribute(position, b);
  7610. _vC.fromBufferAttribute(position, c);
  7611. const morphInfluences = object.morphTargetInfluences;
  7612. if (material.morphTargets && morphPosition && morphInfluences) {
  7613. _morphA.set(0, 0, 0);
  7614. _morphB.set(0, 0, 0);
  7615. _morphC.set(0, 0, 0);
  7616. for (let i = 0, il = morphPosition.length; i < il; i++) {
  7617. const influence = morphInfluences[i];
  7618. const morphAttribute = morphPosition[i];
  7619. if (influence === 0) continue;
  7620. _tempA.fromBufferAttribute(morphAttribute, a);
  7621. _tempB.fromBufferAttribute(morphAttribute, b);
  7622. _tempC.fromBufferAttribute(morphAttribute, c);
  7623. if (morphTargetsRelative) {
  7624. _morphA.addScaledVector(_tempA, influence);
  7625. _morphB.addScaledVector(_tempB, influence);
  7626. _morphC.addScaledVector(_tempC, influence);
  7627. } else {
  7628. _morphA.addScaledVector(_tempA.sub(_vA), influence);
  7629. _morphB.addScaledVector(_tempB.sub(_vB), influence);
  7630. _morphC.addScaledVector(_tempC.sub(_vC), influence);
  7631. }
  7632. }
  7633. _vA.add(_morphA);
  7634. _vB.add(_morphB);
  7635. _vC.add(_morphC);
  7636. }
  7637. if (object.isSkinnedMesh) {
  7638. object.boneTransform(a, _vA);
  7639. object.boneTransform(b, _vB);
  7640. object.boneTransform(c, _vC);
  7641. }
  7642. const intersection = checkIntersection(object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint);
  7643. if (intersection) {
  7644. if (uv) {
  7645. _uvA.fromBufferAttribute(uv, a);
  7646. _uvB.fromBufferAttribute(uv, b);
  7647. _uvC.fromBufferAttribute(uv, c);
  7648. intersection.uv = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
  7649. }
  7650. if (uv2) {
  7651. _uvA.fromBufferAttribute(uv2, a);
  7652. _uvB.fromBufferAttribute(uv2, b);
  7653. _uvC.fromBufferAttribute(uv2, c);
  7654. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
  7655. }
  7656. const face = new Face3(a, b, c);
  7657. Triangle.getNormal(_vA, _vB, _vC, face.normal);
  7658. intersection.face = face;
  7659. }
  7660. return intersection;
  7661. }
  7662. class BoxBufferGeometry extends BufferGeometry {
  7663. constructor(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) {
  7664. super();
  7665. this.type = 'BoxBufferGeometry';
  7666. this.parameters = {
  7667. width: width,
  7668. height: height,
  7669. depth: depth,
  7670. widthSegments: widthSegments,
  7671. heightSegments: heightSegments,
  7672. depthSegments: depthSegments
  7673. };
  7674. const scope = this; // segments
  7675. widthSegments = Math.floor(widthSegments);
  7676. heightSegments = Math.floor(heightSegments);
  7677. depthSegments = Math.floor(depthSegments); // buffers
  7678. const indices = [];
  7679. const vertices = [];
  7680. const normals = [];
  7681. const uvs = []; // helper variables
  7682. let numberOfVertices = 0;
  7683. let groupStart = 0; // build each side of the box geometry
  7684. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  7685. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  7686. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  7687. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  7688. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  7689. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  7690. // build geometry
  7691. this.setIndex(indices);
  7692. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  7693. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  7694. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  7695. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  7696. const segmentWidth = width / gridX;
  7697. const segmentHeight = height / gridY;
  7698. const widthHalf = width / 2;
  7699. const heightHalf = height / 2;
  7700. const depthHalf = depth / 2;
  7701. const gridX1 = gridX + 1;
  7702. const gridY1 = gridY + 1;
  7703. let vertexCounter = 0;
  7704. let groupCount = 0;
  7705. const vector = new Vector3(); // generate vertices, normals and uvs
  7706. for (let iy = 0; iy < gridY1; iy++) {
  7707. const y = iy * segmentHeight - heightHalf;
  7708. for (let ix = 0; ix < gridX1; ix++) {
  7709. const x = ix * segmentWidth - widthHalf; // set values to correct vector component
  7710. vector[u] = x * udir;
  7711. vector[v] = y * vdir;
  7712. vector[w] = depthHalf; // now apply vector to vertex buffer
  7713. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  7714. vector[u] = 0;
  7715. vector[v] = 0;
  7716. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  7717. normals.push(vector.x, vector.y, vector.z); // uvs
  7718. uvs.push(ix / gridX);
  7719. uvs.push(1 - iy / gridY); // counters
  7720. vertexCounter += 1;
  7721. }
  7722. } // indices
  7723. // 1. you need three indices to draw a single face
  7724. // 2. a single segment consists of two faces
  7725. // 3. so we need to generate six (2*3) indices per segment
  7726. for (let iy = 0; iy < gridY; iy++) {
  7727. for (let ix = 0; ix < gridX; ix++) {
  7728. const a = numberOfVertices + ix + gridX1 * iy;
  7729. const b = numberOfVertices + ix + gridX1 * (iy + 1);
  7730. const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  7731. const d = numberOfVertices + (ix + 1) + gridX1 * iy; // faces
  7732. indices.push(a, b, d);
  7733. indices.push(b, c, d); // increase counter
  7734. groupCount += 6;
  7735. }
  7736. } // add a group to the geometry. this will ensure multi material support
  7737. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  7738. groupStart += groupCount; // update total number of vertices
  7739. numberOfVertices += vertexCounter;
  7740. }
  7741. }
  7742. }
  7743. /**
  7744. * Uniform Utilities
  7745. */
  7746. exports.BoxBufferGeometry = BoxBufferGeometry;
  7747. function cloneUniforms(src) {
  7748. const dst = {};
  7749. for (const u in src) {
  7750. dst[u] = {};
  7751. for (const p in src[u]) {
  7752. const property = src[u][p];
  7753. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture)) {
  7754. dst[u][p] = property.clone();
  7755. } else if (Array.isArray(property)) {
  7756. dst[u][p] = property.slice();
  7757. } else {
  7758. dst[u][p] = property;
  7759. }
  7760. }
  7761. }
  7762. return dst;
  7763. }
  7764. function mergeUniforms(uniforms) {
  7765. const merged = {};
  7766. for (let u = 0; u < uniforms.length; u++) {
  7767. const tmp = cloneUniforms(uniforms[u]);
  7768. for (const p in tmp) {
  7769. merged[p] = tmp[p];
  7770. }
  7771. }
  7772. return merged;
  7773. } // Legacy
  7774. const UniformsUtils = {
  7775. clone: cloneUniforms,
  7776. merge: mergeUniforms
  7777. };
  7778. exports.UniformsUtils = UniformsUtils;
  7779. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7780. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7781. /**
  7782. * parameters = {
  7783. * defines: { "label" : "value" },
  7784. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  7785. *
  7786. * fragmentShader: <string>,
  7787. * vertexShader: <string>,
  7788. *
  7789. * wireframe: <boolean>,
  7790. * wireframeLinewidth: <float>,
  7791. *
  7792. * lights: <bool>,
  7793. *
  7794. * skinning: <bool>,
  7795. * morphTargets: <bool>,
  7796. * morphNormals: <bool>
  7797. * }
  7798. */
  7799. function ShaderMaterial(parameters) {
  7800. Material.call(this);
  7801. this.type = 'ShaderMaterial';
  7802. this.defines = {};
  7803. this.uniforms = {};
  7804. this.vertexShader = default_vertex;
  7805. this.fragmentShader = default_fragment;
  7806. this.linewidth = 1;
  7807. this.wireframe = false;
  7808. this.wireframeLinewidth = 1;
  7809. this.fog = false; // set to use scene fog
  7810. this.lights = false; // set to use scene lights
  7811. this.clipping = false; // set to use user-defined clipping planes
  7812. this.skinning = false; // set to use skinning attribute streams
  7813. this.morphTargets = false; // set to use morph targets
  7814. this.morphNormals = false; // set to use morph normals
  7815. this.extensions = {
  7816. derivatives: false,
  7817. // set to use derivatives
  7818. fragDepth: false,
  7819. // set to use fragment depth values
  7820. drawBuffers: false,
  7821. // set to use draw buffers
  7822. shaderTextureLOD: false // set to use shader texture LOD
  7823. }; // When rendered geometry doesn't include these attributes but the material does,
  7824. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7825. this.defaultAttributeValues = {
  7826. 'color': [1, 1, 1],
  7827. 'uv': [0, 0],
  7828. 'uv2': [0, 0]
  7829. };
  7830. this.index0AttributeName = undefined;
  7831. this.uniformsNeedUpdate = false;
  7832. this.glslVersion = null;
  7833. if (parameters !== undefined) {
  7834. if (parameters.attributes !== undefined) {
  7835. console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
  7836. }
  7837. this.setValues(parameters);
  7838. }
  7839. }
  7840. ShaderMaterial.prototype = Object.create(Material.prototype);
  7841. ShaderMaterial.prototype.constructor = ShaderMaterial;
  7842. ShaderMaterial.prototype.isShaderMaterial = true;
  7843. ShaderMaterial.prototype.copy = function (source) {
  7844. Material.prototype.copy.call(this, source);
  7845. this.fragmentShader = source.fragmentShader;
  7846. this.vertexShader = source.vertexShader;
  7847. this.uniforms = cloneUniforms(source.uniforms);
  7848. this.defines = Object.assign({}, source.defines);
  7849. this.wireframe = source.wireframe;
  7850. this.wireframeLinewidth = source.wireframeLinewidth;
  7851. this.lights = source.lights;
  7852. this.clipping = source.clipping;
  7853. this.skinning = source.skinning;
  7854. this.morphTargets = source.morphTargets;
  7855. this.morphNormals = source.morphNormals;
  7856. this.extensions = Object.assign({}, source.extensions);
  7857. this.glslVersion = source.glslVersion;
  7858. return this;
  7859. };
  7860. ShaderMaterial.prototype.toJSON = function (meta) {
  7861. const data = Material.prototype.toJSON.call(this, meta);
  7862. data.glslVersion = this.glslVersion;
  7863. data.uniforms = {};
  7864. for (const name in this.uniforms) {
  7865. const uniform = this.uniforms[name];
  7866. const value = uniform.value;
  7867. if (value && value.isTexture) {
  7868. data.uniforms[name] = {
  7869. type: 't',
  7870. value: value.toJSON(meta).uuid
  7871. };
  7872. } else if (value && value.isColor) {
  7873. data.uniforms[name] = {
  7874. type: 'c',
  7875. value: value.getHex()
  7876. };
  7877. } else if (value && value.isVector2) {
  7878. data.uniforms[name] = {
  7879. type: 'v2',
  7880. value: value.toArray()
  7881. };
  7882. } else if (value && value.isVector3) {
  7883. data.uniforms[name] = {
  7884. type: 'v3',
  7885. value: value.toArray()
  7886. };
  7887. } else if (value && value.isVector4) {
  7888. data.uniforms[name] = {
  7889. type: 'v4',
  7890. value: value.toArray()
  7891. };
  7892. } else if (value && value.isMatrix3) {
  7893. data.uniforms[name] = {
  7894. type: 'm3',
  7895. value: value.toArray()
  7896. };
  7897. } else if (value && value.isMatrix4) {
  7898. data.uniforms[name] = {
  7899. type: 'm4',
  7900. value: value.toArray()
  7901. };
  7902. } else {
  7903. data.uniforms[name] = {
  7904. value: value
  7905. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7906. }
  7907. }
  7908. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  7909. data.vertexShader = this.vertexShader;
  7910. data.fragmentShader = this.fragmentShader;
  7911. const extensions = {};
  7912. for (const key in this.extensions) {
  7913. if (this.extensions[key] === true) extensions[key] = true;
  7914. }
  7915. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  7916. return data;
  7917. };
  7918. function Camera() {
  7919. Object3D.call(this);
  7920. this.type = 'Camera';
  7921. this.matrixWorldInverse = new Matrix4();
  7922. this.projectionMatrix = new Matrix4();
  7923. this.projectionMatrixInverse = new Matrix4();
  7924. }
  7925. Camera.prototype = Object.assign(Object.create(Object3D.prototype), {
  7926. constructor: Camera,
  7927. isCamera: true,
  7928. copy: function (source, recursive) {
  7929. Object3D.prototype.copy.call(this, source, recursive);
  7930. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  7931. this.projectionMatrix.copy(source.projectionMatrix);
  7932. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  7933. return this;
  7934. },
  7935. getWorldDirection: function (target) {
  7936. if (target === undefined) {
  7937. console.warn('THREE.Camera: .getWorldDirection() target is now required');
  7938. target = new Vector3();
  7939. }
  7940. this.updateWorldMatrix(true, false);
  7941. const e = this.matrixWorld.elements;
  7942. return target.set(-e[8], -e[9], -e[10]).normalize();
  7943. },
  7944. updateMatrixWorld: function (force) {
  7945. Object3D.prototype.updateMatrixWorld.call(this, force);
  7946. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7947. },
  7948. updateWorldMatrix: function (updateParents, updateChildren) {
  7949. Object3D.prototype.updateWorldMatrix.call(this, updateParents, updateChildren);
  7950. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7951. },
  7952. clone: function () {
  7953. return new this.constructor().copy(this);
  7954. }
  7955. });
  7956. function PerspectiveCamera(fov = 50, aspect = 1, near = 0.1, far = 2000) {
  7957. Camera.call(this);
  7958. this.type = 'PerspectiveCamera';
  7959. this.fov = fov;
  7960. this.zoom = 1;
  7961. this.near = near;
  7962. this.far = far;
  7963. this.focus = 10;
  7964. this.aspect = aspect;
  7965. this.view = null;
  7966. this.filmGauge = 35; // width of the film (default in millimeters)
  7967. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7968. this.updateProjectionMatrix();
  7969. }
  7970. PerspectiveCamera.prototype = Object.assign(Object.create(Camera.prototype), {
  7971. constructor: PerspectiveCamera,
  7972. isPerspectiveCamera: true,
  7973. copy: function (source, recursive) {
  7974. Camera.prototype.copy.call(this, source, recursive);
  7975. this.fov = source.fov;
  7976. this.zoom = source.zoom;
  7977. this.near = source.near;
  7978. this.far = source.far;
  7979. this.focus = source.focus;
  7980. this.aspect = source.aspect;
  7981. this.view = source.view === null ? null : Object.assign({}, source.view);
  7982. this.filmGauge = source.filmGauge;
  7983. this.filmOffset = source.filmOffset;
  7984. return this;
  7985. },
  7986. /**
  7987. * Sets the FOV by focal length in respect to the current .filmGauge.
  7988. *
  7989. * The default film gauge is 35, so that the focal length can be specified for
  7990. * a 35mm (full frame) camera.
  7991. *
  7992. * Values for focal length and film gauge must have the same unit.
  7993. */
  7994. setFocalLength: function (focalLength) {
  7995. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  7996. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7997. this.fov = MathUtils.RAD2DEG * 2 * Math.atan(vExtentSlope);
  7998. this.updateProjectionMatrix();
  7999. },
  8000. /**
  8001. * Calculates the focal length from the current .fov and .filmGauge.
  8002. */
  8003. getFocalLength: function () {
  8004. const vExtentSlope = Math.tan(MathUtils.DEG2RAD * 0.5 * this.fov);
  8005. return 0.5 * this.getFilmHeight() / vExtentSlope;
  8006. },
  8007. getEffectiveFOV: function () {
  8008. return MathUtils.RAD2DEG * 2 * Math.atan(Math.tan(MathUtils.DEG2RAD * 0.5 * this.fov) / this.zoom);
  8009. },
  8010. getFilmWidth: function () {
  8011. // film not completely covered in portrait format (aspect < 1)
  8012. return this.filmGauge * Math.min(this.aspect, 1);
  8013. },
  8014. getFilmHeight: function () {
  8015. // film not completely covered in landscape format (aspect > 1)
  8016. return this.filmGauge / Math.max(this.aspect, 1);
  8017. },
  8018. /**
  8019. * Sets an offset in a larger frustum. This is useful for multi-window or
  8020. * multi-monitor/multi-machine setups.
  8021. *
  8022. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  8023. * the monitors are in grid like this
  8024. *
  8025. * +---+---+---+
  8026. * | A | B | C |
  8027. * +---+---+---+
  8028. * | D | E | F |
  8029. * +---+---+---+
  8030. *
  8031. * then for each monitor you would call it like this
  8032. *
  8033. * const w = 1920;
  8034. * const h = 1080;
  8035. * const fullWidth = w * 3;
  8036. * const fullHeight = h * 2;
  8037. *
  8038. * --A--
  8039. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  8040. * --B--
  8041. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  8042. * --C--
  8043. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  8044. * --D--
  8045. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  8046. * --E--
  8047. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  8048. * --F--
  8049. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  8050. *
  8051. * Note there is no reason monitors have to be the same size or in a grid.
  8052. */
  8053. setViewOffset: function (fullWidth, fullHeight, x, y, width, height) {
  8054. this.aspect = fullWidth / fullHeight;
  8055. if (this.view === null) {
  8056. this.view = {
  8057. enabled: true,
  8058. fullWidth: 1,
  8059. fullHeight: 1,
  8060. offsetX: 0,
  8061. offsetY: 0,
  8062. width: 1,
  8063. height: 1
  8064. };
  8065. }
  8066. this.view.enabled = true;
  8067. this.view.fullWidth = fullWidth;
  8068. this.view.fullHeight = fullHeight;
  8069. this.view.offsetX = x;
  8070. this.view.offsetY = y;
  8071. this.view.width = width;
  8072. this.view.height = height;
  8073. this.updateProjectionMatrix();
  8074. },
  8075. clearViewOffset: function () {
  8076. if (this.view !== null) {
  8077. this.view.enabled = false;
  8078. }
  8079. this.updateProjectionMatrix();
  8080. },
  8081. updateProjectionMatrix: function () {
  8082. const near = this.near;
  8083. let top = near * Math.tan(MathUtils.DEG2RAD * 0.5 * this.fov) / this.zoom;
  8084. let height = 2 * top;
  8085. let width = this.aspect * height;
  8086. let left = -0.5 * width;
  8087. const view = this.view;
  8088. if (this.view !== null && this.view.enabled) {
  8089. const fullWidth = view.fullWidth,
  8090. fullHeight = view.fullHeight;
  8091. left += view.offsetX * width / fullWidth;
  8092. top -= view.offsetY * height / fullHeight;
  8093. width *= view.width / fullWidth;
  8094. height *= view.height / fullHeight;
  8095. }
  8096. const skew = this.filmOffset;
  8097. if (skew !== 0) left += near * skew / this.getFilmWidth();
  8098. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  8099. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  8100. },
  8101. toJSON: function (meta) {
  8102. const data = Object3D.prototype.toJSON.call(this, meta);
  8103. data.object.fov = this.fov;
  8104. data.object.zoom = this.zoom;
  8105. data.object.near = this.near;
  8106. data.object.far = this.far;
  8107. data.object.focus = this.focus;
  8108. data.object.aspect = this.aspect;
  8109. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  8110. data.object.filmGauge = this.filmGauge;
  8111. data.object.filmOffset = this.filmOffset;
  8112. return data;
  8113. }
  8114. });
  8115. const fov = 90,
  8116. aspect = 1;
  8117. function CubeCamera(near, far, renderTarget) {
  8118. Object3D.call(this);
  8119. this.type = 'CubeCamera';
  8120. if (renderTarget.isWebGLCubeRenderTarget !== true) {
  8121. console.error('THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.');
  8122. return;
  8123. }
  8124. this.renderTarget = renderTarget;
  8125. const cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  8126. cameraPX.layers = this.layers;
  8127. cameraPX.up.set(0, -1, 0);
  8128. cameraPX.lookAt(new Vector3(1, 0, 0));
  8129. this.add(cameraPX);
  8130. const cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  8131. cameraNX.layers = this.layers;
  8132. cameraNX.up.set(0, -1, 0);
  8133. cameraNX.lookAt(new Vector3(-1, 0, 0));
  8134. this.add(cameraNX);
  8135. const cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  8136. cameraPY.layers = this.layers;
  8137. cameraPY.up.set(0, 0, 1);
  8138. cameraPY.lookAt(new Vector3(0, 1, 0));
  8139. this.add(cameraPY);
  8140. const cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  8141. cameraNY.layers = this.layers;
  8142. cameraNY.up.set(0, 0, -1);
  8143. cameraNY.lookAt(new Vector3(0, -1, 0));
  8144. this.add(cameraNY);
  8145. const cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  8146. cameraPZ.layers = this.layers;
  8147. cameraPZ.up.set(0, -1, 0);
  8148. cameraPZ.lookAt(new Vector3(0, 0, 1));
  8149. this.add(cameraPZ);
  8150. const cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  8151. cameraNZ.layers = this.layers;
  8152. cameraNZ.up.set(0, -1, 0);
  8153. cameraNZ.lookAt(new Vector3(0, 0, -1));
  8154. this.add(cameraNZ);
  8155. this.update = function (renderer, scene) {
  8156. if (this.parent === null) this.updateMatrixWorld();
  8157. const currentXrEnabled = renderer.xr.enabled;
  8158. const currentRenderTarget = renderer.getRenderTarget();
  8159. renderer.xr.enabled = false;
  8160. const generateMipmaps = renderTarget.texture.generateMipmaps;
  8161. renderTarget.texture.generateMipmaps = false;
  8162. renderer.setRenderTarget(renderTarget, 0);
  8163. renderer.render(scene, cameraPX);
  8164. renderer.setRenderTarget(renderTarget, 1);
  8165. renderer.render(scene, cameraNX);
  8166. renderer.setRenderTarget(renderTarget, 2);
  8167. renderer.render(scene, cameraPY);
  8168. renderer.setRenderTarget(renderTarget, 3);
  8169. renderer.render(scene, cameraNY);
  8170. renderer.setRenderTarget(renderTarget, 4);
  8171. renderer.render(scene, cameraPZ);
  8172. renderTarget.texture.generateMipmaps = generateMipmaps;
  8173. renderer.setRenderTarget(renderTarget, 5);
  8174. renderer.render(scene, cameraNZ);
  8175. renderer.setRenderTarget(currentRenderTarget);
  8176. renderer.xr.enabled = currentXrEnabled;
  8177. };
  8178. }
  8179. CubeCamera.prototype = Object.create(Object3D.prototype);
  8180. CubeCamera.prototype.constructor = CubeCamera;
  8181. function CubeTexture(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  8182. images = images !== undefined ? images : [];
  8183. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  8184. format = format !== undefined ? format : RGBFormat;
  8185. Texture.call(this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  8186. this.flipY = false; // Why CubeTexture._needsFlipEnvMap is necessary:
  8187. //
  8188. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  8189. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  8190. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  8191. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  8192. // and the flag _needsFlipEnvMap controls this conversion. The flip is not required (and thus _needsFlipEnvMap is set to false)
  8193. // when using WebGLCubeRenderTarget.texture as a cube texture.
  8194. this._needsFlipEnvMap = true;
  8195. }
  8196. CubeTexture.prototype = Object.create(Texture.prototype);
  8197. CubeTexture.prototype.constructor = CubeTexture;
  8198. CubeTexture.prototype.isCubeTexture = true;
  8199. Object.defineProperty(CubeTexture.prototype, 'images', {
  8200. get: function () {
  8201. return this.image;
  8202. },
  8203. set: function (value) {
  8204. this.image = value;
  8205. }
  8206. });
  8207. function WebGLCubeRenderTarget(size, options, dummy) {
  8208. if (Number.isInteger(options)) {
  8209. console.warn('THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )');
  8210. options = dummy;
  8211. }
  8212. WebGLRenderTarget.call(this, size, size, options);
  8213. options = options || {};
  8214. this.texture = new CubeTexture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  8215. this.texture._needsFlipEnvMap = false;
  8216. }
  8217. WebGLCubeRenderTarget.prototype = Object.create(WebGLRenderTarget.prototype);
  8218. WebGLCubeRenderTarget.prototype.constructor = WebGLCubeRenderTarget;
  8219. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  8220. WebGLCubeRenderTarget.prototype.fromEquirectangularTexture = function (renderer, texture) {
  8221. this.texture.type = texture.type;
  8222. this.texture.format = RGBAFormat; // see #18859
  8223. this.texture.encoding = texture.encoding;
  8224. this.texture.generateMipmaps = texture.generateMipmaps;
  8225. this.texture.minFilter = texture.minFilter;
  8226. this.texture.magFilter = texture.magFilter;
  8227. const shader = {
  8228. uniforms: {
  8229. tEquirect: {
  8230. value: null
  8231. }
  8232. },
  8233. vertexShader:
  8234. /* glsl */
  8235. `
  8236. varying vec3 vWorldDirection;
  8237. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  8238. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  8239. }
  8240. void main() {
  8241. vWorldDirection = transformDirection( position, modelMatrix );
  8242. #include <begin_vertex>
  8243. #include <project_vertex>
  8244. }
  8245. `,
  8246. fragmentShader:
  8247. /* glsl */
  8248. `
  8249. uniform sampler2D tEquirect;
  8250. varying vec3 vWorldDirection;
  8251. #include <common>
  8252. void main() {
  8253. vec3 direction = normalize( vWorldDirection );
  8254. vec2 sampleUV = equirectUv( direction );
  8255. gl_FragColor = texture2D( tEquirect, sampleUV );
  8256. }
  8257. `
  8258. };
  8259. const geometry = new BoxBufferGeometry(5, 5, 5);
  8260. const material = new ShaderMaterial({
  8261. name: 'CubemapFromEquirect',
  8262. uniforms: cloneUniforms(shader.uniforms),
  8263. vertexShader: shader.vertexShader,
  8264. fragmentShader: shader.fragmentShader,
  8265. side: BackSide,
  8266. blending: NoBlending
  8267. });
  8268. material.uniforms.tEquirect.value = texture;
  8269. const mesh = new Mesh(geometry, material);
  8270. const currentMinFilter = texture.minFilter; // Avoid blurred poles
  8271. if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter;
  8272. const camera = new CubeCamera(1, 10, this);
  8273. camera.update(renderer, mesh);
  8274. texture.minFilter = currentMinFilter;
  8275. mesh.geometry.dispose();
  8276. mesh.material.dispose();
  8277. return this;
  8278. };
  8279. WebGLCubeRenderTarget.prototype.clear = function (renderer, color, depth, stencil) {
  8280. const currentRenderTarget = renderer.getRenderTarget();
  8281. for (let i = 0; i < 6; i++) {
  8282. renderer.setRenderTarget(this, i);
  8283. renderer.clear(color, depth, stencil);
  8284. }
  8285. renderer.setRenderTarget(currentRenderTarget);
  8286. };
  8287. function DataTexture(data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  8288. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  8289. this.image = {
  8290. data: data || null,
  8291. width: width || 1,
  8292. height: height || 1
  8293. };
  8294. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  8295. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  8296. this.generateMipmaps = false;
  8297. this.flipY = false;
  8298. this.unpackAlignment = 1;
  8299. this.needsUpdate = true;
  8300. }
  8301. DataTexture.prototype = Object.create(Texture.prototype);
  8302. DataTexture.prototype.constructor = DataTexture;
  8303. DataTexture.prototype.isDataTexture = true;
  8304. const _sphere$1 =
  8305. /*@__PURE__*/
  8306. new Sphere();
  8307. const _vector$5 =
  8308. /*@__PURE__*/
  8309. new Vector3();
  8310. class Frustum {
  8311. constructor(p0, p1, p2, p3, p4, p5) {
  8312. 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()];
  8313. }
  8314. set(p0, p1, p2, p3, p4, p5) {
  8315. const planes = this.planes;
  8316. planes[0].copy(p0);
  8317. planes[1].copy(p1);
  8318. planes[2].copy(p2);
  8319. planes[3].copy(p3);
  8320. planes[4].copy(p4);
  8321. planes[5].copy(p5);
  8322. return this;
  8323. }
  8324. clone() {
  8325. return new this.constructor().copy(this);
  8326. }
  8327. copy(frustum) {
  8328. const planes = this.planes;
  8329. for (let i = 0; i < 6; i++) {
  8330. planes[i].copy(frustum.planes[i]);
  8331. }
  8332. return this;
  8333. }
  8334. setFromProjectionMatrix(m) {
  8335. const planes = this.planes;
  8336. const me = m.elements;
  8337. const me0 = me[0],
  8338. me1 = me[1],
  8339. me2 = me[2],
  8340. me3 = me[3];
  8341. const me4 = me[4],
  8342. me5 = me[5],
  8343. me6 = me[6],
  8344. me7 = me[7];
  8345. const me8 = me[8],
  8346. me9 = me[9],
  8347. me10 = me[10],
  8348. me11 = me[11];
  8349. const me12 = me[12],
  8350. me13 = me[13],
  8351. me14 = me[14],
  8352. me15 = me[15];
  8353. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  8354. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  8355. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  8356. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  8357. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  8358. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  8359. return this;
  8360. }
  8361. intersectsObject(object) {
  8362. const geometry = object.geometry;
  8363. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  8364. _sphere$1.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  8365. return this.intersectsSphere(_sphere$1);
  8366. }
  8367. intersectsSprite(sprite) {
  8368. _sphere$1.center.set(0, 0, 0);
  8369. _sphere$1.radius = 0.7071067811865476;
  8370. _sphere$1.applyMatrix4(sprite.matrixWorld);
  8371. return this.intersectsSphere(_sphere$1);
  8372. }
  8373. intersectsSphere(sphere) {
  8374. const planes = this.planes;
  8375. const center = sphere.center;
  8376. const negRadius = -sphere.radius;
  8377. for (let i = 0; i < 6; i++) {
  8378. const distance = planes[i].distanceToPoint(center);
  8379. if (distance < negRadius) {
  8380. return false;
  8381. }
  8382. }
  8383. return true;
  8384. }
  8385. intersectsBox(box) {
  8386. const planes = this.planes;
  8387. for (let i = 0; i < 6; i++) {
  8388. const plane = planes[i]; // corner at max distance
  8389. _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  8390. _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  8391. _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  8392. if (plane.distanceToPoint(_vector$5) < 0) {
  8393. return false;
  8394. }
  8395. }
  8396. return true;
  8397. }
  8398. containsPoint(point) {
  8399. const planes = this.planes;
  8400. for (let i = 0; i < 6; i++) {
  8401. if (planes[i].distanceToPoint(point) < 0) {
  8402. return false;
  8403. }
  8404. }
  8405. return true;
  8406. }
  8407. }
  8408. exports.Frustum = Frustum;
  8409. function WebGLAnimation() {
  8410. let context = null;
  8411. let isAnimating = false;
  8412. let animationLoop = null;
  8413. let requestId = null;
  8414. function onAnimationFrame(time, frame) {
  8415. animationLoop(time, frame);
  8416. requestId = context.requestAnimationFrame(onAnimationFrame);
  8417. }
  8418. return {
  8419. start: function () {
  8420. if (isAnimating === true) return;
  8421. if (animationLoop === null) return;
  8422. requestId = context.requestAnimationFrame(onAnimationFrame);
  8423. isAnimating = true;
  8424. },
  8425. stop: function () {
  8426. context.cancelAnimationFrame(requestId);
  8427. isAnimating = false;
  8428. },
  8429. setAnimationLoop: function (callback) {
  8430. animationLoop = callback;
  8431. },
  8432. setContext: function (value) {
  8433. context = value;
  8434. }
  8435. };
  8436. }
  8437. function WebGLAttributes(gl, capabilities) {
  8438. const isWebGL2 = capabilities.isWebGL2;
  8439. const buffers = new WeakMap();
  8440. function createBuffer(attribute, bufferType) {
  8441. const array = attribute.array;
  8442. const usage = attribute.usage;
  8443. const buffer = gl.createBuffer();
  8444. gl.bindBuffer(bufferType, buffer);
  8445. gl.bufferData(bufferType, array, usage);
  8446. attribute.onUploadCallback();
  8447. let type = 5126;
  8448. if (array instanceof Float32Array) {
  8449. type = 5126;
  8450. } else if (array instanceof Float64Array) {
  8451. console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
  8452. } else if (array instanceof Uint16Array) {
  8453. if (attribute.isFloat16BufferAttribute) {
  8454. if (isWebGL2) {
  8455. type = 5131;
  8456. } else {
  8457. console.warn('THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.');
  8458. }
  8459. } else {
  8460. type = 5123;
  8461. }
  8462. } else if (array instanceof Int16Array) {
  8463. type = 5122;
  8464. } else if (array instanceof Uint32Array) {
  8465. type = 5125;
  8466. } else if (array instanceof Int32Array) {
  8467. type = 5124;
  8468. } else if (array instanceof Int8Array) {
  8469. type = 5120;
  8470. } else if (array instanceof Uint8Array) {
  8471. type = 5121;
  8472. }
  8473. return {
  8474. buffer: buffer,
  8475. type: type,
  8476. bytesPerElement: array.BYTES_PER_ELEMENT,
  8477. version: attribute.version
  8478. };
  8479. }
  8480. function updateBuffer(buffer, attribute, bufferType) {
  8481. const array = attribute.array;
  8482. const updateRange = attribute.updateRange;
  8483. gl.bindBuffer(bufferType, buffer);
  8484. if (updateRange.count === -1) {
  8485. // Not using update ranges
  8486. gl.bufferSubData(bufferType, 0, array);
  8487. } else {
  8488. if (isWebGL2) {
  8489. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count);
  8490. } else {
  8491. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  8492. }
  8493. updateRange.count = -1; // reset range
  8494. }
  8495. } //
  8496. function get(attribute) {
  8497. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  8498. return buffers.get(attribute);
  8499. }
  8500. function remove(attribute) {
  8501. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  8502. const data = buffers.get(attribute);
  8503. if (data) {
  8504. gl.deleteBuffer(data.buffer);
  8505. buffers.delete(attribute);
  8506. }
  8507. }
  8508. function update(attribute, bufferType) {
  8509. if (attribute.isGLBufferAttribute) {
  8510. const cached = buffers.get(attribute);
  8511. if (!cached || cached.version < attribute.version) {
  8512. buffers.set(attribute, {
  8513. buffer: attribute.buffer,
  8514. type: attribute.type,
  8515. bytesPerElement: attribute.elementSize,
  8516. version: attribute.version
  8517. });
  8518. }
  8519. return;
  8520. }
  8521. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  8522. const data = buffers.get(attribute);
  8523. if (data === undefined) {
  8524. buffers.set(attribute, createBuffer(attribute, bufferType));
  8525. } else if (data.version < attribute.version) {
  8526. updateBuffer(data.buffer, attribute, bufferType);
  8527. data.version = attribute.version;
  8528. }
  8529. }
  8530. return {
  8531. get: get,
  8532. remove: remove,
  8533. update: update
  8534. };
  8535. }
  8536. class PlaneBufferGeometry extends BufferGeometry {
  8537. constructor(width = 1, height = 1, widthSegments = 1, heightSegments = 1) {
  8538. super();
  8539. this.type = 'PlaneBufferGeometry';
  8540. this.parameters = {
  8541. width: width,
  8542. height: height,
  8543. widthSegments: widthSegments,
  8544. heightSegments: heightSegments
  8545. };
  8546. const width_half = width / 2;
  8547. const height_half = height / 2;
  8548. const gridX = Math.floor(widthSegments);
  8549. const gridY = Math.floor(heightSegments);
  8550. const gridX1 = gridX + 1;
  8551. const gridY1 = gridY + 1;
  8552. const segment_width = width / gridX;
  8553. const segment_height = height / gridY; //
  8554. const indices = [];
  8555. const vertices = [];
  8556. const normals = [];
  8557. const uvs = [];
  8558. for (let iy = 0; iy < gridY1; iy++) {
  8559. const y = iy * segment_height - height_half;
  8560. for (let ix = 0; ix < gridX1; ix++) {
  8561. const x = ix * segment_width - width_half;
  8562. vertices.push(x, -y, 0);
  8563. normals.push(0, 0, 1);
  8564. uvs.push(ix / gridX);
  8565. uvs.push(1 - iy / gridY);
  8566. }
  8567. }
  8568. for (let iy = 0; iy < gridY; iy++) {
  8569. for (let ix = 0; ix < gridX; ix++) {
  8570. const a = ix + gridX1 * iy;
  8571. const b = ix + gridX1 * (iy + 1);
  8572. const c = ix + 1 + gridX1 * (iy + 1);
  8573. const d = ix + 1 + gridX1 * iy;
  8574. indices.push(a, b, d);
  8575. indices.push(b, c, d);
  8576. }
  8577. }
  8578. this.setIndex(indices);
  8579. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  8580. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  8581. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  8582. }
  8583. }
  8584. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  8585. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  8586. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  8587. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  8588. 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";
  8589. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  8590. var begin_vertex = "vec3 transformed = vec3( position );";
  8591. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  8592. 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";
  8593. 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";
  8594. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif";
  8595. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  8596. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  8597. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  8598. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  8599. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  8600. var color_pars_vertex = "#if defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif";
  8601. var color_vertex = "#if defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor.xyz *= color.xyz;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif";
  8602. var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\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\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}";
  8603. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_maxMipLevel 8.0\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_maxTileSize 256.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\tfloat texelSize = 1.0 / ( 3.0 * cubeUV_maxTileSize );\n\t\tvec2 uv = getUV( direction, face ) * ( faceSize - 1.0 );\n\t\tvec2 f = fract( uv );\n\t\tuv += 0.5 - f;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tif ( mipInt < cubeUV_maxMipLevel ) {\n\t\t\tuv.y += 2.0 * cubeUV_maxTileSize;\n\t\t}\n\t\tuv.y += filterInt * 2.0 * cubeUV_minTileSize;\n\t\tuv.x += 3.0 * max( 0.0, cubeUV_maxTileSize - 2.0 * faceSize );\n\t\tuv *= texelSize;\n\t\tvec3 tl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x += texelSize;\n\t\tvec3 tr = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.y += texelSize;\n\t\tvec3 br = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x -= texelSize;\n\t\tvec3 bl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tvec3 tm = mix( tl, tr, f.x );\n\t\tvec3 bm = mix( bl, br, f.x );\n\t\treturn mix( tm, bm, f.y );\n\t}\n\t#define r0 1.0\n\t#define v0 0.339\n\t#define m0 - 2.0\n\t#define r1 0.8\n\t#define v1 0.276\n\t#define m1 - 1.0\n\t#define r4 0.4\n\t#define v4 0.046\n\t#define m4 2.0\n\t#define r5 0.305\n\t#define v5 0.016\n\t#define m5 3.0\n\t#define r6 0.21\n\t#define v6 0.0038\n\t#define m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= r1 ) {\n\t\t\tmip = ( r0 - roughness ) * ( m1 - m0 ) / ( r0 - r1 ) + m0;\n\t\t} else if ( roughness >= r4 ) {\n\t\t\tmip = ( r1 - roughness ) * ( m4 - m1 ) / ( r1 - r4 ) + m1;\n\t\t} else if ( roughness >= r5 ) {\n\t\t\tmip = ( r4 - roughness ) * ( m5 - m4 ) / ( r4 - r5 ) + m4;\n\t\t} else if ( roughness >= r6 ) {\n\t\t\tmip = ( r5 - roughness ) * ( m6 - m5 ) / ( r5 - r6 ) + m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), m0, cubeUV_maxMipLevel );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif";
  8604. var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";
  8605. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  8606. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  8607. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  8608. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  8609. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  8610. var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * value.a * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = clamp( floor( D ) / 255.0, 0.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = cLogLuvM * value.rgb;\n\tXp_Y_XYZp = max( Xp_Y_XYZp, vec3( 1e-6, 1e-6, 1e-6 ) );\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract( Le );\n\tvResult.z = ( Le - ( floor( vResult.w * 255.0 ) ) / 255.0 ) / 255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2( ( Le - 127.0 ) / 2.0 );\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = cLogLuvInverseM * Xp_Y_XYZp.rgb;\n\treturn vec4( max( vRGB, 0.0 ), 1.0 );\n}";
  8611. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifndef ENVMAP_TYPE_CUBE_UV\n\t\tenvColor = envMapTexelToLinear( envColor );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
  8612. 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";
  8613. 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";
  8614. 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";
  8615. var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif";
  8616. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = - mvPosition.z;\n#endif";
  8617. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  8618. 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";
  8619. 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";
  8620. var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn texture2D( gradientMap, coord ).rgb;\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}";
  8621. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif";
  8622. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  8623. var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\nvIndirectFront += getAmbientLightIrradiance( ambientLightColor );\nvIndirectFront += getLightProbeIrradiance( lightProbe, geometry );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry );\n#endif\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif";
  8624. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in GeometricContext geometry ) {\n\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\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";
  8625. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float roughness, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat sigma = PI * roughness * roughness / ( 1.0 + roughness );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + log2( sigma );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -viewDir, normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( roughness, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif";
  8626. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  8627. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)";
  8628. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  8629. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)";
  8630. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.specularRoughness = max( roughnessFactor, 0.0525 );material.specularRoughness += geometryRoughness;\nmaterial.specularRoughness = min( material.specularRoughness, 1.0 );\n#ifdef REFLECTIVITY\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#endif\n#ifdef CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheen;\n#endif";
  8631. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat specularRoughness;\n\tvec3 specularColor;\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}";
  8632. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
  8633. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.normal, material.specularRoughness, maxMipLevel );\n\t#ifdef CLEARCOAT\n\t\tclearcoatRadiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness, maxMipLevel );\n\t#endif\n#endif";
  8634. 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";
  8635. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  8636. 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";
  8637. 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";
  8638. 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";
  8639. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  8640. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  8641. var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";
  8642. var map_particle_pars_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  8643. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  8644. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  8645. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n#endif";
  8646. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifndef USE_MORPHNORMALS\n\t\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\t\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";
  8647. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t#endif\n#endif";
  8648. var normal_fragment_begin = "#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t\tbitangent = bitangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;";
  8649. var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( -vViewPosition, normal, mapN );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif";
  8650. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tfloat scale = sign( st1.t * st0.s - st0.t * st1.s );\n\t\tvec3 S = normalize( ( q0 * st1.t - q1 * st0.t ) * scale );\n\t\tvec3 T = normalize( ( - q0 * st1.s + q1 * st0.s ) * scale );\n\t\tvec3 N = normalize( surf_norm );\n\t\tmat3 tsn = mat3( S, T, N );\n\t\tmapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif";
  8651. var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  8652. var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN );\n\t#endif\n#endif";
  8653. var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif";
  8654. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ));\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w);\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}";
  8655. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  8656. 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;";
  8657. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  8658. 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";
  8659. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  8660. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  8661. 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\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\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\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\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\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif";
  8662. 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\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\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\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\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\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif";
  8663. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0\n\t\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\tvec4 shadowWorldPosition;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif";
  8664. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}";
  8665. 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";
  8666. 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";
  8667. 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";
  8668. 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";
  8669. 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";
  8670. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  8671. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  8672. var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\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}\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 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }";
  8673. var transmissionmap_fragment = "#ifdef USE_TRANSMISSIONMAP\n\ttotalTransmission *= texture2D( transmissionMap, vUv ).r;\n#endif";
  8674. var transmissionmap_pars_fragment = "#ifdef USE_TRANSMISSIONMAP\n\tuniform sampler2D transmissionMap;\n#endif";
  8675. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  8676. var uv_pars_vertex = "#ifdef USE_UV\n\t#ifdef UVS_VERTEX_ONLY\n\t\tvec2 vUv;\n\t#else\n\t\tvarying vec2 vUv;\n\t#endif\n\tuniform mat3 uvTransform;\n#endif";
  8677. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  8678. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  8679. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\tuniform mat3 uv2Transform;\n#endif";
  8680. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  8681. 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";
  8682. 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}";
  8683. 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}";
  8684. var cube_frag = "#include <envmap_common_pars_fragment>\nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include <envmap_fragment>\n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  8685. 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}";
  8686. var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}";
  8687. var depth_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}";
  8688. 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}";
  8689. 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}";
  8690. var equirect_frag = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  8691. 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}";
  8692. var linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8693. 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 <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  8694. var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\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 <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8695. 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}";
  8696. var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\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}";
  8697. 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}";
  8698. 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 <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8699. var meshmatcap_vert = "#define MATCAP\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#ifndef FLAT_SHADED\n\t\tvNormal = normalize( transformedNormal );\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
  8700. var meshtoon_frag = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <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 <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8701. var meshtoon_vert = "#define TOON\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8702. var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8703. 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}";
  8704. var meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n\t#define TRANSMISSION\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef TRANSMISSION\n\tuniform float transmission;\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 <transmissionmap_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#ifdef TRANSMISSION\n\t\tfloat totalTransmission = transmission;\n\t#endif\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 <transmissionmap_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 TRANSMISSION\n\t\tdiffuseColor.a *= mix( saturate( 1. - totalTransmission + linearToRelativeLuminance( reflectedLight.directSpecular + reflectedLight.indirectSpecular ) ), 1.0, metalness );\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}";
  8705. 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}";
  8706. 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}";
  8707. var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  8708. var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8709. 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}";
  8710. var shadow_frag = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  8711. var shadow_vert = "#include <common>\n#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 <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 <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8712. var sprite_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  8713. 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}";
  8714. const ShaderChunk = {
  8715. alphamap_fragment: alphamap_fragment,
  8716. alphamap_pars_fragment: alphamap_pars_fragment,
  8717. alphatest_fragment: alphatest_fragment,
  8718. aomap_fragment: aomap_fragment,
  8719. aomap_pars_fragment: aomap_pars_fragment,
  8720. begin_vertex: begin_vertex,
  8721. beginnormal_vertex: beginnormal_vertex,
  8722. bsdfs: bsdfs,
  8723. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8724. clipping_planes_fragment: clipping_planes_fragment,
  8725. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8726. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8727. clipping_planes_vertex: clipping_planes_vertex,
  8728. color_fragment: color_fragment,
  8729. color_pars_fragment: color_pars_fragment,
  8730. color_pars_vertex: color_pars_vertex,
  8731. color_vertex: color_vertex,
  8732. common: common,
  8733. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8734. defaultnormal_vertex: defaultnormal_vertex,
  8735. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8736. displacementmap_vertex: displacementmap_vertex,
  8737. emissivemap_fragment: emissivemap_fragment,
  8738. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8739. encodings_fragment: encodings_fragment,
  8740. encodings_pars_fragment: encodings_pars_fragment,
  8741. envmap_fragment: envmap_fragment,
  8742. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8743. envmap_pars_fragment: envmap_pars_fragment,
  8744. envmap_pars_vertex: envmap_pars_vertex,
  8745. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8746. envmap_vertex: envmap_vertex,
  8747. fog_vertex: fog_vertex,
  8748. fog_pars_vertex: fog_pars_vertex,
  8749. fog_fragment: fog_fragment,
  8750. fog_pars_fragment: fog_pars_fragment,
  8751. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8752. lightmap_fragment: lightmap_fragment,
  8753. lightmap_pars_fragment: lightmap_pars_fragment,
  8754. lights_lambert_vertex: lights_lambert_vertex,
  8755. lights_pars_begin: lights_pars_begin,
  8756. lights_toon_fragment: lights_toon_fragment,
  8757. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8758. lights_phong_fragment: lights_phong_fragment,
  8759. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8760. lights_physical_fragment: lights_physical_fragment,
  8761. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8762. lights_fragment_begin: lights_fragment_begin,
  8763. lights_fragment_maps: lights_fragment_maps,
  8764. lights_fragment_end: lights_fragment_end,
  8765. logdepthbuf_fragment: logdepthbuf_fragment,
  8766. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8767. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8768. logdepthbuf_vertex: logdepthbuf_vertex,
  8769. map_fragment: map_fragment,
  8770. map_pars_fragment: map_pars_fragment,
  8771. map_particle_fragment: map_particle_fragment,
  8772. map_particle_pars_fragment: map_particle_pars_fragment,
  8773. metalnessmap_fragment: metalnessmap_fragment,
  8774. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8775. morphnormal_vertex: morphnormal_vertex,
  8776. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8777. morphtarget_vertex: morphtarget_vertex,
  8778. normal_fragment_begin: normal_fragment_begin,
  8779. normal_fragment_maps: normal_fragment_maps,
  8780. normalmap_pars_fragment: normalmap_pars_fragment,
  8781. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8782. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8783. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8784. packing: packing,
  8785. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8786. project_vertex: project_vertex,
  8787. dithering_fragment: dithering_fragment,
  8788. dithering_pars_fragment: dithering_pars_fragment,
  8789. roughnessmap_fragment: roughnessmap_fragment,
  8790. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8791. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8792. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8793. shadowmap_vertex: shadowmap_vertex,
  8794. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8795. skinbase_vertex: skinbase_vertex,
  8796. skinning_pars_vertex: skinning_pars_vertex,
  8797. skinning_vertex: skinning_vertex,
  8798. skinnormal_vertex: skinnormal_vertex,
  8799. specularmap_fragment: specularmap_fragment,
  8800. specularmap_pars_fragment: specularmap_pars_fragment,
  8801. tonemapping_fragment: tonemapping_fragment,
  8802. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8803. transmissionmap_fragment: transmissionmap_fragment,
  8804. transmissionmap_pars_fragment: transmissionmap_pars_fragment,
  8805. uv_pars_fragment: uv_pars_fragment,
  8806. uv_pars_vertex: uv_pars_vertex,
  8807. uv_vertex: uv_vertex,
  8808. uv2_pars_fragment: uv2_pars_fragment,
  8809. uv2_pars_vertex: uv2_pars_vertex,
  8810. uv2_vertex: uv2_vertex,
  8811. worldpos_vertex: worldpos_vertex,
  8812. background_frag: background_frag,
  8813. background_vert: background_vert,
  8814. cube_frag: cube_frag,
  8815. cube_vert: cube_vert,
  8816. depth_frag: depth_frag,
  8817. depth_vert: depth_vert,
  8818. distanceRGBA_frag: distanceRGBA_frag,
  8819. distanceRGBA_vert: distanceRGBA_vert,
  8820. equirect_frag: equirect_frag,
  8821. equirect_vert: equirect_vert,
  8822. linedashed_frag: linedashed_frag,
  8823. linedashed_vert: linedashed_vert,
  8824. meshbasic_frag: meshbasic_frag,
  8825. meshbasic_vert: meshbasic_vert,
  8826. meshlambert_frag: meshlambert_frag,
  8827. meshlambert_vert: meshlambert_vert,
  8828. meshmatcap_frag: meshmatcap_frag,
  8829. meshmatcap_vert: meshmatcap_vert,
  8830. meshtoon_frag: meshtoon_frag,
  8831. meshtoon_vert: meshtoon_vert,
  8832. meshphong_frag: meshphong_frag,
  8833. meshphong_vert: meshphong_vert,
  8834. meshphysical_frag: meshphysical_frag,
  8835. meshphysical_vert: meshphysical_vert,
  8836. normal_frag: normal_frag,
  8837. normal_vert: normal_vert,
  8838. points_frag: points_frag,
  8839. points_vert: points_vert,
  8840. shadow_frag: shadow_frag,
  8841. shadow_vert: shadow_vert,
  8842. sprite_frag: sprite_frag,
  8843. sprite_vert: sprite_vert
  8844. };
  8845. /**
  8846. * Uniforms library for shared webgl shaders
  8847. */
  8848. exports.ShaderChunk = ShaderChunk;
  8849. const UniformsLib = {
  8850. common: {
  8851. diffuse: {
  8852. value: new Color(0xeeeeee)
  8853. },
  8854. opacity: {
  8855. value: 1.0
  8856. },
  8857. map: {
  8858. value: null
  8859. },
  8860. uvTransform: {
  8861. value: new Matrix3()
  8862. },
  8863. uv2Transform: {
  8864. value: new Matrix3()
  8865. },
  8866. alphaMap: {
  8867. value: null
  8868. }
  8869. },
  8870. specularmap: {
  8871. specularMap: {
  8872. value: null
  8873. }
  8874. },
  8875. envmap: {
  8876. envMap: {
  8877. value: null
  8878. },
  8879. flipEnvMap: {
  8880. value: -1
  8881. },
  8882. reflectivity: {
  8883. value: 1.0
  8884. },
  8885. refractionRatio: {
  8886. value: 0.98
  8887. },
  8888. maxMipLevel: {
  8889. value: 0
  8890. }
  8891. },
  8892. aomap: {
  8893. aoMap: {
  8894. value: null
  8895. },
  8896. aoMapIntensity: {
  8897. value: 1
  8898. }
  8899. },
  8900. lightmap: {
  8901. lightMap: {
  8902. value: null
  8903. },
  8904. lightMapIntensity: {
  8905. value: 1
  8906. }
  8907. },
  8908. emissivemap: {
  8909. emissiveMap: {
  8910. value: null
  8911. }
  8912. },
  8913. bumpmap: {
  8914. bumpMap: {
  8915. value: null
  8916. },
  8917. bumpScale: {
  8918. value: 1
  8919. }
  8920. },
  8921. normalmap: {
  8922. normalMap: {
  8923. value: null
  8924. },
  8925. normalScale: {
  8926. value: new Vector2(1, 1)
  8927. }
  8928. },
  8929. displacementmap: {
  8930. displacementMap: {
  8931. value: null
  8932. },
  8933. displacementScale: {
  8934. value: 1
  8935. },
  8936. displacementBias: {
  8937. value: 0
  8938. }
  8939. },
  8940. roughnessmap: {
  8941. roughnessMap: {
  8942. value: null
  8943. }
  8944. },
  8945. metalnessmap: {
  8946. metalnessMap: {
  8947. value: null
  8948. }
  8949. },
  8950. gradientmap: {
  8951. gradientMap: {
  8952. value: null
  8953. }
  8954. },
  8955. fog: {
  8956. fogDensity: {
  8957. value: 0.00025
  8958. },
  8959. fogNear: {
  8960. value: 1
  8961. },
  8962. fogFar: {
  8963. value: 2000
  8964. },
  8965. fogColor: {
  8966. value: new Color(0xffffff)
  8967. }
  8968. },
  8969. lights: {
  8970. ambientLightColor: {
  8971. value: []
  8972. },
  8973. lightProbe: {
  8974. value: []
  8975. },
  8976. directionalLights: {
  8977. value: [],
  8978. properties: {
  8979. direction: {},
  8980. color: {}
  8981. }
  8982. },
  8983. directionalLightShadows: {
  8984. value: [],
  8985. properties: {
  8986. shadowBias: {},
  8987. shadowNormalBias: {},
  8988. shadowRadius: {},
  8989. shadowMapSize: {}
  8990. }
  8991. },
  8992. directionalShadowMap: {
  8993. value: []
  8994. },
  8995. directionalShadowMatrix: {
  8996. value: []
  8997. },
  8998. spotLights: {
  8999. value: [],
  9000. properties: {
  9001. color: {},
  9002. position: {},
  9003. direction: {},
  9004. distance: {},
  9005. coneCos: {},
  9006. penumbraCos: {},
  9007. decay: {}
  9008. }
  9009. },
  9010. spotLightShadows: {
  9011. value: [],
  9012. properties: {
  9013. shadowBias: {},
  9014. shadowNormalBias: {},
  9015. shadowRadius: {},
  9016. shadowMapSize: {}
  9017. }
  9018. },
  9019. spotShadowMap: {
  9020. value: []
  9021. },
  9022. spotShadowMatrix: {
  9023. value: []
  9024. },
  9025. pointLights: {
  9026. value: [],
  9027. properties: {
  9028. color: {},
  9029. position: {},
  9030. decay: {},
  9031. distance: {}
  9032. }
  9033. },
  9034. pointLightShadows: {
  9035. value: [],
  9036. properties: {
  9037. shadowBias: {},
  9038. shadowNormalBias: {},
  9039. shadowRadius: {},
  9040. shadowMapSize: {},
  9041. shadowCameraNear: {},
  9042. shadowCameraFar: {}
  9043. }
  9044. },
  9045. pointShadowMap: {
  9046. value: []
  9047. },
  9048. pointShadowMatrix: {
  9049. value: []
  9050. },
  9051. hemisphereLights: {
  9052. value: [],
  9053. properties: {
  9054. direction: {},
  9055. skyColor: {},
  9056. groundColor: {}
  9057. }
  9058. },
  9059. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  9060. rectAreaLights: {
  9061. value: [],
  9062. properties: {
  9063. color: {},
  9064. position: {},
  9065. width: {},
  9066. height: {}
  9067. }
  9068. },
  9069. ltc_1: {
  9070. value: null
  9071. },
  9072. ltc_2: {
  9073. value: null
  9074. }
  9075. },
  9076. points: {
  9077. diffuse: {
  9078. value: new Color(0xeeeeee)
  9079. },
  9080. opacity: {
  9081. value: 1.0
  9082. },
  9083. size: {
  9084. value: 1.0
  9085. },
  9086. scale: {
  9087. value: 1.0
  9088. },
  9089. map: {
  9090. value: null
  9091. },
  9092. alphaMap: {
  9093. value: null
  9094. },
  9095. uvTransform: {
  9096. value: new Matrix3()
  9097. }
  9098. },
  9099. sprite: {
  9100. diffuse: {
  9101. value: new Color(0xeeeeee)
  9102. },
  9103. opacity: {
  9104. value: 1.0
  9105. },
  9106. center: {
  9107. value: new Vector2(0.5, 0.5)
  9108. },
  9109. rotation: {
  9110. value: 0.0
  9111. },
  9112. map: {
  9113. value: null
  9114. },
  9115. alphaMap: {
  9116. value: null
  9117. },
  9118. uvTransform: {
  9119. value: new Matrix3()
  9120. }
  9121. }
  9122. };
  9123. exports.UniformsLib = UniformsLib;
  9124. const ShaderLib = {
  9125. basic: {
  9126. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  9127. vertexShader: ShaderChunk.meshbasic_vert,
  9128. fragmentShader: ShaderChunk.meshbasic_frag
  9129. },
  9130. lambert: {
  9131. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
  9132. emissive: {
  9133. value: new Color(0x000000)
  9134. }
  9135. }]),
  9136. vertexShader: ShaderChunk.meshlambert_vert,
  9137. fragmentShader: ShaderChunk.meshlambert_frag
  9138. },
  9139. phong: {
  9140. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, {
  9141. emissive: {
  9142. value: new Color(0x000000)
  9143. },
  9144. specular: {
  9145. value: new Color(0x111111)
  9146. },
  9147. shininess: {
  9148. value: 30
  9149. }
  9150. }]),
  9151. vertexShader: ShaderChunk.meshphong_vert,
  9152. fragmentShader: ShaderChunk.meshphong_frag
  9153. },
  9154. standard: {
  9155. 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, {
  9156. emissive: {
  9157. value: new Color(0x000000)
  9158. },
  9159. roughness: {
  9160. value: 1.0
  9161. },
  9162. metalness: {
  9163. value: 0.0
  9164. },
  9165. envMapIntensity: {
  9166. value: 1
  9167. } // temporary
  9168. }]),
  9169. vertexShader: ShaderChunk.meshphysical_vert,
  9170. fragmentShader: ShaderChunk.meshphysical_frag
  9171. },
  9172. toon: {
  9173. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
  9174. emissive: {
  9175. value: new Color(0x000000)
  9176. }
  9177. }]),
  9178. vertexShader: ShaderChunk.meshtoon_vert,
  9179. fragmentShader: ShaderChunk.meshtoon_frag
  9180. },
  9181. matcap: {
  9182. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  9183. matcap: {
  9184. value: null
  9185. }
  9186. }]),
  9187. vertexShader: ShaderChunk.meshmatcap_vert,
  9188. fragmentShader: ShaderChunk.meshmatcap_frag
  9189. },
  9190. points: {
  9191. uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  9192. vertexShader: ShaderChunk.points_vert,
  9193. fragmentShader: ShaderChunk.points_frag
  9194. },
  9195. dashed: {
  9196. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  9197. scale: {
  9198. value: 1
  9199. },
  9200. dashSize: {
  9201. value: 1
  9202. },
  9203. totalSize: {
  9204. value: 2
  9205. }
  9206. }]),
  9207. vertexShader: ShaderChunk.linedashed_vert,
  9208. fragmentShader: ShaderChunk.linedashed_frag
  9209. },
  9210. depth: {
  9211. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  9212. vertexShader: ShaderChunk.depth_vert,
  9213. fragmentShader: ShaderChunk.depth_frag
  9214. },
  9215. normal: {
  9216. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  9217. opacity: {
  9218. value: 1.0
  9219. }
  9220. }]),
  9221. vertexShader: ShaderChunk.normal_vert,
  9222. fragmentShader: ShaderChunk.normal_frag
  9223. },
  9224. sprite: {
  9225. uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  9226. vertexShader: ShaderChunk.sprite_vert,
  9227. fragmentShader: ShaderChunk.sprite_frag
  9228. },
  9229. background: {
  9230. uniforms: {
  9231. uvTransform: {
  9232. value: new Matrix3()
  9233. },
  9234. t2D: {
  9235. value: null
  9236. }
  9237. },
  9238. vertexShader: ShaderChunk.background_vert,
  9239. fragmentShader: ShaderChunk.background_frag
  9240. },
  9241. /* -------------------------------------------------------------------------
  9242. // Cube map shader
  9243. ------------------------------------------------------------------------- */
  9244. cube: {
  9245. uniforms: mergeUniforms([UniformsLib.envmap, {
  9246. opacity: {
  9247. value: 1.0
  9248. }
  9249. }]),
  9250. vertexShader: ShaderChunk.cube_vert,
  9251. fragmentShader: ShaderChunk.cube_frag
  9252. },
  9253. equirect: {
  9254. uniforms: {
  9255. tEquirect: {
  9256. value: null
  9257. }
  9258. },
  9259. vertexShader: ShaderChunk.equirect_vert,
  9260. fragmentShader: ShaderChunk.equirect_frag
  9261. },
  9262. distanceRGBA: {
  9263. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  9264. referencePosition: {
  9265. value: new Vector3()
  9266. },
  9267. nearDistance: {
  9268. value: 1
  9269. },
  9270. farDistance: {
  9271. value: 1000
  9272. }
  9273. }]),
  9274. vertexShader: ShaderChunk.distanceRGBA_vert,
  9275. fragmentShader: ShaderChunk.distanceRGBA_frag
  9276. },
  9277. shadow: {
  9278. uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  9279. color: {
  9280. value: new Color(0x00000)
  9281. },
  9282. opacity: {
  9283. value: 1.0
  9284. }
  9285. }]),
  9286. vertexShader: ShaderChunk.shadow_vert,
  9287. fragmentShader: ShaderChunk.shadow_frag
  9288. }
  9289. };
  9290. exports.ShaderLib = ShaderLib;
  9291. ShaderLib.physical = {
  9292. uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
  9293. clearcoat: {
  9294. value: 0
  9295. },
  9296. clearcoatMap: {
  9297. value: null
  9298. },
  9299. clearcoatRoughness: {
  9300. value: 0
  9301. },
  9302. clearcoatRoughnessMap: {
  9303. value: null
  9304. },
  9305. clearcoatNormalScale: {
  9306. value: new Vector2(1, 1)
  9307. },
  9308. clearcoatNormalMap: {
  9309. value: null
  9310. },
  9311. sheen: {
  9312. value: new Color(0x000000)
  9313. },
  9314. transmission: {
  9315. value: 0
  9316. },
  9317. transmissionMap: {
  9318. value: null
  9319. }
  9320. }]),
  9321. vertexShader: ShaderChunk.meshphysical_vert,
  9322. fragmentShader: ShaderChunk.meshphysical_frag
  9323. };
  9324. function WebGLBackground(renderer, cubemaps, state, objects, premultipliedAlpha) {
  9325. const clearColor = new Color(0x000000);
  9326. let clearAlpha = 0;
  9327. let planeMesh;
  9328. let boxMesh;
  9329. let currentBackground = null;
  9330. let currentBackgroundVersion = 0;
  9331. let currentTonemapping = null;
  9332. function render(renderList, scene, camera, forceClear) {
  9333. let background = scene.isScene === true ? scene.background : null;
  9334. if (background && background.isTexture) {
  9335. background = cubemaps.get(background);
  9336. } // Ignore background in AR
  9337. // TODO: Reconsider this.
  9338. const xr = renderer.xr;
  9339. const session = xr.getSession && xr.getSession();
  9340. if (session && session.environmentBlendMode === 'additive') {
  9341. background = null;
  9342. }
  9343. if (background === null) {
  9344. setClear(clearColor, clearAlpha);
  9345. } else if (background && background.isColor) {
  9346. setClear(background, 1);
  9347. forceClear = true;
  9348. }
  9349. if (renderer.autoClear || forceClear) {
  9350. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  9351. }
  9352. if (background && (background.isCubeTexture || background.isWebGLCubeRenderTarget || background.mapping === CubeUVReflectionMapping)) {
  9353. if (boxMesh === undefined) {
  9354. boxMesh = new Mesh(new BoxBufferGeometry(1, 1, 1), new ShaderMaterial({
  9355. name: 'BackgroundCubeMaterial',
  9356. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  9357. vertexShader: ShaderLib.cube.vertexShader,
  9358. fragmentShader: ShaderLib.cube.fragmentShader,
  9359. side: BackSide,
  9360. depthTest: false,
  9361. depthWrite: false,
  9362. fog: false
  9363. }));
  9364. boxMesh.geometry.deleteAttribute('normal');
  9365. boxMesh.geometry.deleteAttribute('uv');
  9366. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  9367. this.matrixWorld.copyPosition(camera.matrixWorld);
  9368. }; // enable code injection for non-built-in material
  9369. Object.defineProperty(boxMesh.material, 'envMap', {
  9370. get: function () {
  9371. return this.uniforms.envMap.value;
  9372. }
  9373. });
  9374. objects.update(boxMesh);
  9375. }
  9376. if (background.isWebGLCubeRenderTarget) {
  9377. // TODO Deprecate
  9378. background = background.texture;
  9379. }
  9380. boxMesh.material.uniforms.envMap.value = background;
  9381. boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background._needsFlipEnvMap ? -1 : 1;
  9382. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  9383. boxMesh.material.needsUpdate = true;
  9384. currentBackground = background;
  9385. currentBackgroundVersion = background.version;
  9386. currentTonemapping = renderer.toneMapping;
  9387. } // push to the pre-sorted opaque render list
  9388. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  9389. } else if (background && background.isTexture) {
  9390. if (planeMesh === undefined) {
  9391. planeMesh = new Mesh(new PlaneBufferGeometry(2, 2), new ShaderMaterial({
  9392. name: 'BackgroundMaterial',
  9393. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  9394. vertexShader: ShaderLib.background.vertexShader,
  9395. fragmentShader: ShaderLib.background.fragmentShader,
  9396. side: FrontSide,
  9397. depthTest: false,
  9398. depthWrite: false,
  9399. fog: false
  9400. }));
  9401. planeMesh.geometry.deleteAttribute('normal'); // enable code injection for non-built-in material
  9402. Object.defineProperty(planeMesh.material, 'map', {
  9403. get: function () {
  9404. return this.uniforms.t2D.value;
  9405. }
  9406. });
  9407. objects.update(planeMesh);
  9408. }
  9409. planeMesh.material.uniforms.t2D.value = background;
  9410. if (background.matrixAutoUpdate === true) {
  9411. background.updateMatrix();
  9412. }
  9413. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  9414. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  9415. planeMesh.material.needsUpdate = true;
  9416. currentBackground = background;
  9417. currentBackgroundVersion = background.version;
  9418. currentTonemapping = renderer.toneMapping;
  9419. } // push to the pre-sorted opaque render list
  9420. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  9421. }
  9422. }
  9423. function setClear(color, alpha) {
  9424. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  9425. }
  9426. return {
  9427. getClearColor: function () {
  9428. return clearColor;
  9429. },
  9430. setClearColor: function (color, alpha = 1) {
  9431. clearColor.set(color);
  9432. clearAlpha = alpha;
  9433. setClear(clearColor, clearAlpha);
  9434. },
  9435. getClearAlpha: function () {
  9436. return clearAlpha;
  9437. },
  9438. setClearAlpha: function (alpha) {
  9439. clearAlpha = alpha;
  9440. setClear(clearColor, clearAlpha);
  9441. },
  9442. render: render
  9443. };
  9444. }
  9445. function WebGLBindingStates(gl, extensions, attributes, capabilities) {
  9446. const maxVertexAttributes = gl.getParameter(34921);
  9447. const extension = capabilities.isWebGL2 ? null : extensions.get('OES_vertex_array_object');
  9448. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  9449. const bindingStates = {};
  9450. const defaultState = createBindingState(null);
  9451. let currentState = defaultState;
  9452. function setup(object, material, program, geometry, index) {
  9453. let updateBuffers = false;
  9454. if (vaoAvailable) {
  9455. const state = getBindingState(geometry, program, material);
  9456. if (currentState !== state) {
  9457. currentState = state;
  9458. bindVertexArrayObject(currentState.object);
  9459. }
  9460. updateBuffers = needsUpdate(geometry, index);
  9461. if (updateBuffers) saveCache(geometry, index);
  9462. } else {
  9463. const wireframe = material.wireframe === true;
  9464. if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) {
  9465. currentState.geometry = geometry.id;
  9466. currentState.program = program.id;
  9467. currentState.wireframe = wireframe;
  9468. updateBuffers = true;
  9469. }
  9470. }
  9471. if (object.isInstancedMesh === true) {
  9472. updateBuffers = true;
  9473. }
  9474. if (index !== null) {
  9475. attributes.update(index, 34963);
  9476. }
  9477. if (updateBuffers) {
  9478. setupVertexAttributes(object, material, program, geometry);
  9479. if (index !== null) {
  9480. gl.bindBuffer(34963, attributes.get(index).buffer);
  9481. }
  9482. }
  9483. }
  9484. function createVertexArrayObject() {
  9485. if (capabilities.isWebGL2) return gl.createVertexArray();
  9486. return extension.createVertexArrayOES();
  9487. }
  9488. function bindVertexArrayObject(vao) {
  9489. if (capabilities.isWebGL2) return gl.bindVertexArray(vao);
  9490. return extension.bindVertexArrayOES(vao);
  9491. }
  9492. function deleteVertexArrayObject(vao) {
  9493. if (capabilities.isWebGL2) return gl.deleteVertexArray(vao);
  9494. return extension.deleteVertexArrayOES(vao);
  9495. }
  9496. function getBindingState(geometry, program, material) {
  9497. const wireframe = material.wireframe === true;
  9498. let programMap = bindingStates[geometry.id];
  9499. if (programMap === undefined) {
  9500. programMap = {};
  9501. bindingStates[geometry.id] = programMap;
  9502. }
  9503. let stateMap = programMap[program.id];
  9504. if (stateMap === undefined) {
  9505. stateMap = {};
  9506. programMap[program.id] = stateMap;
  9507. }
  9508. let state = stateMap[wireframe];
  9509. if (state === undefined) {
  9510. state = createBindingState(createVertexArrayObject());
  9511. stateMap[wireframe] = state;
  9512. }
  9513. return state;
  9514. }
  9515. function createBindingState(vao) {
  9516. const newAttributes = [];
  9517. const enabledAttributes = [];
  9518. const attributeDivisors = [];
  9519. for (let i = 0; i < maxVertexAttributes; i++) {
  9520. newAttributes[i] = 0;
  9521. enabledAttributes[i] = 0;
  9522. attributeDivisors[i] = 0;
  9523. }
  9524. return {
  9525. // for backward compatibility on non-VAO support browser
  9526. geometry: null,
  9527. program: null,
  9528. wireframe: false,
  9529. newAttributes: newAttributes,
  9530. enabledAttributes: enabledAttributes,
  9531. attributeDivisors: attributeDivisors,
  9532. object: vao,
  9533. attributes: {},
  9534. index: null
  9535. };
  9536. }
  9537. function needsUpdate(geometry, index) {
  9538. const cachedAttributes = currentState.attributes;
  9539. const geometryAttributes = geometry.attributes;
  9540. let attributesNum = 0;
  9541. for (const key in geometryAttributes) {
  9542. const cachedAttribute = cachedAttributes[key];
  9543. const geometryAttribute = geometryAttributes[key];
  9544. if (cachedAttribute === undefined) return true;
  9545. if (cachedAttribute.attribute !== geometryAttribute) return true;
  9546. if (cachedAttribute.data !== geometryAttribute.data) return true;
  9547. attributesNum++;
  9548. }
  9549. if (currentState.attributesNum !== attributesNum) return true;
  9550. if (currentState.index !== index) return true;
  9551. return false;
  9552. }
  9553. function saveCache(geometry, index) {
  9554. const cache = {};
  9555. const attributes = geometry.attributes;
  9556. let attributesNum = 0;
  9557. for (const key in attributes) {
  9558. const attribute = attributes[key];
  9559. const data = {};
  9560. data.attribute = attribute;
  9561. if (attribute.data) {
  9562. data.data = attribute.data;
  9563. }
  9564. cache[key] = data;
  9565. attributesNum++;
  9566. }
  9567. currentState.attributes = cache;
  9568. currentState.attributesNum = attributesNum;
  9569. currentState.index = index;
  9570. }
  9571. function initAttributes() {
  9572. const newAttributes = currentState.newAttributes;
  9573. for (let i = 0, il = newAttributes.length; i < il; i++) {
  9574. newAttributes[i] = 0;
  9575. }
  9576. }
  9577. function enableAttribute(attribute) {
  9578. enableAttributeAndDivisor(attribute, 0);
  9579. }
  9580. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  9581. const newAttributes = currentState.newAttributes;
  9582. const enabledAttributes = currentState.enabledAttributes;
  9583. const attributeDivisors = currentState.attributeDivisors;
  9584. newAttributes[attribute] = 1;
  9585. if (enabledAttributes[attribute] === 0) {
  9586. gl.enableVertexAttribArray(attribute);
  9587. enabledAttributes[attribute] = 1;
  9588. }
  9589. if (attributeDivisors[attribute] !== meshPerAttribute) {
  9590. const extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  9591. extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  9592. attributeDivisors[attribute] = meshPerAttribute;
  9593. }
  9594. }
  9595. function disableUnusedAttributes() {
  9596. const newAttributes = currentState.newAttributes;
  9597. const enabledAttributes = currentState.enabledAttributes;
  9598. for (let i = 0, il = enabledAttributes.length; i < il; i++) {
  9599. if (enabledAttributes[i] !== newAttributes[i]) {
  9600. gl.disableVertexAttribArray(i);
  9601. enabledAttributes[i] = 0;
  9602. }
  9603. }
  9604. }
  9605. function vertexAttribPointer(index, size, type, normalized, stride, offset) {
  9606. if (capabilities.isWebGL2 === true && (type === 5124 || type === 5125)) {
  9607. gl.vertexAttribIPointer(index, size, type, stride, offset);
  9608. } else {
  9609. gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
  9610. }
  9611. }
  9612. function setupVertexAttributes(object, material, program, geometry) {
  9613. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  9614. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  9615. }
  9616. initAttributes();
  9617. const geometryAttributes = geometry.attributes;
  9618. const programAttributes = program.getAttributes();
  9619. const materialDefaultAttributeValues = material.defaultAttributeValues;
  9620. for (const name in programAttributes) {
  9621. const programAttribute = programAttributes[name];
  9622. if (programAttribute >= 0) {
  9623. const geometryAttribute = geometryAttributes[name];
  9624. if (geometryAttribute !== undefined) {
  9625. const normalized = geometryAttribute.normalized;
  9626. const size = geometryAttribute.itemSize;
  9627. const attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  9628. if (attribute === undefined) continue;
  9629. const buffer = attribute.buffer;
  9630. const type = attribute.type;
  9631. const bytesPerElement = attribute.bytesPerElement;
  9632. if (geometryAttribute.isInterleavedBufferAttribute) {
  9633. const data = geometryAttribute.data;
  9634. const stride = data.stride;
  9635. const offset = geometryAttribute.offset;
  9636. if (data && data.isInstancedInterleavedBuffer) {
  9637. enableAttributeAndDivisor(programAttribute, data.meshPerAttribute);
  9638. if (geometry._maxInstanceCount === undefined) {
  9639. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  9640. }
  9641. } else {
  9642. enableAttribute(programAttribute);
  9643. }
  9644. gl.bindBuffer(34962, buffer);
  9645. vertexAttribPointer(programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement);
  9646. } else {
  9647. if (geometryAttribute.isInstancedBufferAttribute) {
  9648. enableAttributeAndDivisor(programAttribute, geometryAttribute.meshPerAttribute);
  9649. if (geometry._maxInstanceCount === undefined) {
  9650. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  9651. }
  9652. } else {
  9653. enableAttribute(programAttribute);
  9654. }
  9655. gl.bindBuffer(34962, buffer);
  9656. vertexAttribPointer(programAttribute, size, type, normalized, 0, 0);
  9657. }
  9658. } else if (name === 'instanceMatrix') {
  9659. const attribute = attributes.get(object.instanceMatrix); // TODO Attribute may not be available on context restore
  9660. if (attribute === undefined) continue;
  9661. const buffer = attribute.buffer;
  9662. const type = attribute.type;
  9663. enableAttributeAndDivisor(programAttribute + 0, 1);
  9664. enableAttributeAndDivisor(programAttribute + 1, 1);
  9665. enableAttributeAndDivisor(programAttribute + 2, 1);
  9666. enableAttributeAndDivisor(programAttribute + 3, 1);
  9667. gl.bindBuffer(34962, buffer);
  9668. gl.vertexAttribPointer(programAttribute + 0, 4, type, false, 64, 0);
  9669. gl.vertexAttribPointer(programAttribute + 1, 4, type, false, 64, 16);
  9670. gl.vertexAttribPointer(programAttribute + 2, 4, type, false, 64, 32);
  9671. gl.vertexAttribPointer(programAttribute + 3, 4, type, false, 64, 48);
  9672. } else if (name === 'instanceColor') {
  9673. const attribute = attributes.get(object.instanceColor); // TODO Attribute may not be available on context restore
  9674. if (attribute === undefined) continue;
  9675. const buffer = attribute.buffer;
  9676. const type = attribute.type;
  9677. enableAttributeAndDivisor(programAttribute, 1);
  9678. gl.bindBuffer(34962, buffer);
  9679. gl.vertexAttribPointer(programAttribute, 3, type, false, 12, 0);
  9680. } else if (materialDefaultAttributeValues !== undefined) {
  9681. const value = materialDefaultAttributeValues[name];
  9682. if (value !== undefined) {
  9683. switch (value.length) {
  9684. case 2:
  9685. gl.vertexAttrib2fv(programAttribute, value);
  9686. break;
  9687. case 3:
  9688. gl.vertexAttrib3fv(programAttribute, value);
  9689. break;
  9690. case 4:
  9691. gl.vertexAttrib4fv(programAttribute, value);
  9692. break;
  9693. default:
  9694. gl.vertexAttrib1fv(programAttribute, value);
  9695. }
  9696. }
  9697. }
  9698. }
  9699. }
  9700. disableUnusedAttributes();
  9701. }
  9702. function dispose() {
  9703. reset();
  9704. for (const geometryId in bindingStates) {
  9705. const programMap = bindingStates[geometryId];
  9706. for (const programId in programMap) {
  9707. const stateMap = programMap[programId];
  9708. for (const wireframe in stateMap) {
  9709. deleteVertexArrayObject(stateMap[wireframe].object);
  9710. delete stateMap[wireframe];
  9711. }
  9712. delete programMap[programId];
  9713. }
  9714. delete bindingStates[geometryId];
  9715. }
  9716. }
  9717. function releaseStatesOfGeometry(geometry) {
  9718. if (bindingStates[geometry.id] === undefined) return;
  9719. const programMap = bindingStates[geometry.id];
  9720. for (const programId in programMap) {
  9721. const stateMap = programMap[programId];
  9722. for (const wireframe in stateMap) {
  9723. deleteVertexArrayObject(stateMap[wireframe].object);
  9724. delete stateMap[wireframe];
  9725. }
  9726. delete programMap[programId];
  9727. }
  9728. delete bindingStates[geometry.id];
  9729. }
  9730. function releaseStatesOfProgram(program) {
  9731. for (const geometryId in bindingStates) {
  9732. const programMap = bindingStates[geometryId];
  9733. if (programMap[program.id] === undefined) continue;
  9734. const stateMap = programMap[program.id];
  9735. for (const wireframe in stateMap) {
  9736. deleteVertexArrayObject(stateMap[wireframe].object);
  9737. delete stateMap[wireframe];
  9738. }
  9739. delete programMap[program.id];
  9740. }
  9741. }
  9742. function reset() {
  9743. resetDefaultState();
  9744. if (currentState === defaultState) return;
  9745. currentState = defaultState;
  9746. bindVertexArrayObject(currentState.object);
  9747. } // for backward-compatilibity
  9748. function resetDefaultState() {
  9749. defaultState.geometry = null;
  9750. defaultState.program = null;
  9751. defaultState.wireframe = false;
  9752. }
  9753. return {
  9754. setup: setup,
  9755. reset: reset,
  9756. resetDefaultState: resetDefaultState,
  9757. dispose: dispose,
  9758. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9759. releaseStatesOfProgram: releaseStatesOfProgram,
  9760. initAttributes: initAttributes,
  9761. enableAttribute: enableAttribute,
  9762. disableUnusedAttributes: disableUnusedAttributes
  9763. };
  9764. }
  9765. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  9766. const isWebGL2 = capabilities.isWebGL2;
  9767. let mode;
  9768. function setMode(value) {
  9769. mode = value;
  9770. }
  9771. function render(start, count) {
  9772. gl.drawArrays(mode, start, count);
  9773. info.update(count, mode, 1);
  9774. }
  9775. function renderInstances(start, count, primcount) {
  9776. if (primcount === 0) return;
  9777. let extension, methodName;
  9778. if (isWebGL2) {
  9779. extension = gl;
  9780. methodName = 'drawArraysInstanced';
  9781. } else {
  9782. extension = extensions.get('ANGLE_instanced_arrays');
  9783. methodName = 'drawArraysInstancedANGLE';
  9784. if (extension === null) {
  9785. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  9786. return;
  9787. }
  9788. }
  9789. extension[methodName](mode, start, count, primcount);
  9790. info.update(count, mode, primcount);
  9791. } //
  9792. this.setMode = setMode;
  9793. this.render = render;
  9794. this.renderInstances = renderInstances;
  9795. }
  9796. function WebGLCapabilities(gl, extensions, parameters) {
  9797. let maxAnisotropy;
  9798. function getMaxAnisotropy() {
  9799. if (maxAnisotropy !== undefined) return maxAnisotropy;
  9800. const extension = extensions.get('EXT_texture_filter_anisotropic');
  9801. if (extension !== null) {
  9802. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  9803. } else {
  9804. maxAnisotropy = 0;
  9805. }
  9806. return maxAnisotropy;
  9807. }
  9808. function getMaxPrecision(precision) {
  9809. if (precision === 'highp') {
  9810. if (gl.getShaderPrecisionFormat(35633, 36338).precision > 0 && gl.getShaderPrecisionFormat(35632, 36338).precision > 0) {
  9811. return 'highp';
  9812. }
  9813. precision = 'mediump';
  9814. }
  9815. if (precision === 'mediump') {
  9816. if (gl.getShaderPrecisionFormat(35633, 36337).precision > 0 && gl.getShaderPrecisionFormat(35632, 36337).precision > 0) {
  9817. return 'mediump';
  9818. }
  9819. }
  9820. return 'lowp';
  9821. }
  9822. /* eslint-disable no-undef */
  9823. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext;
  9824. /* eslint-enable no-undef */
  9825. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9826. const maxPrecision = getMaxPrecision(precision);
  9827. if (maxPrecision !== precision) {
  9828. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  9829. precision = maxPrecision;
  9830. }
  9831. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9832. const maxTextures = gl.getParameter(34930);
  9833. const maxVertexTextures = gl.getParameter(35660);
  9834. const maxTextureSize = gl.getParameter(3379);
  9835. const maxCubemapSize = gl.getParameter(34076);
  9836. const maxAttributes = gl.getParameter(34921);
  9837. const maxVertexUniforms = gl.getParameter(36347);
  9838. const maxVaryings = gl.getParameter(36348);
  9839. const maxFragmentUniforms = gl.getParameter(36349);
  9840. const vertexTextures = maxVertexTextures > 0;
  9841. const floatFragmentTextures = isWebGL2 || !!extensions.get('OES_texture_float');
  9842. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9843. const maxSamples = isWebGL2 ? gl.getParameter(36183) : 0;
  9844. return {
  9845. isWebGL2: isWebGL2,
  9846. getMaxAnisotropy: getMaxAnisotropy,
  9847. getMaxPrecision: getMaxPrecision,
  9848. precision: precision,
  9849. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9850. maxTextures: maxTextures,
  9851. maxVertexTextures: maxVertexTextures,
  9852. maxTextureSize: maxTextureSize,
  9853. maxCubemapSize: maxCubemapSize,
  9854. maxAttributes: maxAttributes,
  9855. maxVertexUniforms: maxVertexUniforms,
  9856. maxVaryings: maxVaryings,
  9857. maxFragmentUniforms: maxFragmentUniforms,
  9858. vertexTextures: vertexTextures,
  9859. floatFragmentTextures: floatFragmentTextures,
  9860. floatVertexTextures: floatVertexTextures,
  9861. maxSamples: maxSamples
  9862. };
  9863. }
  9864. function WebGLClipping(properties) {
  9865. const scope = this;
  9866. let globalState = null,
  9867. numGlobalPlanes = 0,
  9868. localClippingEnabled = false,
  9869. renderingShadows = false;
  9870. const plane = new Plane(),
  9871. viewNormalMatrix = new Matrix3(),
  9872. uniform = {
  9873. value: null,
  9874. needsUpdate: false
  9875. };
  9876. this.uniform = uniform;
  9877. this.numPlanes = 0;
  9878. this.numIntersection = 0;
  9879. this.init = function (planes, enableLocalClipping, camera) {
  9880. const enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  9881. // run another frame in order to reset the state:
  9882. numGlobalPlanes !== 0 || localClippingEnabled;
  9883. localClippingEnabled = enableLocalClipping;
  9884. globalState = projectPlanes(planes, camera, 0);
  9885. numGlobalPlanes = planes.length;
  9886. return enabled;
  9887. };
  9888. this.beginShadows = function () {
  9889. renderingShadows = true;
  9890. projectPlanes(null);
  9891. };
  9892. this.endShadows = function () {
  9893. renderingShadows = false;
  9894. resetGlobalState();
  9895. };
  9896. this.setState = function (material, camera, useCache) {
  9897. const planes = material.clippingPlanes,
  9898. clipIntersection = material.clipIntersection,
  9899. clipShadows = material.clipShadows;
  9900. const materialProperties = properties.get(material);
  9901. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  9902. // there's no local clipping
  9903. if (renderingShadows) {
  9904. // there's no global clipping
  9905. projectPlanes(null);
  9906. } else {
  9907. resetGlobalState();
  9908. }
  9909. } else {
  9910. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9911. lGlobal = nGlobal * 4;
  9912. let dstArray = materialProperties.clippingState || null;
  9913. uniform.value = dstArray; // ensure unique state
  9914. dstArray = projectPlanes(planes, camera, lGlobal, useCache);
  9915. for (let i = 0; i !== lGlobal; ++i) {
  9916. dstArray[i] = globalState[i];
  9917. }
  9918. materialProperties.clippingState = dstArray;
  9919. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9920. this.numPlanes += nGlobal;
  9921. }
  9922. };
  9923. function resetGlobalState() {
  9924. if (uniform.value !== globalState) {
  9925. uniform.value = globalState;
  9926. uniform.needsUpdate = numGlobalPlanes > 0;
  9927. }
  9928. scope.numPlanes = numGlobalPlanes;
  9929. scope.numIntersection = 0;
  9930. }
  9931. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  9932. const nPlanes = planes !== null ? planes.length : 0;
  9933. let dstArray = null;
  9934. if (nPlanes !== 0) {
  9935. dstArray = uniform.value;
  9936. if (skipTransform !== true || dstArray === null) {
  9937. const flatSize = dstOffset + nPlanes * 4,
  9938. viewMatrix = camera.matrixWorldInverse;
  9939. viewNormalMatrix.getNormalMatrix(viewMatrix);
  9940. if (dstArray === null || dstArray.length < flatSize) {
  9941. dstArray = new Float32Array(flatSize);
  9942. }
  9943. for (let i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  9944. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  9945. plane.normal.toArray(dstArray, i4);
  9946. dstArray[i4 + 3] = plane.constant;
  9947. }
  9948. }
  9949. uniform.value = dstArray;
  9950. uniform.needsUpdate = true;
  9951. }
  9952. scope.numPlanes = nPlanes;
  9953. scope.numIntersection = 0;
  9954. return dstArray;
  9955. }
  9956. }
  9957. function WebGLCubeMaps(renderer) {
  9958. let cubemaps = new WeakMap();
  9959. function mapTextureMapping(texture, mapping) {
  9960. if (mapping === EquirectangularReflectionMapping) {
  9961. texture.mapping = CubeReflectionMapping;
  9962. } else if (mapping === EquirectangularRefractionMapping) {
  9963. texture.mapping = CubeRefractionMapping;
  9964. }
  9965. return texture;
  9966. }
  9967. function get(texture) {
  9968. if (texture && texture.isTexture) {
  9969. const mapping = texture.mapping;
  9970. if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) {
  9971. if (cubemaps.has(texture)) {
  9972. const cubemap = cubemaps.get(texture).texture;
  9973. return mapTextureMapping(cubemap, texture.mapping);
  9974. } else {
  9975. const image = texture.image;
  9976. if (image && image.height > 0) {
  9977. const currentRenderList = renderer.getRenderList();
  9978. const currentRenderTarget = renderer.getRenderTarget();
  9979. const currentRenderState = renderer.getRenderState();
  9980. const renderTarget = new WebGLCubeRenderTarget(image.height / 2);
  9981. renderTarget.fromEquirectangularTexture(renderer, texture);
  9982. cubemaps.set(texture, renderTarget);
  9983. renderer.setRenderTarget(currentRenderTarget);
  9984. renderer.setRenderList(currentRenderList);
  9985. renderer.setRenderState(currentRenderState);
  9986. texture.addEventListener('dispose', onTextureDispose);
  9987. return mapTextureMapping(renderTarget.texture, texture.mapping);
  9988. } else {
  9989. // image not yet ready. try the conversion next frame
  9990. return null;
  9991. }
  9992. }
  9993. }
  9994. }
  9995. return texture;
  9996. }
  9997. function onTextureDispose(event) {
  9998. const texture = event.target;
  9999. texture.removeEventListener('dispose', onTextureDispose);
  10000. const cubemap = cubemaps.get(texture);
  10001. if (cubemap !== undefined) {
  10002. cubemaps.delete(texture);
  10003. cubemap.dispose();
  10004. }
  10005. }
  10006. function dispose() {
  10007. cubemaps = new WeakMap();
  10008. }
  10009. return {
  10010. get: get,
  10011. dispose: dispose
  10012. };
  10013. }
  10014. function WebGLExtensions(gl) {
  10015. const extensions = {};
  10016. return {
  10017. has: function (name) {
  10018. if (extensions[name] !== undefined) {
  10019. return extensions[name] !== null;
  10020. }
  10021. let extension;
  10022. switch (name) {
  10023. case 'WEBGL_depth_texture':
  10024. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  10025. break;
  10026. case 'EXT_texture_filter_anisotropic':
  10027. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  10028. break;
  10029. case 'WEBGL_compressed_texture_s3tc':
  10030. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10031. break;
  10032. case 'WEBGL_compressed_texture_pvrtc':
  10033. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10034. break;
  10035. default:
  10036. extension = gl.getExtension(name);
  10037. }
  10038. extensions[name] = extension;
  10039. return extension !== null;
  10040. },
  10041. get: function (name) {
  10042. if (!this.has(name)) {
  10043. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  10044. }
  10045. return extensions[name];
  10046. }
  10047. };
  10048. }
  10049. function WebGLGeometries(gl, attributes, info, bindingStates) {
  10050. const geometries = new WeakMap();
  10051. const wireframeAttributes = new WeakMap();
  10052. function onGeometryDispose(event) {
  10053. const geometry = event.target;
  10054. const buffergeometry = geometries.get(geometry);
  10055. if (buffergeometry.index !== null) {
  10056. attributes.remove(buffergeometry.index);
  10057. }
  10058. for (const name in buffergeometry.attributes) {
  10059. attributes.remove(buffergeometry.attributes[name]);
  10060. }
  10061. geometry.removeEventListener('dispose', onGeometryDispose);
  10062. geometries.delete(geometry);
  10063. const attribute = wireframeAttributes.get(buffergeometry);
  10064. if (attribute) {
  10065. attributes.remove(attribute);
  10066. wireframeAttributes.delete(buffergeometry);
  10067. }
  10068. bindingStates.releaseStatesOfGeometry(buffergeometry);
  10069. if (geometry.isInstancedBufferGeometry === true) {
  10070. delete geometry._maxInstanceCount;
  10071. } //
  10072. info.memory.geometries--;
  10073. }
  10074. function get(object, geometry) {
  10075. let buffergeometry = geometries.get(geometry);
  10076. if (buffergeometry) return buffergeometry;
  10077. geometry.addEventListener('dispose', onGeometryDispose);
  10078. if (geometry.isBufferGeometry) {
  10079. buffergeometry = geometry;
  10080. } else if (geometry.isGeometry) {
  10081. if (geometry._bufferGeometry === undefined) {
  10082. geometry._bufferGeometry = new BufferGeometry().setFromObject(object);
  10083. }
  10084. buffergeometry = geometry._bufferGeometry;
  10085. }
  10086. geometries.set(geometry, buffergeometry);
  10087. info.memory.geometries++;
  10088. return buffergeometry;
  10089. }
  10090. function update(geometry) {
  10091. const geometryAttributes = geometry.attributes; // Updating index buffer in VAO now. See WebGLBindingStates.
  10092. for (const name in geometryAttributes) {
  10093. attributes.update(geometryAttributes[name], 34962);
  10094. } // morph targets
  10095. const morphAttributes = geometry.morphAttributes;
  10096. for (const name in morphAttributes) {
  10097. const array = morphAttributes[name];
  10098. for (let i = 0, l = array.length; i < l; i++) {
  10099. attributes.update(array[i], 34962);
  10100. }
  10101. }
  10102. }
  10103. function updateWireframeAttribute(geometry) {
  10104. const indices = [];
  10105. const geometryIndex = geometry.index;
  10106. const geometryPosition = geometry.attributes.position;
  10107. let version = 0;
  10108. if (geometryIndex !== null) {
  10109. const array = geometryIndex.array;
  10110. version = geometryIndex.version;
  10111. for (let i = 0, l = array.length; i < l; i += 3) {
  10112. const a = array[i + 0];
  10113. const b = array[i + 1];
  10114. const c = array[i + 2];
  10115. indices.push(a, b, b, c, c, a);
  10116. }
  10117. } else {
  10118. const array = geometryPosition.array;
  10119. version = geometryPosition.version;
  10120. for (let i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  10121. const a = i + 0;
  10122. const b = i + 1;
  10123. const c = i + 2;
  10124. indices.push(a, b, b, c, c, a);
  10125. }
  10126. }
  10127. const attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  10128. attribute.version = version; // Updating index buffer in VAO now. See WebGLBindingStates
  10129. //
  10130. const previousAttribute = wireframeAttributes.get(geometry);
  10131. if (previousAttribute) attributes.remove(previousAttribute); //
  10132. wireframeAttributes.set(geometry, attribute);
  10133. }
  10134. function getWireframeAttribute(geometry) {
  10135. const currentAttribute = wireframeAttributes.get(geometry);
  10136. if (currentAttribute) {
  10137. const geometryIndex = geometry.index;
  10138. if (geometryIndex !== null) {
  10139. // if the attribute is obsolete, create a new one
  10140. if (currentAttribute.version < geometryIndex.version) {
  10141. updateWireframeAttribute(geometry);
  10142. }
  10143. }
  10144. } else {
  10145. updateWireframeAttribute(geometry);
  10146. }
  10147. return wireframeAttributes.get(geometry);
  10148. }
  10149. return {
  10150. get: get,
  10151. update: update,
  10152. getWireframeAttribute: getWireframeAttribute
  10153. };
  10154. }
  10155. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  10156. const isWebGL2 = capabilities.isWebGL2;
  10157. let mode;
  10158. function setMode(value) {
  10159. mode = value;
  10160. }
  10161. let type, bytesPerElement;
  10162. function setIndex(value) {
  10163. type = value.type;
  10164. bytesPerElement = value.bytesPerElement;
  10165. }
  10166. function render(start, count) {
  10167. gl.drawElements(mode, count, type, start * bytesPerElement);
  10168. info.update(count, mode, 1);
  10169. }
  10170. function renderInstances(start, count, primcount) {
  10171. if (primcount === 0) return;
  10172. let extension, methodName;
  10173. if (isWebGL2) {
  10174. extension = gl;
  10175. methodName = 'drawElementsInstanced';
  10176. } else {
  10177. extension = extensions.get('ANGLE_instanced_arrays');
  10178. methodName = 'drawElementsInstancedANGLE';
  10179. if (extension === null) {
  10180. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  10181. return;
  10182. }
  10183. }
  10184. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  10185. info.update(count, mode, primcount);
  10186. } //
  10187. this.setMode = setMode;
  10188. this.setIndex = setIndex;
  10189. this.render = render;
  10190. this.renderInstances = renderInstances;
  10191. }
  10192. function WebGLInfo(gl) {
  10193. const memory = {
  10194. geometries: 0,
  10195. textures: 0
  10196. };
  10197. const render = {
  10198. frame: 0,
  10199. calls: 0,
  10200. triangles: 0,
  10201. points: 0,
  10202. lines: 0
  10203. };
  10204. function update(count, mode, instanceCount) {
  10205. render.calls++;
  10206. switch (mode) {
  10207. case 4:
  10208. render.triangles += instanceCount * (count / 3);
  10209. break;
  10210. case 1:
  10211. render.lines += instanceCount * (count / 2);
  10212. break;
  10213. case 3:
  10214. render.lines += instanceCount * (count - 1);
  10215. break;
  10216. case 2:
  10217. render.lines += instanceCount * count;
  10218. break;
  10219. case 0:
  10220. render.points += instanceCount * count;
  10221. break;
  10222. default:
  10223. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  10224. break;
  10225. }
  10226. }
  10227. function reset() {
  10228. render.frame++;
  10229. render.calls = 0;
  10230. render.triangles = 0;
  10231. render.points = 0;
  10232. render.lines = 0;
  10233. }
  10234. return {
  10235. memory: memory,
  10236. render: render,
  10237. programs: null,
  10238. autoReset: true,
  10239. reset: reset,
  10240. update: update
  10241. };
  10242. }
  10243. function numericalSort(a, b) {
  10244. return a[0] - b[0];
  10245. }
  10246. function absNumericalSort(a, b) {
  10247. return Math.abs(b[1]) - Math.abs(a[1]);
  10248. }
  10249. function WebGLMorphtargets(gl) {
  10250. const influencesList = {};
  10251. const morphInfluences = new Float32Array(8);
  10252. const workInfluences = [];
  10253. for (let i = 0; i < 8; i++) {
  10254. workInfluences[i] = [i, 0];
  10255. }
  10256. function update(object, geometry, material, program) {
  10257. const objectInfluences = object.morphTargetInfluences; // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10258. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10259. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10260. let influences = influencesList[geometry.id];
  10261. if (influences === undefined) {
  10262. // initialise list
  10263. influences = [];
  10264. for (let i = 0; i < length; i++) {
  10265. influences[i] = [i, 0];
  10266. }
  10267. influencesList[geometry.id] = influences;
  10268. } // Collect influences
  10269. for (let i = 0; i < length; i++) {
  10270. const influence = influences[i];
  10271. influence[0] = i;
  10272. influence[1] = objectInfluences[i];
  10273. }
  10274. influences.sort(absNumericalSort);
  10275. for (let i = 0; i < 8; i++) {
  10276. if (i < length && influences[i][1]) {
  10277. workInfluences[i][0] = influences[i][0];
  10278. workInfluences[i][1] = influences[i][1];
  10279. } else {
  10280. workInfluences[i][0] = Number.MAX_SAFE_INTEGER;
  10281. workInfluences[i][1] = 0;
  10282. }
  10283. }
  10284. workInfluences.sort(numericalSort);
  10285. const morphTargets = material.morphTargets && geometry.morphAttributes.position;
  10286. const morphNormals = material.morphNormals && geometry.morphAttributes.normal;
  10287. let morphInfluencesSum = 0;
  10288. for (let i = 0; i < 8; i++) {
  10289. const influence = workInfluences[i];
  10290. const index = influence[0];
  10291. const value = influence[1];
  10292. if (index !== Number.MAX_SAFE_INTEGER && value) {
  10293. if (morphTargets && geometry.getAttribute('morphTarget' + i) !== morphTargets[index]) {
  10294. geometry.setAttribute('morphTarget' + i, morphTargets[index]);
  10295. }
  10296. if (morphNormals && geometry.getAttribute('morphNormal' + i) !== morphNormals[index]) {
  10297. geometry.setAttribute('morphNormal' + i, morphNormals[index]);
  10298. }
  10299. morphInfluences[i] = value;
  10300. morphInfluencesSum += value;
  10301. } else {
  10302. if (morphTargets && geometry.hasAttribute('morphTarget' + i) === true) {
  10303. geometry.deleteAttribute('morphTarget' + i);
  10304. }
  10305. if (morphNormals && geometry.hasAttribute('morphNormal' + i) === true) {
  10306. geometry.deleteAttribute('morphNormal' + i);
  10307. }
  10308. morphInfluences[i] = 0;
  10309. }
  10310. } // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10311. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10312. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10313. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10314. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  10315. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  10316. }
  10317. return {
  10318. update: update
  10319. };
  10320. }
  10321. function WebGLObjects(gl, geometries, attributes, info) {
  10322. let updateMap = new WeakMap();
  10323. function update(object) {
  10324. const frame = info.render.frame;
  10325. const geometry = object.geometry;
  10326. const buffergeometry = geometries.get(object, geometry); // Update once per frame
  10327. if (updateMap.get(buffergeometry) !== frame) {
  10328. if (geometry.isGeometry) {
  10329. buffergeometry.updateFromObject(object);
  10330. }
  10331. geometries.update(buffergeometry);
  10332. updateMap.set(buffergeometry, frame);
  10333. }
  10334. if (object.isInstancedMesh) {
  10335. attributes.update(object.instanceMatrix, 34962);
  10336. if (object.instanceColor !== null) {
  10337. attributes.update(object.instanceColor, 34962);
  10338. }
  10339. }
  10340. return buffergeometry;
  10341. }
  10342. function dispose() {
  10343. updateMap = new WeakMap();
  10344. }
  10345. return {
  10346. update: update,
  10347. dispose: dispose
  10348. };
  10349. }
  10350. function DataTexture2DArray(data = null, width = 1, height = 1, depth = 1) {
  10351. Texture.call(this, null);
  10352. this.image = {
  10353. data,
  10354. width,
  10355. height,
  10356. depth
  10357. };
  10358. this.magFilter = NearestFilter;
  10359. this.minFilter = NearestFilter;
  10360. this.wrapR = ClampToEdgeWrapping;
  10361. this.generateMipmaps = false;
  10362. this.flipY = false;
  10363. this.needsUpdate = true;
  10364. }
  10365. DataTexture2DArray.prototype = Object.create(Texture.prototype);
  10366. DataTexture2DArray.prototype.constructor = DataTexture2DArray;
  10367. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  10368. function DataTexture3D(data = null, width = 1, height = 1, depth = 1) {
  10369. // We're going to add .setXXX() methods for setting properties later.
  10370. // Users can still set in DataTexture3D directly.
  10371. //
  10372. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  10373. // texture.anisotropy = 16;
  10374. //
  10375. // See #14839
  10376. Texture.call(this, null);
  10377. this.image = {
  10378. data,
  10379. width,
  10380. height,
  10381. depth
  10382. };
  10383. this.magFilter = NearestFilter;
  10384. this.minFilter = NearestFilter;
  10385. this.wrapR = ClampToEdgeWrapping;
  10386. this.generateMipmaps = false;
  10387. this.flipY = false;
  10388. this.needsUpdate = true;
  10389. }
  10390. DataTexture3D.prototype = Object.create(Texture.prototype);
  10391. DataTexture3D.prototype.constructor = DataTexture3D;
  10392. DataTexture3D.prototype.isDataTexture3D = true;
  10393. /**
  10394. * Uniforms of a program.
  10395. * Those form a tree structure with a special top-level container for the root,
  10396. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10397. *
  10398. *
  10399. * Properties of inner nodes including the top-level container:
  10400. *
  10401. * .seq - array of nested uniforms
  10402. * .map - nested uniforms by name
  10403. *
  10404. *
  10405. * Methods of all nodes except the top-level container:
  10406. *
  10407. * .setValue( gl, value, [textures] )
  10408. *
  10409. * uploads a uniform value(s)
  10410. * the 'textures' parameter is needed for sampler uniforms
  10411. *
  10412. *
  10413. * Static methods of the top-level container (textures factorizations):
  10414. *
  10415. * .upload( gl, seq, values, textures )
  10416. *
  10417. * sets uniforms in 'seq' to 'values[id].value'
  10418. *
  10419. * .seqWithValue( seq, values ) : filteredSeq
  10420. *
  10421. * filters 'seq' entries with corresponding entry in values
  10422. *
  10423. *
  10424. * Methods of the top-level container (textures factorizations):
  10425. *
  10426. * .setValue( gl, name, value, textures )
  10427. *
  10428. * sets uniform with name 'name' to 'value'
  10429. *
  10430. * .setOptional( gl, obj, prop )
  10431. *
  10432. * like .set for an optional property of the object
  10433. *
  10434. */
  10435. const emptyTexture = new Texture();
  10436. const emptyTexture2dArray = new DataTexture2DArray();
  10437. const emptyTexture3d = new DataTexture3D();
  10438. const emptyCubeTexture = new CubeTexture(); // --- Utilities ---
  10439. // Array Caches (provide typed arrays for temporary by size)
  10440. const arrayCacheF32 = [];
  10441. const arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  10442. const mat4array = new Float32Array(16);
  10443. const mat3array = new Float32Array(9);
  10444. const mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  10445. function flatten(array, nBlocks, blockSize) {
  10446. const firstElem = array[0];
  10447. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  10448. // see http://jacksondunstan.com/articles/983
  10449. const n = nBlocks * blockSize;
  10450. let r = arrayCacheF32[n];
  10451. if (r === undefined) {
  10452. r = new Float32Array(n);
  10453. arrayCacheF32[n] = r;
  10454. }
  10455. if (nBlocks !== 0) {
  10456. firstElem.toArray(r, 0);
  10457. for (let i = 1, offset = 0; i !== nBlocks; ++i) {
  10458. offset += blockSize;
  10459. array[i].toArray(r, offset);
  10460. }
  10461. }
  10462. return r;
  10463. }
  10464. function arraysEqual(a, b) {
  10465. if (a.length !== b.length) return false;
  10466. for (let i = 0, l = a.length; i < l; i++) {
  10467. if (a[i] !== b[i]) return false;
  10468. }
  10469. return true;
  10470. }
  10471. function copyArray(a, b) {
  10472. for (let i = 0, l = b.length; i < l; i++) {
  10473. a[i] = b[i];
  10474. }
  10475. } // Texture unit allocation
  10476. function allocTexUnits(textures, n) {
  10477. let r = arrayCacheI32[n];
  10478. if (r === undefined) {
  10479. r = new Int32Array(n);
  10480. arrayCacheI32[n] = r;
  10481. }
  10482. for (let i = 0; i !== n; ++i) {
  10483. r[i] = textures.allocateTextureUnit();
  10484. }
  10485. return r;
  10486. } // --- Setters ---
  10487. // Note: Defining these methods externally, because they come in a bunch
  10488. // and this way their names minify.
  10489. // Single scalar
  10490. function setValueV1f(gl, v) {
  10491. const cache = this.cache;
  10492. if (cache[0] === v) return;
  10493. gl.uniform1f(this.addr, v);
  10494. cache[0] = v;
  10495. } // Single float vector (from flat array or THREE.VectorN)
  10496. function setValueV2f(gl, v) {
  10497. const cache = this.cache;
  10498. if (v.x !== undefined) {
  10499. if (cache[0] !== v.x || cache[1] !== v.y) {
  10500. gl.uniform2f(this.addr, v.x, v.y);
  10501. cache[0] = v.x;
  10502. cache[1] = v.y;
  10503. }
  10504. } else {
  10505. if (arraysEqual(cache, v)) return;
  10506. gl.uniform2fv(this.addr, v);
  10507. copyArray(cache, v);
  10508. }
  10509. }
  10510. function setValueV3f(gl, v) {
  10511. const cache = this.cache;
  10512. if (v.x !== undefined) {
  10513. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  10514. gl.uniform3f(this.addr, v.x, v.y, v.z);
  10515. cache[0] = v.x;
  10516. cache[1] = v.y;
  10517. cache[2] = v.z;
  10518. }
  10519. } else if (v.r !== undefined) {
  10520. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  10521. gl.uniform3f(this.addr, v.r, v.g, v.b);
  10522. cache[0] = v.r;
  10523. cache[1] = v.g;
  10524. cache[2] = v.b;
  10525. }
  10526. } else {
  10527. if (arraysEqual(cache, v)) return;
  10528. gl.uniform3fv(this.addr, v);
  10529. copyArray(cache, v);
  10530. }
  10531. }
  10532. function setValueV4f(gl, v) {
  10533. const cache = this.cache;
  10534. if (v.x !== undefined) {
  10535. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  10536. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  10537. cache[0] = v.x;
  10538. cache[1] = v.y;
  10539. cache[2] = v.z;
  10540. cache[3] = v.w;
  10541. }
  10542. } else {
  10543. if (arraysEqual(cache, v)) return;
  10544. gl.uniform4fv(this.addr, v);
  10545. copyArray(cache, v);
  10546. }
  10547. } // Single matrix (from flat array or MatrixN)
  10548. function setValueM2(gl, v) {
  10549. const cache = this.cache;
  10550. const elements = v.elements;
  10551. if (elements === undefined) {
  10552. if (arraysEqual(cache, v)) return;
  10553. gl.uniformMatrix2fv(this.addr, false, v);
  10554. copyArray(cache, v);
  10555. } else {
  10556. if (arraysEqual(cache, elements)) return;
  10557. mat2array.set(elements);
  10558. gl.uniformMatrix2fv(this.addr, false, mat2array);
  10559. copyArray(cache, elements);
  10560. }
  10561. }
  10562. function setValueM3(gl, v) {
  10563. const cache = this.cache;
  10564. const elements = v.elements;
  10565. if (elements === undefined) {
  10566. if (arraysEqual(cache, v)) return;
  10567. gl.uniformMatrix3fv(this.addr, false, v);
  10568. copyArray(cache, v);
  10569. } else {
  10570. if (arraysEqual(cache, elements)) return;
  10571. mat3array.set(elements);
  10572. gl.uniformMatrix3fv(this.addr, false, mat3array);
  10573. copyArray(cache, elements);
  10574. }
  10575. }
  10576. function setValueM4(gl, v) {
  10577. const cache = this.cache;
  10578. const elements = v.elements;
  10579. if (elements === undefined) {
  10580. if (arraysEqual(cache, v)) return;
  10581. gl.uniformMatrix4fv(this.addr, false, v);
  10582. copyArray(cache, v);
  10583. } else {
  10584. if (arraysEqual(cache, elements)) return;
  10585. mat4array.set(elements);
  10586. gl.uniformMatrix4fv(this.addr, false, mat4array);
  10587. copyArray(cache, elements);
  10588. }
  10589. } // Single texture (2D / Cube)
  10590. function setValueT1(gl, v, textures) {
  10591. const cache = this.cache;
  10592. const unit = textures.allocateTextureUnit();
  10593. if (cache[0] !== unit) {
  10594. gl.uniform1i(this.addr, unit);
  10595. cache[0] = unit;
  10596. }
  10597. textures.safeSetTexture2D(v || emptyTexture, unit);
  10598. }
  10599. function setValueT2DArray1(gl, v, textures) {
  10600. const cache = this.cache;
  10601. const unit = textures.allocateTextureUnit();
  10602. if (cache[0] !== unit) {
  10603. gl.uniform1i(this.addr, unit);
  10604. cache[0] = unit;
  10605. }
  10606. textures.setTexture2DArray(v || emptyTexture2dArray, unit);
  10607. }
  10608. function setValueT3D1(gl, v, textures) {
  10609. const cache = this.cache;
  10610. const unit = textures.allocateTextureUnit();
  10611. if (cache[0] !== unit) {
  10612. gl.uniform1i(this.addr, unit);
  10613. cache[0] = unit;
  10614. }
  10615. textures.setTexture3D(v || emptyTexture3d, unit);
  10616. }
  10617. function setValueT6(gl, v, textures) {
  10618. const cache = this.cache;
  10619. const unit = textures.allocateTextureUnit();
  10620. if (cache[0] !== unit) {
  10621. gl.uniform1i(this.addr, unit);
  10622. cache[0] = unit;
  10623. }
  10624. textures.safeSetTextureCube(v || emptyCubeTexture, unit);
  10625. } // Integer / Boolean vectors or arrays thereof (always flat arrays)
  10626. function setValueV1i(gl, v) {
  10627. const cache = this.cache;
  10628. if (cache[0] === v) return;
  10629. gl.uniform1i(this.addr, v);
  10630. cache[0] = v;
  10631. }
  10632. function setValueV2i(gl, v) {
  10633. const cache = this.cache;
  10634. if (arraysEqual(cache, v)) return;
  10635. gl.uniform2iv(this.addr, v);
  10636. copyArray(cache, v);
  10637. }
  10638. function setValueV3i(gl, v) {
  10639. const cache = this.cache;
  10640. if (arraysEqual(cache, v)) return;
  10641. gl.uniform3iv(this.addr, v);
  10642. copyArray(cache, v);
  10643. }
  10644. function setValueV4i(gl, v) {
  10645. const cache = this.cache;
  10646. if (arraysEqual(cache, v)) return;
  10647. gl.uniform4iv(this.addr, v);
  10648. copyArray(cache, v);
  10649. } // uint
  10650. function setValueV1ui(gl, v) {
  10651. const cache = this.cache;
  10652. if (cache[0] === v) return;
  10653. gl.uniform1ui(this.addr, v);
  10654. cache[0] = v;
  10655. } // Helper to pick the right setter for the singular case
  10656. function getSingularSetter(type) {
  10657. switch (type) {
  10658. case 0x1406:
  10659. return setValueV1f;
  10660. // FLOAT
  10661. case 0x8b50:
  10662. return setValueV2f;
  10663. // _VEC2
  10664. case 0x8b51:
  10665. return setValueV3f;
  10666. // _VEC3
  10667. case 0x8b52:
  10668. return setValueV4f;
  10669. // _VEC4
  10670. case 0x8b5a:
  10671. return setValueM2;
  10672. // _MAT2
  10673. case 0x8b5b:
  10674. return setValueM3;
  10675. // _MAT3
  10676. case 0x8b5c:
  10677. return setValueM4;
  10678. // _MAT4
  10679. case 0x1404:
  10680. case 0x8b56:
  10681. return setValueV1i;
  10682. // INT, BOOL
  10683. case 0x8b53:
  10684. case 0x8b57:
  10685. return setValueV2i;
  10686. // _VEC2
  10687. case 0x8b54:
  10688. case 0x8b58:
  10689. return setValueV3i;
  10690. // _VEC3
  10691. case 0x8b55:
  10692. case 0x8b59:
  10693. return setValueV4i;
  10694. // _VEC4
  10695. case 0x1405:
  10696. return setValueV1ui;
  10697. // UINT
  10698. case 0x8b5e: // SAMPLER_2D
  10699. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10700. case 0x8dca: // INT_SAMPLER_2D
  10701. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10702. case 0x8b62:
  10703. // SAMPLER_2D_SHADOW
  10704. return setValueT1;
  10705. case 0x8b5f: // SAMPLER_3D
  10706. case 0x8dcb: // INT_SAMPLER_3D
  10707. case 0x8dd3:
  10708. // UNSIGNED_INT_SAMPLER_3D
  10709. return setValueT3D1;
  10710. case 0x8b60: // SAMPLER_CUBE
  10711. case 0x8dcc: // INT_SAMPLER_CUBE
  10712. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10713. case 0x8dc5:
  10714. // SAMPLER_CUBE_SHADOW
  10715. return setValueT6;
  10716. case 0x8dc1: // SAMPLER_2D_ARRAY
  10717. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10718. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10719. case 0x8dc4:
  10720. // SAMPLER_2D_ARRAY_SHADOW
  10721. return setValueT2DArray1;
  10722. }
  10723. } // Array of scalars
  10724. function setValueV1fArray(gl, v) {
  10725. gl.uniform1fv(this.addr, v);
  10726. } // Integer / Boolean vectors or arrays thereof (always flat arrays)
  10727. function setValueV1iArray(gl, v) {
  10728. gl.uniform1iv(this.addr, v);
  10729. }
  10730. function setValueV2iArray(gl, v) {
  10731. gl.uniform2iv(this.addr, v);
  10732. }
  10733. function setValueV3iArray(gl, v) {
  10734. gl.uniform3iv(this.addr, v);
  10735. }
  10736. function setValueV4iArray(gl, v) {
  10737. gl.uniform4iv(this.addr, v);
  10738. } // Array of vectors (flat or from THREE classes)
  10739. function setValueV2fArray(gl, v) {
  10740. const data = flatten(v, this.size, 2);
  10741. gl.uniform2fv(this.addr, data);
  10742. }
  10743. function setValueV3fArray(gl, v) {
  10744. const data = flatten(v, this.size, 3);
  10745. gl.uniform3fv(this.addr, data);
  10746. }
  10747. function setValueV4fArray(gl, v) {
  10748. const data = flatten(v, this.size, 4);
  10749. gl.uniform4fv(this.addr, data);
  10750. } // Array of matrices (flat or from THREE clases)
  10751. function setValueM2Array(gl, v) {
  10752. const data = flatten(v, this.size, 4);
  10753. gl.uniformMatrix2fv(this.addr, false, data);
  10754. }
  10755. function setValueM3Array(gl, v) {
  10756. const data = flatten(v, this.size, 9);
  10757. gl.uniformMatrix3fv(this.addr, false, data);
  10758. }
  10759. function setValueM4Array(gl, v) {
  10760. const data = flatten(v, this.size, 16);
  10761. gl.uniformMatrix4fv(this.addr, false, data);
  10762. } // Array of textures (2D / Cube)
  10763. function setValueT1Array(gl, v, textures) {
  10764. const n = v.length;
  10765. const units = allocTexUnits(textures, n);
  10766. gl.uniform1iv(this.addr, units);
  10767. for (let i = 0; i !== n; ++i) {
  10768. textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
  10769. }
  10770. }
  10771. function setValueT6Array(gl, v, textures) {
  10772. const n = v.length;
  10773. const units = allocTexUnits(textures, n);
  10774. gl.uniform1iv(this.addr, units);
  10775. for (let i = 0; i !== n; ++i) {
  10776. textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
  10777. }
  10778. } // Helper to pick the right setter for a pure (bottom-level) array
  10779. function getPureArraySetter(type) {
  10780. switch (type) {
  10781. case 0x1406:
  10782. return setValueV1fArray;
  10783. // FLOAT
  10784. case 0x8b50:
  10785. return setValueV2fArray;
  10786. // _VEC2
  10787. case 0x8b51:
  10788. return setValueV3fArray;
  10789. // _VEC3
  10790. case 0x8b52:
  10791. return setValueV4fArray;
  10792. // _VEC4
  10793. case 0x8b5a:
  10794. return setValueM2Array;
  10795. // _MAT2
  10796. case 0x8b5b:
  10797. return setValueM3Array;
  10798. // _MAT3
  10799. case 0x8b5c:
  10800. return setValueM4Array;
  10801. // _MAT4
  10802. case 0x1404:
  10803. case 0x8b56:
  10804. return setValueV1iArray;
  10805. // INT, BOOL
  10806. case 0x8b53:
  10807. case 0x8b57:
  10808. return setValueV2iArray;
  10809. // _VEC2
  10810. case 0x8b54:
  10811. case 0x8b58:
  10812. return setValueV3iArray;
  10813. // _VEC3
  10814. case 0x8b55:
  10815. case 0x8b59:
  10816. return setValueV4iArray;
  10817. // _VEC4
  10818. case 0x8b5e: // SAMPLER_2D
  10819. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10820. case 0x8dca: // INT_SAMPLER_2D
  10821. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10822. case 0x8b62:
  10823. // SAMPLER_2D_SHADOW
  10824. return setValueT1Array;
  10825. case 0x8b60: // SAMPLER_CUBE
  10826. case 0x8dcc: // INT_SAMPLER_CUBE
  10827. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10828. case 0x8dc5:
  10829. // SAMPLER_CUBE_SHADOW
  10830. return setValueT6Array;
  10831. }
  10832. } // --- Uniform Classes ---
  10833. function SingleUniform(id, activeInfo, addr) {
  10834. this.id = id;
  10835. this.addr = addr;
  10836. this.cache = [];
  10837. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  10838. }
  10839. function PureArrayUniform(id, activeInfo, addr) {
  10840. this.id = id;
  10841. this.addr = addr;
  10842. this.cache = [];
  10843. this.size = activeInfo.size;
  10844. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  10845. }
  10846. PureArrayUniform.prototype.updateCache = function (data) {
  10847. const cache = this.cache;
  10848. if (data instanceof Float32Array && cache.length !== data.length) {
  10849. this.cache = new Float32Array(data.length);
  10850. }
  10851. copyArray(cache, data);
  10852. };
  10853. function StructuredUniform(id) {
  10854. this.id = id;
  10855. this.seq = [];
  10856. this.map = {};
  10857. }
  10858. StructuredUniform.prototype.setValue = function (gl, value, textures) {
  10859. const seq = this.seq;
  10860. for (let i = 0, n = seq.length; i !== n; ++i) {
  10861. const u = seq[i];
  10862. u.setValue(gl, value[u.id], textures);
  10863. }
  10864. }; // --- Top-level ---
  10865. // Parser - builds up the property tree from the path strings
  10866. const RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g; // extracts
  10867. // - the identifier (member name or array index)
  10868. // - followed by an optional right bracket (found when array index)
  10869. // - followed by an optional left bracket or dot (type of subscript)
  10870. //
  10871. // Note: These portions can be read in a non-overlapping fashion and
  10872. // allow straightforward parsing of the hierarchy that WebGL encodes
  10873. // in the uniform names.
  10874. function addUniform(container, uniformObject) {
  10875. container.seq.push(uniformObject);
  10876. container.map[uniformObject.id] = uniformObject;
  10877. }
  10878. function parseUniform(activeInfo, addr, container) {
  10879. const path = activeInfo.name,
  10880. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  10881. RePathPart.lastIndex = 0;
  10882. while (true) {
  10883. const match = RePathPart.exec(path),
  10884. matchEnd = RePathPart.lastIndex;
  10885. let id = match[1];
  10886. const idIsIndex = match[2] === ']',
  10887. subscript = match[3];
  10888. if (idIsIndex) id = id | 0; // convert to integer
  10889. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  10890. // bare name or "pure" bottom-level array "[0]" suffix
  10891. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  10892. break;
  10893. } else {
  10894. // step into inner node / create it in case it doesn't exist
  10895. const map = container.map;
  10896. let next = map[id];
  10897. if (next === undefined) {
  10898. next = new StructuredUniform(id);
  10899. addUniform(container, next);
  10900. }
  10901. container = next;
  10902. }
  10903. }
  10904. } // Root Container
  10905. function WebGLUniforms(gl, program) {
  10906. this.seq = [];
  10907. this.map = {};
  10908. const n = gl.getProgramParameter(program, 35718);
  10909. for (let i = 0; i < n; ++i) {
  10910. const info = gl.getActiveUniform(program, i),
  10911. addr = gl.getUniformLocation(program, info.name);
  10912. parseUniform(info, addr, this);
  10913. }
  10914. }
  10915. WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
  10916. const u = this.map[name];
  10917. if (u !== undefined) u.setValue(gl, value, textures);
  10918. };
  10919. WebGLUniforms.prototype.setOptional = function (gl, object, name) {
  10920. const v = object[name];
  10921. if (v !== undefined) this.setValue(gl, name, v);
  10922. }; // Static interface
  10923. WebGLUniforms.upload = function (gl, seq, values, textures) {
  10924. for (let i = 0, n = seq.length; i !== n; ++i) {
  10925. const u = seq[i],
  10926. v = values[u.id];
  10927. if (v.needsUpdate !== false) {
  10928. // note: always updating when .needsUpdate is undefined
  10929. u.setValue(gl, v.value, textures);
  10930. }
  10931. }
  10932. };
  10933. WebGLUniforms.seqWithValue = function (seq, values) {
  10934. const r = [];
  10935. for (let i = 0, n = seq.length; i !== n; ++i) {
  10936. const u = seq[i];
  10937. if (u.id in values) r.push(u);
  10938. }
  10939. return r;
  10940. };
  10941. function WebGLShader(gl, type, string) {
  10942. const shader = gl.createShader(type);
  10943. gl.shaderSource(shader, string);
  10944. gl.compileShader(shader);
  10945. return shader;
  10946. }
  10947. let programIdCount = 0;
  10948. function addLineNumbers(string) {
  10949. const lines = string.split('\n');
  10950. for (let i = 0; i < lines.length; i++) {
  10951. lines[i] = i + 1 + ': ' + lines[i];
  10952. }
  10953. return lines.join('\n');
  10954. }
  10955. function getEncodingComponents(encoding) {
  10956. switch (encoding) {
  10957. case LinearEncoding:
  10958. return ['Linear', '( value )'];
  10959. case sRGBEncoding:
  10960. return ['sRGB', '( value )'];
  10961. case RGBEEncoding:
  10962. return ['RGBE', '( value )'];
  10963. case RGBM7Encoding:
  10964. return ['RGBM', '( value, 7.0 )'];
  10965. case RGBM16Encoding:
  10966. return ['RGBM', '( value, 16.0 )'];
  10967. case RGBDEncoding:
  10968. return ['RGBD', '( value, 256.0 )'];
  10969. case GammaEncoding:
  10970. return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
  10971. case LogLuvEncoding:
  10972. return ['LogLuv', '( value )'];
  10973. default:
  10974. console.warn('THREE.WebGLProgram: Unsupported encoding:', encoding);
  10975. return ['Linear', '( value )'];
  10976. }
  10977. }
  10978. function getShaderErrors(gl, shader, type) {
  10979. const status = gl.getShaderParameter(shader, 35713);
  10980. const log = gl.getShaderInfoLog(shader).trim();
  10981. if (status && log === '') return ''; // --enable-privileged-webgl-extension
  10982. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  10983. const source = gl.getShaderSource(shader);
  10984. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers(source);
  10985. }
  10986. function getTexelDecodingFunction(functionName, encoding) {
  10987. const components = getEncodingComponents(encoding);
  10988. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
  10989. }
  10990. function getTexelEncodingFunction(functionName, encoding) {
  10991. const components = getEncodingComponents(encoding);
  10992. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  10993. }
  10994. function getToneMappingFunction(functionName, toneMapping) {
  10995. let toneMappingName;
  10996. switch (toneMapping) {
  10997. case LinearToneMapping:
  10998. toneMappingName = 'Linear';
  10999. break;
  11000. case ReinhardToneMapping:
  11001. toneMappingName = 'Reinhard';
  11002. break;
  11003. case CineonToneMapping:
  11004. toneMappingName = 'OptimizedCineon';
  11005. break;
  11006. case ACESFilmicToneMapping:
  11007. toneMappingName = 'ACESFilmic';
  11008. break;
  11009. case CustomToneMapping:
  11010. toneMappingName = 'Custom';
  11011. break;
  11012. default:
  11013. console.warn('THREE.WebGLProgram: Unsupported toneMapping:', toneMapping);
  11014. toneMappingName = 'Linear';
  11015. }
  11016. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11017. }
  11018. function generateExtensions(parameters) {
  11019. const chunks = [parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ? '#extension GL_OES_standard_derivatives : enable' : '', (parameters.extensionFragDepth || parameters.logarithmicDepthBuffer) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '', parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ? '#extension GL_EXT_draw_buffers : require' : '', (parameters.extensionShaderTextureLOD || parameters.envMap) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''];
  11020. return chunks.filter(filterEmptyLine).join('\n');
  11021. }
  11022. function generateDefines(defines) {
  11023. const chunks = [];
  11024. for (const name in defines) {
  11025. const value = defines[name];
  11026. if (value === false) continue;
  11027. chunks.push('#define ' + name + ' ' + value);
  11028. }
  11029. return chunks.join('\n');
  11030. }
  11031. function fetchAttributeLocations(gl, program) {
  11032. const attributes = {};
  11033. const n = gl.getProgramParameter(program, 35721);
  11034. for (let i = 0; i < n; i++) {
  11035. const info = gl.getActiveAttrib(program, i);
  11036. const name = info.name; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11037. attributes[name] = gl.getAttribLocation(program, name);
  11038. }
  11039. return attributes;
  11040. }
  11041. function filterEmptyLine(string) {
  11042. return string !== '';
  11043. }
  11044. function replaceLightNums(string, parameters) {
  11045. 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);
  11046. }
  11047. function replaceClippingPlaneNums(string, parameters) {
  11048. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  11049. } // Resolve Includes
  11050. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11051. function resolveIncludes(string) {
  11052. return string.replace(includePattern, includeReplacer);
  11053. }
  11054. function includeReplacer(match, include) {
  11055. const string = ShaderChunk[include];
  11056. if (string === undefined) {
  11057. throw new Error('Can not resolve #include <' + include + '>');
  11058. }
  11059. return resolveIncludes(string);
  11060. } // Unroll Loops
  11061. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  11062. const unrollLoopPattern = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;
  11063. function unrollLoops(string) {
  11064. return string.replace(unrollLoopPattern, loopReplacer).replace(deprecatedUnrollLoopPattern, deprecatedLoopReplacer);
  11065. }
  11066. function deprecatedLoopReplacer(match, start, end, snippet) {
  11067. console.warn('WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.');
  11068. return loopReplacer(match, start, end, snippet);
  11069. }
  11070. function loopReplacer(match, start, end, snippet) {
  11071. let string = '';
  11072. for (let i = parseInt(start); i < parseInt(end); i++) {
  11073. string += snippet.replace(/\[\s*i\s*\]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  11074. }
  11075. return string;
  11076. } //
  11077. function generatePrecision(parameters) {
  11078. let precisionstring = "precision " + parameters.precision + " float;\nprecision " + parameters.precision + " int;";
  11079. if (parameters.precision === "highp") {
  11080. precisionstring += "\n#define HIGH_PRECISION";
  11081. } else if (parameters.precision === "mediump") {
  11082. precisionstring += "\n#define MEDIUM_PRECISION";
  11083. } else if (parameters.precision === "lowp") {
  11084. precisionstring += "\n#define LOW_PRECISION";
  11085. }
  11086. return precisionstring;
  11087. }
  11088. function generateShadowMapTypeDefine(parameters) {
  11089. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11090. if (parameters.shadowMapType === PCFShadowMap) {
  11091. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11092. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  11093. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11094. } else if (parameters.shadowMapType === VSMShadowMap) {
  11095. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11096. }
  11097. return shadowMapTypeDefine;
  11098. }
  11099. function generateEnvMapTypeDefine(parameters) {
  11100. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11101. if (parameters.envMap) {
  11102. switch (parameters.envMapMode) {
  11103. case CubeReflectionMapping:
  11104. case CubeRefractionMapping:
  11105. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11106. break;
  11107. case CubeUVReflectionMapping:
  11108. case CubeUVRefractionMapping:
  11109. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11110. break;
  11111. }
  11112. }
  11113. return envMapTypeDefine;
  11114. }
  11115. function generateEnvMapModeDefine(parameters) {
  11116. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11117. if (parameters.envMap) {
  11118. switch (parameters.envMapMode) {
  11119. case CubeRefractionMapping:
  11120. case CubeUVRefractionMapping:
  11121. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11122. break;
  11123. }
  11124. }
  11125. return envMapModeDefine;
  11126. }
  11127. function generateEnvMapBlendingDefine(parameters) {
  11128. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11129. if (parameters.envMap) {
  11130. switch (parameters.combine) {
  11131. case MultiplyOperation:
  11132. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11133. break;
  11134. case MixOperation:
  11135. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11136. break;
  11137. case AddOperation:
  11138. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11139. break;
  11140. }
  11141. }
  11142. return envMapBlendingDefine;
  11143. }
  11144. function WebGLProgram(renderer, cacheKey, parameters, bindingStates) {
  11145. const gl = renderer.getContext();
  11146. const defines = parameters.defines;
  11147. let vertexShader = parameters.vertexShader;
  11148. let fragmentShader = parameters.fragmentShader;
  11149. const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  11150. const envMapTypeDefine = generateEnvMapTypeDefine(parameters);
  11151. const envMapModeDefine = generateEnvMapModeDefine(parameters);
  11152. const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
  11153. const gammaFactorDefine = renderer.gammaFactor > 0 ? renderer.gammaFactor : 1.0;
  11154. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters);
  11155. const customDefines = generateDefines(defines);
  11156. const program = gl.createProgram();
  11157. let prefixVertex, prefixFragment;
  11158. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + "\n" : '';
  11159. if (parameters.isRawShaderMaterial) {
  11160. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  11161. if (prefixVertex.length > 0) {
  11162. prefixVertex += '\n';
  11163. }
  11164. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  11165. if (prefixFragment.length > 0) {
  11166. prefixFragment += '\n';
  11167. }
  11168. } else {
  11169. prefixVertex = [generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.instancing ? '#define USE_INSTANCING' : '', parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '', parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', '#define GAMMA_FACTOR ' + gammaFactorDefine, '#define MAX_BONES ' + parameters.maxBones, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors ? '#define USE_COLOR' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.skinning ? '#define USE_SKINNING' : '', parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', 'uniform mat4 modelMatrix;', 'uniform mat4 modelViewMatrix;', 'uniform mat4 projectionMatrix;', 'uniform mat4 viewMatrix;', 'uniform mat3 normalMatrix;', 'uniform vec3 cameraPosition;', 'uniform bool isOrthographic;', '#ifdef USE_INSTANCING', ' attribute mat4 instanceMatrix;', '#endif', '#ifdef USE_INSTANCING_COLOR', ' attribute vec3 instanceColor;', '#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');
  11170. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + (parameters.alphaTest % 1 ? '' : '.0') : '', // add '.0' if integer
  11171. '#define GAMMA_FACTOR ' + gammaFactorDefine, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.matcap ? '#define USE_MATCAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapTypeDefine : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.envMap ? '#define ' + envMapBlendingDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.sheen ? '#define USE_SHEEN' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.gradientMap ? '#define USE_GRADIENTMAP' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '', parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', (parameters.extensionShaderTextureLOD || parameters.envMap) && parameters.rendererExtensionShaderTextureLod ? '#define TEXTURE_LOD_EXT' : '', 'uniform mat4 viewMatrix;', 'uniform vec3 cameraPosition;', 'uniform bool isOrthographic;', parameters.toneMapping !== NoToneMapping ? '#define TONE_MAPPING' : '', parameters.toneMapping !== NoToneMapping ? ShaderChunk['tonemapping_pars_fragment'] : '', // this code is required here because it is used by the toneMapping() function defined below
  11172. parameters.toneMapping !== NoToneMapping ? getToneMappingFunction('toneMapping', parameters.toneMapping) : '', parameters.dithering ? '#define DITHERING' : '', ShaderChunk['encodings_pars_fragment'], // this code is required here because it is used by the various encoding/decoding function defined below
  11173. parameters.map ? getTexelDecodingFunction('mapTexelToLinear', parameters.mapEncoding) : '', parameters.matcap ? getTexelDecodingFunction('matcapTexelToLinear', parameters.matcapEncoding) : '', parameters.envMap ? getTexelDecodingFunction('envMapTexelToLinear', parameters.envMapEncoding) : '', parameters.emissiveMap ? getTexelDecodingFunction('emissiveMapTexelToLinear', parameters.emissiveMapEncoding) : '', parameters.lightMap ? getTexelDecodingFunction('lightMapTexelToLinear', parameters.lightMapEncoding) : '', getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding), parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');
  11174. }
  11175. vertexShader = resolveIncludes(vertexShader);
  11176. vertexShader = replaceLightNums(vertexShader, parameters);
  11177. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  11178. fragmentShader = resolveIncludes(fragmentShader);
  11179. fragmentShader = replaceLightNums(fragmentShader, parameters);
  11180. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  11181. vertexShader = unrollLoops(vertexShader);
  11182. fragmentShader = unrollLoops(fragmentShader);
  11183. if (parameters.isWebGL2 && parameters.isRawShaderMaterial !== true) {
  11184. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11185. versionString = '#version 300 es\n';
  11186. prefixVertex = ['#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  11187. prefixFragment = ['#define varying in', parameters.glslVersion === GLSL3 ? '' : 'out highp vec4 pc_fragColor;', parameters.glslVersion === GLSL3 ? '' : '#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;
  11188. }
  11189. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11190. const fragmentGlsl = versionString + prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  11191. // console.log( '*FRAGMENT*', fragmentGlsl );
  11192. const glVertexShader = WebGLShader(gl, 35633, vertexGlsl);
  11193. const glFragmentShader = WebGLShader(gl, 35632, fragmentGlsl);
  11194. gl.attachShader(program, glVertexShader);
  11195. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  11196. if (parameters.index0AttributeName !== undefined) {
  11197. gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
  11198. } else if (parameters.morphTargets === true) {
  11199. // programs with morphTargets displace position out of attribute 0
  11200. gl.bindAttribLocation(program, 0, 'position');
  11201. }
  11202. gl.linkProgram(program); // check for link errors
  11203. if (renderer.debug.checkShaderErrors) {
  11204. const programLog = gl.getProgramInfoLog(program).trim();
  11205. const vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  11206. const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  11207. let runnable = true;
  11208. let haveDiagnostics = true;
  11209. if (gl.getProgramParameter(program, 35714) === false) {
  11210. runnable = false;
  11211. const vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  11212. const fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  11213. console.error('THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter(program, 35715), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors);
  11214. } else if (programLog !== '') {
  11215. console.warn('THREE.WebGLProgram: gl.getProgramInfoLog()', programLog);
  11216. } else if (vertexLog === '' || fragmentLog === '') {
  11217. haveDiagnostics = false;
  11218. }
  11219. if (haveDiagnostics) {
  11220. this.diagnostics = {
  11221. runnable: runnable,
  11222. programLog: programLog,
  11223. vertexShader: {
  11224. log: vertexLog,
  11225. prefix: prefixVertex
  11226. },
  11227. fragmentShader: {
  11228. log: fragmentLog,
  11229. prefix: prefixFragment
  11230. }
  11231. };
  11232. }
  11233. } // Clean up
  11234. // Crashes in iOS9 and iOS10. #18402
  11235. // gl.detachShader( program, glVertexShader );
  11236. // gl.detachShader( program, glFragmentShader );
  11237. gl.deleteShader(glVertexShader);
  11238. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  11239. let cachedUniforms;
  11240. this.getUniforms = function () {
  11241. if (cachedUniforms === undefined) {
  11242. cachedUniforms = new WebGLUniforms(gl, program);
  11243. }
  11244. return cachedUniforms;
  11245. }; // set up caching for attribute locations
  11246. let cachedAttributes;
  11247. this.getAttributes = function () {
  11248. if (cachedAttributes === undefined) {
  11249. cachedAttributes = fetchAttributeLocations(gl, program);
  11250. }
  11251. return cachedAttributes;
  11252. }; // free resource
  11253. this.destroy = function () {
  11254. bindingStates.releaseStatesOfProgram(this);
  11255. gl.deleteProgram(program);
  11256. this.program = undefined;
  11257. }; //
  11258. this.name = parameters.shaderName;
  11259. this.id = programIdCount++;
  11260. this.cacheKey = cacheKey;
  11261. this.usedTimes = 1;
  11262. this.program = program;
  11263. this.vertexShader = glVertexShader;
  11264. this.fragmentShader = glFragmentShader;
  11265. return this;
  11266. }
  11267. function WebGLPrograms(renderer, cubemaps, extensions, capabilities, bindingStates, clipping) {
  11268. const programs = [];
  11269. const isWebGL2 = capabilities.isWebGL2;
  11270. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11271. const floatVertexTextures = capabilities.floatVertexTextures;
  11272. const maxVertexUniforms = capabilities.maxVertexUniforms;
  11273. const vertexTextures = capabilities.vertexTextures;
  11274. let precision = capabilities.precision;
  11275. const shaderIDs = {
  11276. MeshDepthMaterial: 'depth',
  11277. MeshDistanceMaterial: 'distanceRGBA',
  11278. MeshNormalMaterial: 'normal',
  11279. MeshBasicMaterial: 'basic',
  11280. MeshLambertMaterial: 'lambert',
  11281. MeshPhongMaterial: 'phong',
  11282. MeshToonMaterial: 'toon',
  11283. MeshStandardMaterial: 'physical',
  11284. MeshPhysicalMaterial: 'physical',
  11285. MeshMatcapMaterial: 'matcap',
  11286. LineBasicMaterial: 'basic',
  11287. LineDashedMaterial: 'dashed',
  11288. PointsMaterial: 'points',
  11289. ShadowMaterial: 'shadow',
  11290. SpriteMaterial: 'sprite'
  11291. };
  11292. const parameterNames = ["precision", "isWebGL2", "supportsVertexTextures", "outputEncoding", "instancing", "instancingColor", "map", "mapEncoding", "matcap", "matcapEncoding", "envMap", "envMapMode", "envMapEncoding", "envMapCubeUV", "lightMap", "lightMapEncoding", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "objectSpaceNormalMap", "tangentSpaceNormalMap", "clearcoatMap", "clearcoatRoughnessMap", "clearcoatNormalMap", "displacementMap", "specularMap", "roughnessMap", "metalnessMap", "gradientMap", "alphaMap", "combine", "vertexColors", "vertexTangents", "vertexUvs", "uvsVertexOnly", "fog", "useFog", "fogExp2", "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning", "maxBones", "useVertexTexture", "morphTargets", "morphNormals", "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha", "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights", "numDirLightShadows", "numPointLightShadows", "numSpotLightShadows", "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights', "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering", "sheen", "transmissionMap"];
  11293. function getMaxBones(object) {
  11294. const skeleton = object.skeleton;
  11295. const bones = skeleton.bones;
  11296. if (floatVertexTextures) {
  11297. return 1024;
  11298. } else {
  11299. // default for when object is not specified
  11300. // ( for example when prebuilding shader to be used with multiple objects )
  11301. //
  11302. // - leave some extra space for other uniforms
  11303. // - limit here is ANGLE's 254 max uniform vectors
  11304. // (up to 54 should be safe)
  11305. const nVertexUniforms = maxVertexUniforms;
  11306. const nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
  11307. const maxBones = Math.min(nVertexMatrices, bones.length);
  11308. if (maxBones < bones.length) {
  11309. console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
  11310. return 0;
  11311. }
  11312. return maxBones;
  11313. }
  11314. }
  11315. function getTextureEncodingFromMap(map) {
  11316. let encoding;
  11317. if (!map) {
  11318. encoding = LinearEncoding;
  11319. } else if (map.isTexture) {
  11320. encoding = map.encoding;
  11321. } else if (map.isWebGLRenderTarget) {
  11322. console.warn("THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead.");
  11323. encoding = map.texture.encoding;
  11324. }
  11325. return encoding;
  11326. }
  11327. function getParameters(material, lights, shadows, scene, object) {
  11328. const fog = scene.fog;
  11329. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11330. const envMap = cubemaps.get(material.envMap || environment);
  11331. const shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  11332. // (not to blow over maxLights budget)
  11333. const maxBones = object.isSkinnedMesh ? getMaxBones(object) : 0;
  11334. if (material.precision !== null) {
  11335. precision = capabilities.getMaxPrecision(material.precision);
  11336. if (precision !== material.precision) {
  11337. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  11338. }
  11339. }
  11340. let vertexShader, fragmentShader;
  11341. if (shaderID) {
  11342. const shader = ShaderLib[shaderID];
  11343. vertexShader = shader.vertexShader;
  11344. fragmentShader = shader.fragmentShader;
  11345. } else {
  11346. vertexShader = material.vertexShader;
  11347. fragmentShader = material.fragmentShader;
  11348. }
  11349. const currentRenderTarget = renderer.getRenderTarget();
  11350. const parameters = {
  11351. isWebGL2: isWebGL2,
  11352. shaderID: shaderID,
  11353. shaderName: material.type,
  11354. vertexShader: vertexShader,
  11355. fragmentShader: fragmentShader,
  11356. defines: material.defines,
  11357. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11358. glslVersion: material.glslVersion,
  11359. precision: precision,
  11360. instancing: object.isInstancedMesh === true,
  11361. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11362. supportsVertexTextures: vertexTextures,
  11363. outputEncoding: currentRenderTarget !== null ? getTextureEncodingFromMap(currentRenderTarget.texture) : renderer.outputEncoding,
  11364. map: !!material.map,
  11365. mapEncoding: getTextureEncodingFromMap(material.map),
  11366. matcap: !!material.matcap,
  11367. matcapEncoding: getTextureEncodingFromMap(material.matcap),
  11368. envMap: !!envMap,
  11369. envMapMode: envMap && envMap.mapping,
  11370. envMapEncoding: getTextureEncodingFromMap(envMap),
  11371. envMapCubeUV: !!envMap && (envMap.mapping === CubeUVReflectionMapping || envMap.mapping === CubeUVRefractionMapping),
  11372. lightMap: !!material.lightMap,
  11373. lightMapEncoding: getTextureEncodingFromMap(material.lightMap),
  11374. aoMap: !!material.aoMap,
  11375. emissiveMap: !!material.emissiveMap,
  11376. emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap),
  11377. bumpMap: !!material.bumpMap,
  11378. normalMap: !!material.normalMap,
  11379. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11380. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11381. clearcoatMap: !!material.clearcoatMap,
  11382. clearcoatRoughnessMap: !!material.clearcoatRoughnessMap,
  11383. clearcoatNormalMap: !!material.clearcoatNormalMap,
  11384. displacementMap: !!material.displacementMap,
  11385. roughnessMap: !!material.roughnessMap,
  11386. metalnessMap: !!material.metalnessMap,
  11387. specularMap: !!material.specularMap,
  11388. alphaMap: !!material.alphaMap,
  11389. gradientMap: !!material.gradientMap,
  11390. sheen: !!material.sheen,
  11391. transmissionMap: !!material.transmissionMap,
  11392. combine: material.combine,
  11393. vertexTangents: material.normalMap && material.vertexTangents,
  11394. vertexColors: material.vertexColors,
  11395. vertexUvs: !!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatMap || !!material.clearcoatRoughnessMap || !!material.clearcoatNormalMap || !!material.displacementMap || !!material.transmissionMap,
  11396. uvsVertexOnly: !(!!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap || !!material.transmissionMap) && !!material.displacementMap,
  11397. fog: !!fog,
  11398. useFog: material.fog,
  11399. fogExp2: fog && fog.isFogExp2,
  11400. flatShading: material.flatShading,
  11401. sizeAttenuation: material.sizeAttenuation,
  11402. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11403. skinning: material.skinning && maxBones > 0,
  11404. maxBones: maxBones,
  11405. useVertexTexture: floatVertexTextures,
  11406. morphTargets: material.morphTargets,
  11407. morphNormals: material.morphNormals,
  11408. maxMorphTargets: renderer.maxMorphTargets,
  11409. maxMorphNormals: renderer.maxMorphNormals,
  11410. numDirLights: lights.directional.length,
  11411. numPointLights: lights.point.length,
  11412. numSpotLights: lights.spot.length,
  11413. numRectAreaLights: lights.rectArea.length,
  11414. numHemiLights: lights.hemi.length,
  11415. numDirLightShadows: lights.directionalShadowMap.length,
  11416. numPointLightShadows: lights.pointShadowMap.length,
  11417. numSpotLightShadows: lights.spotShadowMap.length,
  11418. numClippingPlanes: clipping.numPlanes,
  11419. numClipIntersection: clipping.numIntersection,
  11420. dithering: material.dithering,
  11421. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11422. shadowMapType: renderer.shadowMap.type,
  11423. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11424. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11425. premultipliedAlpha: material.premultipliedAlpha,
  11426. alphaTest: material.alphaTest,
  11427. doubleSided: material.side === DoubleSide,
  11428. flipSided: material.side === BackSide,
  11429. depthPacking: material.depthPacking !== undefined ? material.depthPacking : false,
  11430. index0AttributeName: material.index0AttributeName,
  11431. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11432. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11433. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11434. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11435. rendererExtensionFragDepth: isWebGL2 || extensions.has('EXT_frag_depth'),
  11436. rendererExtensionDrawBuffers: isWebGL2 || extensions.has('WEBGL_draw_buffers'),
  11437. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has('EXT_shader_texture_lod'),
  11438. customProgramCacheKey: material.customProgramCacheKey()
  11439. };
  11440. return parameters;
  11441. }
  11442. function getProgramCacheKey(parameters) {
  11443. const array = [];
  11444. if (parameters.shaderID) {
  11445. array.push(parameters.shaderID);
  11446. } else {
  11447. array.push(parameters.fragmentShader);
  11448. array.push(parameters.vertexShader);
  11449. }
  11450. if (parameters.defines !== undefined) {
  11451. for (const name in parameters.defines) {
  11452. array.push(name);
  11453. array.push(parameters.defines[name]);
  11454. }
  11455. }
  11456. if (parameters.isRawShaderMaterial === false) {
  11457. for (let i = 0; i < parameterNames.length; i++) {
  11458. array.push(parameters[parameterNames[i]]);
  11459. }
  11460. array.push(renderer.outputEncoding);
  11461. array.push(renderer.gammaFactor);
  11462. }
  11463. array.push(parameters.customProgramCacheKey);
  11464. return array.join();
  11465. }
  11466. function getUniforms(material) {
  11467. const shaderID = shaderIDs[material.type];
  11468. let uniforms;
  11469. if (shaderID) {
  11470. const shader = ShaderLib[shaderID];
  11471. uniforms = UniformsUtils.clone(shader.uniforms);
  11472. } else {
  11473. uniforms = material.uniforms;
  11474. }
  11475. return uniforms;
  11476. }
  11477. function acquireProgram(parameters, cacheKey) {
  11478. let program; // Check if code has been already compiled
  11479. for (let p = 0, pl = programs.length; p < pl; p++) {
  11480. const preexistingProgram = programs[p];
  11481. if (preexistingProgram.cacheKey === cacheKey) {
  11482. program = preexistingProgram;
  11483. ++program.usedTimes;
  11484. break;
  11485. }
  11486. }
  11487. if (program === undefined) {
  11488. program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates);
  11489. programs.push(program);
  11490. }
  11491. return program;
  11492. }
  11493. function releaseProgram(program) {
  11494. if (--program.usedTimes === 0) {
  11495. // Remove from unordered set
  11496. const i = programs.indexOf(program);
  11497. programs[i] = programs[programs.length - 1];
  11498. programs.pop(); // Free WebGL resources
  11499. program.destroy();
  11500. }
  11501. }
  11502. return {
  11503. getParameters: getParameters,
  11504. getProgramCacheKey: getProgramCacheKey,
  11505. getUniforms: getUniforms,
  11506. acquireProgram: acquireProgram,
  11507. releaseProgram: releaseProgram,
  11508. // Exposed for resource monitoring & error feedback via renderer.info:
  11509. programs: programs
  11510. };
  11511. }
  11512. function WebGLProperties() {
  11513. let properties = new WeakMap();
  11514. function get(object) {
  11515. let map = properties.get(object);
  11516. if (map === undefined) {
  11517. map = {};
  11518. properties.set(object, map);
  11519. }
  11520. return map;
  11521. }
  11522. function remove(object) {
  11523. properties.delete(object);
  11524. }
  11525. function update(object, key, value) {
  11526. properties.get(object)[key] = value;
  11527. }
  11528. function dispose() {
  11529. properties = new WeakMap();
  11530. }
  11531. return {
  11532. get: get,
  11533. remove: remove,
  11534. update: update,
  11535. dispose: dispose
  11536. };
  11537. }
  11538. function painterSortStable(a, b) {
  11539. if (a.groupOrder !== b.groupOrder) {
  11540. return a.groupOrder - b.groupOrder;
  11541. } else if (a.renderOrder !== b.renderOrder) {
  11542. return a.renderOrder - b.renderOrder;
  11543. } else if (a.program !== b.program) {
  11544. return a.program.id - b.program.id;
  11545. } else if (a.material.id !== b.material.id) {
  11546. return a.material.id - b.material.id;
  11547. } else if (a.z !== b.z) {
  11548. return a.z - b.z;
  11549. } else {
  11550. return a.id - b.id;
  11551. }
  11552. }
  11553. function reversePainterSortStable(a, b) {
  11554. if (a.groupOrder !== b.groupOrder) {
  11555. return a.groupOrder - b.groupOrder;
  11556. } else if (a.renderOrder !== b.renderOrder) {
  11557. return a.renderOrder - b.renderOrder;
  11558. } else if (a.z !== b.z) {
  11559. return b.z - a.z;
  11560. } else {
  11561. return a.id - b.id;
  11562. }
  11563. }
  11564. function WebGLRenderList(properties) {
  11565. const renderItems = [];
  11566. let renderItemsIndex = 0;
  11567. const opaque = [];
  11568. const transparent = [];
  11569. const defaultProgram = {
  11570. id: -1
  11571. };
  11572. function init() {
  11573. renderItemsIndex = 0;
  11574. opaque.length = 0;
  11575. transparent.length = 0;
  11576. }
  11577. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  11578. let renderItem = renderItems[renderItemsIndex];
  11579. const materialProperties = properties.get(material);
  11580. if (renderItem === undefined) {
  11581. renderItem = {
  11582. id: object.id,
  11583. object: object,
  11584. geometry: geometry,
  11585. material: material,
  11586. program: materialProperties.program || defaultProgram,
  11587. groupOrder: groupOrder,
  11588. renderOrder: object.renderOrder,
  11589. z: z,
  11590. group: group
  11591. };
  11592. renderItems[renderItemsIndex] = renderItem;
  11593. } else {
  11594. renderItem.id = object.id;
  11595. renderItem.object = object;
  11596. renderItem.geometry = geometry;
  11597. renderItem.material = material;
  11598. renderItem.program = materialProperties.program || defaultProgram;
  11599. renderItem.groupOrder = groupOrder;
  11600. renderItem.renderOrder = object.renderOrder;
  11601. renderItem.z = z;
  11602. renderItem.group = group;
  11603. }
  11604. renderItemsIndex++;
  11605. return renderItem;
  11606. }
  11607. function push(object, geometry, material, groupOrder, z, group) {
  11608. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  11609. (material.transparent === true ? transparent : opaque).push(renderItem);
  11610. }
  11611. function unshift(object, geometry, material, groupOrder, z, group) {
  11612. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  11613. (material.transparent === true ? transparent : opaque).unshift(renderItem);
  11614. }
  11615. function sort(customOpaqueSort, customTransparentSort) {
  11616. if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable);
  11617. if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable);
  11618. }
  11619. function finish() {
  11620. // Clear references from inactive renderItems in the list
  11621. for (let i = renderItemsIndex, il = renderItems.length; i < il; i++) {
  11622. const renderItem = renderItems[i];
  11623. if (renderItem.id === null) break;
  11624. renderItem.id = null;
  11625. renderItem.object = null;
  11626. renderItem.geometry = null;
  11627. renderItem.material = null;
  11628. renderItem.program = null;
  11629. renderItem.group = null;
  11630. }
  11631. }
  11632. return {
  11633. opaque: opaque,
  11634. transparent: transparent,
  11635. init: init,
  11636. push: push,
  11637. unshift: unshift,
  11638. finish: finish,
  11639. sort: sort
  11640. };
  11641. }
  11642. function WebGLRenderLists(properties) {
  11643. let lists = new WeakMap();
  11644. function get(scene, camera) {
  11645. const cameras = lists.get(scene);
  11646. let list;
  11647. if (cameras === undefined) {
  11648. list = new WebGLRenderList(properties);
  11649. lists.set(scene, new WeakMap());
  11650. lists.get(scene).set(camera, list);
  11651. } else {
  11652. list = cameras.get(camera);
  11653. if (list === undefined) {
  11654. list = new WebGLRenderList(properties);
  11655. cameras.set(camera, list);
  11656. }
  11657. }
  11658. return list;
  11659. }
  11660. function dispose() {
  11661. lists = new WeakMap();
  11662. }
  11663. return {
  11664. get: get,
  11665. dispose: dispose
  11666. };
  11667. }
  11668. function UniformsCache() {
  11669. const lights = {};
  11670. return {
  11671. get: function (light) {
  11672. if (lights[light.id] !== undefined) {
  11673. return lights[light.id];
  11674. }
  11675. let uniforms;
  11676. switch (light.type) {
  11677. case 'DirectionalLight':
  11678. uniforms = {
  11679. direction: new Vector3(),
  11680. color: new Color()
  11681. };
  11682. break;
  11683. case 'SpotLight':
  11684. uniforms = {
  11685. position: new Vector3(),
  11686. direction: new Vector3(),
  11687. color: new Color(),
  11688. distance: 0,
  11689. coneCos: 0,
  11690. penumbraCos: 0,
  11691. decay: 0
  11692. };
  11693. break;
  11694. case 'PointLight':
  11695. uniforms = {
  11696. position: new Vector3(),
  11697. color: new Color(),
  11698. distance: 0,
  11699. decay: 0
  11700. };
  11701. break;
  11702. case 'HemisphereLight':
  11703. uniforms = {
  11704. direction: new Vector3(),
  11705. skyColor: new Color(),
  11706. groundColor: new Color()
  11707. };
  11708. break;
  11709. case 'RectAreaLight':
  11710. uniforms = {
  11711. color: new Color(),
  11712. position: new Vector3(),
  11713. halfWidth: new Vector3(),
  11714. halfHeight: new Vector3()
  11715. };
  11716. break;
  11717. }
  11718. lights[light.id] = uniforms;
  11719. return uniforms;
  11720. }
  11721. };
  11722. }
  11723. function ShadowUniformsCache() {
  11724. const lights = {};
  11725. return {
  11726. get: function (light) {
  11727. if (lights[light.id] !== undefined) {
  11728. return lights[light.id];
  11729. }
  11730. let uniforms;
  11731. switch (light.type) {
  11732. case 'DirectionalLight':
  11733. uniforms = {
  11734. shadowBias: 0,
  11735. shadowNormalBias: 0,
  11736. shadowRadius: 1,
  11737. shadowMapSize: new Vector2()
  11738. };
  11739. break;
  11740. case 'SpotLight':
  11741. uniforms = {
  11742. shadowBias: 0,
  11743. shadowNormalBias: 0,
  11744. shadowRadius: 1,
  11745. shadowMapSize: new Vector2()
  11746. };
  11747. break;
  11748. case 'PointLight':
  11749. uniforms = {
  11750. shadowBias: 0,
  11751. shadowNormalBias: 0,
  11752. shadowRadius: 1,
  11753. shadowMapSize: new Vector2(),
  11754. shadowCameraNear: 1,
  11755. shadowCameraFar: 1000
  11756. };
  11757. break;
  11758. // TODO (abelnation): set RectAreaLight shadow uniforms
  11759. }
  11760. lights[light.id] = uniforms;
  11761. return uniforms;
  11762. }
  11763. };
  11764. }
  11765. let nextVersion = 0;
  11766. function shadowCastingLightsFirst(lightA, lightB) {
  11767. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  11768. }
  11769. function WebGLLights(extensions, capabilities) {
  11770. const cache = new UniformsCache();
  11771. const shadowCache = ShadowUniformsCache();
  11772. const state = {
  11773. version: 0,
  11774. hash: {
  11775. directionalLength: -1,
  11776. pointLength: -1,
  11777. spotLength: -1,
  11778. rectAreaLength: -1,
  11779. hemiLength: -1,
  11780. numDirectionalShadows: -1,
  11781. numPointShadows: -1,
  11782. numSpotShadows: -1
  11783. },
  11784. ambient: [0, 0, 0],
  11785. probe: [],
  11786. directional: [],
  11787. directionalShadow: [],
  11788. directionalShadowMap: [],
  11789. directionalShadowMatrix: [],
  11790. spot: [],
  11791. spotShadow: [],
  11792. spotShadowMap: [],
  11793. spotShadowMatrix: [],
  11794. rectArea: [],
  11795. rectAreaLTC1: null,
  11796. rectAreaLTC2: null,
  11797. point: [],
  11798. pointShadow: [],
  11799. pointShadowMap: [],
  11800. pointShadowMatrix: [],
  11801. hemi: []
  11802. };
  11803. for (let i = 0; i < 9; i++) state.probe.push(new Vector3());
  11804. const vector3 = new Vector3();
  11805. const matrix4 = new Matrix4();
  11806. const matrix42 = new Matrix4();
  11807. function setup(lights, shadows, camera) {
  11808. let r = 0,
  11809. g = 0,
  11810. b = 0;
  11811. for (let i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  11812. let directionalLength = 0;
  11813. let pointLength = 0;
  11814. let spotLength = 0;
  11815. let rectAreaLength = 0;
  11816. let hemiLength = 0;
  11817. let numDirectionalShadows = 0;
  11818. let numPointShadows = 0;
  11819. let numSpotShadows = 0;
  11820. const viewMatrix = camera.matrixWorldInverse;
  11821. lights.sort(shadowCastingLightsFirst);
  11822. for (let i = 0, l = lights.length; i < l; i++) {
  11823. const light = lights[i];
  11824. const color = light.color;
  11825. const intensity = light.intensity;
  11826. const distance = light.distance;
  11827. const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  11828. if (light.isAmbientLight) {
  11829. r += color.r * intensity;
  11830. g += color.g * intensity;
  11831. b += color.b * intensity;
  11832. } else if (light.isLightProbe) {
  11833. for (let j = 0; j < 9; j++) {
  11834. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  11835. }
  11836. } else if (light.isDirectionalLight) {
  11837. const uniforms = cache.get(light);
  11838. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  11839. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  11840. vector3.setFromMatrixPosition(light.target.matrixWorld);
  11841. uniforms.direction.sub(vector3);
  11842. uniforms.direction.transformDirection(viewMatrix);
  11843. if (light.castShadow) {
  11844. const shadow = light.shadow;
  11845. const shadowUniforms = shadowCache.get(light);
  11846. shadowUniforms.shadowBias = shadow.bias;
  11847. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11848. shadowUniforms.shadowRadius = shadow.radius;
  11849. shadowUniforms.shadowMapSize = shadow.mapSize;
  11850. state.directionalShadow[directionalLength] = shadowUniforms;
  11851. state.directionalShadowMap[directionalLength] = shadowMap;
  11852. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  11853. numDirectionalShadows++;
  11854. }
  11855. state.directional[directionalLength] = uniforms;
  11856. directionalLength++;
  11857. } else if (light.isSpotLight) {
  11858. const uniforms = cache.get(light);
  11859. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11860. uniforms.position.applyMatrix4(viewMatrix);
  11861. uniforms.color.copy(color).multiplyScalar(intensity);
  11862. uniforms.distance = distance;
  11863. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  11864. vector3.setFromMatrixPosition(light.target.matrixWorld);
  11865. uniforms.direction.sub(vector3);
  11866. uniforms.direction.transformDirection(viewMatrix);
  11867. uniforms.coneCos = Math.cos(light.angle);
  11868. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  11869. uniforms.decay = light.decay;
  11870. if (light.castShadow) {
  11871. const shadow = light.shadow;
  11872. const shadowUniforms = shadowCache.get(light);
  11873. shadowUniforms.shadowBias = shadow.bias;
  11874. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11875. shadowUniforms.shadowRadius = shadow.radius;
  11876. shadowUniforms.shadowMapSize = shadow.mapSize;
  11877. state.spotShadow[spotLength] = shadowUniforms;
  11878. state.spotShadowMap[spotLength] = shadowMap;
  11879. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  11880. numSpotShadows++;
  11881. }
  11882. state.spot[spotLength] = uniforms;
  11883. spotLength++;
  11884. } else if (light.isRectAreaLight) {
  11885. const uniforms = cache.get(light); // (a) intensity is the total visible light emitted
  11886. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  11887. // (b) intensity is the brightness of the light
  11888. uniforms.color.copy(color).multiplyScalar(intensity);
  11889. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11890. uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  11891. matrix42.identity();
  11892. matrix4.copy(light.matrixWorld);
  11893. matrix4.premultiply(viewMatrix);
  11894. matrix42.extractRotation(matrix4);
  11895. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  11896. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  11897. uniforms.halfWidth.applyMatrix4(matrix42);
  11898. uniforms.halfHeight.applyMatrix4(matrix42); // TODO (abelnation): RectAreaLight distance?
  11899. // uniforms.distance = distance;
  11900. state.rectArea[rectAreaLength] = uniforms;
  11901. rectAreaLength++;
  11902. } else if (light.isPointLight) {
  11903. const uniforms = cache.get(light);
  11904. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11905. uniforms.position.applyMatrix4(viewMatrix);
  11906. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  11907. uniforms.distance = light.distance;
  11908. uniforms.decay = light.decay;
  11909. if (light.castShadow) {
  11910. const shadow = light.shadow;
  11911. const shadowUniforms = shadowCache.get(light);
  11912. shadowUniforms.shadowBias = shadow.bias;
  11913. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11914. shadowUniforms.shadowRadius = shadow.radius;
  11915. shadowUniforms.shadowMapSize = shadow.mapSize;
  11916. shadowUniforms.shadowCameraNear = shadow.camera.near;
  11917. shadowUniforms.shadowCameraFar = shadow.camera.far;
  11918. state.pointShadow[pointLength] = shadowUniforms;
  11919. state.pointShadowMap[pointLength] = shadowMap;
  11920. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  11921. numPointShadows++;
  11922. }
  11923. state.point[pointLength] = uniforms;
  11924. pointLength++;
  11925. } else if (light.isHemisphereLight) {
  11926. const uniforms = cache.get(light);
  11927. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  11928. uniforms.direction.transformDirection(viewMatrix);
  11929. uniforms.direction.normalize();
  11930. uniforms.skyColor.copy(light.color).multiplyScalar(intensity);
  11931. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity);
  11932. state.hemi[hemiLength] = uniforms;
  11933. hemiLength++;
  11934. }
  11935. }
  11936. if (rectAreaLength > 0) {
  11937. if (capabilities.isWebGL2) {
  11938. // WebGL 2
  11939. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  11940. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  11941. } else {
  11942. // WebGL 1
  11943. if (extensions.has('OES_texture_float_linear') === true) {
  11944. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  11945. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  11946. } else if (extensions.has('OES_texture_half_float_linear') === true) {
  11947. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  11948. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  11949. } else {
  11950. console.error('THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.');
  11951. }
  11952. }
  11953. }
  11954. state.ambient[0] = r;
  11955. state.ambient[1] = g;
  11956. state.ambient[2] = b;
  11957. const hash = state.hash;
  11958. 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) {
  11959. state.directional.length = directionalLength;
  11960. state.spot.length = spotLength;
  11961. state.rectArea.length = rectAreaLength;
  11962. state.point.length = pointLength;
  11963. state.hemi.length = hemiLength;
  11964. state.directionalShadow.length = numDirectionalShadows;
  11965. state.directionalShadowMap.length = numDirectionalShadows;
  11966. state.pointShadow.length = numPointShadows;
  11967. state.pointShadowMap.length = numPointShadows;
  11968. state.spotShadow.length = numSpotShadows;
  11969. state.spotShadowMap.length = numSpotShadows;
  11970. state.directionalShadowMatrix.length = numDirectionalShadows;
  11971. state.pointShadowMatrix.length = numPointShadows;
  11972. state.spotShadowMatrix.length = numSpotShadows;
  11973. hash.directionalLength = directionalLength;
  11974. hash.pointLength = pointLength;
  11975. hash.spotLength = spotLength;
  11976. hash.rectAreaLength = rectAreaLength;
  11977. hash.hemiLength = hemiLength;
  11978. hash.numDirectionalShadows = numDirectionalShadows;
  11979. hash.numPointShadows = numPointShadows;
  11980. hash.numSpotShadows = numSpotShadows;
  11981. state.version = nextVersion++;
  11982. }
  11983. }
  11984. return {
  11985. setup: setup,
  11986. state: state
  11987. };
  11988. }
  11989. function WebGLRenderState(extensions, capabilities) {
  11990. const lights = new WebGLLights(extensions, capabilities);
  11991. const lightsArray = [];
  11992. const shadowsArray = [];
  11993. function init() {
  11994. lightsArray.length = 0;
  11995. shadowsArray.length = 0;
  11996. }
  11997. function pushLight(light) {
  11998. lightsArray.push(light);
  11999. }
  12000. function pushShadow(shadowLight) {
  12001. shadowsArray.push(shadowLight);
  12002. }
  12003. function setupLights(camera) {
  12004. lights.setup(lightsArray, shadowsArray, camera);
  12005. }
  12006. const state = {
  12007. lightsArray: lightsArray,
  12008. shadowsArray: shadowsArray,
  12009. lights: lights
  12010. };
  12011. return {
  12012. init: init,
  12013. state: state,
  12014. setupLights: setupLights,
  12015. pushLight: pushLight,
  12016. pushShadow: pushShadow
  12017. };
  12018. }
  12019. function WebGLRenderStates(extensions, capabilities) {
  12020. let renderStates = new WeakMap();
  12021. function get(scene, camera) {
  12022. let renderState;
  12023. if (renderStates.has(scene) === false) {
  12024. renderState = new WebGLRenderState(extensions, capabilities);
  12025. renderStates.set(scene, new WeakMap());
  12026. renderStates.get(scene).set(camera, renderState);
  12027. } else {
  12028. if (renderStates.get(scene).has(camera) === false) {
  12029. renderState = new WebGLRenderState(extensions, capabilities);
  12030. renderStates.get(scene).set(camera, renderState);
  12031. } else {
  12032. renderState = renderStates.get(scene).get(camera);
  12033. }
  12034. }
  12035. return renderState;
  12036. }
  12037. function dispose() {
  12038. renderStates = new WeakMap();
  12039. }
  12040. return {
  12041. get: get,
  12042. dispose: dispose
  12043. };
  12044. }
  12045. /**
  12046. * parameters = {
  12047. *
  12048. * opacity: <float>,
  12049. *
  12050. * map: new THREE.Texture( <Image> ),
  12051. *
  12052. * alphaMap: new THREE.Texture( <Image> ),
  12053. *
  12054. * displacementMap: new THREE.Texture( <Image> ),
  12055. * displacementScale: <float>,
  12056. * displacementBias: <float>,
  12057. *
  12058. * wireframe: <boolean>,
  12059. * wireframeLinewidth: <float>
  12060. * }
  12061. */
  12062. function MeshDepthMaterial(parameters) {
  12063. Material.call(this);
  12064. this.type = 'MeshDepthMaterial';
  12065. this.depthPacking = BasicDepthPacking;
  12066. this.skinning = false;
  12067. this.morphTargets = false;
  12068. this.map = null;
  12069. this.alphaMap = null;
  12070. this.displacementMap = null;
  12071. this.displacementScale = 1;
  12072. this.displacementBias = 0;
  12073. this.wireframe = false;
  12074. this.wireframeLinewidth = 1;
  12075. this.fog = false;
  12076. this.setValues(parameters);
  12077. }
  12078. MeshDepthMaterial.prototype = Object.create(Material.prototype);
  12079. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  12080. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  12081. MeshDepthMaterial.prototype.copy = function (source) {
  12082. Material.prototype.copy.call(this, source);
  12083. this.depthPacking = source.depthPacking;
  12084. this.skinning = source.skinning;
  12085. this.morphTargets = source.morphTargets;
  12086. this.map = source.map;
  12087. this.alphaMap = source.alphaMap;
  12088. this.displacementMap = source.displacementMap;
  12089. this.displacementScale = source.displacementScale;
  12090. this.displacementBias = source.displacementBias;
  12091. this.wireframe = source.wireframe;
  12092. this.wireframeLinewidth = source.wireframeLinewidth;
  12093. return this;
  12094. };
  12095. /**
  12096. * parameters = {
  12097. *
  12098. * referencePosition: <float>,
  12099. * nearDistance: <float>,
  12100. * farDistance: <float>,
  12101. *
  12102. * skinning: <bool>,
  12103. * morphTargets: <bool>,
  12104. *
  12105. * map: new THREE.Texture( <Image> ),
  12106. *
  12107. * alphaMap: new THREE.Texture( <Image> ),
  12108. *
  12109. * displacementMap: new THREE.Texture( <Image> ),
  12110. * displacementScale: <float>,
  12111. * displacementBias: <float>
  12112. *
  12113. * }
  12114. */
  12115. function MeshDistanceMaterial(parameters) {
  12116. Material.call(this);
  12117. this.type = 'MeshDistanceMaterial';
  12118. this.referencePosition = new Vector3();
  12119. this.nearDistance = 1;
  12120. this.farDistance = 1000;
  12121. this.skinning = false;
  12122. this.morphTargets = false;
  12123. this.map = null;
  12124. this.alphaMap = null;
  12125. this.displacementMap = null;
  12126. this.displacementScale = 1;
  12127. this.displacementBias = 0;
  12128. this.fog = false;
  12129. this.setValues(parameters);
  12130. }
  12131. MeshDistanceMaterial.prototype = Object.create(Material.prototype);
  12132. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  12133. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  12134. MeshDistanceMaterial.prototype.copy = function (source) {
  12135. Material.prototype.copy.call(this, source);
  12136. this.referencePosition.copy(source.referencePosition);
  12137. this.nearDistance = source.nearDistance;
  12138. this.farDistance = source.farDistance;
  12139. this.skinning = source.skinning;
  12140. this.morphTargets = source.morphTargets;
  12141. this.map = source.map;
  12142. this.alphaMap = source.alphaMap;
  12143. this.displacementMap = source.displacementMap;
  12144. this.displacementScale = source.displacementScale;
  12145. this.displacementBias = source.displacementBias;
  12146. return this;
  12147. };
  12148. var vsm_frag = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy ) / resolution ) );\n\tfor ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n\t\t#ifdef HORIZONAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( i, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, i ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean * HALF_SAMPLE_RATE;\n\tsquared_mean = squared_mean * HALF_SAMPLE_RATE;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
  12149. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12150. function WebGLShadowMap(_renderer, _objects, maxTextureSize) {
  12151. let _frustum = new Frustum();
  12152. const _shadowMapSize = new Vector2(),
  12153. _viewportSize = new Vector2(),
  12154. _viewport = new Vector4(),
  12155. _depthMaterials = [],
  12156. _distanceMaterials = [],
  12157. _materialCache = {};
  12158. const shadowSide = {
  12159. 0: BackSide,
  12160. 1: FrontSide,
  12161. 2: DoubleSide
  12162. };
  12163. const shadowMaterialVertical = new ShaderMaterial({
  12164. defines: {
  12165. SAMPLE_RATE: 2.0 / 8.0,
  12166. HALF_SAMPLE_RATE: 1.0 / 8.0
  12167. },
  12168. uniforms: {
  12169. shadow_pass: {
  12170. value: null
  12171. },
  12172. resolution: {
  12173. value: new Vector2()
  12174. },
  12175. radius: {
  12176. value: 4.0
  12177. }
  12178. },
  12179. vertexShader: vsm_vert,
  12180. fragmentShader: vsm_frag
  12181. });
  12182. const shadowMaterialHorizonal = shadowMaterialVertical.clone();
  12183. shadowMaterialHorizonal.defines.HORIZONAL_PASS = 1;
  12184. const fullScreenTri = new BufferGeometry();
  12185. fullScreenTri.setAttribute("position", new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  12186. const fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical);
  12187. const scope = this;
  12188. this.enabled = false;
  12189. this.autoUpdate = true;
  12190. this.needsUpdate = false;
  12191. this.type = PCFShadowMap;
  12192. this.render = function (lights, scene, camera) {
  12193. if (scope.enabled === false) return;
  12194. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  12195. if (lights.length === 0) return;
  12196. const currentRenderTarget = _renderer.getRenderTarget();
  12197. const activeCubeFace = _renderer.getActiveCubeFace();
  12198. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12199. const _state = _renderer.state; // Set GL state for depth map.
  12200. _state.setBlending(NoBlending);
  12201. _state.buffers.color.setClear(1, 1, 1, 1);
  12202. _state.buffers.depth.setTest(true);
  12203. _state.setScissorTest(false); // render depth map
  12204. for (let i = 0, il = lights.length; i < il; i++) {
  12205. const light = lights[i];
  12206. const shadow = light.shadow;
  12207. if (shadow === undefined) {
  12208. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  12209. continue;
  12210. }
  12211. if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue;
  12212. _shadowMapSize.copy(shadow.mapSize);
  12213. const shadowFrameExtents = shadow.getFrameExtents();
  12214. _shadowMapSize.multiply(shadowFrameExtents);
  12215. _viewportSize.copy(shadow.mapSize);
  12216. if (_shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize) {
  12217. if (_shadowMapSize.x > maxTextureSize) {
  12218. _viewportSize.x = Math.floor(maxTextureSize / shadowFrameExtents.x);
  12219. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12220. shadow.mapSize.x = _viewportSize.x;
  12221. }
  12222. if (_shadowMapSize.y > maxTextureSize) {
  12223. _viewportSize.y = Math.floor(maxTextureSize / shadowFrameExtents.y);
  12224. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12225. shadow.mapSize.y = _viewportSize.y;
  12226. }
  12227. }
  12228. if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
  12229. const pars = {
  12230. minFilter: LinearFilter,
  12231. magFilter: LinearFilter,
  12232. format: RGBAFormat
  12233. };
  12234. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12235. shadow.map.texture.name = light.name + ".shadowMap";
  12236. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12237. shadow.camera.updateProjectionMatrix();
  12238. }
  12239. if (shadow.map === null) {
  12240. const pars = {
  12241. minFilter: NearestFilter,
  12242. magFilter: NearestFilter,
  12243. format: RGBAFormat
  12244. };
  12245. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12246. shadow.map.texture.name = light.name + ".shadowMap";
  12247. shadow.camera.updateProjectionMatrix();
  12248. }
  12249. _renderer.setRenderTarget(shadow.map);
  12250. _renderer.clear();
  12251. const viewportCount = shadow.getViewportCount();
  12252. for (let vp = 0; vp < viewportCount; vp++) {
  12253. const viewport = shadow.getViewport(vp);
  12254. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  12255. _state.viewport(_viewport);
  12256. shadow.updateMatrices(light, vp);
  12257. _frustum = shadow.getFrustum();
  12258. renderObject(scene, camera, shadow.camera, light, this.type);
  12259. } // do blur pass for VSM
  12260. if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
  12261. VSMPass(shadow, camera);
  12262. }
  12263. shadow.needsUpdate = false;
  12264. }
  12265. scope.needsUpdate = false;
  12266. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  12267. };
  12268. function VSMPass(shadow, camera) {
  12269. const geometry = _objects.update(fullScreenMesh); // vertical pass
  12270. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12271. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12272. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12273. _renderer.setRenderTarget(shadow.mapPass);
  12274. _renderer.clear();
  12275. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizonal pass
  12276. shadowMaterialHorizonal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12277. shadowMaterialHorizonal.uniforms.resolution.value = shadow.mapSize;
  12278. shadowMaterialHorizonal.uniforms.radius.value = shadow.radius;
  12279. _renderer.setRenderTarget(shadow.map);
  12280. _renderer.clear();
  12281. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizonal, fullScreenMesh, null);
  12282. }
  12283. function getDepthMaterialVariant(useMorphing, useSkinning, useInstancing) {
  12284. const index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  12285. let material = _depthMaterials[index];
  12286. if (material === undefined) {
  12287. material = new MeshDepthMaterial({
  12288. depthPacking: RGBADepthPacking,
  12289. morphTargets: useMorphing,
  12290. skinning: useSkinning
  12291. });
  12292. _depthMaterials[index] = material;
  12293. }
  12294. return material;
  12295. }
  12296. function getDistanceMaterialVariant(useMorphing, useSkinning, useInstancing) {
  12297. const index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  12298. let material = _distanceMaterials[index];
  12299. if (material === undefined) {
  12300. material = new MeshDistanceMaterial({
  12301. morphTargets: useMorphing,
  12302. skinning: useSkinning
  12303. });
  12304. _distanceMaterials[index] = material;
  12305. }
  12306. return material;
  12307. }
  12308. function getDepthMaterial(object, geometry, material, light, shadowCameraNear, shadowCameraFar, type) {
  12309. let result = null;
  12310. let getMaterialVariant = getDepthMaterialVariant;
  12311. let customMaterial = object.customDepthMaterial;
  12312. if (light.isPointLight === true) {
  12313. getMaterialVariant = getDistanceMaterialVariant;
  12314. customMaterial = object.customDistanceMaterial;
  12315. }
  12316. if (customMaterial === undefined) {
  12317. let useMorphing = false;
  12318. if (material.morphTargets === true) {
  12319. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  12320. }
  12321. let useSkinning = false;
  12322. if (object.isSkinnedMesh === true) {
  12323. if (material.skinning === true) {
  12324. useSkinning = true;
  12325. } else {
  12326. console.warn('THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object);
  12327. }
  12328. }
  12329. const useInstancing = object.isInstancedMesh === true;
  12330. result = getMaterialVariant(useMorphing, useSkinning, useInstancing);
  12331. } else {
  12332. result = customMaterial;
  12333. }
  12334. if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0) {
  12335. // in this case we need a unique material instance reflecting the
  12336. // appropriate state
  12337. const keyA = result.uuid,
  12338. keyB = material.uuid;
  12339. let materialsForVariant = _materialCache[keyA];
  12340. if (materialsForVariant === undefined) {
  12341. materialsForVariant = {};
  12342. _materialCache[keyA] = materialsForVariant;
  12343. }
  12344. let cachedMaterial = materialsForVariant[keyB];
  12345. if (cachedMaterial === undefined) {
  12346. cachedMaterial = result.clone();
  12347. materialsForVariant[keyB] = cachedMaterial;
  12348. }
  12349. result = cachedMaterial;
  12350. }
  12351. result.visible = material.visible;
  12352. result.wireframe = material.wireframe;
  12353. if (type === VSMShadowMap) {
  12354. result.side = material.shadowSide !== null ? material.shadowSide : material.side;
  12355. } else {
  12356. result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side];
  12357. }
  12358. result.clipShadows = material.clipShadows;
  12359. result.clippingPlanes = material.clippingPlanes;
  12360. result.clipIntersection = material.clipIntersection;
  12361. result.wireframeLinewidth = material.wireframeLinewidth;
  12362. result.linewidth = material.linewidth;
  12363. if (light.isPointLight === true && result.isMeshDistanceMaterial === true) {
  12364. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  12365. result.nearDistance = shadowCameraNear;
  12366. result.farDistance = shadowCameraFar;
  12367. }
  12368. return result;
  12369. }
  12370. function renderObject(object, camera, shadowCamera, light, type) {
  12371. if (object.visible === false) return;
  12372. const visible = object.layers.test(camera.layers);
  12373. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  12374. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  12375. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  12376. const geometry = _objects.update(object);
  12377. const material = object.material;
  12378. if (Array.isArray(material)) {
  12379. const groups = geometry.groups;
  12380. for (let k = 0, kl = groups.length; k < kl; k++) {
  12381. const group = groups[k];
  12382. const groupMaterial = material[group.materialIndex];
  12383. if (groupMaterial && groupMaterial.visible) {
  12384. const depthMaterial = getDepthMaterial(object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  12385. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  12386. }
  12387. }
  12388. } else if (material.visible) {
  12389. const depthMaterial = getDepthMaterial(object, geometry, material, light, shadowCamera.near, shadowCamera.far, type);
  12390. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  12391. }
  12392. }
  12393. }
  12394. const children = object.children;
  12395. for (let i = 0, l = children.length; i < l; i++) {
  12396. renderObject(children[i], camera, shadowCamera, light, type);
  12397. }
  12398. }
  12399. }
  12400. function WebGLState(gl, extensions, capabilities) {
  12401. const isWebGL2 = capabilities.isWebGL2;
  12402. function ColorBuffer() {
  12403. let locked = false;
  12404. const color = new Vector4();
  12405. let currentColorMask = null;
  12406. const currentColorClear = new Vector4(0, 0, 0, 0);
  12407. return {
  12408. setMask: function (colorMask) {
  12409. if (currentColorMask !== colorMask && !locked) {
  12410. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  12411. currentColorMask = colorMask;
  12412. }
  12413. },
  12414. setLocked: function (lock) {
  12415. locked = lock;
  12416. },
  12417. setClear: function (r, g, b, a, premultipliedAlpha) {
  12418. if (premultipliedAlpha === true) {
  12419. r *= a;
  12420. g *= a;
  12421. b *= a;
  12422. }
  12423. color.set(r, g, b, a);
  12424. if (currentColorClear.equals(color) === false) {
  12425. gl.clearColor(r, g, b, a);
  12426. currentColorClear.copy(color);
  12427. }
  12428. },
  12429. reset: function () {
  12430. locked = false;
  12431. currentColorMask = null;
  12432. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  12433. }
  12434. };
  12435. }
  12436. function DepthBuffer() {
  12437. let locked = false;
  12438. let currentDepthMask = null;
  12439. let currentDepthFunc = null;
  12440. let currentDepthClear = null;
  12441. return {
  12442. setTest: function (depthTest) {
  12443. if (depthTest) {
  12444. enable(2929);
  12445. } else {
  12446. disable(2929);
  12447. }
  12448. },
  12449. setMask: function (depthMask) {
  12450. if (currentDepthMask !== depthMask && !locked) {
  12451. gl.depthMask(depthMask);
  12452. currentDepthMask = depthMask;
  12453. }
  12454. },
  12455. setFunc: function (depthFunc) {
  12456. if (currentDepthFunc !== depthFunc) {
  12457. if (depthFunc) {
  12458. switch (depthFunc) {
  12459. case NeverDepth:
  12460. gl.depthFunc(512);
  12461. break;
  12462. case AlwaysDepth:
  12463. gl.depthFunc(519);
  12464. break;
  12465. case LessDepth:
  12466. gl.depthFunc(513);
  12467. break;
  12468. case LessEqualDepth:
  12469. gl.depthFunc(515);
  12470. break;
  12471. case EqualDepth:
  12472. gl.depthFunc(514);
  12473. break;
  12474. case GreaterEqualDepth:
  12475. gl.depthFunc(518);
  12476. break;
  12477. case GreaterDepth:
  12478. gl.depthFunc(516);
  12479. break;
  12480. case NotEqualDepth:
  12481. gl.depthFunc(517);
  12482. break;
  12483. default:
  12484. gl.depthFunc(515);
  12485. }
  12486. } else {
  12487. gl.depthFunc(515);
  12488. }
  12489. currentDepthFunc = depthFunc;
  12490. }
  12491. },
  12492. setLocked: function (lock) {
  12493. locked = lock;
  12494. },
  12495. setClear: function (depth) {
  12496. if (currentDepthClear !== depth) {
  12497. gl.clearDepth(depth);
  12498. currentDepthClear = depth;
  12499. }
  12500. },
  12501. reset: function () {
  12502. locked = false;
  12503. currentDepthMask = null;
  12504. currentDepthFunc = null;
  12505. currentDepthClear = null;
  12506. }
  12507. };
  12508. }
  12509. function StencilBuffer() {
  12510. let locked = false;
  12511. let currentStencilMask = null;
  12512. let currentStencilFunc = null;
  12513. let currentStencilRef = null;
  12514. let currentStencilFuncMask = null;
  12515. let currentStencilFail = null;
  12516. let currentStencilZFail = null;
  12517. let currentStencilZPass = null;
  12518. let currentStencilClear = null;
  12519. return {
  12520. setTest: function (stencilTest) {
  12521. if (!locked) {
  12522. if (stencilTest) {
  12523. enable(2960);
  12524. } else {
  12525. disable(2960);
  12526. }
  12527. }
  12528. },
  12529. setMask: function (stencilMask) {
  12530. if (currentStencilMask !== stencilMask && !locked) {
  12531. gl.stencilMask(stencilMask);
  12532. currentStencilMask = stencilMask;
  12533. }
  12534. },
  12535. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  12536. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  12537. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  12538. currentStencilFunc = stencilFunc;
  12539. currentStencilRef = stencilRef;
  12540. currentStencilFuncMask = stencilMask;
  12541. }
  12542. },
  12543. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  12544. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  12545. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  12546. currentStencilFail = stencilFail;
  12547. currentStencilZFail = stencilZFail;
  12548. currentStencilZPass = stencilZPass;
  12549. }
  12550. },
  12551. setLocked: function (lock) {
  12552. locked = lock;
  12553. },
  12554. setClear: function (stencil) {
  12555. if (currentStencilClear !== stencil) {
  12556. gl.clearStencil(stencil);
  12557. currentStencilClear = stencil;
  12558. }
  12559. },
  12560. reset: function () {
  12561. locked = false;
  12562. currentStencilMask = null;
  12563. currentStencilFunc = null;
  12564. currentStencilRef = null;
  12565. currentStencilFuncMask = null;
  12566. currentStencilFail = null;
  12567. currentStencilZFail = null;
  12568. currentStencilZPass = null;
  12569. currentStencilClear = null;
  12570. }
  12571. };
  12572. } //
  12573. const colorBuffer = new ColorBuffer();
  12574. const depthBuffer = new DepthBuffer();
  12575. const stencilBuffer = new StencilBuffer();
  12576. let enabledCapabilities = {};
  12577. let currentProgram = null;
  12578. let currentBlendingEnabled = null;
  12579. let currentBlending = null;
  12580. let currentBlendEquation = null;
  12581. let currentBlendSrc = null;
  12582. let currentBlendDst = null;
  12583. let currentBlendEquationAlpha = null;
  12584. let currentBlendSrcAlpha = null;
  12585. let currentBlendDstAlpha = null;
  12586. let currentPremultipledAlpha = false;
  12587. let currentFlipSided = null;
  12588. let currentCullFace = null;
  12589. let currentLineWidth = null;
  12590. let currentPolygonOffsetFactor = null;
  12591. let currentPolygonOffsetUnits = null;
  12592. const maxTextures = gl.getParameter(35661);
  12593. let lineWidthAvailable = false;
  12594. let version = 0;
  12595. const glVersion = gl.getParameter(7938);
  12596. if (glVersion.indexOf('WebGL') !== -1) {
  12597. version = parseFloat(/^WebGL\ ([0-9])/.exec(glVersion)[1]);
  12598. lineWidthAvailable = version >= 1.0;
  12599. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  12600. version = parseFloat(/^OpenGL\ ES\ ([0-9])/.exec(glVersion)[1]);
  12601. lineWidthAvailable = version >= 2.0;
  12602. }
  12603. let currentTextureSlot = null;
  12604. let currentBoundTextures = {};
  12605. const currentScissor = new Vector4();
  12606. const currentViewport = new Vector4();
  12607. function createTexture(type, target, count) {
  12608. const data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  12609. const texture = gl.createTexture();
  12610. gl.bindTexture(type, texture);
  12611. gl.texParameteri(type, 10241, 9728);
  12612. gl.texParameteri(type, 10240, 9728);
  12613. for (let i = 0; i < count; i++) {
  12614. gl.texImage2D(target + i, 0, 6408, 1, 1, 0, 6408, 5121, data);
  12615. }
  12616. return texture;
  12617. }
  12618. const emptyTextures = {};
  12619. emptyTextures[3553] = createTexture(3553, 3553, 1);
  12620. emptyTextures[34067] = createTexture(34067, 34069, 6); // init
  12621. colorBuffer.setClear(0, 0, 0, 1);
  12622. depthBuffer.setClear(1);
  12623. stencilBuffer.setClear(0);
  12624. enable(2929);
  12625. depthBuffer.setFunc(LessEqualDepth);
  12626. setFlipSided(false);
  12627. setCullFace(CullFaceBack);
  12628. enable(2884);
  12629. setBlending(NoBlending); //
  12630. function enable(id) {
  12631. if (enabledCapabilities[id] !== true) {
  12632. gl.enable(id);
  12633. enabledCapabilities[id] = true;
  12634. }
  12635. }
  12636. function disable(id) {
  12637. if (enabledCapabilities[id] !== false) {
  12638. gl.disable(id);
  12639. enabledCapabilities[id] = false;
  12640. }
  12641. }
  12642. function useProgram(program) {
  12643. if (currentProgram !== program) {
  12644. gl.useProgram(program);
  12645. currentProgram = program;
  12646. return true;
  12647. }
  12648. return false;
  12649. }
  12650. const equationToGL = {
  12651. [AddEquation]: 32774,
  12652. [SubtractEquation]: 32778,
  12653. [ReverseSubtractEquation]: 32779
  12654. };
  12655. if (isWebGL2) {
  12656. equationToGL[MinEquation] = 32775;
  12657. equationToGL[MaxEquation] = 32776;
  12658. } else {
  12659. const extension = extensions.get('EXT_blend_minmax');
  12660. if (extension !== null) {
  12661. equationToGL[MinEquation] = extension.MIN_EXT;
  12662. equationToGL[MaxEquation] = extension.MAX_EXT;
  12663. }
  12664. }
  12665. const factorToGL = {
  12666. [ZeroFactor]: 0,
  12667. [OneFactor]: 1,
  12668. [SrcColorFactor]: 768,
  12669. [SrcAlphaFactor]: 770,
  12670. [SrcAlphaSaturateFactor]: 776,
  12671. [DstColorFactor]: 774,
  12672. [DstAlphaFactor]: 772,
  12673. [OneMinusSrcColorFactor]: 769,
  12674. [OneMinusSrcAlphaFactor]: 771,
  12675. [OneMinusDstColorFactor]: 775,
  12676. [OneMinusDstAlphaFactor]: 773
  12677. };
  12678. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  12679. if (blending === NoBlending) {
  12680. if (currentBlendingEnabled) {
  12681. disable(3042);
  12682. currentBlendingEnabled = false;
  12683. }
  12684. return;
  12685. }
  12686. if (!currentBlendingEnabled) {
  12687. enable(3042);
  12688. currentBlendingEnabled = true;
  12689. }
  12690. if (blending !== CustomBlending) {
  12691. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  12692. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  12693. gl.blendEquation(32774);
  12694. currentBlendEquation = AddEquation;
  12695. currentBlendEquationAlpha = AddEquation;
  12696. }
  12697. if (premultipliedAlpha) {
  12698. switch (blending) {
  12699. case NormalBlending:
  12700. gl.blendFuncSeparate(1, 771, 1, 771);
  12701. break;
  12702. case AdditiveBlending:
  12703. gl.blendFunc(1, 1);
  12704. break;
  12705. case SubtractiveBlending:
  12706. gl.blendFuncSeparate(0, 0, 769, 771);
  12707. break;
  12708. case MultiplyBlending:
  12709. gl.blendFuncSeparate(0, 768, 0, 770);
  12710. break;
  12711. default:
  12712. console.error('THREE.WebGLState: Invalid blending: ', blending);
  12713. break;
  12714. }
  12715. } else {
  12716. switch (blending) {
  12717. case NormalBlending:
  12718. gl.blendFuncSeparate(770, 771, 1, 771);
  12719. break;
  12720. case AdditiveBlending:
  12721. gl.blendFunc(770, 1);
  12722. break;
  12723. case SubtractiveBlending:
  12724. gl.blendFunc(0, 769);
  12725. break;
  12726. case MultiplyBlending:
  12727. gl.blendFunc(0, 768);
  12728. break;
  12729. default:
  12730. console.error('THREE.WebGLState: Invalid blending: ', blending);
  12731. break;
  12732. }
  12733. }
  12734. currentBlendSrc = null;
  12735. currentBlendDst = null;
  12736. currentBlendSrcAlpha = null;
  12737. currentBlendDstAlpha = null;
  12738. currentBlending = blending;
  12739. currentPremultipledAlpha = premultipliedAlpha;
  12740. }
  12741. return;
  12742. } // custom blending
  12743. blendEquationAlpha = blendEquationAlpha || blendEquation;
  12744. blendSrcAlpha = blendSrcAlpha || blendSrc;
  12745. blendDstAlpha = blendDstAlpha || blendDst;
  12746. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  12747. gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]);
  12748. currentBlendEquation = blendEquation;
  12749. currentBlendEquationAlpha = blendEquationAlpha;
  12750. }
  12751. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  12752. gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]);
  12753. currentBlendSrc = blendSrc;
  12754. currentBlendDst = blendDst;
  12755. currentBlendSrcAlpha = blendSrcAlpha;
  12756. currentBlendDstAlpha = blendDstAlpha;
  12757. }
  12758. currentBlending = blending;
  12759. currentPremultipledAlpha = null;
  12760. }
  12761. function setMaterial(material, frontFaceCW) {
  12762. material.side === DoubleSide ? disable(2884) : enable(2884);
  12763. let flipSided = material.side === BackSide;
  12764. if (frontFaceCW) flipSided = !flipSided;
  12765. setFlipSided(flipSided);
  12766. 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);
  12767. depthBuffer.setFunc(material.depthFunc);
  12768. depthBuffer.setTest(material.depthTest);
  12769. depthBuffer.setMask(material.depthWrite);
  12770. colorBuffer.setMask(material.colorWrite);
  12771. const stencilWrite = material.stencilWrite;
  12772. stencilBuffer.setTest(stencilWrite);
  12773. if (stencilWrite) {
  12774. stencilBuffer.setMask(material.stencilWriteMask);
  12775. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  12776. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  12777. }
  12778. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  12779. } //
  12780. function setFlipSided(flipSided) {
  12781. if (currentFlipSided !== flipSided) {
  12782. if (flipSided) {
  12783. gl.frontFace(2304);
  12784. } else {
  12785. gl.frontFace(2305);
  12786. }
  12787. currentFlipSided = flipSided;
  12788. }
  12789. }
  12790. function setCullFace(cullFace) {
  12791. if (cullFace !== CullFaceNone) {
  12792. enable(2884);
  12793. if (cullFace !== currentCullFace) {
  12794. if (cullFace === CullFaceBack) {
  12795. gl.cullFace(1029);
  12796. } else if (cullFace === CullFaceFront) {
  12797. gl.cullFace(1028);
  12798. } else {
  12799. gl.cullFace(1032);
  12800. }
  12801. }
  12802. } else {
  12803. disable(2884);
  12804. }
  12805. currentCullFace = cullFace;
  12806. }
  12807. function setLineWidth(width) {
  12808. if (width !== currentLineWidth) {
  12809. if (lineWidthAvailable) gl.lineWidth(width);
  12810. currentLineWidth = width;
  12811. }
  12812. }
  12813. function setPolygonOffset(polygonOffset, factor, units) {
  12814. if (polygonOffset) {
  12815. enable(32823);
  12816. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  12817. gl.polygonOffset(factor, units);
  12818. currentPolygonOffsetFactor = factor;
  12819. currentPolygonOffsetUnits = units;
  12820. }
  12821. } else {
  12822. disable(32823);
  12823. }
  12824. }
  12825. function setScissorTest(scissorTest) {
  12826. if (scissorTest) {
  12827. enable(3089);
  12828. } else {
  12829. disable(3089);
  12830. }
  12831. } // texture
  12832. function activeTexture(webglSlot) {
  12833. if (webglSlot === undefined) webglSlot = 33984 + maxTextures - 1;
  12834. if (currentTextureSlot !== webglSlot) {
  12835. gl.activeTexture(webglSlot);
  12836. currentTextureSlot = webglSlot;
  12837. }
  12838. }
  12839. function bindTexture(webglType, webglTexture) {
  12840. if (currentTextureSlot === null) {
  12841. activeTexture();
  12842. }
  12843. let boundTexture = currentBoundTextures[currentTextureSlot];
  12844. if (boundTexture === undefined) {
  12845. boundTexture = {
  12846. type: undefined,
  12847. texture: undefined
  12848. };
  12849. currentBoundTextures[currentTextureSlot] = boundTexture;
  12850. }
  12851. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  12852. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  12853. boundTexture.type = webglType;
  12854. boundTexture.texture = webglTexture;
  12855. }
  12856. }
  12857. function unbindTexture() {
  12858. const boundTexture = currentBoundTextures[currentTextureSlot];
  12859. if (boundTexture !== undefined && boundTexture.type !== undefined) {
  12860. gl.bindTexture(boundTexture.type, null);
  12861. boundTexture.type = undefined;
  12862. boundTexture.texture = undefined;
  12863. }
  12864. }
  12865. function compressedTexImage2D() {
  12866. try {
  12867. gl.compressedTexImage2D.apply(gl, arguments);
  12868. } catch (error) {
  12869. console.error('THREE.WebGLState:', error);
  12870. }
  12871. }
  12872. function texImage2D() {
  12873. try {
  12874. gl.texImage2D.apply(gl, arguments);
  12875. } catch (error) {
  12876. console.error('THREE.WebGLState:', error);
  12877. }
  12878. }
  12879. function texImage3D() {
  12880. try {
  12881. gl.texImage3D.apply(gl, arguments);
  12882. } catch (error) {
  12883. console.error('THREE.WebGLState:', error);
  12884. }
  12885. } //
  12886. function scissor(scissor) {
  12887. if (currentScissor.equals(scissor) === false) {
  12888. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  12889. currentScissor.copy(scissor);
  12890. }
  12891. }
  12892. function viewport(viewport) {
  12893. if (currentViewport.equals(viewport) === false) {
  12894. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  12895. currentViewport.copy(viewport);
  12896. }
  12897. } //
  12898. function reset() {
  12899. enabledCapabilities = {};
  12900. currentTextureSlot = null;
  12901. currentBoundTextures = {};
  12902. currentProgram = null;
  12903. currentBlendingEnabled = null;
  12904. currentBlending = null;
  12905. currentBlendEquation = null;
  12906. currentBlendSrc = null;
  12907. currentBlendDst = null;
  12908. currentBlendEquationAlpha = null;
  12909. currentBlendSrcAlpha = null;
  12910. currentBlendDstAlpha = null;
  12911. currentPremultipledAlpha = false;
  12912. currentFlipSided = null;
  12913. currentCullFace = null;
  12914. currentLineWidth = null;
  12915. currentPolygonOffsetFactor = null;
  12916. currentPolygonOffsetUnits = null;
  12917. colorBuffer.reset();
  12918. depthBuffer.reset();
  12919. stencilBuffer.reset();
  12920. }
  12921. return {
  12922. buffers: {
  12923. color: colorBuffer,
  12924. depth: depthBuffer,
  12925. stencil: stencilBuffer
  12926. },
  12927. enable: enable,
  12928. disable: disable,
  12929. useProgram: useProgram,
  12930. setBlending: setBlending,
  12931. setMaterial: setMaterial,
  12932. setFlipSided: setFlipSided,
  12933. setCullFace: setCullFace,
  12934. setLineWidth: setLineWidth,
  12935. setPolygonOffset: setPolygonOffset,
  12936. setScissorTest: setScissorTest,
  12937. activeTexture: activeTexture,
  12938. bindTexture: bindTexture,
  12939. unbindTexture: unbindTexture,
  12940. compressedTexImage2D: compressedTexImage2D,
  12941. texImage2D: texImage2D,
  12942. texImage3D: texImage3D,
  12943. scissor: scissor,
  12944. viewport: viewport,
  12945. reset: reset
  12946. };
  12947. }
  12948. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  12949. const isWebGL2 = capabilities.isWebGL2;
  12950. const maxTextures = capabilities.maxTextures;
  12951. const maxCubemapSize = capabilities.maxCubemapSize;
  12952. const maxTextureSize = capabilities.maxTextureSize;
  12953. const maxSamples = capabilities.maxSamples;
  12954. const _videoTextures = new WeakMap();
  12955. let _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  12956. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  12957. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  12958. let useOffscreenCanvas = false;
  12959. try {
  12960. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext("2d") !== null;
  12961. } catch (err) {// Ignore any errors
  12962. }
  12963. function createCanvas(width, height) {
  12964. // Use OffscreenCanvas when available. Specially needed in web workers
  12965. return useOffscreenCanvas ? new OffscreenCanvas(width, height) : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  12966. }
  12967. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  12968. let scale = 1; // handle case if texture exceeds max size
  12969. if (image.width > maxSize || image.height > maxSize) {
  12970. scale = maxSize / Math.max(image.width, image.height);
  12971. } // only perform resize if necessary
  12972. if (scale < 1 || needsPowerOfTwo === true) {
  12973. // only perform resize for certain image types
  12974. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  12975. const floor = needsPowerOfTwo ? MathUtils.floorPowerOfTwo : Math.floor;
  12976. const width = floor(scale * image.width);
  12977. const height = floor(scale * image.height);
  12978. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  12979. const canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  12980. canvas.width = width;
  12981. canvas.height = height;
  12982. const context = canvas.getContext('2d');
  12983. context.drawImage(image, 0, 0, width, height);
  12984. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  12985. return canvas;
  12986. } else {
  12987. if ('data' in image) {
  12988. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  12989. }
  12990. return image;
  12991. }
  12992. }
  12993. return image;
  12994. }
  12995. function isPowerOfTwo(image) {
  12996. return MathUtils.isPowerOfTwo(image.width) && MathUtils.isPowerOfTwo(image.height);
  12997. }
  12998. function textureNeedsPowerOfTwo(texture) {
  12999. if (isWebGL2) return false;
  13000. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13001. }
  13002. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  13003. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13004. }
  13005. function generateMipmap(target, texture, width, height) {
  13006. _gl.generateMipmap(target);
  13007. const textureProperties = properties.get(texture); // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
  13008. textureProperties.__maxMipLevel = Math.log(Math.max(width, height)) * Math.LOG2E;
  13009. }
  13010. function getInternalFormat(internalFormatName, glFormat, glType) {
  13011. if (isWebGL2 === false) return glFormat;
  13012. if (internalFormatName !== null) {
  13013. if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName];
  13014. console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'');
  13015. }
  13016. let internalFormat = glFormat;
  13017. if (glFormat === 6403) {
  13018. if (glType === 5126) internalFormat = 33326;
  13019. if (glType === 5131) internalFormat = 33325;
  13020. if (glType === 5121) internalFormat = 33321;
  13021. }
  13022. if (glFormat === 6407) {
  13023. if (glType === 5126) internalFormat = 34837;
  13024. if (glType === 5131) internalFormat = 34843;
  13025. if (glType === 5121) internalFormat = 32849;
  13026. }
  13027. if (glFormat === 6408) {
  13028. if (glType === 5126) internalFormat = 34836;
  13029. if (glType === 5131) internalFormat = 34842;
  13030. if (glType === 5121) internalFormat = 32856;
  13031. }
  13032. if (internalFormat === 33325 || internalFormat === 33326 || internalFormat === 34842 || internalFormat === 34836) {
  13033. extensions.get('EXT_color_buffer_float');
  13034. }
  13035. return internalFormat;
  13036. } // Fallback filters for non-power-of-2 textures
  13037. function filterFallback(f) {
  13038. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  13039. return 9728;
  13040. }
  13041. return 9729;
  13042. } //
  13043. function onTextureDispose(event) {
  13044. const texture = event.target;
  13045. texture.removeEventListener('dispose', onTextureDispose);
  13046. deallocateTexture(texture);
  13047. if (texture.isVideoTexture) {
  13048. _videoTextures.delete(texture);
  13049. }
  13050. info.memory.textures--;
  13051. }
  13052. function onRenderTargetDispose(event) {
  13053. const renderTarget = event.target;
  13054. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  13055. deallocateRenderTarget(renderTarget);
  13056. info.memory.textures--;
  13057. } //
  13058. function deallocateTexture(texture) {
  13059. const textureProperties = properties.get(texture);
  13060. if (textureProperties.__webglInit === undefined) return;
  13061. _gl.deleteTexture(textureProperties.__webglTexture);
  13062. properties.remove(texture);
  13063. }
  13064. function deallocateRenderTarget(renderTarget) {
  13065. const renderTargetProperties = properties.get(renderTarget);
  13066. const textureProperties = properties.get(renderTarget.texture);
  13067. if (!renderTarget) return;
  13068. if (textureProperties.__webglTexture !== undefined) {
  13069. _gl.deleteTexture(textureProperties.__webglTexture);
  13070. }
  13071. if (renderTarget.depthTexture) {
  13072. renderTarget.depthTexture.dispose();
  13073. }
  13074. if (renderTarget.isWebGLCubeRenderTarget) {
  13075. for (let i = 0; i < 6; i++) {
  13076. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  13077. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  13078. }
  13079. } else {
  13080. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  13081. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  13082. if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
  13083. if (renderTargetProperties.__webglColorRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer);
  13084. if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
  13085. }
  13086. properties.remove(renderTarget.texture);
  13087. properties.remove(renderTarget);
  13088. } //
  13089. let textureUnits = 0;
  13090. function resetTextureUnits() {
  13091. textureUnits = 0;
  13092. }
  13093. function allocateTextureUnit() {
  13094. const textureUnit = textureUnits;
  13095. if (textureUnit >= maxTextures) {
  13096. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures);
  13097. }
  13098. textureUnits += 1;
  13099. return textureUnit;
  13100. } //
  13101. function setTexture2D(texture, slot) {
  13102. const textureProperties = properties.get(texture);
  13103. if (texture.isVideoTexture) updateVideoTexture(texture);
  13104. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13105. const image = texture.image;
  13106. if (image === undefined) {
  13107. console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
  13108. } else if (image.complete === false) {
  13109. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  13110. } else {
  13111. uploadTexture(textureProperties, texture, slot);
  13112. return;
  13113. }
  13114. }
  13115. state.activeTexture(33984 + slot);
  13116. state.bindTexture(3553, textureProperties.__webglTexture);
  13117. }
  13118. function setTexture2DArray(texture, slot) {
  13119. const textureProperties = properties.get(texture);
  13120. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13121. uploadTexture(textureProperties, texture, slot);
  13122. return;
  13123. }
  13124. state.activeTexture(33984 + slot);
  13125. state.bindTexture(35866, textureProperties.__webglTexture);
  13126. }
  13127. function setTexture3D(texture, slot) {
  13128. const textureProperties = properties.get(texture);
  13129. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13130. uploadTexture(textureProperties, texture, slot);
  13131. return;
  13132. }
  13133. state.activeTexture(33984 + slot);
  13134. state.bindTexture(32879, textureProperties.__webglTexture);
  13135. }
  13136. function setTextureCube(texture, slot) {
  13137. const textureProperties = properties.get(texture);
  13138. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13139. uploadCubeTexture(textureProperties, texture, slot);
  13140. return;
  13141. }
  13142. state.activeTexture(33984 + slot);
  13143. state.bindTexture(34067, textureProperties.__webglTexture);
  13144. }
  13145. const wrappingToGL = {
  13146. [RepeatWrapping]: 10497,
  13147. [ClampToEdgeWrapping]: 33071,
  13148. [MirroredRepeatWrapping]: 33648
  13149. };
  13150. const filterToGL = {
  13151. [NearestFilter]: 9728,
  13152. [NearestMipmapNearestFilter]: 9984,
  13153. [NearestMipmapLinearFilter]: 9986,
  13154. [LinearFilter]: 9729,
  13155. [LinearMipmapNearestFilter]: 9985,
  13156. [LinearMipmapLinearFilter]: 9987
  13157. };
  13158. function setTextureParameters(textureType, texture, supportsMips) {
  13159. if (supportsMips) {
  13160. _gl.texParameteri(textureType, 10242, wrappingToGL[texture.wrapS]);
  13161. _gl.texParameteri(textureType, 10243, wrappingToGL[texture.wrapT]);
  13162. if (textureType === 32879 || textureType === 35866) {
  13163. _gl.texParameteri(textureType, 32882, wrappingToGL[texture.wrapR]);
  13164. }
  13165. _gl.texParameteri(textureType, 10240, filterToGL[texture.magFilter]);
  13166. _gl.texParameteri(textureType, 10241, filterToGL[texture.minFilter]);
  13167. } else {
  13168. _gl.texParameteri(textureType, 10242, 33071);
  13169. _gl.texParameteri(textureType, 10243, 33071);
  13170. if (textureType === 32879 || textureType === 35866) {
  13171. _gl.texParameteri(textureType, 32882, 33071);
  13172. }
  13173. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  13174. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  13175. }
  13176. _gl.texParameteri(textureType, 10240, filterFallback(texture.magFilter));
  13177. _gl.texParameteri(textureType, 10241, filterFallback(texture.minFilter));
  13178. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  13179. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  13180. }
  13181. }
  13182. const extension = extensions.get('EXT_texture_filter_anisotropic');
  13183. if (extension) {
  13184. if (texture.type === FloatType && extensions.get('OES_texture_float_linear') === null) return;
  13185. if (texture.type === HalfFloatType && (isWebGL2 || extensions.get('OES_texture_half_float_linear')) === null) return;
  13186. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  13187. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  13188. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  13189. }
  13190. }
  13191. }
  13192. function initTexture(textureProperties, texture) {
  13193. if (textureProperties.__webglInit === undefined) {
  13194. textureProperties.__webglInit = true;
  13195. texture.addEventListener('dispose', onTextureDispose);
  13196. textureProperties.__webglTexture = _gl.createTexture();
  13197. info.memory.textures++;
  13198. }
  13199. }
  13200. function uploadTexture(textureProperties, texture, slot) {
  13201. let textureType = 3553;
  13202. if (texture.isDataTexture2DArray) textureType = 35866;
  13203. if (texture.isDataTexture3D) textureType = 32879;
  13204. initTexture(textureProperties, texture);
  13205. state.activeTexture(33984 + slot);
  13206. state.bindTexture(textureType, textureProperties.__webglTexture);
  13207. _gl.pixelStorei(37440, texture.flipY);
  13208. _gl.pixelStorei(37441, texture.premultiplyAlpha);
  13209. _gl.pixelStorei(3317, texture.unpackAlignment);
  13210. const needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo(texture.image) === false;
  13211. const image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
  13212. const supportsMips = isPowerOfTwo(image) || isWebGL2,
  13213. glFormat = utils.convert(texture.format);
  13214. let glType = utils.convert(texture.type),
  13215. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  13216. setTextureParameters(textureType, texture, supportsMips);
  13217. let mipmap;
  13218. const mipmaps = texture.mipmaps;
  13219. if (texture.isDepthTexture) {
  13220. // populate depth texture with dummy data
  13221. glInternalFormat = 6402;
  13222. if (isWebGL2) {
  13223. if (texture.type === FloatType) {
  13224. glInternalFormat = 36012;
  13225. } else if (texture.type === UnsignedIntType) {
  13226. glInternalFormat = 33190;
  13227. } else if (texture.type === UnsignedInt248Type) {
  13228. glInternalFormat = 35056;
  13229. } else {
  13230. glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
  13231. }
  13232. } else {
  13233. if (texture.type === FloatType) {
  13234. console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');
  13235. }
  13236. } // validation checks for WebGL 1
  13237. if (texture.format === DepthFormat && glInternalFormat === 6402) {
  13238. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13239. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13240. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13241. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  13242. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  13243. texture.type = UnsignedShortType;
  13244. glType = utils.convert(texture.type);
  13245. }
  13246. }
  13247. if (texture.format === DepthStencilFormat && glInternalFormat === 6402) {
  13248. // Depth stencil textures need the DEPTH_STENCIL internal format
  13249. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13250. glInternalFormat = 34041; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13251. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13252. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13253. if (texture.type !== UnsignedInt248Type) {
  13254. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  13255. texture.type = UnsignedInt248Type;
  13256. glType = utils.convert(texture.type);
  13257. }
  13258. } //
  13259. state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  13260. } else if (texture.isDataTexture) {
  13261. // use manually created mipmaps if available
  13262. // if there are no manual mipmaps
  13263. // set 0 level mipmap and then use GL to generate other mipmap levels
  13264. if (mipmaps.length > 0 && supportsMips) {
  13265. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13266. mipmap = mipmaps[i];
  13267. state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13268. }
  13269. texture.generateMipmaps = false;
  13270. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13271. } else {
  13272. state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  13273. textureProperties.__maxMipLevel = 0;
  13274. }
  13275. } else if (texture.isCompressedTexture) {
  13276. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13277. mipmap = mipmaps[i];
  13278. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  13279. if (glFormat !== null) {
  13280. state.compressedTexImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  13281. } else {
  13282. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  13283. }
  13284. } else {
  13285. state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13286. }
  13287. }
  13288. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13289. } else if (texture.isDataTexture2DArray) {
  13290. state.texImage3D(35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  13291. textureProperties.__maxMipLevel = 0;
  13292. } else if (texture.isDataTexture3D) {
  13293. state.texImage3D(32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  13294. textureProperties.__maxMipLevel = 0;
  13295. } else {
  13296. // regular Texture (image, video, canvas)
  13297. // use manually created mipmaps if available
  13298. // if there are no manual mipmaps
  13299. // set 0 level mipmap and then use GL to generate other mipmap levels
  13300. if (mipmaps.length > 0 && supportsMips) {
  13301. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13302. mipmap = mipmaps[i];
  13303. state.texImage2D(3553, i, glInternalFormat, glFormat, glType, mipmap);
  13304. }
  13305. texture.generateMipmaps = false;
  13306. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13307. } else {
  13308. state.texImage2D(3553, 0, glInternalFormat, glFormat, glType, image);
  13309. textureProperties.__maxMipLevel = 0;
  13310. }
  13311. }
  13312. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13313. generateMipmap(textureType, texture, image.width, image.height);
  13314. }
  13315. textureProperties.__version = texture.version;
  13316. if (texture.onUpdate) texture.onUpdate(texture);
  13317. }
  13318. function uploadCubeTexture(textureProperties, texture, slot) {
  13319. if (texture.image.length !== 6) return;
  13320. initTexture(textureProperties, texture);
  13321. state.activeTexture(33984 + slot);
  13322. state.bindTexture(34067, textureProperties.__webglTexture);
  13323. _gl.pixelStorei(37440, texture.flipY);
  13324. const isCompressed = texture && (texture.isCompressedTexture || texture.image[0].isCompressedTexture);
  13325. const isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  13326. const cubeImage = [];
  13327. for (let i = 0; i < 6; i++) {
  13328. if (!isCompressed && !isDataTexture) {
  13329. cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize);
  13330. } else {
  13331. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  13332. }
  13333. }
  13334. const image = cubeImage[0],
  13335. supportsMips = isPowerOfTwo(image) || isWebGL2,
  13336. glFormat = utils.convert(texture.format),
  13337. glType = utils.convert(texture.type),
  13338. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  13339. setTextureParameters(34067, texture, supportsMips);
  13340. let mipmaps;
  13341. if (isCompressed) {
  13342. for (let i = 0; i < 6; i++) {
  13343. mipmaps = cubeImage[i].mipmaps;
  13344. for (let j = 0; j < mipmaps.length; j++) {
  13345. const mipmap = mipmaps[j];
  13346. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  13347. if (glFormat !== null) {
  13348. state.compressedTexImage2D(34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  13349. } else {
  13350. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  13351. }
  13352. } else {
  13353. state.texImage2D(34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13354. }
  13355. }
  13356. }
  13357. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13358. } else {
  13359. mipmaps = texture.mipmaps;
  13360. for (let i = 0; i < 6; i++) {
  13361. if (isDataTexture) {
  13362. state.texImage2D(34069 + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  13363. for (let j = 0; j < mipmaps.length; j++) {
  13364. const mipmap = mipmaps[j];
  13365. const mipmapImage = mipmap.image[i].image;
  13366. state.texImage2D(34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  13367. }
  13368. } else {
  13369. state.texImage2D(34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  13370. for (let j = 0; j < mipmaps.length; j++) {
  13371. const mipmap = mipmaps[j];
  13372. state.texImage2D(34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  13373. }
  13374. }
  13375. }
  13376. textureProperties.__maxMipLevel = mipmaps.length;
  13377. }
  13378. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13379. // We assume images for cube map have the same size.
  13380. generateMipmap(34067, texture, image.width, image.height);
  13381. }
  13382. textureProperties.__version = texture.version;
  13383. if (texture.onUpdate) texture.onUpdate(texture);
  13384. } // Render targets
  13385. // Setup storage for target texture and bind it to correct framebuffer
  13386. function setupFrameBufferTexture(framebuffer, renderTarget, attachment, textureTarget) {
  13387. const glFormat = utils.convert(renderTarget.texture.format);
  13388. const glType = utils.convert(renderTarget.texture.type);
  13389. const glInternalFormat = getInternalFormat(renderTarget.texture.internalFormat, glFormat, glType);
  13390. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  13391. _gl.bindFramebuffer(36160, framebuffer);
  13392. _gl.framebufferTexture2D(36160, attachment, textureTarget, properties.get(renderTarget.texture).__webglTexture, 0);
  13393. _gl.bindFramebuffer(36160, null);
  13394. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  13395. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  13396. _gl.bindRenderbuffer(36161, renderbuffer);
  13397. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  13398. let glInternalFormat = 33189;
  13399. if (isMultisample) {
  13400. const depthTexture = renderTarget.depthTexture;
  13401. if (depthTexture && depthTexture.isDepthTexture) {
  13402. if (depthTexture.type === FloatType) {
  13403. glInternalFormat = 36012;
  13404. } else if (depthTexture.type === UnsignedIntType) {
  13405. glInternalFormat = 33190;
  13406. }
  13407. }
  13408. const samples = getRenderTargetSamples(renderTarget);
  13409. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13410. } else {
  13411. _gl.renderbufferStorage(36161, glInternalFormat, renderTarget.width, renderTarget.height);
  13412. }
  13413. _gl.framebufferRenderbuffer(36160, 36096, 36161, renderbuffer);
  13414. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  13415. if (isMultisample) {
  13416. const samples = getRenderTargetSamples(renderTarget);
  13417. _gl.renderbufferStorageMultisample(36161, samples, 35056, renderTarget.width, renderTarget.height);
  13418. } else {
  13419. _gl.renderbufferStorage(36161, 34041, renderTarget.width, renderTarget.height);
  13420. }
  13421. _gl.framebufferRenderbuffer(36160, 33306, 36161, renderbuffer);
  13422. } else {
  13423. const glFormat = utils.convert(renderTarget.texture.format);
  13424. const glType = utils.convert(renderTarget.texture.type);
  13425. const glInternalFormat = getInternalFormat(renderTarget.texture.internalFormat, glFormat, glType);
  13426. if (isMultisample) {
  13427. const samples = getRenderTargetSamples(renderTarget);
  13428. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13429. } else {
  13430. _gl.renderbufferStorage(36161, glInternalFormat, renderTarget.width, renderTarget.height);
  13431. }
  13432. }
  13433. _gl.bindRenderbuffer(36161, null);
  13434. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  13435. function setupDepthTexture(framebuffer, renderTarget) {
  13436. const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
  13437. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  13438. _gl.bindFramebuffer(36160, framebuffer);
  13439. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  13440. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  13441. } // upload an empty depth texture with framebuffer size
  13442. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  13443. renderTarget.depthTexture.image.width = renderTarget.width;
  13444. renderTarget.depthTexture.image.height = renderTarget.height;
  13445. renderTarget.depthTexture.needsUpdate = true;
  13446. }
  13447. setTexture2D(renderTarget.depthTexture, 0);
  13448. const webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  13449. if (renderTarget.depthTexture.format === DepthFormat) {
  13450. _gl.framebufferTexture2D(36160, 36096, 3553, webglDepthTexture, 0);
  13451. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  13452. _gl.framebufferTexture2D(36160, 33306, 3553, webglDepthTexture, 0);
  13453. } else {
  13454. throw new Error('Unknown depthTexture format');
  13455. }
  13456. } // Setup GL resources for a non-texture depth buffer
  13457. function setupDepthRenderbuffer(renderTarget) {
  13458. const renderTargetProperties = properties.get(renderTarget);
  13459. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  13460. if (renderTarget.depthTexture) {
  13461. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  13462. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  13463. } else {
  13464. if (isCube) {
  13465. renderTargetProperties.__webglDepthbuffer = [];
  13466. for (let i = 0; i < 6; i++) {
  13467. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer[i]);
  13468. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  13469. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false);
  13470. }
  13471. } else {
  13472. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer);
  13473. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  13474. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
  13475. }
  13476. }
  13477. _gl.bindFramebuffer(36160, null);
  13478. } // Set up GL resources for the render target
  13479. function setupRenderTarget(renderTarget) {
  13480. const renderTargetProperties = properties.get(renderTarget);
  13481. const textureProperties = properties.get(renderTarget.texture);
  13482. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  13483. textureProperties.__webglTexture = _gl.createTexture();
  13484. info.memory.textures++;
  13485. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  13486. const isMultisample = renderTarget.isWebGLMultisampleRenderTarget === true;
  13487. const supportsMips = isPowerOfTwo(renderTarget) || isWebGL2; // Handles WebGL2 RGBFormat fallback - #18858
  13488. if (isWebGL2 && renderTarget.texture.format === RGBFormat && (renderTarget.texture.type === FloatType || renderTarget.texture.type === HalfFloatType)) {
  13489. renderTarget.texture.format = RGBAFormat;
  13490. console.warn('THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.');
  13491. } // Setup framebuffer
  13492. if (isCube) {
  13493. renderTargetProperties.__webglFramebuffer = [];
  13494. for (let i = 0; i < 6; i++) {
  13495. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  13496. }
  13497. } else {
  13498. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  13499. if (isMultisample) {
  13500. if (isWebGL2) {
  13501. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  13502. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  13503. _gl.bindRenderbuffer(36161, renderTargetProperties.__webglColorRenderbuffer);
  13504. const glFormat = utils.convert(renderTarget.texture.format);
  13505. const glType = utils.convert(renderTarget.texture.type);
  13506. const glInternalFormat = getInternalFormat(renderTarget.texture.internalFormat, glFormat, glType);
  13507. const samples = getRenderTargetSamples(renderTarget);
  13508. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13509. _gl.bindFramebuffer(36160, renderTargetProperties.__webglMultisampledFramebuffer);
  13510. _gl.framebufferRenderbuffer(36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer);
  13511. _gl.bindRenderbuffer(36161, null);
  13512. if (renderTarget.depthBuffer) {
  13513. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  13514. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  13515. }
  13516. _gl.bindFramebuffer(36160, null);
  13517. } else {
  13518. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  13519. }
  13520. }
  13521. } // Setup color buffer
  13522. if (isCube) {
  13523. state.bindTexture(34067, textureProperties.__webglTexture);
  13524. setTextureParameters(34067, renderTarget.texture, supportsMips);
  13525. for (let i = 0; i < 6; i++) {
  13526. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, 36064, 34069 + i);
  13527. }
  13528. if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
  13529. generateMipmap(34067, renderTarget.texture, renderTarget.width, renderTarget.height);
  13530. }
  13531. state.bindTexture(34067, null);
  13532. } else {
  13533. state.bindTexture(3553, textureProperties.__webglTexture);
  13534. setTextureParameters(3553, renderTarget.texture, supportsMips);
  13535. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553);
  13536. if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
  13537. generateMipmap(3553, renderTarget.texture, renderTarget.width, renderTarget.height);
  13538. }
  13539. state.bindTexture(3553, null);
  13540. } // Setup depth and stencil buffers
  13541. if (renderTarget.depthBuffer) {
  13542. setupDepthRenderbuffer(renderTarget);
  13543. }
  13544. }
  13545. function updateRenderTargetMipmap(renderTarget) {
  13546. const texture = renderTarget.texture;
  13547. const supportsMips = isPowerOfTwo(renderTarget) || isWebGL2;
  13548. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13549. const target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
  13550. const webglTexture = properties.get(texture).__webglTexture;
  13551. state.bindTexture(target, webglTexture);
  13552. generateMipmap(target, texture, renderTarget.width, renderTarget.height);
  13553. state.bindTexture(target, null);
  13554. }
  13555. }
  13556. function updateMultisampleRenderTarget(renderTarget) {
  13557. if (renderTarget.isWebGLMultisampleRenderTarget) {
  13558. if (isWebGL2) {
  13559. const renderTargetProperties = properties.get(renderTarget);
  13560. _gl.bindFramebuffer(36008, renderTargetProperties.__webglMultisampledFramebuffer);
  13561. _gl.bindFramebuffer(36009, renderTargetProperties.__webglFramebuffer);
  13562. const width = renderTarget.width;
  13563. const height = renderTarget.height;
  13564. let mask = 16384;
  13565. if (renderTarget.depthBuffer) mask |= 256;
  13566. if (renderTarget.stencilBuffer) mask |= 1024;
  13567. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, 9728);
  13568. _gl.bindFramebuffer(36160, renderTargetProperties.__webglMultisampledFramebuffer); // see #18905
  13569. } else {
  13570. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  13571. }
  13572. }
  13573. }
  13574. function getRenderTargetSamples(renderTarget) {
  13575. return isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ? Math.min(maxSamples, renderTarget.samples) : 0;
  13576. }
  13577. function updateVideoTexture(texture) {
  13578. const frame = info.render.frame; // Check the last frame we updated the VideoTexture
  13579. if (_videoTextures.get(texture) !== frame) {
  13580. _videoTextures.set(texture, frame);
  13581. texture.update();
  13582. }
  13583. } // backwards compatibility
  13584. let warnedTexture2D = false;
  13585. let warnedTextureCube = false;
  13586. function safeSetTexture2D(texture, slot) {
  13587. if (texture && texture.isWebGLRenderTarget) {
  13588. if (warnedTexture2D === false) {
  13589. console.warn("THREE.WebGLTextures.safeSetTexture2D: don't use render targets as textures. Use their .texture property instead.");
  13590. warnedTexture2D = true;
  13591. }
  13592. texture = texture.texture;
  13593. }
  13594. setTexture2D(texture, slot);
  13595. }
  13596. function safeSetTextureCube(texture, slot) {
  13597. if (texture && texture.isWebGLCubeRenderTarget) {
  13598. if (warnedTextureCube === false) {
  13599. console.warn("THREE.WebGLTextures.safeSetTextureCube: don't use cube render targets as textures. Use their .texture property instead.");
  13600. warnedTextureCube = true;
  13601. }
  13602. texture = texture.texture;
  13603. }
  13604. setTextureCube(texture, slot);
  13605. } //
  13606. this.allocateTextureUnit = allocateTextureUnit;
  13607. this.resetTextureUnits = resetTextureUnits;
  13608. this.setTexture2D = setTexture2D;
  13609. this.setTexture2DArray = setTexture2DArray;
  13610. this.setTexture3D = setTexture3D;
  13611. this.setTextureCube = setTextureCube;
  13612. this.setupRenderTarget = setupRenderTarget;
  13613. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  13614. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  13615. this.safeSetTexture2D = safeSetTexture2D;
  13616. this.safeSetTextureCube = safeSetTextureCube;
  13617. }
  13618. function WebGLUtils(gl, extensions, capabilities) {
  13619. const isWebGL2 = capabilities.isWebGL2;
  13620. function convert(p) {
  13621. let extension;
  13622. if (p === UnsignedByteType) return 5121;
  13623. if (p === UnsignedShort4444Type) return 32819;
  13624. if (p === UnsignedShort5551Type) return 32820;
  13625. if (p === UnsignedShort565Type) return 33635;
  13626. if (p === ByteType) return 5120;
  13627. if (p === ShortType) return 5122;
  13628. if (p === UnsignedShortType) return 5123;
  13629. if (p === IntType) return 5124;
  13630. if (p === UnsignedIntType) return 5125;
  13631. if (p === FloatType) return 5126;
  13632. if (p === HalfFloatType) {
  13633. if (isWebGL2) return 5131;
  13634. extension = extensions.get('OES_texture_half_float');
  13635. if (extension !== null) {
  13636. return extension.HALF_FLOAT_OES;
  13637. } else {
  13638. return null;
  13639. }
  13640. }
  13641. if (p === AlphaFormat) return 6406;
  13642. if (p === RGBFormat) return 6407;
  13643. if (p === RGBAFormat) return 6408;
  13644. if (p === LuminanceFormat) return 6409;
  13645. if (p === LuminanceAlphaFormat) return 6410;
  13646. if (p === DepthFormat) return 6402;
  13647. if (p === DepthStencilFormat) return 34041;
  13648. if (p === RedFormat) return 6403; // WebGL2 formats.
  13649. if (p === RedIntegerFormat) return 36244;
  13650. if (p === RGFormat) return 33319;
  13651. if (p === RGIntegerFormat) return 33320;
  13652. if (p === RGBIntegerFormat) return 36248;
  13653. if (p === RGBAIntegerFormat) return 36249;
  13654. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  13655. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  13656. if (extension !== null) {
  13657. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13658. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13659. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13660. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13661. } else {
  13662. return null;
  13663. }
  13664. }
  13665. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  13666. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  13667. if (extension !== null) {
  13668. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13669. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13670. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13671. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13672. } else {
  13673. return null;
  13674. }
  13675. }
  13676. if (p === RGB_ETC1_Format) {
  13677. extension = extensions.get('WEBGL_compressed_texture_etc1');
  13678. if (extension !== null) {
  13679. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13680. } else {
  13681. return null;
  13682. }
  13683. }
  13684. if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
  13685. extension = extensions.get('WEBGL_compressed_texture_etc');
  13686. if (extension !== null) {
  13687. if (p === RGB_ETC2_Format) return extension.COMPRESSED_RGB8_ETC2;
  13688. if (p === RGBA_ETC2_EAC_Format) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  13689. }
  13690. }
  13691. if (p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format || p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format || p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format || p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format || p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format || p === SRGB8_ALPHA8_ASTC_4x4_Format || p === SRGB8_ALPHA8_ASTC_5x4_Format || p === SRGB8_ALPHA8_ASTC_5x5_Format || p === SRGB8_ALPHA8_ASTC_6x5_Format || p === SRGB8_ALPHA8_ASTC_6x6_Format || p === SRGB8_ALPHA8_ASTC_8x5_Format || p === SRGB8_ALPHA8_ASTC_8x6_Format || p === SRGB8_ALPHA8_ASTC_8x8_Format || p === SRGB8_ALPHA8_ASTC_10x5_Format || p === SRGB8_ALPHA8_ASTC_10x6_Format || p === SRGB8_ALPHA8_ASTC_10x8_Format || p === SRGB8_ALPHA8_ASTC_10x10_Format || p === SRGB8_ALPHA8_ASTC_12x10_Format || p === SRGB8_ALPHA8_ASTC_12x12_Format) {
  13692. extension = extensions.get('WEBGL_compressed_texture_astc');
  13693. if (extension !== null) {
  13694. // TODO Complete?
  13695. return p;
  13696. } else {
  13697. return null;
  13698. }
  13699. }
  13700. if (p === RGBA_BPTC_Format) {
  13701. extension = extensions.get('EXT_texture_compression_bptc');
  13702. if (extension !== null) {
  13703. // TODO Complete?
  13704. return p;
  13705. } else {
  13706. return null;
  13707. }
  13708. }
  13709. if (p === UnsignedInt248Type) {
  13710. if (isWebGL2) return 34042;
  13711. extension = extensions.get('WEBGL_depth_texture');
  13712. if (extension !== null) {
  13713. return extension.UNSIGNED_INT_24_8_WEBGL;
  13714. } else {
  13715. return null;
  13716. }
  13717. }
  13718. }
  13719. return {
  13720. convert: convert
  13721. };
  13722. }
  13723. function ArrayCamera(array = []) {
  13724. PerspectiveCamera.call(this);
  13725. this.cameras = array;
  13726. }
  13727. ArrayCamera.prototype = Object.assign(Object.create(PerspectiveCamera.prototype), {
  13728. constructor: ArrayCamera,
  13729. isArrayCamera: true
  13730. });
  13731. function Group() {
  13732. Object3D.call(this);
  13733. this.type = 'Group';
  13734. }
  13735. Group.prototype = Object.assign(Object.create(Object3D.prototype), {
  13736. constructor: Group,
  13737. isGroup: true
  13738. });
  13739. function WebXRController() {
  13740. this._targetRay = null;
  13741. this._grip = null;
  13742. this._hand = null;
  13743. }
  13744. Object.assign(WebXRController.prototype, {
  13745. constructor: WebXRController,
  13746. getHandSpace: function () {
  13747. if (this._hand === null) {
  13748. this._hand = new Group();
  13749. this._hand.matrixAutoUpdate = false;
  13750. this._hand.visible = false;
  13751. this._hand.joints = [];
  13752. this._hand.inputState = {
  13753. pinching: false
  13754. };
  13755. if (window.XRHand) {
  13756. for (let i = 0; i <= window.XRHand.LITTLE_PHALANX_TIP; i++) {
  13757. // The transform of this joint will be updated with the joint pose on each frame
  13758. const joint = new Group();
  13759. joint.matrixAutoUpdate = false;
  13760. joint.visible = false;
  13761. this._hand.joints.push(joint); // ??
  13762. this._hand.add(joint);
  13763. }
  13764. }
  13765. }
  13766. return this._hand;
  13767. },
  13768. getTargetRaySpace: function () {
  13769. if (this._targetRay === null) {
  13770. this._targetRay = new Group();
  13771. this._targetRay.matrixAutoUpdate = false;
  13772. this._targetRay.visible = false;
  13773. }
  13774. return this._targetRay;
  13775. },
  13776. getGripSpace: function () {
  13777. if (this._grip === null) {
  13778. this._grip = new Group();
  13779. this._grip.matrixAutoUpdate = false;
  13780. this._grip.visible = false;
  13781. }
  13782. return this._grip;
  13783. },
  13784. dispatchEvent: function (event) {
  13785. if (this._targetRay !== null) {
  13786. this._targetRay.dispatchEvent(event);
  13787. }
  13788. if (this._grip !== null) {
  13789. this._grip.dispatchEvent(event);
  13790. }
  13791. if (this._hand !== null) {
  13792. this._hand.dispatchEvent(event);
  13793. }
  13794. return this;
  13795. },
  13796. disconnect: function (inputSource) {
  13797. this.dispatchEvent({
  13798. type: 'disconnected',
  13799. data: inputSource
  13800. });
  13801. if (this._targetRay !== null) {
  13802. this._targetRay.visible = false;
  13803. }
  13804. if (this._grip !== null) {
  13805. this._grip.visible = false;
  13806. }
  13807. if (this._hand !== null) {
  13808. this._hand.visible = false;
  13809. }
  13810. return this;
  13811. },
  13812. update: function (inputSource, frame, referenceSpace) {
  13813. let inputPose = null;
  13814. let gripPose = null;
  13815. let handPose = null;
  13816. const targetRay = this._targetRay;
  13817. const grip = this._grip;
  13818. const hand = this._hand;
  13819. if (inputSource && frame.session.visibilityState !== 'visible-blurred') {
  13820. if (hand && inputSource.hand) {
  13821. handPose = true;
  13822. for (let i = 0; i <= window.XRHand.LITTLE_PHALANX_TIP; i++) {
  13823. if (inputSource.hand[i]) {
  13824. // Update the joints groups with the XRJoint poses
  13825. const jointPose = frame.getJointPose(inputSource.hand[i], referenceSpace);
  13826. const joint = hand.joints[i];
  13827. if (jointPose !== null) {
  13828. joint.matrix.fromArray(jointPose.transform.matrix);
  13829. joint.matrix.decompose(joint.position, joint.rotation, joint.scale);
  13830. joint.jointRadius = jointPose.radius;
  13831. }
  13832. joint.visible = jointPose !== null; // Custom events
  13833. // Check pinch
  13834. const indexTip = hand.joints[window.XRHand.INDEX_PHALANX_TIP];
  13835. const thumbTip = hand.joints[window.XRHand.THUMB_PHALANX_TIP];
  13836. const distance = indexTip.position.distanceTo(thumbTip.position);
  13837. const distanceToPinch = 0.02;
  13838. const threshold = 0.005;
  13839. if (hand.inputState.pinching && distance > distanceToPinch + threshold) {
  13840. hand.inputState.pinching = false;
  13841. this.dispatchEvent({
  13842. type: "pinchend",
  13843. handedness: inputSource.handedness,
  13844. target: this
  13845. });
  13846. } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) {
  13847. hand.inputState.pinching = true;
  13848. this.dispatchEvent({
  13849. type: "pinchstart",
  13850. handedness: inputSource.handedness,
  13851. target: this
  13852. });
  13853. }
  13854. }
  13855. }
  13856. } else {
  13857. if (targetRay !== null) {
  13858. inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  13859. if (inputPose !== null) {
  13860. targetRay.matrix.fromArray(inputPose.transform.matrix);
  13861. targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale);
  13862. }
  13863. }
  13864. if (grip !== null && inputSource.gripSpace) {
  13865. gripPose = frame.getPose(inputSource.gripSpace, referenceSpace);
  13866. if (gripPose !== null) {
  13867. grip.matrix.fromArray(gripPose.transform.matrix);
  13868. grip.matrix.decompose(grip.position, grip.rotation, grip.scale);
  13869. }
  13870. }
  13871. }
  13872. }
  13873. if (targetRay !== null) {
  13874. targetRay.visible = inputPose !== null;
  13875. }
  13876. if (grip !== null) {
  13877. grip.visible = gripPose !== null;
  13878. }
  13879. if (hand !== null) {
  13880. hand.visible = handPose !== null;
  13881. }
  13882. return this;
  13883. }
  13884. });
  13885. function WebXRManager(renderer, gl) {
  13886. const scope = this;
  13887. let session = null;
  13888. let framebufferScaleFactor = 1.0;
  13889. let referenceSpace = null;
  13890. let referenceSpaceType = 'local-floor';
  13891. let pose = null;
  13892. const controllers = [];
  13893. const inputSourcesMap = new Map(); //
  13894. const cameraL = new PerspectiveCamera();
  13895. cameraL.layers.enable(1);
  13896. cameraL.viewport = new Vector4();
  13897. const cameraR = new PerspectiveCamera();
  13898. cameraR.layers.enable(2);
  13899. cameraR.viewport = new Vector4();
  13900. const cameras = [cameraL, cameraR];
  13901. const cameraVR = new ArrayCamera();
  13902. cameraVR.layers.enable(1);
  13903. cameraVR.layers.enable(2);
  13904. let _currentDepthNear = null;
  13905. let _currentDepthFar = null; //
  13906. this.enabled = false;
  13907. this.isPresenting = false;
  13908. this.getController = function (index) {
  13909. let controller = controllers[index];
  13910. if (controller === undefined) {
  13911. controller = new WebXRController();
  13912. controllers[index] = controller;
  13913. }
  13914. return controller.getTargetRaySpace();
  13915. };
  13916. this.getControllerGrip = function (index) {
  13917. let controller = controllers[index];
  13918. if (controller === undefined) {
  13919. controller = new WebXRController();
  13920. controllers[index] = controller;
  13921. }
  13922. return controller.getGripSpace();
  13923. };
  13924. this.getHand = function (index) {
  13925. let controller = controllers[index];
  13926. if (controller === undefined) {
  13927. controller = new WebXRController();
  13928. controllers[index] = controller;
  13929. }
  13930. return controller.getHandSpace();
  13931. }; //
  13932. function onSessionEvent(event) {
  13933. const controller = inputSourcesMap.get(event.inputSource);
  13934. if (controller) {
  13935. controller.dispatchEvent({
  13936. type: event.type,
  13937. data: event.inputSource
  13938. });
  13939. }
  13940. }
  13941. function onSessionEnd() {
  13942. inputSourcesMap.forEach(function (controller, inputSource) {
  13943. controller.disconnect(inputSource);
  13944. });
  13945. inputSourcesMap.clear(); //
  13946. renderer.setFramebuffer(null);
  13947. renderer.setRenderTarget(renderer.getRenderTarget()); // Hack #15830
  13948. animation.stop();
  13949. scope.isPresenting = false;
  13950. scope.dispatchEvent({
  13951. type: 'sessionend'
  13952. });
  13953. }
  13954. function onRequestReferenceSpace(value) {
  13955. referenceSpace = value;
  13956. animation.setContext(session);
  13957. animation.start();
  13958. scope.isPresenting = true;
  13959. scope.dispatchEvent({
  13960. type: 'sessionstart'
  13961. });
  13962. }
  13963. this.setFramebufferScaleFactor = function (value) {
  13964. framebufferScaleFactor = value;
  13965. if (scope.isPresenting === true) {
  13966. console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.');
  13967. }
  13968. };
  13969. this.setReferenceSpaceType = function (value) {
  13970. referenceSpaceType = value;
  13971. if (scope.isPresenting === true) {
  13972. console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.');
  13973. }
  13974. };
  13975. this.getReferenceSpace = function () {
  13976. return referenceSpace;
  13977. };
  13978. this.getSession = function () {
  13979. return session;
  13980. };
  13981. this.setSession = function (value) {
  13982. session = value;
  13983. if (session !== null) {
  13984. session.addEventListener('select', onSessionEvent);
  13985. session.addEventListener('selectstart', onSessionEvent);
  13986. session.addEventListener('selectend', onSessionEvent);
  13987. session.addEventListener('squeeze', onSessionEvent);
  13988. session.addEventListener('squeezestart', onSessionEvent);
  13989. session.addEventListener('squeezeend', onSessionEvent);
  13990. session.addEventListener('end', onSessionEnd);
  13991. const attributes = gl.getContextAttributes();
  13992. if (attributes.xrCompatible !== true) {
  13993. gl.makeXRCompatible();
  13994. }
  13995. const layerInit = {
  13996. antialias: attributes.antialias,
  13997. alpha: attributes.alpha,
  13998. depth: attributes.depth,
  13999. stencil: attributes.stencil,
  14000. framebufferScaleFactor: framebufferScaleFactor
  14001. }; // eslint-disable-next-line no-undef
  14002. const baseLayer = new XRWebGLLayer(session, gl, layerInit);
  14003. session.updateRenderState({
  14004. baseLayer: baseLayer
  14005. });
  14006. session.requestReferenceSpace(referenceSpaceType).then(onRequestReferenceSpace); //
  14007. session.addEventListener('inputsourceschange', updateInputSources);
  14008. }
  14009. };
  14010. function updateInputSources(event) {
  14011. const inputSources = session.inputSources; // Assign inputSources to available controllers
  14012. for (let i = 0; i < controllers.length; i++) {
  14013. inputSourcesMap.set(inputSources[i], controllers[i]);
  14014. } // Notify disconnected
  14015. for (let i = 0; i < event.removed.length; i++) {
  14016. const inputSource = event.removed[i];
  14017. const controller = inputSourcesMap.get(inputSource);
  14018. if (controller) {
  14019. controller.dispatchEvent({
  14020. type: 'disconnected',
  14021. data: inputSource
  14022. });
  14023. inputSourcesMap.delete(inputSource);
  14024. }
  14025. } // Notify connected
  14026. for (let i = 0; i < event.added.length; i++) {
  14027. const inputSource = event.added[i];
  14028. const controller = inputSourcesMap.get(inputSource);
  14029. if (controller) {
  14030. controller.dispatchEvent({
  14031. type: 'connected',
  14032. data: inputSource
  14033. });
  14034. }
  14035. }
  14036. } //
  14037. const cameraLPos = new Vector3();
  14038. const cameraRPos = new Vector3();
  14039. /**
  14040. * Assumes 2 cameras that are parallel and share an X-axis, and that
  14041. * the cameras' projection and world matrices have already been set.
  14042. * And that near and far planes are identical for both cameras.
  14043. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  14044. */
  14045. function setProjectionFromUnion(camera, cameraL, cameraR) {
  14046. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  14047. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  14048. const ipd = cameraLPos.distanceTo(cameraRPos);
  14049. const projL = cameraL.projectionMatrix.elements;
  14050. const projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  14051. // most likely identical top and bottom frustum extents.
  14052. // Use the left camera for these values.
  14053. const near = projL[14] / (projL[10] - 1);
  14054. const far = projL[14] / (projL[10] + 1);
  14055. const topFov = (projL[9] + 1) / projL[5];
  14056. const bottomFov = (projL[9] - 1) / projL[5];
  14057. const leftFov = (projL[8] - 1) / projL[0];
  14058. const rightFov = (projR[8] + 1) / projR[0];
  14059. const left = near * leftFov;
  14060. const right = near * rightFov; // Calculate the new camera's position offset from the
  14061. // left camera. xOffset should be roughly half `ipd`.
  14062. const zOffset = ipd / (-leftFov + rightFov);
  14063. const xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  14064. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  14065. camera.translateX(xOffset);
  14066. camera.translateZ(zOffset);
  14067. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  14068. camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); // Find the union of the frustum values of the cameras and scale
  14069. // the values so that the near plane's position does not change in world space,
  14070. // although must now be relative to the new union camera.
  14071. const near2 = near + zOffset;
  14072. const far2 = far + zOffset;
  14073. const left2 = left - xOffset;
  14074. const right2 = right + (ipd - xOffset);
  14075. const top2 = topFov * far / far2 * near2;
  14076. const bottom2 = bottomFov * far / far2 * near2;
  14077. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  14078. }
  14079. function updateCamera(camera, parent) {
  14080. if (parent === null) {
  14081. camera.matrixWorld.copy(camera.matrix);
  14082. } else {
  14083. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  14084. }
  14085. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  14086. }
  14087. this.getCamera = function (camera) {
  14088. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  14089. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  14090. if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) {
  14091. // Note that the new renderState won't apply until the next frame. See #18320
  14092. session.updateRenderState({
  14093. depthNear: cameraVR.near,
  14094. depthFar: cameraVR.far
  14095. });
  14096. _currentDepthNear = cameraVR.near;
  14097. _currentDepthFar = cameraVR.far;
  14098. }
  14099. const parent = camera.parent;
  14100. const cameras = cameraVR.cameras;
  14101. updateCamera(cameraVR, parent);
  14102. for (let i = 0; i < cameras.length; i++) {
  14103. updateCamera(cameras[i], parent);
  14104. } // update camera and its children
  14105. camera.matrixWorld.copy(cameraVR.matrixWorld);
  14106. const children = camera.children;
  14107. for (let i = 0, l = children.length; i < l; i++) {
  14108. children[i].updateMatrixWorld(true);
  14109. } // update projection matrix for proper view frustum culling
  14110. if (cameras.length === 2) {
  14111. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  14112. } else {
  14113. // assume single camera setup (AR)
  14114. cameraVR.projectionMatrix.copy(cameraL.projectionMatrix);
  14115. }
  14116. return cameraVR;
  14117. }; // Animation Loop
  14118. let onAnimationFrameCallback = null;
  14119. function onAnimationFrame(time, frame) {
  14120. pose = frame.getViewerPose(referenceSpace);
  14121. if (pose !== null) {
  14122. const views = pose.views;
  14123. const baseLayer = session.renderState.baseLayer;
  14124. renderer.setFramebuffer(baseLayer.framebuffer);
  14125. let cameraVRNeedsUpdate = false; // check if it's necessary to rebuild cameraVR's camera list
  14126. if (views.length !== cameraVR.cameras.length) {
  14127. cameraVR.cameras.length = 0;
  14128. cameraVRNeedsUpdate = true;
  14129. }
  14130. for (let i = 0; i < views.length; i++) {
  14131. const view = views[i];
  14132. const viewport = baseLayer.getViewport(view);
  14133. const camera = cameras[i];
  14134. camera.matrix.fromArray(view.transform.matrix);
  14135. camera.projectionMatrix.fromArray(view.projectionMatrix);
  14136. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  14137. if (i === 0) {
  14138. cameraVR.matrix.copy(camera.matrix);
  14139. }
  14140. if (cameraVRNeedsUpdate === true) {
  14141. cameraVR.cameras.push(camera);
  14142. }
  14143. }
  14144. } //
  14145. const inputSources = session.inputSources;
  14146. for (let i = 0; i < controllers.length; i++) {
  14147. const controller = controllers[i];
  14148. const inputSource = inputSources[i];
  14149. controller.update(inputSource, frame, referenceSpace);
  14150. }
  14151. if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame);
  14152. }
  14153. const animation = new WebGLAnimation();
  14154. animation.setAnimationLoop(onAnimationFrame);
  14155. this.setAnimationLoop = function (callback) {
  14156. onAnimationFrameCallback = callback;
  14157. };
  14158. this.dispose = function () {};
  14159. }
  14160. Object.assign(WebXRManager.prototype, EventDispatcher.prototype);
  14161. function WebGLMaterials(properties) {
  14162. function refreshFogUniforms(uniforms, fog) {
  14163. uniforms.fogColor.value.copy(fog.color);
  14164. if (fog.isFog) {
  14165. uniforms.fogNear.value = fog.near;
  14166. uniforms.fogFar.value = fog.far;
  14167. } else if (fog.isFogExp2) {
  14168. uniforms.fogDensity.value = fog.density;
  14169. }
  14170. }
  14171. function refreshMaterialUniforms(uniforms, material, pixelRatio, height) {
  14172. if (material.isMeshBasicMaterial) {
  14173. refreshUniformsCommon(uniforms, material);
  14174. } else if (material.isMeshLambertMaterial) {
  14175. refreshUniformsCommon(uniforms, material);
  14176. refreshUniformsLambert(uniforms, material);
  14177. } else if (material.isMeshToonMaterial) {
  14178. refreshUniformsCommon(uniforms, material);
  14179. refreshUniformsToon(uniforms, material);
  14180. } else if (material.isMeshPhongMaterial) {
  14181. refreshUniformsCommon(uniforms, material);
  14182. refreshUniformsPhong(uniforms, material);
  14183. } else if (material.isMeshStandardMaterial) {
  14184. refreshUniformsCommon(uniforms, material);
  14185. if (material.isMeshPhysicalMaterial) {
  14186. refreshUniformsPhysical(uniforms, material);
  14187. } else {
  14188. refreshUniformsStandard(uniforms, material);
  14189. }
  14190. } else if (material.isMeshMatcapMaterial) {
  14191. refreshUniformsCommon(uniforms, material);
  14192. refreshUniformsMatcap(uniforms, material);
  14193. } else if (material.isMeshDepthMaterial) {
  14194. refreshUniformsCommon(uniforms, material);
  14195. refreshUniformsDepth(uniforms, material);
  14196. } else if (material.isMeshDistanceMaterial) {
  14197. refreshUniformsCommon(uniforms, material);
  14198. refreshUniformsDistance(uniforms, material);
  14199. } else if (material.isMeshNormalMaterial) {
  14200. refreshUniformsCommon(uniforms, material);
  14201. refreshUniformsNormal(uniforms, material);
  14202. } else if (material.isLineBasicMaterial) {
  14203. refreshUniformsLine(uniforms, material);
  14204. if (material.isLineDashedMaterial) {
  14205. refreshUniformsDash(uniforms, material);
  14206. }
  14207. } else if (material.isPointsMaterial) {
  14208. refreshUniformsPoints(uniforms, material, pixelRatio, height);
  14209. } else if (material.isSpriteMaterial) {
  14210. refreshUniformsSprites(uniforms, material);
  14211. } else if (material.isShadowMaterial) {
  14212. uniforms.color.value.copy(material.color);
  14213. uniforms.opacity.value = material.opacity;
  14214. } else if (material.isShaderMaterial) {
  14215. material.uniformsNeedUpdate = false; // #15581
  14216. }
  14217. }
  14218. function refreshUniformsCommon(uniforms, material) {
  14219. uniforms.opacity.value = material.opacity;
  14220. if (material.color) {
  14221. uniforms.diffuse.value.copy(material.color);
  14222. }
  14223. if (material.emissive) {
  14224. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  14225. }
  14226. if (material.map) {
  14227. uniforms.map.value = material.map;
  14228. }
  14229. if (material.alphaMap) {
  14230. uniforms.alphaMap.value = material.alphaMap;
  14231. }
  14232. if (material.specularMap) {
  14233. uniforms.specularMap.value = material.specularMap;
  14234. }
  14235. const envMap = properties.get(material).envMap;
  14236. if (envMap) {
  14237. uniforms.envMap.value = envMap;
  14238. uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap._needsFlipEnvMap ? -1 : 1;
  14239. uniforms.reflectivity.value = material.reflectivity;
  14240. uniforms.refractionRatio.value = material.refractionRatio;
  14241. const maxMipLevel = properties.get(envMap).__maxMipLevel;
  14242. if (maxMipLevel !== undefined) {
  14243. uniforms.maxMipLevel.value = maxMipLevel;
  14244. }
  14245. }
  14246. if (material.lightMap) {
  14247. uniforms.lightMap.value = material.lightMap;
  14248. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  14249. }
  14250. if (material.aoMap) {
  14251. uniforms.aoMap.value = material.aoMap;
  14252. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  14253. } // uv repeat and offset setting priorities
  14254. // 1. color map
  14255. // 2. specular map
  14256. // 3. displacementMap map
  14257. // 4. normal map
  14258. // 5. bump map
  14259. // 6. roughnessMap map
  14260. // 7. metalnessMap map
  14261. // 8. alphaMap map
  14262. // 9. emissiveMap map
  14263. // 10. clearcoat map
  14264. // 11. clearcoat normal map
  14265. // 12. clearcoat roughnessMap map
  14266. let uvScaleMap;
  14267. if (material.map) {
  14268. uvScaleMap = material.map;
  14269. } else if (material.specularMap) {
  14270. uvScaleMap = material.specularMap;
  14271. } else if (material.displacementMap) {
  14272. uvScaleMap = material.displacementMap;
  14273. } else if (material.normalMap) {
  14274. uvScaleMap = material.normalMap;
  14275. } else if (material.bumpMap) {
  14276. uvScaleMap = material.bumpMap;
  14277. } else if (material.roughnessMap) {
  14278. uvScaleMap = material.roughnessMap;
  14279. } else if (material.metalnessMap) {
  14280. uvScaleMap = material.metalnessMap;
  14281. } else if (material.alphaMap) {
  14282. uvScaleMap = material.alphaMap;
  14283. } else if (material.emissiveMap) {
  14284. uvScaleMap = material.emissiveMap;
  14285. } else if (material.clearcoatMap) {
  14286. uvScaleMap = material.clearcoatMap;
  14287. } else if (material.clearcoatNormalMap) {
  14288. uvScaleMap = material.clearcoatNormalMap;
  14289. } else if (material.clearcoatRoughnessMap) {
  14290. uvScaleMap = material.clearcoatRoughnessMap;
  14291. }
  14292. if (uvScaleMap !== undefined) {
  14293. // backwards compatibility
  14294. if (uvScaleMap.isWebGLRenderTarget) {
  14295. uvScaleMap = uvScaleMap.texture;
  14296. }
  14297. if (uvScaleMap.matrixAutoUpdate === true) {
  14298. uvScaleMap.updateMatrix();
  14299. }
  14300. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  14301. } // uv repeat and offset setting priorities for uv2
  14302. // 1. ao map
  14303. // 2. light map
  14304. let uv2ScaleMap;
  14305. if (material.aoMap) {
  14306. uv2ScaleMap = material.aoMap;
  14307. } else if (material.lightMap) {
  14308. uv2ScaleMap = material.lightMap;
  14309. }
  14310. if (uv2ScaleMap !== undefined) {
  14311. // backwards compatibility
  14312. if (uv2ScaleMap.isWebGLRenderTarget) {
  14313. uv2ScaleMap = uv2ScaleMap.texture;
  14314. }
  14315. if (uv2ScaleMap.matrixAutoUpdate === true) {
  14316. uv2ScaleMap.updateMatrix();
  14317. }
  14318. uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix);
  14319. }
  14320. }
  14321. function refreshUniformsLine(uniforms, material) {
  14322. uniforms.diffuse.value.copy(material.color);
  14323. uniforms.opacity.value = material.opacity;
  14324. }
  14325. function refreshUniformsDash(uniforms, material) {
  14326. uniforms.dashSize.value = material.dashSize;
  14327. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14328. uniforms.scale.value = material.scale;
  14329. }
  14330. function refreshUniformsPoints(uniforms, material, pixelRatio, height) {
  14331. uniforms.diffuse.value.copy(material.color);
  14332. uniforms.opacity.value = material.opacity;
  14333. uniforms.size.value = material.size * pixelRatio;
  14334. uniforms.scale.value = height * 0.5;
  14335. if (material.map) {
  14336. uniforms.map.value = material.map;
  14337. }
  14338. if (material.alphaMap) {
  14339. uniforms.alphaMap.value = material.alphaMap;
  14340. } // uv repeat and offset setting priorities
  14341. // 1. color map
  14342. // 2. alpha map
  14343. let uvScaleMap;
  14344. if (material.map) {
  14345. uvScaleMap = material.map;
  14346. } else if (material.alphaMap) {
  14347. uvScaleMap = material.alphaMap;
  14348. }
  14349. if (uvScaleMap !== undefined) {
  14350. if (uvScaleMap.matrixAutoUpdate === true) {
  14351. uvScaleMap.updateMatrix();
  14352. }
  14353. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  14354. }
  14355. }
  14356. function refreshUniformsSprites(uniforms, material) {
  14357. uniforms.diffuse.value.copy(material.color);
  14358. uniforms.opacity.value = material.opacity;
  14359. uniforms.rotation.value = material.rotation;
  14360. if (material.map) {
  14361. uniforms.map.value = material.map;
  14362. }
  14363. if (material.alphaMap) {
  14364. uniforms.alphaMap.value = material.alphaMap;
  14365. } // uv repeat and offset setting priorities
  14366. // 1. color map
  14367. // 2. alpha map
  14368. let uvScaleMap;
  14369. if (material.map) {
  14370. uvScaleMap = material.map;
  14371. } else if (material.alphaMap) {
  14372. uvScaleMap = material.alphaMap;
  14373. }
  14374. if (uvScaleMap !== undefined) {
  14375. if (uvScaleMap.matrixAutoUpdate === true) {
  14376. uvScaleMap.updateMatrix();
  14377. }
  14378. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  14379. }
  14380. }
  14381. function refreshUniformsLambert(uniforms, material) {
  14382. if (material.emissiveMap) {
  14383. uniforms.emissiveMap.value = material.emissiveMap;
  14384. }
  14385. }
  14386. function refreshUniformsPhong(uniforms, material) {
  14387. uniforms.specular.value.copy(material.specular);
  14388. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  14389. if (material.emissiveMap) {
  14390. uniforms.emissiveMap.value = material.emissiveMap;
  14391. }
  14392. if (material.bumpMap) {
  14393. uniforms.bumpMap.value = material.bumpMap;
  14394. uniforms.bumpScale.value = material.bumpScale;
  14395. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14396. }
  14397. if (material.normalMap) {
  14398. uniforms.normalMap.value = material.normalMap;
  14399. uniforms.normalScale.value.copy(material.normalScale);
  14400. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14401. }
  14402. if (material.displacementMap) {
  14403. uniforms.displacementMap.value = material.displacementMap;
  14404. uniforms.displacementScale.value = material.displacementScale;
  14405. uniforms.displacementBias.value = material.displacementBias;
  14406. }
  14407. }
  14408. function refreshUniformsToon(uniforms, material) {
  14409. if (material.gradientMap) {
  14410. uniforms.gradientMap.value = material.gradientMap;
  14411. }
  14412. if (material.emissiveMap) {
  14413. uniforms.emissiveMap.value = material.emissiveMap;
  14414. }
  14415. if (material.bumpMap) {
  14416. uniforms.bumpMap.value = material.bumpMap;
  14417. uniforms.bumpScale.value = material.bumpScale;
  14418. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14419. }
  14420. if (material.normalMap) {
  14421. uniforms.normalMap.value = material.normalMap;
  14422. uniforms.normalScale.value.copy(material.normalScale);
  14423. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14424. }
  14425. if (material.displacementMap) {
  14426. uniforms.displacementMap.value = material.displacementMap;
  14427. uniforms.displacementScale.value = material.displacementScale;
  14428. uniforms.displacementBias.value = material.displacementBias;
  14429. }
  14430. }
  14431. function refreshUniformsStandard(uniforms, material) {
  14432. uniforms.roughness.value = material.roughness;
  14433. uniforms.metalness.value = material.metalness;
  14434. if (material.roughnessMap) {
  14435. uniforms.roughnessMap.value = material.roughnessMap;
  14436. }
  14437. if (material.metalnessMap) {
  14438. uniforms.metalnessMap.value = material.metalnessMap;
  14439. }
  14440. if (material.emissiveMap) {
  14441. uniforms.emissiveMap.value = material.emissiveMap;
  14442. }
  14443. if (material.bumpMap) {
  14444. uniforms.bumpMap.value = material.bumpMap;
  14445. uniforms.bumpScale.value = material.bumpScale;
  14446. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14447. }
  14448. if (material.normalMap) {
  14449. uniforms.normalMap.value = material.normalMap;
  14450. uniforms.normalScale.value.copy(material.normalScale);
  14451. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14452. }
  14453. if (material.displacementMap) {
  14454. uniforms.displacementMap.value = material.displacementMap;
  14455. uniforms.displacementScale.value = material.displacementScale;
  14456. uniforms.displacementBias.value = material.displacementBias;
  14457. }
  14458. const envMap = properties.get(material).envMap;
  14459. if (envMap) {
  14460. //uniforms.envMap.value = material.envMap; // part of uniforms common
  14461. uniforms.envMapIntensity.value = material.envMapIntensity;
  14462. }
  14463. }
  14464. function refreshUniformsPhysical(uniforms, material) {
  14465. refreshUniformsStandard(uniforms, material);
  14466. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  14467. uniforms.clearcoat.value = material.clearcoat;
  14468. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  14469. if (material.sheen) uniforms.sheen.value.copy(material.sheen);
  14470. if (material.clearcoatMap) {
  14471. uniforms.clearcoatMap.value = material.clearcoatMap;
  14472. }
  14473. if (material.clearcoatRoughnessMap) {
  14474. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  14475. }
  14476. if (material.clearcoatNormalMap) {
  14477. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  14478. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  14479. if (material.side === BackSide) {
  14480. uniforms.clearcoatNormalScale.value.negate();
  14481. }
  14482. }
  14483. uniforms.transmission.value = material.transmission;
  14484. if (material.transmissionMap) {
  14485. uniforms.transmissionMap.value = material.transmissionMap;
  14486. }
  14487. }
  14488. function refreshUniformsMatcap(uniforms, material) {
  14489. if (material.matcap) {
  14490. uniforms.matcap.value = material.matcap;
  14491. }
  14492. if (material.bumpMap) {
  14493. uniforms.bumpMap.value = material.bumpMap;
  14494. uniforms.bumpScale.value = material.bumpScale;
  14495. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14496. }
  14497. if (material.normalMap) {
  14498. uniforms.normalMap.value = material.normalMap;
  14499. uniforms.normalScale.value.copy(material.normalScale);
  14500. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14501. }
  14502. if (material.displacementMap) {
  14503. uniforms.displacementMap.value = material.displacementMap;
  14504. uniforms.displacementScale.value = material.displacementScale;
  14505. uniforms.displacementBias.value = material.displacementBias;
  14506. }
  14507. }
  14508. function refreshUniformsDepth(uniforms, material) {
  14509. if (material.displacementMap) {
  14510. uniforms.displacementMap.value = material.displacementMap;
  14511. uniforms.displacementScale.value = material.displacementScale;
  14512. uniforms.displacementBias.value = material.displacementBias;
  14513. }
  14514. }
  14515. function refreshUniformsDistance(uniforms, material) {
  14516. if (material.displacementMap) {
  14517. uniforms.displacementMap.value = material.displacementMap;
  14518. uniforms.displacementScale.value = material.displacementScale;
  14519. uniforms.displacementBias.value = material.displacementBias;
  14520. }
  14521. uniforms.referencePosition.value.copy(material.referencePosition);
  14522. uniforms.nearDistance.value = material.nearDistance;
  14523. uniforms.farDistance.value = material.farDistance;
  14524. }
  14525. function refreshUniformsNormal(uniforms, material) {
  14526. if (material.bumpMap) {
  14527. uniforms.bumpMap.value = material.bumpMap;
  14528. uniforms.bumpScale.value = material.bumpScale;
  14529. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14530. }
  14531. if (material.normalMap) {
  14532. uniforms.normalMap.value = material.normalMap;
  14533. uniforms.normalScale.value.copy(material.normalScale);
  14534. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14535. }
  14536. if (material.displacementMap) {
  14537. uniforms.displacementMap.value = material.displacementMap;
  14538. uniforms.displacementScale.value = material.displacementScale;
  14539. uniforms.displacementBias.value = material.displacementBias;
  14540. }
  14541. }
  14542. return {
  14543. refreshFogUniforms: refreshFogUniforms,
  14544. refreshMaterialUniforms: refreshMaterialUniforms
  14545. };
  14546. }
  14547. function createCanvasElement() {
  14548. const canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  14549. canvas.style.display = 'block';
  14550. return canvas;
  14551. }
  14552. function WebGLRenderer(parameters) {
  14553. parameters = parameters || {};
  14554. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  14555. _context = parameters.context !== undefined ? parameters.context : null,
  14556. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  14557. _depth = parameters.depth !== undefined ? parameters.depth : true,
  14558. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  14559. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  14560. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  14561. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  14562. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  14563. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  14564. let currentRenderList = null;
  14565. let currentRenderState = null; // public properties
  14566. this.domElement = _canvas; // Debug configuration container
  14567. this.debug = {
  14568. /**
  14569. * Enables error checking and reporting when shader programs are being compiled
  14570. * @type {boolean}
  14571. */
  14572. checkShaderErrors: true
  14573. }; // clearing
  14574. this.autoClear = true;
  14575. this.autoClearColor = true;
  14576. this.autoClearDepth = true;
  14577. this.autoClearStencil = true; // scene graph
  14578. this.sortObjects = true; // user-defined clipping
  14579. this.clippingPlanes = [];
  14580. this.localClippingEnabled = false; // physically based shading
  14581. this.gammaFactor = 2.0; // for backwards compatibility
  14582. this.outputEncoding = LinearEncoding; // physical lights
  14583. this.physicallyCorrectLights = false; // tone mapping
  14584. this.toneMapping = NoToneMapping;
  14585. this.toneMappingExposure = 1.0; // morphs
  14586. this.maxMorphTargets = 8;
  14587. this.maxMorphNormals = 4; // internal properties
  14588. const _this = this;
  14589. let _isContextLost = false; // internal state cache
  14590. let _framebuffer = null;
  14591. let _currentActiveCubeFace = 0;
  14592. let _currentActiveMipmapLevel = 0;
  14593. let _currentRenderTarget = null;
  14594. let _currentFramebuffer = null;
  14595. let _currentMaterialId = -1;
  14596. let _currentCamera = null;
  14597. let _currentArrayCamera = null;
  14598. const _currentViewport = new Vector4();
  14599. const _currentScissor = new Vector4();
  14600. let _currentScissorTest = null; //
  14601. let _width = _canvas.width;
  14602. let _height = _canvas.height;
  14603. let _pixelRatio = 1;
  14604. let _opaqueSort = null;
  14605. let _transparentSort = null;
  14606. const _viewport = new Vector4(0, 0, _width, _height);
  14607. const _scissor = new Vector4(0, 0, _width, _height);
  14608. let _scissorTest = false; // frustum
  14609. const _frustum = new Frustum(); // clipping
  14610. let _clippingEnabled = false;
  14611. let _localClippingEnabled = false; // camera matrices cache
  14612. const _projScreenMatrix = new Matrix4();
  14613. const _vector3 = new Vector3();
  14614. const _emptyScene = {
  14615. background: null,
  14616. fog: null,
  14617. environment: null,
  14618. overrideMaterial: null,
  14619. isScene: true
  14620. };
  14621. function getTargetPixelRatio() {
  14622. return _currentRenderTarget === null ? _pixelRatio : 1;
  14623. } // initialize
  14624. let _gl = _context;
  14625. function getContext(contextNames, contextAttributes) {
  14626. for (let i = 0; i < contextNames.length; i++) {
  14627. const contextName = contextNames[i];
  14628. const context = _canvas.getContext(contextName, contextAttributes);
  14629. if (context !== null) return context;
  14630. }
  14631. return null;
  14632. }
  14633. try {
  14634. const contextAttributes = {
  14635. alpha: _alpha,
  14636. depth: _depth,
  14637. stencil: _stencil,
  14638. antialias: _antialias,
  14639. premultipliedAlpha: _premultipliedAlpha,
  14640. preserveDrawingBuffer: _preserveDrawingBuffer,
  14641. powerPreference: _powerPreference,
  14642. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  14643. }; // event listeners must be registered before WebGL context is created, see #12753
  14644. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  14645. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  14646. if (_gl === null) {
  14647. const contextNames = ['webgl2', 'webgl', 'experimental-webgl'];
  14648. if (_this.isWebGL1Renderer === true) {
  14649. contextNames.shift();
  14650. }
  14651. _gl = getContext(contextNames, contextAttributes);
  14652. if (_gl === null) {
  14653. if (getContext(contextNames)) {
  14654. throw new Error('Error creating WebGL context with your selected attributes.');
  14655. } else {
  14656. throw new Error('Error creating WebGL context.');
  14657. }
  14658. }
  14659. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  14660. if (_gl.getShaderPrecisionFormat === undefined) {
  14661. _gl.getShaderPrecisionFormat = function () {
  14662. return {
  14663. 'rangeMin': 1,
  14664. 'rangeMax': 1,
  14665. 'precision': 1
  14666. };
  14667. };
  14668. }
  14669. } catch (error) {
  14670. console.error('THREE.WebGLRenderer: ' + error.message);
  14671. throw error;
  14672. }
  14673. let extensions, capabilities, state, info;
  14674. let properties, textures, cubemaps, attributes, geometries, objects;
  14675. let programCache, materials, renderLists, renderStates, clipping;
  14676. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  14677. let utils, bindingStates;
  14678. function initGLContext() {
  14679. extensions = new WebGLExtensions(_gl);
  14680. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  14681. if (capabilities.isWebGL2 === false) {
  14682. extensions.get('WEBGL_depth_texture');
  14683. extensions.get('OES_texture_float');
  14684. extensions.get('OES_texture_half_float');
  14685. extensions.get('OES_texture_half_float_linear');
  14686. extensions.get('OES_standard_derivatives');
  14687. extensions.get('OES_element_index_uint');
  14688. extensions.get('OES_vertex_array_object');
  14689. extensions.get('ANGLE_instanced_arrays');
  14690. }
  14691. extensions.get('OES_texture_float_linear');
  14692. utils = new WebGLUtils(_gl, extensions, capabilities);
  14693. state = new WebGLState(_gl, extensions, capabilities);
  14694. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  14695. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  14696. info = new WebGLInfo(_gl);
  14697. properties = new WebGLProperties();
  14698. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  14699. cubemaps = new WebGLCubeMaps(_this);
  14700. attributes = new WebGLAttributes(_gl, capabilities);
  14701. bindingStates = new WebGLBindingStates(_gl, extensions, attributes, capabilities);
  14702. geometries = new WebGLGeometries(_gl, attributes, info, bindingStates);
  14703. objects = new WebGLObjects(_gl, geometries, attributes, info);
  14704. morphtargets = new WebGLMorphtargets(_gl);
  14705. clipping = new WebGLClipping(properties);
  14706. programCache = new WebGLPrograms(_this, cubemaps, extensions, capabilities, bindingStates, clipping);
  14707. materials = new WebGLMaterials(properties);
  14708. renderLists = new WebGLRenderLists(properties);
  14709. renderStates = new WebGLRenderStates(extensions, capabilities);
  14710. background = new WebGLBackground(_this, cubemaps, state, objects, _premultipliedAlpha);
  14711. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  14712. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  14713. info.programs = programCache.programs;
  14714. _this.capabilities = capabilities;
  14715. _this.extensions = extensions;
  14716. _this.properties = properties;
  14717. _this.renderLists = renderLists;
  14718. _this.state = state;
  14719. _this.info = info;
  14720. }
  14721. initGLContext(); // xr
  14722. const xr = new WebXRManager(_this, _gl);
  14723. this.xr = xr; // shadow map
  14724. const shadowMap = new WebGLShadowMap(_this, objects, capabilities.maxTextureSize);
  14725. this.shadowMap = shadowMap; // API
  14726. this.getContext = function () {
  14727. return _gl;
  14728. };
  14729. this.getContextAttributes = function () {
  14730. return _gl.getContextAttributes();
  14731. };
  14732. this.forceContextLoss = function () {
  14733. const extension = extensions.get('WEBGL_lose_context');
  14734. if (extension) extension.loseContext();
  14735. };
  14736. this.forceContextRestore = function () {
  14737. const extension = extensions.get('WEBGL_lose_context');
  14738. if (extension) extension.restoreContext();
  14739. };
  14740. this.getPixelRatio = function () {
  14741. return _pixelRatio;
  14742. };
  14743. this.setPixelRatio = function (value) {
  14744. if (value === undefined) return;
  14745. _pixelRatio = value;
  14746. this.setSize(_width, _height, false);
  14747. };
  14748. this.getSize = function (target) {
  14749. if (target === undefined) {
  14750. console.warn('WebGLRenderer: .getsize() now requires a Vector2 as an argument');
  14751. target = new Vector2();
  14752. }
  14753. return target.set(_width, _height);
  14754. };
  14755. this.setSize = function (width, height, updateStyle) {
  14756. if (xr.isPresenting) {
  14757. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  14758. return;
  14759. }
  14760. _width = width;
  14761. _height = height;
  14762. _canvas.width = Math.floor(width * _pixelRatio);
  14763. _canvas.height = Math.floor(height * _pixelRatio);
  14764. if (updateStyle !== false) {
  14765. _canvas.style.width = width + 'px';
  14766. _canvas.style.height = height + 'px';
  14767. }
  14768. this.setViewport(0, 0, width, height);
  14769. };
  14770. this.getDrawingBufferSize = function (target) {
  14771. if (target === undefined) {
  14772. console.warn('WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument');
  14773. target = new Vector2();
  14774. }
  14775. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  14776. };
  14777. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  14778. _width = width;
  14779. _height = height;
  14780. _pixelRatio = pixelRatio;
  14781. _canvas.width = Math.floor(width * pixelRatio);
  14782. _canvas.height = Math.floor(height * pixelRatio);
  14783. this.setViewport(0, 0, width, height);
  14784. };
  14785. this.getCurrentViewport = function (target) {
  14786. if (target === undefined) {
  14787. console.warn('WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument');
  14788. target = new Vector4();
  14789. }
  14790. return target.copy(_currentViewport);
  14791. };
  14792. this.getViewport = function (target) {
  14793. return target.copy(_viewport);
  14794. };
  14795. this.setViewport = function (x, y, width, height) {
  14796. if (x.isVector4) {
  14797. _viewport.set(x.x, x.y, x.z, x.w);
  14798. } else {
  14799. _viewport.set(x, y, width, height);
  14800. }
  14801. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  14802. };
  14803. this.getScissor = function (target) {
  14804. return target.copy(_scissor);
  14805. };
  14806. this.setScissor = function (x, y, width, height) {
  14807. if (x.isVector4) {
  14808. _scissor.set(x.x, x.y, x.z, x.w);
  14809. } else {
  14810. _scissor.set(x, y, width, height);
  14811. }
  14812. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  14813. };
  14814. this.getScissorTest = function () {
  14815. return _scissorTest;
  14816. };
  14817. this.setScissorTest = function (boolean) {
  14818. state.setScissorTest(_scissorTest = boolean);
  14819. };
  14820. this.setOpaqueSort = function (method) {
  14821. _opaqueSort = method;
  14822. };
  14823. this.setTransparentSort = function (method) {
  14824. _transparentSort = method;
  14825. }; // Clearing
  14826. this.getClearColor = function () {
  14827. return background.getClearColor();
  14828. };
  14829. this.setClearColor = function () {
  14830. background.setClearColor.apply(background, arguments);
  14831. };
  14832. this.getClearAlpha = function () {
  14833. return background.getClearAlpha();
  14834. };
  14835. this.setClearAlpha = function () {
  14836. background.setClearAlpha.apply(background, arguments);
  14837. };
  14838. this.clear = function (color, depth, stencil) {
  14839. let bits = 0;
  14840. if (color === undefined || color) bits |= 16384;
  14841. if (depth === undefined || depth) bits |= 256;
  14842. if (stencil === undefined || stencil) bits |= 1024;
  14843. _gl.clear(bits);
  14844. };
  14845. this.clearColor = function () {
  14846. this.clear(true, false, false);
  14847. };
  14848. this.clearDepth = function () {
  14849. this.clear(false, true, false);
  14850. };
  14851. this.clearStencil = function () {
  14852. this.clear(false, false, true);
  14853. }; //
  14854. this.dispose = function () {
  14855. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  14856. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  14857. renderLists.dispose();
  14858. renderStates.dispose();
  14859. properties.dispose();
  14860. cubemaps.dispose();
  14861. objects.dispose();
  14862. bindingStates.dispose();
  14863. xr.dispose();
  14864. animation.stop();
  14865. }; // Events
  14866. function onContextLost(event) {
  14867. event.preventDefault();
  14868. console.log('THREE.WebGLRenderer: Context Lost.');
  14869. _isContextLost = true;
  14870. }
  14871. function onContextRestore()
  14872. /* event */
  14873. {
  14874. console.log('THREE.WebGLRenderer: Context Restored.');
  14875. _isContextLost = false;
  14876. initGLContext();
  14877. }
  14878. function onMaterialDispose(event) {
  14879. const material = event.target;
  14880. material.removeEventListener('dispose', onMaterialDispose);
  14881. deallocateMaterial(material);
  14882. } // Buffer deallocation
  14883. function deallocateMaterial(material) {
  14884. releaseMaterialProgramReference(material);
  14885. properties.remove(material);
  14886. }
  14887. function releaseMaterialProgramReference(material) {
  14888. const programInfo = properties.get(material).program;
  14889. if (programInfo !== undefined) {
  14890. programCache.releaseProgram(programInfo);
  14891. }
  14892. } // Buffer rendering
  14893. function renderObjectImmediate(object, program) {
  14894. object.render(function (object) {
  14895. _this.renderBufferImmediate(object, program);
  14896. });
  14897. }
  14898. this.renderBufferImmediate = function (object, program) {
  14899. bindingStates.initAttributes();
  14900. const buffers = properties.get(object);
  14901. if (object.hasPositions && !buffers.position) buffers.position = _gl.createBuffer();
  14902. if (object.hasNormals && !buffers.normal) buffers.normal = _gl.createBuffer();
  14903. if (object.hasUvs && !buffers.uv) buffers.uv = _gl.createBuffer();
  14904. if (object.hasColors && !buffers.color) buffers.color = _gl.createBuffer();
  14905. const programAttributes = program.getAttributes();
  14906. if (object.hasPositions) {
  14907. _gl.bindBuffer(34962, buffers.position);
  14908. _gl.bufferData(34962, object.positionArray, 35048);
  14909. bindingStates.enableAttribute(programAttributes.position);
  14910. _gl.vertexAttribPointer(programAttributes.position, 3, 5126, false, 0, 0);
  14911. }
  14912. if (object.hasNormals) {
  14913. _gl.bindBuffer(34962, buffers.normal);
  14914. _gl.bufferData(34962, object.normalArray, 35048);
  14915. bindingStates.enableAttribute(programAttributes.normal);
  14916. _gl.vertexAttribPointer(programAttributes.normal, 3, 5126, false, 0, 0);
  14917. }
  14918. if (object.hasUvs) {
  14919. _gl.bindBuffer(34962, buffers.uv);
  14920. _gl.bufferData(34962, object.uvArray, 35048);
  14921. bindingStates.enableAttribute(programAttributes.uv);
  14922. _gl.vertexAttribPointer(programAttributes.uv, 2, 5126, false, 0, 0);
  14923. }
  14924. if (object.hasColors) {
  14925. _gl.bindBuffer(34962, buffers.color);
  14926. _gl.bufferData(34962, object.colorArray, 35048);
  14927. bindingStates.enableAttribute(programAttributes.color);
  14928. _gl.vertexAttribPointer(programAttributes.color, 3, 5126, false, 0, 0);
  14929. }
  14930. bindingStates.disableUnusedAttributes();
  14931. _gl.drawArrays(4, 0, object.count);
  14932. object.count = 0;
  14933. };
  14934. this.renderBufferDirect = function (camera, scene, geometry, material, object, group) {
  14935. if (scene === null) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  14936. const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  14937. const program = setProgram(camera, scene, material, object);
  14938. state.setMaterial(material, frontFaceCW); //
  14939. let index = geometry.index;
  14940. const position = geometry.attributes.position; //
  14941. if (index === null) {
  14942. if (position === undefined || position.count === 0) return;
  14943. } else if (index.count === 0) {
  14944. return;
  14945. } //
  14946. let rangeFactor = 1;
  14947. if (material.wireframe === true) {
  14948. index = geometries.getWireframeAttribute(geometry);
  14949. rangeFactor = 2;
  14950. }
  14951. if (material.morphTargets || material.morphNormals) {
  14952. morphtargets.update(object, geometry, material, program);
  14953. }
  14954. bindingStates.setup(object, material, program, geometry, index);
  14955. let attribute;
  14956. let renderer = bufferRenderer;
  14957. if (index !== null) {
  14958. attribute = attributes.get(index);
  14959. renderer = indexedBufferRenderer;
  14960. renderer.setIndex(attribute);
  14961. } //
  14962. const dataCount = index !== null ? index.count : position.count;
  14963. const rangeStart = geometry.drawRange.start * rangeFactor;
  14964. const rangeCount = geometry.drawRange.count * rangeFactor;
  14965. const groupStart = group !== null ? group.start * rangeFactor : 0;
  14966. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  14967. const drawStart = Math.max(rangeStart, groupStart);
  14968. const drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  14969. const drawCount = Math.max(0, drawEnd - drawStart + 1);
  14970. if (drawCount === 0) return; //
  14971. if (object.isMesh) {
  14972. if (material.wireframe === true) {
  14973. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  14974. renderer.setMode(1);
  14975. } else {
  14976. renderer.setMode(4);
  14977. }
  14978. } else if (object.isLine) {
  14979. let lineWidth = material.linewidth;
  14980. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  14981. state.setLineWidth(lineWidth * getTargetPixelRatio());
  14982. if (object.isLineSegments) {
  14983. renderer.setMode(1);
  14984. } else if (object.isLineLoop) {
  14985. renderer.setMode(2);
  14986. } else {
  14987. renderer.setMode(3);
  14988. }
  14989. } else if (object.isPoints) {
  14990. renderer.setMode(0);
  14991. } else if (object.isSprite) {
  14992. renderer.setMode(4);
  14993. }
  14994. if (object.isInstancedMesh) {
  14995. renderer.renderInstances(drawStart, drawCount, object.count);
  14996. } else if (geometry.isInstancedBufferGeometry) {
  14997. const instanceCount = Math.min(geometry.instanceCount, geometry._maxInstanceCount);
  14998. renderer.renderInstances(drawStart, drawCount, instanceCount);
  14999. } else {
  15000. renderer.render(drawStart, drawCount);
  15001. }
  15002. }; // Compile
  15003. this.compile = function (scene, camera) {
  15004. currentRenderState = renderStates.get(scene, camera);
  15005. currentRenderState.init();
  15006. scene.traverseVisible(function (object) {
  15007. if (object.isLight && object.layers.test(camera.layers)) {
  15008. currentRenderState.pushLight(object);
  15009. if (object.castShadow) {
  15010. currentRenderState.pushShadow(object);
  15011. }
  15012. }
  15013. });
  15014. currentRenderState.setupLights(camera);
  15015. const compiled = new WeakMap();
  15016. scene.traverse(function (object) {
  15017. const material = object.material;
  15018. if (material) {
  15019. if (Array.isArray(material)) {
  15020. for (let i = 0; i < material.length; i++) {
  15021. const material2 = material[i];
  15022. if (compiled.has(material2) === false) {
  15023. initMaterial(material2, scene, object);
  15024. compiled.set(material2);
  15025. }
  15026. }
  15027. } else if (compiled.has(material) === false) {
  15028. initMaterial(material, scene, object);
  15029. compiled.set(material);
  15030. }
  15031. }
  15032. });
  15033. }; // Animation Loop
  15034. let onAnimationFrameCallback = null;
  15035. function onAnimationFrame(time) {
  15036. if (xr.isPresenting) return;
  15037. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  15038. }
  15039. const animation = new WebGLAnimation();
  15040. animation.setAnimationLoop(onAnimationFrame);
  15041. if (typeof window !== 'undefined') animation.setContext(window);
  15042. this.setAnimationLoop = function (callback) {
  15043. onAnimationFrameCallback = callback;
  15044. xr.setAnimationLoop(callback);
  15045. callback === null ? animation.stop() : animation.start();
  15046. }; // Rendering
  15047. this.render = function (scene, camera) {
  15048. let renderTarget, forceClear;
  15049. if (arguments[2] !== undefined) {
  15050. console.warn('THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.');
  15051. renderTarget = arguments[2];
  15052. }
  15053. if (arguments[3] !== undefined) {
  15054. console.warn('THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.');
  15055. forceClear = arguments[3];
  15056. }
  15057. if (camera !== undefined && camera.isCamera !== true) {
  15058. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  15059. return;
  15060. }
  15061. if (_isContextLost === true) return; // reset caching for this frame
  15062. bindingStates.resetDefaultState();
  15063. _currentMaterialId = -1;
  15064. _currentCamera = null; // update scene graph
  15065. if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  15066. if (camera.parent === null) camera.updateMatrixWorld();
  15067. if (xr.enabled === true && xr.isPresenting === true) {
  15068. camera = xr.getCamera(camera);
  15069. } //
  15070. if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, renderTarget || _currentRenderTarget);
  15071. currentRenderState = renderStates.get(scene, camera);
  15072. currentRenderState.init();
  15073. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  15074. _frustum.setFromProjectionMatrix(_projScreenMatrix);
  15075. _localClippingEnabled = this.localClippingEnabled;
  15076. _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  15077. currentRenderList = renderLists.get(scene, camera);
  15078. currentRenderList.init();
  15079. projectObject(scene, camera, 0, _this.sortObjects);
  15080. currentRenderList.finish();
  15081. if (_this.sortObjects === true) {
  15082. currentRenderList.sort(_opaqueSort, _transparentSort);
  15083. } //
  15084. if (_clippingEnabled === true) clipping.beginShadows();
  15085. const shadowsArray = currentRenderState.state.shadowsArray;
  15086. shadowMap.render(shadowsArray, scene, camera);
  15087. currentRenderState.setupLights(camera);
  15088. if (_clippingEnabled === true) clipping.endShadows(); //
  15089. if (this.info.autoReset === true) this.info.reset();
  15090. if (renderTarget !== undefined) {
  15091. this.setRenderTarget(renderTarget);
  15092. } //
  15093. background.render(currentRenderList, scene, camera, forceClear); // render scene
  15094. const opaqueObjects = currentRenderList.opaque;
  15095. const transparentObjects = currentRenderList.transparent;
  15096. if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera);
  15097. if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera); //
  15098. if (scene.isScene === true) scene.onAfterRender(_this, scene, camera); //
  15099. if (_currentRenderTarget !== null) {
  15100. // Generate mipmap if we're using any kind of mipmap filtering
  15101. textures.updateRenderTargetMipmap(_currentRenderTarget); // resolve multisample renderbuffers to a single-sample texture if necessary
  15102. textures.updateMultisampleRenderTarget(_currentRenderTarget);
  15103. } // Ensure depth buffer writing is enabled so it can be cleared on next render
  15104. state.buffers.depth.setTest(true);
  15105. state.buffers.depth.setMask(true);
  15106. state.buffers.color.setMask(true);
  15107. state.setPolygonOffset(false); // _gl.finish();
  15108. currentRenderList = null;
  15109. currentRenderState = null;
  15110. };
  15111. function projectObject(object, camera, groupOrder, sortObjects) {
  15112. if (object.visible === false) return;
  15113. const visible = object.layers.test(camera.layers);
  15114. if (visible) {
  15115. if (object.isGroup) {
  15116. groupOrder = object.renderOrder;
  15117. } else if (object.isLOD) {
  15118. if (object.autoUpdate === true) object.update(camera);
  15119. } else if (object.isLight) {
  15120. currentRenderState.pushLight(object);
  15121. if (object.castShadow) {
  15122. currentRenderState.pushShadow(object);
  15123. }
  15124. } else if (object.isSprite) {
  15125. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  15126. if (sortObjects) {
  15127. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15128. }
  15129. const geometry = objects.update(object);
  15130. const material = object.material;
  15131. if (material.visible) {
  15132. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  15133. }
  15134. }
  15135. } else if (object.isImmediateRenderObject) {
  15136. if (sortObjects) {
  15137. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15138. }
  15139. currentRenderList.push(object, null, object.material, groupOrder, _vector3.z, null);
  15140. } else if (object.isMesh || object.isLine || object.isPoints) {
  15141. if (object.isSkinnedMesh) {
  15142. // update skeleton only once in a frame
  15143. if (object.skeleton.frame !== info.render.frame) {
  15144. object.skeleton.update();
  15145. object.skeleton.frame = info.render.frame;
  15146. }
  15147. }
  15148. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  15149. if (sortObjects) {
  15150. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15151. }
  15152. const geometry = objects.update(object);
  15153. const material = object.material;
  15154. if (Array.isArray(material)) {
  15155. const groups = geometry.groups;
  15156. for (let i = 0, l = groups.length; i < l; i++) {
  15157. const group = groups[i];
  15158. const groupMaterial = material[group.materialIndex];
  15159. if (groupMaterial && groupMaterial.visible) {
  15160. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  15161. }
  15162. }
  15163. } else if (material.visible) {
  15164. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  15165. }
  15166. }
  15167. }
  15168. }
  15169. const children = object.children;
  15170. for (let i = 0, l = children.length; i < l; i++) {
  15171. projectObject(children[i], camera, groupOrder, sortObjects);
  15172. }
  15173. }
  15174. function renderObjects(renderList, scene, camera) {
  15175. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  15176. for (let i = 0, l = renderList.length; i < l; i++) {
  15177. const renderItem = renderList[i];
  15178. const object = renderItem.object;
  15179. const geometry = renderItem.geometry;
  15180. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  15181. const group = renderItem.group;
  15182. if (camera.isArrayCamera) {
  15183. _currentArrayCamera = camera;
  15184. const cameras = camera.cameras;
  15185. for (let j = 0, jl = cameras.length; j < jl; j++) {
  15186. const camera2 = cameras[j];
  15187. if (object.layers.test(camera2.layers)) {
  15188. state.viewport(_currentViewport.copy(camera2.viewport));
  15189. currentRenderState.setupLights(camera2);
  15190. renderObject(object, scene, camera2, geometry, material, group);
  15191. }
  15192. }
  15193. } else {
  15194. _currentArrayCamera = null;
  15195. renderObject(object, scene, camera, geometry, material, group);
  15196. }
  15197. }
  15198. }
  15199. function renderObject(object, scene, camera, geometry, material, group) {
  15200. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  15201. currentRenderState = renderStates.get(scene, _currentArrayCamera || camera);
  15202. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  15203. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  15204. if (object.isImmediateRenderObject) {
  15205. const program = setProgram(camera, scene, material, object);
  15206. state.setMaterial(material);
  15207. bindingStates.reset();
  15208. renderObjectImmediate(object, program);
  15209. } else {
  15210. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  15211. }
  15212. object.onAfterRender(_this, scene, camera, geometry, material, group);
  15213. currentRenderState = renderStates.get(scene, _currentArrayCamera || camera);
  15214. }
  15215. function initMaterial(material, scene, object) {
  15216. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  15217. const materialProperties = properties.get(material);
  15218. const lights = currentRenderState.state.lights;
  15219. const shadowsArray = currentRenderState.state.shadowsArray;
  15220. const lightsStateVersion = lights.state.version;
  15221. const parameters = programCache.getParameters(material, lights.state, shadowsArray, scene, object);
  15222. const programCacheKey = programCache.getProgramCacheKey(parameters);
  15223. let program = materialProperties.program;
  15224. let programChange = true;
  15225. if (program === undefined) {
  15226. // new material
  15227. material.addEventListener('dispose', onMaterialDispose);
  15228. } else if (program.cacheKey !== programCacheKey) {
  15229. // changed glsl or parameters
  15230. releaseMaterialProgramReference(material);
  15231. } else if (materialProperties.lightsStateVersion !== lightsStateVersion) {
  15232. programChange = false;
  15233. } else if (parameters.shaderID !== undefined) {
  15234. // same glsl and uniform list, envMap still needs the update here to avoid a frame-late effect
  15235. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  15236. materialProperties.envMap = cubemaps.get(material.envMap || environment);
  15237. return;
  15238. } else {
  15239. // only rebuild uniform list
  15240. programChange = false;
  15241. }
  15242. if (programChange) {
  15243. parameters.uniforms = programCache.getUniforms(material);
  15244. material.onBeforeCompile(parameters, _this);
  15245. program = programCache.acquireProgram(parameters, programCacheKey);
  15246. materialProperties.program = program;
  15247. materialProperties.uniforms = parameters.uniforms;
  15248. materialProperties.outputEncoding = parameters.outputEncoding;
  15249. }
  15250. const uniforms = materialProperties.uniforms;
  15251. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  15252. materialProperties.numClippingPlanes = clipping.numPlanes;
  15253. materialProperties.numIntersection = clipping.numIntersection;
  15254. uniforms.clippingPlanes = clipping.uniform;
  15255. }
  15256. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  15257. materialProperties.fog = scene.fog;
  15258. materialProperties.envMap = cubemaps.get(material.envMap || materialProperties.environment); // store the light setup it was created for
  15259. materialProperties.needsLights = materialNeedsLights(material);
  15260. materialProperties.lightsStateVersion = lightsStateVersion;
  15261. if (materialProperties.needsLights) {
  15262. // wire up the material to this renderer's lighting state
  15263. uniforms.ambientLightColor.value = lights.state.ambient;
  15264. uniforms.lightProbe.value = lights.state.probe;
  15265. uniforms.directionalLights.value = lights.state.directional;
  15266. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  15267. uniforms.spotLights.value = lights.state.spot;
  15268. uniforms.spotLightShadows.value = lights.state.spotShadow;
  15269. uniforms.rectAreaLights.value = lights.state.rectArea;
  15270. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  15271. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  15272. uniforms.pointLights.value = lights.state.point;
  15273. uniforms.pointLightShadows.value = lights.state.pointShadow;
  15274. uniforms.hemisphereLights.value = lights.state.hemi;
  15275. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  15276. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  15277. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  15278. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  15279. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  15280. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  15281. }
  15282. const progUniforms = materialProperties.program.getUniforms();
  15283. const uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  15284. materialProperties.uniformsList = uniformsList;
  15285. }
  15286. function setProgram(camera, scene, material, object) {
  15287. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  15288. textures.resetTextureUnits();
  15289. const fog = scene.fog;
  15290. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  15291. const encoding = _currentRenderTarget === null ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  15292. const envMap = cubemaps.get(material.envMap || environment);
  15293. const materialProperties = properties.get(material);
  15294. const lights = currentRenderState.state.lights;
  15295. if (_clippingEnabled === true) {
  15296. if (_localClippingEnabled === true || camera !== _currentCamera) {
  15297. const useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  15298. // object instead of the material, once it becomes feasible
  15299. // (#8465, #8379)
  15300. clipping.setState(material, camera, useCache);
  15301. }
  15302. }
  15303. if (material.version === materialProperties.__version) {
  15304. if (material.fog && materialProperties.fog !== fog) {
  15305. initMaterial(material, scene, object);
  15306. } else if (materialProperties.environment !== environment) {
  15307. initMaterial(material, scene, object);
  15308. } else if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  15309. initMaterial(material, scene, object);
  15310. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) {
  15311. initMaterial(material, scene, object);
  15312. } else if (materialProperties.outputEncoding !== encoding) {
  15313. initMaterial(material, scene, object);
  15314. } else if (materialProperties.envMap !== envMap) {
  15315. initMaterial(material, scene, object);
  15316. }
  15317. } else {
  15318. initMaterial(material, scene, object);
  15319. materialProperties.__version = material.version;
  15320. }
  15321. let refreshProgram = false;
  15322. let refreshMaterial = false;
  15323. let refreshLights = false;
  15324. const program = materialProperties.program,
  15325. p_uniforms = program.getUniforms(),
  15326. m_uniforms = materialProperties.uniforms;
  15327. if (state.useProgram(program.program)) {
  15328. refreshProgram = true;
  15329. refreshMaterial = true;
  15330. refreshLights = true;
  15331. }
  15332. if (material.id !== _currentMaterialId) {
  15333. _currentMaterialId = material.id;
  15334. refreshMaterial = true;
  15335. }
  15336. if (refreshProgram || _currentCamera !== camera) {
  15337. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  15338. if (capabilities.logarithmicDepthBuffer) {
  15339. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  15340. }
  15341. if (_currentCamera !== camera) {
  15342. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  15343. // now, in case this material supports lights - or later, when
  15344. // the next material that does gets activated:
  15345. refreshMaterial = true; // set to true on material change
  15346. refreshLights = true; // remains set until update done
  15347. } // load material specific uniforms
  15348. // (shader material also gets them for the sake of genericity)
  15349. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) {
  15350. const uCamPos = p_uniforms.map.cameraPosition;
  15351. if (uCamPos !== undefined) {
  15352. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  15353. }
  15354. }
  15355. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) {
  15356. p_uniforms.setValue(_gl, 'isOrthographic', camera.isOrthographicCamera === true);
  15357. }
  15358. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.isShadowMaterial || material.skinning) {
  15359. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  15360. }
  15361. } // skinning uniforms must be set even if material didn't change
  15362. // auto-setting of texture unit for bone texture must go before other textures
  15363. // otherwise textures used for skinning can take over texture units reserved for other material textures
  15364. if (material.skinning) {
  15365. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  15366. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  15367. const skeleton = object.skeleton;
  15368. if (skeleton) {
  15369. const bones = skeleton.bones;
  15370. if (capabilities.floatVertexTextures) {
  15371. if (skeleton.boneTexture === null) {
  15372. // layout (1 matrix = 4 pixels)
  15373. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  15374. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  15375. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  15376. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  15377. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  15378. let size = Math.sqrt(bones.length * 4); // 4 pixels needed for 1 matrix
  15379. size = MathUtils.ceilPowerOfTwo(size);
  15380. size = Math.max(size, 4);
  15381. const boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  15382. boneMatrices.set(skeleton.boneMatrices); // copy current values
  15383. const boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  15384. skeleton.boneMatrices = boneMatrices;
  15385. skeleton.boneTexture = boneTexture;
  15386. skeleton.boneTextureSize = size;
  15387. }
  15388. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  15389. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  15390. } else {
  15391. p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
  15392. }
  15393. }
  15394. }
  15395. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  15396. materialProperties.receiveShadow = object.receiveShadow;
  15397. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  15398. }
  15399. if (refreshMaterial) {
  15400. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  15401. if (materialProperties.needsLights) {
  15402. // the current material requires lighting info
  15403. // note: all lighting uniforms are always set correctly
  15404. // they simply reference the renderer's state for their
  15405. // values
  15406. //
  15407. // use the current material's .needsUpdate flags to set
  15408. // the GL state when required
  15409. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  15410. } // refresh uniforms common to several materials
  15411. if (fog && material.fog) {
  15412. materials.refreshFogUniforms(m_uniforms, fog);
  15413. }
  15414. materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height);
  15415. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  15416. }
  15417. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  15418. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  15419. material.uniformsNeedUpdate = false;
  15420. }
  15421. if (material.isSpriteMaterial) {
  15422. p_uniforms.setValue(_gl, 'center', object.center);
  15423. } // common matrices
  15424. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  15425. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  15426. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  15427. return program;
  15428. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  15429. function markUniformsLightsNeedsUpdate(uniforms, value) {
  15430. uniforms.ambientLightColor.needsUpdate = value;
  15431. uniforms.lightProbe.needsUpdate = value;
  15432. uniforms.directionalLights.needsUpdate = value;
  15433. uniforms.directionalLightShadows.needsUpdate = value;
  15434. uniforms.pointLights.needsUpdate = value;
  15435. uniforms.pointLightShadows.needsUpdate = value;
  15436. uniforms.spotLights.needsUpdate = value;
  15437. uniforms.spotLightShadows.needsUpdate = value;
  15438. uniforms.rectAreaLights.needsUpdate = value;
  15439. uniforms.hemisphereLights.needsUpdate = value;
  15440. }
  15441. function materialNeedsLights(material) {
  15442. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  15443. } //
  15444. this.setFramebuffer = function (value) {
  15445. if (_framebuffer !== value && _currentRenderTarget === null) _gl.bindFramebuffer(36160, value);
  15446. _framebuffer = value;
  15447. };
  15448. this.getActiveCubeFace = function () {
  15449. return _currentActiveCubeFace;
  15450. };
  15451. this.getActiveMipmapLevel = function () {
  15452. return _currentActiveMipmapLevel;
  15453. };
  15454. this.getRenderList = function () {
  15455. return currentRenderList;
  15456. };
  15457. this.setRenderList = function (renderList) {
  15458. currentRenderList = renderList;
  15459. };
  15460. this.getRenderState = function () {
  15461. return currentRenderState;
  15462. };
  15463. this.setRenderState = function (renderState) {
  15464. currentRenderState = renderState;
  15465. };
  15466. this.getRenderTarget = function () {
  15467. return _currentRenderTarget;
  15468. };
  15469. this.setRenderTarget = function (renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) {
  15470. _currentRenderTarget = renderTarget;
  15471. _currentActiveCubeFace = activeCubeFace;
  15472. _currentActiveMipmapLevel = activeMipmapLevel;
  15473. if (renderTarget && properties.get(renderTarget).__webglFramebuffer === undefined) {
  15474. textures.setupRenderTarget(renderTarget);
  15475. }
  15476. let framebuffer = _framebuffer;
  15477. let isCube = false;
  15478. if (renderTarget) {
  15479. const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  15480. if (renderTarget.isWebGLCubeRenderTarget) {
  15481. framebuffer = __webglFramebuffer[activeCubeFace];
  15482. isCube = true;
  15483. } else if (renderTarget.isWebGLMultisampleRenderTarget) {
  15484. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  15485. } else {
  15486. framebuffer = __webglFramebuffer;
  15487. }
  15488. _currentViewport.copy(renderTarget.viewport);
  15489. _currentScissor.copy(renderTarget.scissor);
  15490. _currentScissorTest = renderTarget.scissorTest;
  15491. } else {
  15492. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  15493. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  15494. _currentScissorTest = _scissorTest;
  15495. }
  15496. if (_currentFramebuffer !== framebuffer) {
  15497. _gl.bindFramebuffer(36160, framebuffer);
  15498. _currentFramebuffer = framebuffer;
  15499. }
  15500. state.viewport(_currentViewport);
  15501. state.scissor(_currentScissor);
  15502. state.setScissorTest(_currentScissorTest);
  15503. if (isCube) {
  15504. const textureProperties = properties.get(renderTarget.texture);
  15505. _gl.framebufferTexture2D(36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel);
  15506. }
  15507. };
  15508. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  15509. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  15510. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  15511. return;
  15512. }
  15513. let framebuffer = properties.get(renderTarget).__webglFramebuffer;
  15514. if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) {
  15515. framebuffer = framebuffer[activeCubeFaceIndex];
  15516. }
  15517. if (framebuffer) {
  15518. let restore = false;
  15519. if (framebuffer !== _currentFramebuffer) {
  15520. _gl.bindFramebuffer(36160, framebuffer);
  15521. restore = true;
  15522. }
  15523. try {
  15524. const texture = renderTarget.texture;
  15525. const textureFormat = texture.format;
  15526. const textureType = texture.type;
  15527. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(35739)) {
  15528. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  15529. return;
  15530. }
  15531. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(35738) && // IE11, Edge and Chrome Mac < 52 (#9513)
  15532. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.get('OES_texture_float') || extensions.get('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  15533. !(textureType === HalfFloatType && (capabilities.isWebGL2 ? extensions.get('EXT_color_buffer_float') : extensions.get('EXT_color_buffer_half_float')))) {
  15534. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  15535. return;
  15536. }
  15537. if (_gl.checkFramebufferStatus(36160) === 36053) {
  15538. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  15539. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  15540. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  15541. }
  15542. } else {
  15543. console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
  15544. }
  15545. } finally {
  15546. if (restore) {
  15547. _gl.bindFramebuffer(36160, _currentFramebuffer);
  15548. }
  15549. }
  15550. }
  15551. };
  15552. this.copyFramebufferToTexture = function (position, texture, level = 0) {
  15553. const levelScale = Math.pow(2, -level);
  15554. const width = Math.floor(texture.image.width * levelScale);
  15555. const height = Math.floor(texture.image.height * levelScale);
  15556. const glFormat = utils.convert(texture.format);
  15557. textures.setTexture2D(texture, 0);
  15558. _gl.copyTexImage2D(3553, level, glFormat, position.x, position.y, width, height, 0);
  15559. state.unbindTexture();
  15560. };
  15561. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level = 0) {
  15562. const width = srcTexture.image.width;
  15563. const height = srcTexture.image.height;
  15564. const glFormat = utils.convert(dstTexture.format);
  15565. const glType = utils.convert(dstTexture.type);
  15566. textures.setTexture2D(dstTexture, 0); // As another texture upload may have changed pixelStorei
  15567. // parameters, make sure they are correct for the dstTexture
  15568. _gl.pixelStorei(37440, dstTexture.flipY);
  15569. _gl.pixelStorei(37441, dstTexture.premultiplyAlpha);
  15570. _gl.pixelStorei(3317, dstTexture.unpackAlignment);
  15571. if (srcTexture.isDataTexture) {
  15572. _gl.texSubImage2D(3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  15573. } else {
  15574. if (srcTexture.isCompressedTexture) {
  15575. _gl.compressedTexSubImage2D(3553, level, position.x, position.y, srcTexture.mipmaps[0].width, srcTexture.mipmaps[0].height, glFormat, srcTexture.mipmaps[0].data);
  15576. } else {
  15577. _gl.texSubImage2D(3553, level, position.x, position.y, glFormat, glType, srcTexture.image);
  15578. }
  15579. } // Generate mipmaps only when copying level 0
  15580. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(3553);
  15581. state.unbindTexture();
  15582. };
  15583. this.initTexture = function (texture) {
  15584. textures.setTexture2D(texture, 0);
  15585. state.unbindTexture();
  15586. };
  15587. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  15588. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  15589. detail: this
  15590. })); // eslint-disable-line no-undef
  15591. }
  15592. }
  15593. function WebGL1Renderer(parameters) {
  15594. WebGLRenderer.call(this, parameters);
  15595. }
  15596. WebGL1Renderer.prototype = Object.assign(Object.create(WebGLRenderer.prototype), {
  15597. constructor: WebGL1Renderer,
  15598. isWebGL1Renderer: true
  15599. });
  15600. class FogExp2 {
  15601. constructor(color, density) {
  15602. Object.defineProperty(this, 'isFogExp2', {
  15603. value: true
  15604. });
  15605. this.name = '';
  15606. this.color = new Color(color);
  15607. this.density = density !== undefined ? density : 0.00025;
  15608. }
  15609. clone() {
  15610. return new FogExp2(this.color, this.density);
  15611. }
  15612. toJSON()
  15613. /* meta */
  15614. {
  15615. return {
  15616. type: 'FogExp2',
  15617. color: this.color.getHex(),
  15618. density: this.density
  15619. };
  15620. }
  15621. }
  15622. exports.FogExp2 = FogExp2;
  15623. class Fog {
  15624. constructor(color, near, far) {
  15625. Object.defineProperty(this, 'isFog', {
  15626. value: true
  15627. });
  15628. this.name = '';
  15629. this.color = new Color(color);
  15630. this.near = near !== undefined ? near : 1;
  15631. this.far = far !== undefined ? far : 1000;
  15632. }
  15633. clone() {
  15634. return new Fog(this.color, this.near, this.far);
  15635. }
  15636. toJSON()
  15637. /* meta */
  15638. {
  15639. return {
  15640. type: 'Fog',
  15641. color: this.color.getHex(),
  15642. near: this.near,
  15643. far: this.far
  15644. };
  15645. }
  15646. }
  15647. exports.Fog = Fog;
  15648. class Scene extends Object3D {
  15649. constructor() {
  15650. super();
  15651. Object.defineProperty(this, 'isScene', {
  15652. value: true
  15653. });
  15654. this.type = 'Scene';
  15655. this.background = null;
  15656. this.environment = null;
  15657. this.fog = null;
  15658. this.overrideMaterial = null;
  15659. this.autoUpdate = true; // checked by the renderer
  15660. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  15661. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  15662. detail: this
  15663. })); // eslint-disable-line no-undef
  15664. }
  15665. }
  15666. copy(source, recursive) {
  15667. super.copy(source, recursive);
  15668. if (source.background !== null) this.background = source.background.clone();
  15669. if (source.environment !== null) this.environment = source.environment.clone();
  15670. if (source.fog !== null) this.fog = source.fog.clone();
  15671. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  15672. this.autoUpdate = source.autoUpdate;
  15673. this.matrixAutoUpdate = source.matrixAutoUpdate;
  15674. return this;
  15675. }
  15676. toJSON(meta) {
  15677. const data = super.toJSON(meta);
  15678. if (this.background !== null) data.object.background = this.background.toJSON(meta);
  15679. if (this.environment !== null) data.object.environment = this.environment.toJSON(meta);
  15680. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  15681. return data;
  15682. }
  15683. }
  15684. exports.Scene = Scene;
  15685. function InterleavedBuffer(array, stride) {
  15686. this.array = array;
  15687. this.stride = stride;
  15688. this.count = array !== undefined ? array.length / stride : 0;
  15689. this.usage = StaticDrawUsage;
  15690. this.updateRange = {
  15691. offset: 0,
  15692. count: -1
  15693. };
  15694. this.version = 0;
  15695. this.uuid = MathUtils.generateUUID();
  15696. }
  15697. Object.defineProperty(InterleavedBuffer.prototype, 'needsUpdate', {
  15698. set: function (value) {
  15699. if (value === true) this.version++;
  15700. }
  15701. });
  15702. Object.assign(InterleavedBuffer.prototype, {
  15703. isInterleavedBuffer: true,
  15704. onUploadCallback: function () {},
  15705. setUsage: function (value) {
  15706. this.usage = value;
  15707. return this;
  15708. },
  15709. copy: function (source) {
  15710. this.array = new source.array.constructor(source.array);
  15711. this.count = source.count;
  15712. this.stride = source.stride;
  15713. this.usage = source.usage;
  15714. return this;
  15715. },
  15716. copyAt: function (index1, attribute, index2) {
  15717. index1 *= this.stride;
  15718. index2 *= attribute.stride;
  15719. for (let i = 0, l = this.stride; i < l; i++) {
  15720. this.array[index1 + i] = attribute.array[index2 + i];
  15721. }
  15722. return this;
  15723. },
  15724. set: function (value, offset = 0) {
  15725. this.array.set(value, offset);
  15726. return this;
  15727. },
  15728. clone: function (data) {
  15729. if (data.arrayBuffers === undefined) {
  15730. data.arrayBuffers = {};
  15731. }
  15732. if (this.array.buffer._uuid === undefined) {
  15733. this.array.buffer._uuid = MathUtils.generateUUID();
  15734. }
  15735. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  15736. data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer;
  15737. }
  15738. const array = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]);
  15739. const ib = new InterleavedBuffer(array, this.stride);
  15740. ib.setUsage(this.usage);
  15741. return ib;
  15742. },
  15743. onUpload: function (callback) {
  15744. this.onUploadCallback = callback;
  15745. return this;
  15746. },
  15747. toJSON: function (data) {
  15748. if (data.arrayBuffers === undefined) {
  15749. data.arrayBuffers = {};
  15750. } // generate UUID for array buffer if necessary
  15751. if (this.array.buffer._uuid === undefined) {
  15752. this.array.buffer._uuid = MathUtils.generateUUID();
  15753. }
  15754. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  15755. data.arrayBuffers[this.array.buffer._uuid] = Array.prototype.slice.call(new Uint32Array(this.array.buffer));
  15756. } //
  15757. return {
  15758. uuid: this.uuid,
  15759. buffer: this.array.buffer._uuid,
  15760. type: this.array.constructor.name,
  15761. stride: this.stride
  15762. };
  15763. }
  15764. });
  15765. const _vector$6 = new Vector3();
  15766. function InterleavedBufferAttribute(interleavedBuffer, itemSize, offset, normalized) {
  15767. this.name = '';
  15768. this.data = interleavedBuffer;
  15769. this.itemSize = itemSize;
  15770. this.offset = offset;
  15771. this.normalized = normalized === true;
  15772. }
  15773. Object.defineProperties(InterleavedBufferAttribute.prototype, {
  15774. count: {
  15775. get: function () {
  15776. return this.data.count;
  15777. }
  15778. },
  15779. array: {
  15780. get: function () {
  15781. return this.data.array;
  15782. }
  15783. },
  15784. needsUpdate: {
  15785. set: function (value) {
  15786. this.data.needsUpdate = value;
  15787. }
  15788. }
  15789. });
  15790. Object.assign(InterleavedBufferAttribute.prototype, {
  15791. isInterleavedBufferAttribute: true,
  15792. applyMatrix4: function (m) {
  15793. for (let i = 0, l = this.data.count; i < l; i++) {
  15794. _vector$6.x = this.getX(i);
  15795. _vector$6.y = this.getY(i);
  15796. _vector$6.z = this.getZ(i);
  15797. _vector$6.applyMatrix4(m);
  15798. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  15799. }
  15800. return this;
  15801. },
  15802. setX: function (index, x) {
  15803. this.data.array[index * this.data.stride + this.offset] = x;
  15804. return this;
  15805. },
  15806. setY: function (index, y) {
  15807. this.data.array[index * this.data.stride + this.offset + 1] = y;
  15808. return this;
  15809. },
  15810. setZ: function (index, z) {
  15811. this.data.array[index * this.data.stride + this.offset + 2] = z;
  15812. return this;
  15813. },
  15814. setW: function (index, w) {
  15815. this.data.array[index * this.data.stride + this.offset + 3] = w;
  15816. return this;
  15817. },
  15818. getX: function (index) {
  15819. return this.data.array[index * this.data.stride + this.offset];
  15820. },
  15821. getY: function (index) {
  15822. return this.data.array[index * this.data.stride + this.offset + 1];
  15823. },
  15824. getZ: function (index) {
  15825. return this.data.array[index * this.data.stride + this.offset + 2];
  15826. },
  15827. getW: function (index) {
  15828. return this.data.array[index * this.data.stride + this.offset + 3];
  15829. },
  15830. setXY: function (index, x, y) {
  15831. index = index * this.data.stride + this.offset;
  15832. this.data.array[index + 0] = x;
  15833. this.data.array[index + 1] = y;
  15834. return this;
  15835. },
  15836. setXYZ: function (index, x, y, z) {
  15837. index = index * this.data.stride + this.offset;
  15838. this.data.array[index + 0] = x;
  15839. this.data.array[index + 1] = y;
  15840. this.data.array[index + 2] = z;
  15841. return this;
  15842. },
  15843. setXYZW: function (index, x, y, z, w) {
  15844. index = index * this.data.stride + this.offset;
  15845. this.data.array[index + 0] = x;
  15846. this.data.array[index + 1] = y;
  15847. this.data.array[index + 2] = z;
  15848. this.data.array[index + 3] = w;
  15849. return this;
  15850. },
  15851. clone: function (data) {
  15852. if (data === undefined) {
  15853. console.log('THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.');
  15854. const array = [];
  15855. for (let i = 0; i < this.count; i++) {
  15856. const index = i * this.data.stride + this.offset;
  15857. for (let j = 0; j < this.itemSize; j++) {
  15858. array.push(this.data.array[index + j]);
  15859. }
  15860. }
  15861. return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized);
  15862. } else {
  15863. if (data.interleavedBuffers === undefined) {
  15864. data.interleavedBuffers = {};
  15865. }
  15866. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  15867. data.interleavedBuffers[this.data.uuid] = this.data.clone(data);
  15868. }
  15869. return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
  15870. }
  15871. },
  15872. toJSON: function (data) {
  15873. if (data === undefined) {
  15874. console.log('THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.');
  15875. const array = [];
  15876. for (let i = 0; i < this.count; i++) {
  15877. const index = i * this.data.stride + this.offset;
  15878. for (let j = 0; j < this.itemSize; j++) {
  15879. array.push(this.data.array[index + j]);
  15880. }
  15881. } // deinterleave data and save it as an ordinary buffer attribute for now
  15882. return {
  15883. itemSize: this.itemSize,
  15884. type: this.array.constructor.name,
  15885. array: array,
  15886. normalized: this.normalized
  15887. };
  15888. } else {
  15889. // save as true interlaved attribtue
  15890. if (data.interleavedBuffers === undefined) {
  15891. data.interleavedBuffers = {};
  15892. }
  15893. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  15894. data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data);
  15895. }
  15896. return {
  15897. isInterleavedBufferAttribute: true,
  15898. itemSize: this.itemSize,
  15899. data: this.data.uuid,
  15900. offset: this.offset,
  15901. normalized: this.normalized
  15902. };
  15903. }
  15904. }
  15905. });
  15906. /**
  15907. * parameters = {
  15908. * color: <hex>,
  15909. * map: new THREE.Texture( <Image> ),
  15910. * alphaMap: new THREE.Texture( <Image> ),
  15911. * rotation: <float>,
  15912. * sizeAttenuation: <bool>
  15913. * }
  15914. */
  15915. function SpriteMaterial(parameters) {
  15916. Material.call(this);
  15917. this.type = 'SpriteMaterial';
  15918. this.color = new Color(0xffffff);
  15919. this.map = null;
  15920. this.alphaMap = null;
  15921. this.rotation = 0;
  15922. this.sizeAttenuation = true;
  15923. this.transparent = true;
  15924. this.setValues(parameters);
  15925. }
  15926. SpriteMaterial.prototype = Object.create(Material.prototype);
  15927. SpriteMaterial.prototype.constructor = SpriteMaterial;
  15928. SpriteMaterial.prototype.isSpriteMaterial = true;
  15929. SpriteMaterial.prototype.copy = function (source) {
  15930. Material.prototype.copy.call(this, source);
  15931. this.color.copy(source.color);
  15932. this.map = source.map;
  15933. this.alphaMap = source.alphaMap;
  15934. this.rotation = source.rotation;
  15935. this.sizeAttenuation = source.sizeAttenuation;
  15936. return this;
  15937. };
  15938. let _geometry;
  15939. const _intersectPoint = new Vector3();
  15940. const _worldScale = new Vector3();
  15941. const _mvPosition = new Vector3();
  15942. const _alignedPosition = new Vector2();
  15943. const _rotatedPosition = new Vector2();
  15944. const _viewWorldMatrix = new Matrix4();
  15945. const _vA$1 = new Vector3();
  15946. const _vB$1 = new Vector3();
  15947. const _vC$1 = new Vector3();
  15948. const _uvA$1 = new Vector2();
  15949. const _uvB$1 = new Vector2();
  15950. const _uvC$1 = new Vector2();
  15951. function Sprite(material) {
  15952. Object3D.call(this);
  15953. this.type = 'Sprite';
  15954. if (_geometry === undefined) {
  15955. _geometry = new BufferGeometry();
  15956. const 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]);
  15957. const interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  15958. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  15959. _geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  15960. _geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  15961. }
  15962. this.geometry = _geometry;
  15963. this.material = material !== undefined ? material : new SpriteMaterial();
  15964. this.center = new Vector2(0.5, 0.5);
  15965. }
  15966. Sprite.prototype = Object.assign(Object.create(Object3D.prototype), {
  15967. constructor: Sprite,
  15968. isSprite: true,
  15969. raycast: function (raycaster, intersects) {
  15970. if (raycaster.camera === null) {
  15971. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  15972. }
  15973. _worldScale.setFromMatrixScale(this.matrixWorld);
  15974. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  15975. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  15976. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  15977. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  15978. _worldScale.multiplyScalar(-_mvPosition.z);
  15979. }
  15980. const rotation = this.material.rotation;
  15981. let sin, cos;
  15982. if (rotation !== 0) {
  15983. cos = Math.cos(rotation);
  15984. sin = Math.sin(rotation);
  15985. }
  15986. const center = this.center;
  15987. transformVertex(_vA$1.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15988. transformVertex(_vB$1.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15989. transformVertex(_vC$1.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15990. _uvA$1.set(0, 0);
  15991. _uvB$1.set(1, 0);
  15992. _uvC$1.set(1, 1); // check first triangle
  15993. let intersect = raycaster.ray.intersectTriangle(_vA$1, _vB$1, _vC$1, false, _intersectPoint);
  15994. if (intersect === null) {
  15995. // check second triangle
  15996. transformVertex(_vB$1.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15997. _uvB$1.set(0, 1);
  15998. intersect = raycaster.ray.intersectTriangle(_vA$1, _vC$1, _vB$1, false, _intersectPoint);
  15999. if (intersect === null) {
  16000. return;
  16001. }
  16002. }
  16003. const distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  16004. if (distance < raycaster.near || distance > raycaster.far) return;
  16005. intersects.push({
  16006. distance: distance,
  16007. point: _intersectPoint.clone(),
  16008. uv: Triangle.getUV(_intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2()),
  16009. face: null,
  16010. object: this
  16011. });
  16012. },
  16013. copy: function (source) {
  16014. Object3D.prototype.copy.call(this, source);
  16015. if (source.center !== undefined) this.center.copy(source.center);
  16016. this.material = source.material;
  16017. return this;
  16018. }
  16019. });
  16020. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  16021. // compute position in camera space
  16022. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  16023. if (sin !== undefined) {
  16024. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  16025. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  16026. } else {
  16027. _rotatedPosition.copy(_alignedPosition);
  16028. }
  16029. vertexPosition.copy(mvPosition);
  16030. vertexPosition.x += _rotatedPosition.x;
  16031. vertexPosition.y += _rotatedPosition.y; // transform to world space
  16032. vertexPosition.applyMatrix4(_viewWorldMatrix);
  16033. }
  16034. const _v1$4 = new Vector3();
  16035. const _v2$2 = new Vector3();
  16036. function LOD() {
  16037. Object3D.call(this);
  16038. this._currentLevel = 0;
  16039. this.type = 'LOD';
  16040. Object.defineProperties(this, {
  16041. levels: {
  16042. enumerable: true,
  16043. value: []
  16044. }
  16045. });
  16046. this.autoUpdate = true;
  16047. }
  16048. LOD.prototype = Object.assign(Object.create(Object3D.prototype), {
  16049. constructor: LOD,
  16050. isLOD: true,
  16051. copy: function (source) {
  16052. Object3D.prototype.copy.call(this, source, false);
  16053. const levels = source.levels;
  16054. for (let i = 0, l = levels.length; i < l; i++) {
  16055. const level = levels[i];
  16056. this.addLevel(level.object.clone(), level.distance);
  16057. }
  16058. this.autoUpdate = source.autoUpdate;
  16059. return this;
  16060. },
  16061. addLevel: function (object, distance = 0) {
  16062. distance = Math.abs(distance);
  16063. const levels = this.levels;
  16064. let l;
  16065. for (l = 0; l < levels.length; l++) {
  16066. if (distance < levels[l].distance) {
  16067. break;
  16068. }
  16069. }
  16070. levels.splice(l, 0, {
  16071. distance: distance,
  16072. object: object
  16073. });
  16074. this.add(object);
  16075. return this;
  16076. },
  16077. getCurrentLevel: function () {
  16078. return this._currentLevel;
  16079. },
  16080. getObjectForDistance: function (distance) {
  16081. const levels = this.levels;
  16082. if (levels.length > 0) {
  16083. let i, l;
  16084. for (i = 1, l = levels.length; i < l; i++) {
  16085. if (distance < levels[i].distance) {
  16086. break;
  16087. }
  16088. }
  16089. return levels[i - 1].object;
  16090. }
  16091. return null;
  16092. },
  16093. raycast: function (raycaster, intersects) {
  16094. const levels = this.levels;
  16095. if (levels.length > 0) {
  16096. _v1$4.setFromMatrixPosition(this.matrixWorld);
  16097. const distance = raycaster.ray.origin.distanceTo(_v1$4);
  16098. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  16099. }
  16100. },
  16101. update: function (camera) {
  16102. const levels = this.levels;
  16103. if (levels.length > 1) {
  16104. _v1$4.setFromMatrixPosition(camera.matrixWorld);
  16105. _v2$2.setFromMatrixPosition(this.matrixWorld);
  16106. const distance = _v1$4.distanceTo(_v2$2) / camera.zoom;
  16107. levels[0].object.visible = true;
  16108. let i, l;
  16109. for (i = 1, l = levels.length; i < l; i++) {
  16110. if (distance >= levels[i].distance) {
  16111. levels[i - 1].object.visible = false;
  16112. levels[i].object.visible = true;
  16113. } else {
  16114. break;
  16115. }
  16116. }
  16117. this._currentLevel = i - 1;
  16118. for (; i < l; i++) {
  16119. levels[i].object.visible = false;
  16120. }
  16121. }
  16122. },
  16123. toJSON: function (meta) {
  16124. const data = Object3D.prototype.toJSON.call(this, meta);
  16125. if (this.autoUpdate === false) data.object.autoUpdate = false;
  16126. data.object.levels = [];
  16127. const levels = this.levels;
  16128. for (let i = 0, l = levels.length; i < l; i++) {
  16129. const level = levels[i];
  16130. data.object.levels.push({
  16131. object: level.object.uuid,
  16132. distance: level.distance
  16133. });
  16134. }
  16135. return data;
  16136. }
  16137. });
  16138. function SkinnedMesh(geometry, material) {
  16139. if (geometry && geometry.isGeometry) {
  16140. console.error('THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16141. }
  16142. Mesh.call(this, geometry, material);
  16143. this.type = 'SkinnedMesh';
  16144. this.bindMode = 'attached';
  16145. this.bindMatrix = new Matrix4();
  16146. this.bindMatrixInverse = new Matrix4();
  16147. }
  16148. SkinnedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
  16149. constructor: SkinnedMesh,
  16150. isSkinnedMesh: true,
  16151. copy: function (source) {
  16152. Mesh.prototype.copy.call(this, source);
  16153. this.bindMode = source.bindMode;
  16154. this.bindMatrix.copy(source.bindMatrix);
  16155. this.bindMatrixInverse.copy(source.bindMatrixInverse);
  16156. this.skeleton = source.skeleton;
  16157. return this;
  16158. },
  16159. bind: function (skeleton, bindMatrix) {
  16160. this.skeleton = skeleton;
  16161. if (bindMatrix === undefined) {
  16162. this.updateMatrixWorld(true);
  16163. this.skeleton.calculateInverses();
  16164. bindMatrix = this.matrixWorld;
  16165. }
  16166. this.bindMatrix.copy(bindMatrix);
  16167. this.bindMatrixInverse.copy(bindMatrix).invert();
  16168. },
  16169. pose: function () {
  16170. this.skeleton.pose();
  16171. },
  16172. normalizeSkinWeights: function () {
  16173. const vector = new Vector4();
  16174. const skinWeight = this.geometry.attributes.skinWeight;
  16175. for (let i = 0, l = skinWeight.count; i < l; i++) {
  16176. vector.x = skinWeight.getX(i);
  16177. vector.y = skinWeight.getY(i);
  16178. vector.z = skinWeight.getZ(i);
  16179. vector.w = skinWeight.getW(i);
  16180. const scale = 1.0 / vector.manhattanLength();
  16181. if (scale !== Infinity) {
  16182. vector.multiplyScalar(scale);
  16183. } else {
  16184. vector.set(1, 0, 0, 0); // do something reasonable
  16185. }
  16186. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  16187. }
  16188. },
  16189. updateMatrixWorld: function (force) {
  16190. Mesh.prototype.updateMatrixWorld.call(this, force);
  16191. if (this.bindMode === 'attached') {
  16192. this.bindMatrixInverse.copy(this.matrixWorld).invert();
  16193. } else if (this.bindMode === 'detached') {
  16194. this.bindMatrixInverse.copy(this.bindMatrix).invert();
  16195. } else {
  16196. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  16197. }
  16198. },
  16199. boneTransform: function () {
  16200. const basePosition = new Vector3();
  16201. const skinIndex = new Vector4();
  16202. const skinWeight = new Vector4();
  16203. const vector = new Vector3();
  16204. const matrix = new Matrix4();
  16205. return function (index, target) {
  16206. const skeleton = this.skeleton;
  16207. const geometry = this.geometry;
  16208. skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index);
  16209. skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index);
  16210. basePosition.fromBufferAttribute(geometry.attributes.position, index).applyMatrix4(this.bindMatrix);
  16211. target.set(0, 0, 0);
  16212. for (let i = 0; i < 4; i++) {
  16213. const weight = skinWeight.getComponent(i);
  16214. if (weight !== 0) {
  16215. const boneIndex = skinIndex.getComponent(i);
  16216. matrix.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]);
  16217. target.addScaledVector(vector.copy(basePosition).applyMatrix4(matrix), weight);
  16218. }
  16219. }
  16220. return target.applyMatrix4(this.bindMatrixInverse);
  16221. };
  16222. }()
  16223. });
  16224. function Bone() {
  16225. Object3D.call(this);
  16226. this.type = 'Bone';
  16227. }
  16228. Bone.prototype = Object.assign(Object.create(Object3D.prototype), {
  16229. constructor: Bone,
  16230. isBone: true
  16231. });
  16232. const _offsetMatrix = new Matrix4();
  16233. const _identityMatrix = new Matrix4();
  16234. function Skeleton(bones = [], boneInverses = []) {
  16235. this.uuid = MathUtils.generateUUID();
  16236. this.bones = bones.slice(0);
  16237. this.boneInverses = boneInverses;
  16238. this.boneMatrices = null;
  16239. this.boneTexture = null;
  16240. this.boneTextureSize = 0;
  16241. this.frame = -1;
  16242. this.init();
  16243. }
  16244. Object.assign(Skeleton.prototype, {
  16245. init: function () {
  16246. const bones = this.bones;
  16247. const boneInverses = this.boneInverses;
  16248. this.boneMatrices = new Float32Array(bones.length * 16); // calculate inverse bone matrices if necessary
  16249. if (boneInverses.length === 0) {
  16250. this.calculateInverses();
  16251. } else {
  16252. // handle special case
  16253. if (bones.length !== boneInverses.length) {
  16254. console.warn('THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.');
  16255. this.boneInverses = [];
  16256. for (let i = 0, il = this.bones.length; i < il; i++) {
  16257. this.boneInverses.push(new Matrix4());
  16258. }
  16259. }
  16260. }
  16261. },
  16262. calculateInverses: function () {
  16263. this.boneInverses.length = 0;
  16264. for (let i = 0, il = this.bones.length; i < il; i++) {
  16265. const inverse = new Matrix4();
  16266. if (this.bones[i]) {
  16267. inverse.copy(this.bones[i].matrixWorld).invert();
  16268. }
  16269. this.boneInverses.push(inverse);
  16270. }
  16271. },
  16272. pose: function () {
  16273. // recover the bind-time world matrices
  16274. for (let i = 0, il = this.bones.length; i < il; i++) {
  16275. const bone = this.bones[i];
  16276. if (bone) {
  16277. bone.matrixWorld.copy(this.boneInverses[i]).invert();
  16278. }
  16279. } // compute the local matrices, positions, rotations and scales
  16280. for (let i = 0, il = this.bones.length; i < il; i++) {
  16281. const bone = this.bones[i];
  16282. if (bone) {
  16283. if (bone.parent && bone.parent.isBone) {
  16284. bone.matrix.copy(bone.parent.matrixWorld).invert();
  16285. bone.matrix.multiply(bone.matrixWorld);
  16286. } else {
  16287. bone.matrix.copy(bone.matrixWorld);
  16288. }
  16289. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  16290. }
  16291. }
  16292. },
  16293. update: function () {
  16294. const bones = this.bones;
  16295. const boneInverses = this.boneInverses;
  16296. const boneMatrices = this.boneMatrices;
  16297. const boneTexture = this.boneTexture; // flatten bone matrices to array
  16298. for (let i = 0, il = bones.length; i < il; i++) {
  16299. // compute the offset between the current and the original transform
  16300. const matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  16301. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  16302. _offsetMatrix.toArray(boneMatrices, i * 16);
  16303. }
  16304. if (boneTexture !== null) {
  16305. boneTexture.needsUpdate = true;
  16306. }
  16307. },
  16308. clone: function () {
  16309. return new Skeleton(this.bones, this.boneInverses);
  16310. },
  16311. getBoneByName: function (name) {
  16312. for (let i = 0, il = this.bones.length; i < il; i++) {
  16313. const bone = this.bones[i];
  16314. if (bone.name === name) {
  16315. return bone;
  16316. }
  16317. }
  16318. return undefined;
  16319. },
  16320. dispose: function () {
  16321. if (this.boneTexture !== null) {
  16322. this.boneTexture.dispose();
  16323. this.boneTexture = null;
  16324. }
  16325. },
  16326. fromJSON: function (json, bones) {
  16327. this.uuid = json.uuid;
  16328. for (let i = 0, l = json.bones.length; i < l; i++) {
  16329. const uuid = json.bones[i];
  16330. let bone = bones[uuid];
  16331. if (bone === undefined) {
  16332. console.warn('THREE.Skeleton: No bone found with UUID:', uuid);
  16333. bone = new Bone();
  16334. }
  16335. this.bones.push(bone);
  16336. this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i]));
  16337. }
  16338. this.init();
  16339. return this;
  16340. },
  16341. toJSON: function () {
  16342. const data = {
  16343. metadata: {
  16344. version: 4.5,
  16345. type: 'Skeleton',
  16346. generator: 'Skeleton.toJSON'
  16347. },
  16348. bones: [],
  16349. boneInverses: []
  16350. };
  16351. data.uuid = this.uuid;
  16352. const bones = this.bones;
  16353. const boneInverses = this.boneInverses;
  16354. for (let i = 0, l = bones.length; i < l; i++) {
  16355. const bone = bones[i];
  16356. data.bones.push(bone.uuid);
  16357. const boneInverse = boneInverses[i];
  16358. data.boneInverses.push(boneInverse.toArray());
  16359. }
  16360. return data;
  16361. }
  16362. });
  16363. const _instanceLocalMatrix = new Matrix4();
  16364. const _instanceWorldMatrix = new Matrix4();
  16365. const _instanceIntersects = [];
  16366. const _mesh = new Mesh();
  16367. function InstancedMesh(geometry, material, count) {
  16368. Mesh.call(this, geometry, material);
  16369. this.instanceMatrix = new BufferAttribute(new Float32Array(count * 16), 16);
  16370. this.instanceColor = null;
  16371. this.count = count;
  16372. this.frustumCulled = false;
  16373. }
  16374. InstancedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
  16375. constructor: InstancedMesh,
  16376. isInstancedMesh: true,
  16377. copy: function (source) {
  16378. Mesh.prototype.copy.call(this, source);
  16379. this.instanceMatrix.copy(source.instanceMatrix);
  16380. this.count = source.count;
  16381. return this;
  16382. },
  16383. getColorAt: function (index, color) {
  16384. color.fromArray(this.instanceColor.array, index * 3);
  16385. },
  16386. getMatrixAt: function (index, matrix) {
  16387. matrix.fromArray(this.instanceMatrix.array, index * 16);
  16388. },
  16389. raycast: function (raycaster, intersects) {
  16390. const matrixWorld = this.matrixWorld;
  16391. const raycastTimes = this.count;
  16392. _mesh.geometry = this.geometry;
  16393. _mesh.material = this.material;
  16394. if (_mesh.material === undefined) return;
  16395. for (let instanceId = 0; instanceId < raycastTimes; instanceId++) {
  16396. // calculate the world matrix for each instance
  16397. this.getMatrixAt(instanceId, _instanceLocalMatrix);
  16398. _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); // the mesh represents this single instance
  16399. _mesh.matrixWorld = _instanceWorldMatrix;
  16400. _mesh.raycast(raycaster, _instanceIntersects); // process the result of raycast
  16401. for (let i = 0, l = _instanceIntersects.length; i < l; i++) {
  16402. const intersect = _instanceIntersects[i];
  16403. intersect.instanceId = instanceId;
  16404. intersect.object = this;
  16405. intersects.push(intersect);
  16406. }
  16407. _instanceIntersects.length = 0;
  16408. }
  16409. },
  16410. setColorAt: function (index, color) {
  16411. if (this.instanceColor === null) {
  16412. this.instanceColor = new BufferAttribute(new Float32Array(this.count * 3), 3);
  16413. }
  16414. color.toArray(this.instanceColor.array, index * 3);
  16415. },
  16416. setMatrixAt: function (index, matrix) {
  16417. matrix.toArray(this.instanceMatrix.array, index * 16);
  16418. },
  16419. updateMorphTargets: function () {}
  16420. });
  16421. /**
  16422. * parameters = {
  16423. * color: <hex>,
  16424. * opacity: <float>,
  16425. *
  16426. * linewidth: <float>,
  16427. * linecap: "round",
  16428. * linejoin: "round"
  16429. * }
  16430. */
  16431. function LineBasicMaterial(parameters) {
  16432. Material.call(this);
  16433. this.type = 'LineBasicMaterial';
  16434. this.color = new Color(0xffffff);
  16435. this.linewidth = 1;
  16436. this.linecap = 'round';
  16437. this.linejoin = 'round';
  16438. this.morphTargets = false;
  16439. this.setValues(parameters);
  16440. }
  16441. LineBasicMaterial.prototype = Object.create(Material.prototype);
  16442. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  16443. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  16444. LineBasicMaterial.prototype.copy = function (source) {
  16445. Material.prototype.copy.call(this, source);
  16446. this.color.copy(source.color);
  16447. this.linewidth = source.linewidth;
  16448. this.linecap = source.linecap;
  16449. this.linejoin = source.linejoin;
  16450. this.morphTargets = source.morphTargets;
  16451. return this;
  16452. };
  16453. const _start = new Vector3();
  16454. const _end = new Vector3();
  16455. const _inverseMatrix$1 = new Matrix4();
  16456. const _ray$1 = new Ray();
  16457. const _sphere$2 = new Sphere();
  16458. function Line(geometry, material, mode) {
  16459. if (mode === 1) {
  16460. console.error('THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.');
  16461. }
  16462. Object3D.call(this);
  16463. this.type = 'Line';
  16464. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  16465. this.material = material !== undefined ? material : new LineBasicMaterial();
  16466. this.updateMorphTargets();
  16467. }
  16468. Line.prototype = Object.assign(Object.create(Object3D.prototype), {
  16469. constructor: Line,
  16470. isLine: true,
  16471. copy: function (source) {
  16472. Object3D.prototype.copy.call(this, source);
  16473. this.material = source.material;
  16474. this.geometry = source.geometry;
  16475. return this;
  16476. },
  16477. computeLineDistances: function () {
  16478. const geometry = this.geometry;
  16479. if (geometry.isBufferGeometry) {
  16480. // we assume non-indexed geometry
  16481. if (geometry.index === null) {
  16482. const positionAttribute = geometry.attributes.position;
  16483. const lineDistances = [0];
  16484. for (let i = 1, l = positionAttribute.count; i < l; i++) {
  16485. _start.fromBufferAttribute(positionAttribute, i - 1);
  16486. _end.fromBufferAttribute(positionAttribute, i);
  16487. lineDistances[i] = lineDistances[i - 1];
  16488. lineDistances[i] += _start.distanceTo(_end);
  16489. }
  16490. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  16491. } else {
  16492. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  16493. }
  16494. } else if (geometry.isGeometry) {
  16495. const vertices = geometry.vertices;
  16496. const lineDistances = geometry.lineDistances;
  16497. lineDistances[0] = 0;
  16498. for (let i = 1, l = vertices.length; i < l; i++) {
  16499. lineDistances[i] = lineDistances[i - 1];
  16500. lineDistances[i] += vertices[i - 1].distanceTo(vertices[i]);
  16501. }
  16502. }
  16503. return this;
  16504. },
  16505. raycast: function (raycaster, intersects) {
  16506. const geometry = this.geometry;
  16507. const matrixWorld = this.matrixWorld;
  16508. const threshold = raycaster.params.Line.threshold; // Checking boundingSphere distance to ray
  16509. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  16510. _sphere$2.copy(geometry.boundingSphere);
  16511. _sphere$2.applyMatrix4(matrixWorld);
  16512. _sphere$2.radius += threshold;
  16513. if (raycaster.ray.intersectsSphere(_sphere$2) === false) return; //
  16514. _inverseMatrix$1.copy(matrixWorld).invert();
  16515. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  16516. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  16517. const localThresholdSq = localThreshold * localThreshold;
  16518. const vStart = new Vector3();
  16519. const vEnd = new Vector3();
  16520. const interSegment = new Vector3();
  16521. const interRay = new Vector3();
  16522. const step = this.isLineSegments ? 2 : 1;
  16523. if (geometry.isBufferGeometry) {
  16524. const index = geometry.index;
  16525. const attributes = geometry.attributes;
  16526. const positionAttribute = attributes.position;
  16527. if (index !== null) {
  16528. const indices = index.array;
  16529. for (let i = 0, l = indices.length - 1; i < l; i += step) {
  16530. const a = indices[i];
  16531. const b = indices[i + 1];
  16532. vStart.fromBufferAttribute(positionAttribute, a);
  16533. vEnd.fromBufferAttribute(positionAttribute, b);
  16534. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  16535. if (distSq > localThresholdSq) continue;
  16536. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16537. const distance = raycaster.ray.origin.distanceTo(interRay);
  16538. if (distance < raycaster.near || distance > raycaster.far) continue;
  16539. intersects.push({
  16540. distance: distance,
  16541. // What do we want? intersection point on the ray or on the segment??
  16542. // point: raycaster.ray.at( distance ),
  16543. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16544. index: i,
  16545. face: null,
  16546. faceIndex: null,
  16547. object: this
  16548. });
  16549. }
  16550. } else {
  16551. for (let i = 0, l = positionAttribute.count - 1; i < l; i += step) {
  16552. vStart.fromBufferAttribute(positionAttribute, i);
  16553. vEnd.fromBufferAttribute(positionAttribute, i + 1);
  16554. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  16555. if (distSq > localThresholdSq) continue;
  16556. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16557. const distance = raycaster.ray.origin.distanceTo(interRay);
  16558. if (distance < raycaster.near || distance > raycaster.far) continue;
  16559. intersects.push({
  16560. distance: distance,
  16561. // What do we want? intersection point on the ray or on the segment??
  16562. // point: raycaster.ray.at( distance ),
  16563. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16564. index: i,
  16565. face: null,
  16566. faceIndex: null,
  16567. object: this
  16568. });
  16569. }
  16570. }
  16571. } else if (geometry.isGeometry) {
  16572. const vertices = geometry.vertices;
  16573. const nbVertices = vertices.length;
  16574. for (let i = 0; i < nbVertices - 1; i += step) {
  16575. const distSq = _ray$1.distanceSqToSegment(vertices[i], vertices[i + 1], interRay, interSegment);
  16576. if (distSq > localThresholdSq) continue;
  16577. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16578. const distance = raycaster.ray.origin.distanceTo(interRay);
  16579. if (distance < raycaster.near || distance > raycaster.far) continue;
  16580. intersects.push({
  16581. distance: distance,
  16582. // What do we want? intersection point on the ray or on the segment??
  16583. // point: raycaster.ray.at( distance ),
  16584. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16585. index: i,
  16586. face: null,
  16587. faceIndex: null,
  16588. object: this
  16589. });
  16590. }
  16591. }
  16592. },
  16593. updateMorphTargets: function () {
  16594. const geometry = this.geometry;
  16595. if (geometry.isBufferGeometry) {
  16596. const morphAttributes = geometry.morphAttributes;
  16597. const keys = Object.keys(morphAttributes);
  16598. if (keys.length > 0) {
  16599. const morphAttribute = morphAttributes[keys[0]];
  16600. if (morphAttribute !== undefined) {
  16601. this.morphTargetInfluences = [];
  16602. this.morphTargetDictionary = {};
  16603. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  16604. const name = morphAttribute[m].name || String(m);
  16605. this.morphTargetInfluences.push(0);
  16606. this.morphTargetDictionary[name] = m;
  16607. }
  16608. }
  16609. }
  16610. } else {
  16611. const morphTargets = geometry.morphTargets;
  16612. if (morphTargets !== undefined && morphTargets.length > 0) {
  16613. console.error('THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  16614. }
  16615. }
  16616. }
  16617. });
  16618. const _start$1 = new Vector3();
  16619. const _end$1 = new Vector3();
  16620. function LineSegments(geometry, material) {
  16621. Line.call(this, geometry, material);
  16622. this.type = 'LineSegments';
  16623. }
  16624. LineSegments.prototype = Object.assign(Object.create(Line.prototype), {
  16625. constructor: LineSegments,
  16626. isLineSegments: true,
  16627. computeLineDistances: function () {
  16628. const geometry = this.geometry;
  16629. if (geometry.isBufferGeometry) {
  16630. // we assume non-indexed geometry
  16631. if (geometry.index === null) {
  16632. const positionAttribute = geometry.attributes.position;
  16633. const lineDistances = [];
  16634. for (let i = 0, l = positionAttribute.count; i < l; i += 2) {
  16635. _start$1.fromBufferAttribute(positionAttribute, i);
  16636. _end$1.fromBufferAttribute(positionAttribute, i + 1);
  16637. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  16638. lineDistances[i + 1] = lineDistances[i] + _start$1.distanceTo(_end$1);
  16639. }
  16640. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  16641. } else {
  16642. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  16643. }
  16644. } else if (geometry.isGeometry) {
  16645. const vertices = geometry.vertices;
  16646. const lineDistances = geometry.lineDistances;
  16647. for (let i = 0, l = vertices.length; i < l; i += 2) {
  16648. _start$1.copy(vertices[i]);
  16649. _end$1.copy(vertices[i + 1]);
  16650. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  16651. lineDistances[i + 1] = lineDistances[i] + _start$1.distanceTo(_end$1);
  16652. }
  16653. }
  16654. return this;
  16655. }
  16656. });
  16657. function LineLoop(geometry, material) {
  16658. Line.call(this, geometry, material);
  16659. this.type = 'LineLoop';
  16660. }
  16661. LineLoop.prototype = Object.assign(Object.create(Line.prototype), {
  16662. constructor: LineLoop,
  16663. isLineLoop: true
  16664. });
  16665. /**
  16666. * parameters = {
  16667. * color: <hex>,
  16668. * opacity: <float>,
  16669. * map: new THREE.Texture( <Image> ),
  16670. * alphaMap: new THREE.Texture( <Image> ),
  16671. *
  16672. * size: <float>,
  16673. * sizeAttenuation: <bool>
  16674. *
  16675. * morphTargets: <bool>
  16676. * }
  16677. */
  16678. function PointsMaterial(parameters) {
  16679. Material.call(this);
  16680. this.type = 'PointsMaterial';
  16681. this.color = new Color(0xffffff);
  16682. this.map = null;
  16683. this.alphaMap = null;
  16684. this.size = 1;
  16685. this.sizeAttenuation = true;
  16686. this.morphTargets = false;
  16687. this.setValues(parameters);
  16688. }
  16689. PointsMaterial.prototype = Object.create(Material.prototype);
  16690. PointsMaterial.prototype.constructor = PointsMaterial;
  16691. PointsMaterial.prototype.isPointsMaterial = true;
  16692. PointsMaterial.prototype.copy = function (source) {
  16693. Material.prototype.copy.call(this, source);
  16694. this.color.copy(source.color);
  16695. this.map = source.map;
  16696. this.alphaMap = source.alphaMap;
  16697. this.size = source.size;
  16698. this.sizeAttenuation = source.sizeAttenuation;
  16699. this.morphTargets = source.morphTargets;
  16700. return this;
  16701. };
  16702. const _inverseMatrix$2 = new Matrix4();
  16703. const _ray$2 = new Ray();
  16704. const _sphere$3 = new Sphere();
  16705. const _position$1 = new Vector3();
  16706. function Points(geometry, material) {
  16707. Object3D.call(this);
  16708. this.type = 'Points';
  16709. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  16710. this.material = material !== undefined ? material : new PointsMaterial();
  16711. this.updateMorphTargets();
  16712. }
  16713. Points.prototype = Object.assign(Object.create(Object3D.prototype), {
  16714. constructor: Points,
  16715. isPoints: true,
  16716. copy: function (source) {
  16717. Object3D.prototype.copy.call(this, source);
  16718. this.material = source.material;
  16719. this.geometry = source.geometry;
  16720. return this;
  16721. },
  16722. raycast: function (raycaster, intersects) {
  16723. const geometry = this.geometry;
  16724. const matrixWorld = this.matrixWorld;
  16725. const threshold = raycaster.params.Points.threshold; // Checking boundingSphere distance to ray
  16726. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  16727. _sphere$3.copy(geometry.boundingSphere);
  16728. _sphere$3.applyMatrix4(matrixWorld);
  16729. _sphere$3.radius += threshold;
  16730. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  16731. _inverseMatrix$2.copy(matrixWorld).invert();
  16732. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2);
  16733. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  16734. const localThresholdSq = localThreshold * localThreshold;
  16735. if (geometry.isBufferGeometry) {
  16736. const index = geometry.index;
  16737. const attributes = geometry.attributes;
  16738. const positionAttribute = attributes.position;
  16739. if (index !== null) {
  16740. const indices = index.array;
  16741. for (let i = 0, il = indices.length; i < il; i++) {
  16742. const a = indices[i];
  16743. _position$1.fromBufferAttribute(positionAttribute, a);
  16744. testPoint(_position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  16745. }
  16746. } else {
  16747. for (let i = 0, l = positionAttribute.count; i < l; i++) {
  16748. _position$1.fromBufferAttribute(positionAttribute, i);
  16749. testPoint(_position$1, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  16750. }
  16751. }
  16752. } else {
  16753. const vertices = geometry.vertices;
  16754. for (let i = 0, l = vertices.length; i < l; i++) {
  16755. testPoint(vertices[i], i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  16756. }
  16757. }
  16758. },
  16759. updateMorphTargets: function () {
  16760. const geometry = this.geometry;
  16761. if (geometry.isBufferGeometry) {
  16762. const morphAttributes = geometry.morphAttributes;
  16763. const keys = Object.keys(morphAttributes);
  16764. if (keys.length > 0) {
  16765. const morphAttribute = morphAttributes[keys[0]];
  16766. if (morphAttribute !== undefined) {
  16767. this.morphTargetInfluences = [];
  16768. this.morphTargetDictionary = {};
  16769. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  16770. const name = morphAttribute[m].name || String(m);
  16771. this.morphTargetInfluences.push(0);
  16772. this.morphTargetDictionary[name] = m;
  16773. }
  16774. }
  16775. }
  16776. } else {
  16777. const morphTargets = geometry.morphTargets;
  16778. if (morphTargets !== undefined && morphTargets.length > 0) {
  16779. console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  16780. }
  16781. }
  16782. }
  16783. });
  16784. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  16785. const rayPointDistanceSq = _ray$2.distanceSqToPoint(point);
  16786. if (rayPointDistanceSq < localThresholdSq) {
  16787. const intersectPoint = new Vector3();
  16788. _ray$2.closestPointToPoint(point, intersectPoint);
  16789. intersectPoint.applyMatrix4(matrixWorld);
  16790. const distance = raycaster.ray.origin.distanceTo(intersectPoint);
  16791. if (distance < raycaster.near || distance > raycaster.far) return;
  16792. intersects.push({
  16793. distance: distance,
  16794. distanceToRay: Math.sqrt(rayPointDistanceSq),
  16795. point: intersectPoint,
  16796. index: index,
  16797. face: null,
  16798. object: object
  16799. });
  16800. }
  16801. }
  16802. function VideoTexture(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  16803. Texture.call(this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16804. this.format = format !== undefined ? format : RGBFormat;
  16805. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  16806. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  16807. this.generateMipmaps = false;
  16808. const scope = this;
  16809. function updateVideo() {
  16810. scope.needsUpdate = true;
  16811. video.requestVideoFrameCallback(updateVideo);
  16812. }
  16813. if ('requestVideoFrameCallback' in video) {
  16814. video.requestVideoFrameCallback(updateVideo);
  16815. }
  16816. }
  16817. VideoTexture.prototype = Object.assign(Object.create(Texture.prototype), {
  16818. constructor: VideoTexture,
  16819. clone: function () {
  16820. return new this.constructor(this.image).copy(this);
  16821. },
  16822. isVideoTexture: true,
  16823. update: function () {
  16824. const video = this.image;
  16825. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  16826. if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) {
  16827. this.needsUpdate = true;
  16828. }
  16829. }
  16830. });
  16831. function CompressedTexture(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  16832. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  16833. this.image = {
  16834. width: width,
  16835. height: height
  16836. };
  16837. this.mipmaps = mipmaps; // no flipping for cube textures
  16838. // (also flipping doesn't work for compressed textures )
  16839. this.flipY = false; // can't generate mipmaps for compressed textures
  16840. // mips must be embedded in DDS files
  16841. this.generateMipmaps = false;
  16842. }
  16843. CompressedTexture.prototype = Object.create(Texture.prototype);
  16844. CompressedTexture.prototype.constructor = CompressedTexture;
  16845. CompressedTexture.prototype.isCompressedTexture = true;
  16846. function CanvasTexture(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  16847. Texture.call(this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16848. this.needsUpdate = true;
  16849. }
  16850. CanvasTexture.prototype = Object.create(Texture.prototype);
  16851. CanvasTexture.prototype.constructor = CanvasTexture;
  16852. CanvasTexture.prototype.isCanvasTexture = true;
  16853. function DepthTexture(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  16854. format = format !== undefined ? format : DepthFormat;
  16855. if (format !== DepthFormat && format !== DepthStencilFormat) {
  16856. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  16857. }
  16858. if (type === undefined && format === DepthFormat) type = UnsignedShortType;
  16859. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  16860. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16861. this.image = {
  16862. width: width,
  16863. height: height
  16864. };
  16865. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  16866. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  16867. this.flipY = false;
  16868. this.generateMipmaps = false;
  16869. }
  16870. DepthTexture.prototype = Object.create(Texture.prototype);
  16871. DepthTexture.prototype.constructor = DepthTexture;
  16872. DepthTexture.prototype.isDepthTexture = true;
  16873. let _geometryId = 0; // Geometry uses even numbers as Id
  16874. const _m1$3 = new Matrix4();
  16875. const _obj$1 = new Object3D();
  16876. const _offset$1 = new Vector3();
  16877. function Geometry() {
  16878. Object.defineProperty(this, 'id', {
  16879. value: _geometryId += 2
  16880. });
  16881. this.uuid = MathUtils.generateUUID();
  16882. this.name = '';
  16883. this.type = 'Geometry';
  16884. this.vertices = [];
  16885. this.colors = [];
  16886. this.faces = [];
  16887. this.faceVertexUvs = [[]];
  16888. this.morphTargets = [];
  16889. this.morphNormals = [];
  16890. this.skinWeights = [];
  16891. this.skinIndices = [];
  16892. this.lineDistances = [];
  16893. this.boundingBox = null;
  16894. this.boundingSphere = null; // update flags
  16895. this.elementsNeedUpdate = false;
  16896. this.verticesNeedUpdate = false;
  16897. this.uvsNeedUpdate = false;
  16898. this.normalsNeedUpdate = false;
  16899. this.colorsNeedUpdate = false;
  16900. this.lineDistancesNeedUpdate = false;
  16901. this.groupsNeedUpdate = false;
  16902. }
  16903. Geometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  16904. constructor: Geometry,
  16905. isGeometry: true,
  16906. applyMatrix4: function (matrix) {
  16907. const normalMatrix = new Matrix3().getNormalMatrix(matrix);
  16908. for (let i = 0, il = this.vertices.length; i < il; i++) {
  16909. const vertex = this.vertices[i];
  16910. vertex.applyMatrix4(matrix);
  16911. }
  16912. for (let i = 0, il = this.faces.length; i < il; i++) {
  16913. const face = this.faces[i];
  16914. face.normal.applyMatrix3(normalMatrix).normalize();
  16915. for (let j = 0, jl = face.vertexNormals.length; j < jl; j++) {
  16916. face.vertexNormals[j].applyMatrix3(normalMatrix).normalize();
  16917. }
  16918. }
  16919. if (this.boundingBox !== null) {
  16920. this.computeBoundingBox();
  16921. }
  16922. if (this.boundingSphere !== null) {
  16923. this.computeBoundingSphere();
  16924. }
  16925. this.verticesNeedUpdate = true;
  16926. this.normalsNeedUpdate = true;
  16927. return this;
  16928. },
  16929. rotateX: function (angle) {
  16930. // rotate geometry around world x-axis
  16931. _m1$3.makeRotationX(angle);
  16932. this.applyMatrix4(_m1$3);
  16933. return this;
  16934. },
  16935. rotateY: function (angle) {
  16936. // rotate geometry around world y-axis
  16937. _m1$3.makeRotationY(angle);
  16938. this.applyMatrix4(_m1$3);
  16939. return this;
  16940. },
  16941. rotateZ: function (angle) {
  16942. // rotate geometry around world z-axis
  16943. _m1$3.makeRotationZ(angle);
  16944. this.applyMatrix4(_m1$3);
  16945. return this;
  16946. },
  16947. translate: function (x, y, z) {
  16948. // translate geometry
  16949. _m1$3.makeTranslation(x, y, z);
  16950. this.applyMatrix4(_m1$3);
  16951. return this;
  16952. },
  16953. scale: function (x, y, z) {
  16954. // scale geometry
  16955. _m1$3.makeScale(x, y, z);
  16956. this.applyMatrix4(_m1$3);
  16957. return this;
  16958. },
  16959. lookAt: function (vector) {
  16960. _obj$1.lookAt(vector);
  16961. _obj$1.updateMatrix();
  16962. this.applyMatrix4(_obj$1.matrix);
  16963. return this;
  16964. },
  16965. fromBufferGeometry: function (geometry) {
  16966. const scope = this;
  16967. const index = geometry.index !== null ? geometry.index : undefined;
  16968. const attributes = geometry.attributes;
  16969. if (attributes.position === undefined) {
  16970. console.error('THREE.Geometry.fromBufferGeometry(): Position attribute required for conversion.');
  16971. return this;
  16972. }
  16973. const position = attributes.position;
  16974. const normal = attributes.normal;
  16975. const color = attributes.color;
  16976. const uv = attributes.uv;
  16977. const uv2 = attributes.uv2;
  16978. if (uv2 !== undefined) this.faceVertexUvs[1] = [];
  16979. for (let i = 0; i < position.count; i++) {
  16980. scope.vertices.push(new Vector3().fromBufferAttribute(position, i));
  16981. if (color !== undefined) {
  16982. scope.colors.push(new Color().fromBufferAttribute(color, i));
  16983. }
  16984. }
  16985. function addFace(a, b, c, materialIndex) {
  16986. const vertexColors = color === undefined ? [] : [scope.colors[a].clone(), scope.colors[b].clone(), scope.colors[c].clone()];
  16987. const vertexNormals = normal === undefined ? [] : [new Vector3().fromBufferAttribute(normal, a), new Vector3().fromBufferAttribute(normal, b), new Vector3().fromBufferAttribute(normal, c)];
  16988. const face = new Face3(a, b, c, vertexNormals, vertexColors, materialIndex);
  16989. scope.faces.push(face);
  16990. if (uv !== undefined) {
  16991. scope.faceVertexUvs[0].push([new Vector2().fromBufferAttribute(uv, a), new Vector2().fromBufferAttribute(uv, b), new Vector2().fromBufferAttribute(uv, c)]);
  16992. }
  16993. if (uv2 !== undefined) {
  16994. scope.faceVertexUvs[1].push([new Vector2().fromBufferAttribute(uv2, a), new Vector2().fromBufferAttribute(uv2, b), new Vector2().fromBufferAttribute(uv2, c)]);
  16995. }
  16996. }
  16997. const groups = geometry.groups;
  16998. if (groups.length > 0) {
  16999. for (let i = 0; i < groups.length; i++) {
  17000. const group = groups[i];
  17001. const start = group.start;
  17002. const count = group.count;
  17003. for (let j = start, jl = start + count; j < jl; j += 3) {
  17004. if (index !== undefined) {
  17005. addFace(index.getX(j), index.getX(j + 1), index.getX(j + 2), group.materialIndex);
  17006. } else {
  17007. addFace(j, j + 1, j + 2, group.materialIndex);
  17008. }
  17009. }
  17010. }
  17011. } else {
  17012. if (index !== undefined) {
  17013. for (let i = 0; i < index.count; i += 3) {
  17014. addFace(index.getX(i), index.getX(i + 1), index.getX(i + 2));
  17015. }
  17016. } else {
  17017. for (let i = 0; i < position.count; i += 3) {
  17018. addFace(i, i + 1, i + 2);
  17019. }
  17020. }
  17021. }
  17022. this.computeFaceNormals();
  17023. if (geometry.boundingBox !== null) {
  17024. this.boundingBox = geometry.boundingBox.clone();
  17025. }
  17026. if (geometry.boundingSphere !== null) {
  17027. this.boundingSphere = geometry.boundingSphere.clone();
  17028. }
  17029. return this;
  17030. },
  17031. center: function () {
  17032. this.computeBoundingBox();
  17033. this.boundingBox.getCenter(_offset$1).negate();
  17034. this.translate(_offset$1.x, _offset$1.y, _offset$1.z);
  17035. return this;
  17036. },
  17037. normalize: function () {
  17038. this.computeBoundingSphere();
  17039. const center = this.boundingSphere.center;
  17040. const radius = this.boundingSphere.radius;
  17041. const s = radius === 0 ? 1 : 1.0 / radius;
  17042. const matrix = new Matrix4();
  17043. matrix.set(s, 0, 0, -s * center.x, 0, s, 0, -s * center.y, 0, 0, s, -s * center.z, 0, 0, 0, 1);
  17044. this.applyMatrix4(matrix);
  17045. return this;
  17046. },
  17047. computeFaceNormals: function () {
  17048. const cb = new Vector3(),
  17049. ab = new Vector3();
  17050. for (let f = 0, fl = this.faces.length; f < fl; f++) {
  17051. const face = this.faces[f];
  17052. const vA = this.vertices[face.a];
  17053. const vB = this.vertices[face.b];
  17054. const vC = this.vertices[face.c];
  17055. cb.subVectors(vC, vB);
  17056. ab.subVectors(vA, vB);
  17057. cb.cross(ab);
  17058. cb.normalize();
  17059. face.normal.copy(cb);
  17060. }
  17061. },
  17062. computeVertexNormals: function (areaWeighted = true) {
  17063. const vertices = new Array(this.vertices.length);
  17064. for (let v = 0, vl = this.vertices.length; v < vl; v++) {
  17065. vertices[v] = new Vector3();
  17066. }
  17067. if (areaWeighted) {
  17068. // vertex normals weighted by triangle areas
  17069. // http://www.iquilezles.org/www/articles/normals/normals.htm
  17070. const cb = new Vector3(),
  17071. ab = new Vector3();
  17072. for (let f = 0, fl = this.faces.length; f < fl; f++) {
  17073. const face = this.faces[f];
  17074. const vA = this.vertices[face.a];
  17075. const vB = this.vertices[face.b];
  17076. const vC = this.vertices[face.c];
  17077. cb.subVectors(vC, vB);
  17078. ab.subVectors(vA, vB);
  17079. cb.cross(ab);
  17080. vertices[face.a].add(cb);
  17081. vertices[face.b].add(cb);
  17082. vertices[face.c].add(cb);
  17083. }
  17084. } else {
  17085. this.computeFaceNormals();
  17086. for (let f = 0, fl = this.faces.length; f < fl; f++) {
  17087. const face = this.faces[f];
  17088. vertices[face.a].add(face.normal);
  17089. vertices[face.b].add(face.normal);
  17090. vertices[face.c].add(face.normal);
  17091. }
  17092. }
  17093. for (let v = 0, vl = this.vertices.length; v < vl; v++) {
  17094. vertices[v].normalize();
  17095. }
  17096. for (let f = 0, fl = this.faces.length; f < fl; f++) {
  17097. const face = this.faces[f];
  17098. const vertexNormals = face.vertexNormals;
  17099. if (vertexNormals.length === 3) {
  17100. vertexNormals[0].copy(vertices[face.a]);
  17101. vertexNormals[1].copy(vertices[face.b]);
  17102. vertexNormals[2].copy(vertices[face.c]);
  17103. } else {
  17104. vertexNormals[0] = vertices[face.a].clone();
  17105. vertexNormals[1] = vertices[face.b].clone();
  17106. vertexNormals[2] = vertices[face.c].clone();
  17107. }
  17108. }
  17109. if (this.faces.length > 0) {
  17110. this.normalsNeedUpdate = true;
  17111. }
  17112. },
  17113. computeFlatVertexNormals: function () {
  17114. this.computeFaceNormals();
  17115. for (let f = 0, fl = this.faces.length; f < fl; f++) {
  17116. const face = this.faces[f];
  17117. const vertexNormals = face.vertexNormals;
  17118. if (vertexNormals.length === 3) {
  17119. vertexNormals[0].copy(face.normal);
  17120. vertexNormals[1].copy(face.normal);
  17121. vertexNormals[2].copy(face.normal);
  17122. } else {
  17123. vertexNormals[0] = face.normal.clone();
  17124. vertexNormals[1] = face.normal.clone();
  17125. vertexNormals[2] = face.normal.clone();
  17126. }
  17127. }
  17128. if (this.faces.length > 0) {
  17129. this.normalsNeedUpdate = true;
  17130. }
  17131. },
  17132. computeMorphNormals: function () {
  17133. // save original normals
  17134. // - create temp variables on first access
  17135. // otherwise just copy (for faster repeated calls)
  17136. for (let f = 0, fl = this.faces.length; f < fl; f++) {
  17137. const face = this.faces[f];
  17138. if (!face.__originalFaceNormal) {
  17139. face.__originalFaceNormal = face.normal.clone();
  17140. } else {
  17141. face.__originalFaceNormal.copy(face.normal);
  17142. }
  17143. if (!face.__originalVertexNormals) face.__originalVertexNormals = [];
  17144. for (let i = 0, il = face.vertexNormals.length; i < il; i++) {
  17145. if (!face.__originalVertexNormals[i]) {
  17146. face.__originalVertexNormals[i] = face.vertexNormals[i].clone();
  17147. } else {
  17148. face.__originalVertexNormals[i].copy(face.vertexNormals[i]);
  17149. }
  17150. }
  17151. } // use temp geometry to compute face and vertex normals for each morph
  17152. const tmpGeo = new Geometry();
  17153. tmpGeo.faces = this.faces;
  17154. for (let i = 0, il = this.morphTargets.length; i < il; i++) {
  17155. // create on first access
  17156. if (!this.morphNormals[i]) {
  17157. this.morphNormals[i] = {};
  17158. this.morphNormals[i].faceNormals = [];
  17159. this.morphNormals[i].vertexNormals = [];
  17160. const dstNormalsFace = this.morphNormals[i].faceNormals;
  17161. const dstNormalsVertex = this.morphNormals[i].vertexNormals;
  17162. for (let f = 0, fl = this.faces.length; f < fl; f++) {
  17163. const faceNormal = new Vector3();
  17164. const vertexNormals = {
  17165. a: new Vector3(),
  17166. b: new Vector3(),
  17167. c: new Vector3()
  17168. };
  17169. dstNormalsFace.push(faceNormal);
  17170. dstNormalsVertex.push(vertexNormals);
  17171. }
  17172. }
  17173. const morphNormals = this.morphNormals[i]; // set vertices to morph target
  17174. tmpGeo.vertices = this.morphTargets[i].vertices; // compute morph normals
  17175. tmpGeo.computeFaceNormals();
  17176. tmpGeo.computeVertexNormals(); // store morph normals
  17177. for (let f = 0, fl = this.faces.length; f < fl; f++) {
  17178. const face = this.faces[f];
  17179. const faceNormal = morphNormals.faceNormals[f];
  17180. const vertexNormals = morphNormals.vertexNormals[f];
  17181. faceNormal.copy(face.normal);
  17182. vertexNormals.a.copy(face.vertexNormals[0]);
  17183. vertexNormals.b.copy(face.vertexNormals[1]);
  17184. vertexNormals.c.copy(face.vertexNormals[2]);
  17185. }
  17186. } // restore original normals
  17187. for (let f = 0, fl = this.faces.length; f < fl; f++) {
  17188. const face = this.faces[f];
  17189. face.normal = face.__originalFaceNormal;
  17190. face.vertexNormals = face.__originalVertexNormals;
  17191. }
  17192. },
  17193. computeBoundingBox: function () {
  17194. if (this.boundingBox === null) {
  17195. this.boundingBox = new Box3();
  17196. }
  17197. this.boundingBox.setFromPoints(this.vertices);
  17198. },
  17199. computeBoundingSphere: function () {
  17200. if (this.boundingSphere === null) {
  17201. this.boundingSphere = new Sphere();
  17202. }
  17203. this.boundingSphere.setFromPoints(this.vertices);
  17204. },
  17205. merge: function (geometry, matrix, materialIndexOffset = 0) {
  17206. if (!(geometry && geometry.isGeometry)) {
  17207. console.error('THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry);
  17208. return;
  17209. }
  17210. let normalMatrix;
  17211. const vertexOffset = this.vertices.length,
  17212. vertices1 = this.vertices,
  17213. vertices2 = geometry.vertices,
  17214. faces1 = this.faces,
  17215. faces2 = geometry.faces,
  17216. colors1 = this.colors,
  17217. colors2 = geometry.colors;
  17218. if (matrix !== undefined) {
  17219. normalMatrix = new Matrix3().getNormalMatrix(matrix);
  17220. } // vertices
  17221. for (let i = 0, il = vertices2.length; i < il; i++) {
  17222. const vertex = vertices2[i];
  17223. const vertexCopy = vertex.clone();
  17224. if (matrix !== undefined) vertexCopy.applyMatrix4(matrix);
  17225. vertices1.push(vertexCopy);
  17226. } // colors
  17227. for (let i = 0, il = colors2.length; i < il; i++) {
  17228. colors1.push(colors2[i].clone());
  17229. } // faces
  17230. for (let i = 0, il = faces2.length; i < il; i++) {
  17231. const face = faces2[i];
  17232. let normal, color;
  17233. const faceVertexNormals = face.vertexNormals,
  17234. faceVertexColors = face.vertexColors;
  17235. const faceCopy = new Face3(face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset);
  17236. faceCopy.normal.copy(face.normal);
  17237. if (normalMatrix !== undefined) {
  17238. faceCopy.normal.applyMatrix3(normalMatrix).normalize();
  17239. }
  17240. for (let j = 0, jl = faceVertexNormals.length; j < jl; j++) {
  17241. normal = faceVertexNormals[j].clone();
  17242. if (normalMatrix !== undefined) {
  17243. normal.applyMatrix3(normalMatrix).normalize();
  17244. }
  17245. faceCopy.vertexNormals.push(normal);
  17246. }
  17247. faceCopy.color.copy(face.color);
  17248. for (let j = 0, jl = faceVertexColors.length; j < jl; j++) {
  17249. color = faceVertexColors[j];
  17250. faceCopy.vertexColors.push(color.clone());
  17251. }
  17252. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  17253. faces1.push(faceCopy);
  17254. } // uvs
  17255. for (let i = 0, il = geometry.faceVertexUvs.length; i < il; i++) {
  17256. const faceVertexUvs2 = geometry.faceVertexUvs[i];
  17257. if (this.faceVertexUvs[i] === undefined) this.faceVertexUvs[i] = [];
  17258. for (let j = 0, jl = faceVertexUvs2.length; j < jl; j++) {
  17259. const uvs2 = faceVertexUvs2[j],
  17260. uvsCopy = [];
  17261. for (let k = 0, kl = uvs2.length; k < kl; k++) {
  17262. uvsCopy.push(uvs2[k].clone());
  17263. }
  17264. this.faceVertexUvs[i].push(uvsCopy);
  17265. }
  17266. }
  17267. },
  17268. mergeMesh: function (mesh) {
  17269. if (!(mesh && mesh.isMesh)) {
  17270. console.error('THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh);
  17271. return;
  17272. }
  17273. if (mesh.matrixAutoUpdate) mesh.updateMatrix();
  17274. this.merge(mesh.geometry, mesh.matrix);
  17275. },
  17276. /*
  17277. * Checks for duplicate vertices with hashmap.
  17278. * Duplicated vertices are removed
  17279. * and faces' vertices are updated.
  17280. */
  17281. mergeVertices: function (precisionPoints = 4) {
  17282. const verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  17283. const unique = [],
  17284. changes = [];
  17285. const precision = Math.pow(10, precisionPoints);
  17286. for (let i = 0, il = this.vertices.length; i < il; i++) {
  17287. const v = this.vertices[i];
  17288. const key = Math.round(v.x * precision) + '_' + Math.round(v.y * precision) + '_' + Math.round(v.z * precision);
  17289. if (verticesMap[key] === undefined) {
  17290. verticesMap[key] = i;
  17291. unique.push(this.vertices[i]);
  17292. changes[i] = unique.length - 1;
  17293. } else {
  17294. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  17295. changes[i] = changes[verticesMap[key]];
  17296. }
  17297. } // if faces are completely degenerate after merging vertices, we
  17298. // have to remove them from the geometry.
  17299. const faceIndicesToRemove = [];
  17300. for (let i = 0, il = this.faces.length; i < il; i++) {
  17301. const face = this.faces[i];
  17302. face.a = changes[face.a];
  17303. face.b = changes[face.b];
  17304. face.c = changes[face.c];
  17305. const indices = [face.a, face.b, face.c]; // if any duplicate vertices are found in a Face3
  17306. // we have to remove the face as nothing can be saved
  17307. for (let n = 0; n < 3; n++) {
  17308. if (indices[n] === indices[(n + 1) % 3]) {
  17309. faceIndicesToRemove.push(i);
  17310. break;
  17311. }
  17312. }
  17313. }
  17314. for (let i = faceIndicesToRemove.length - 1; i >= 0; i--) {
  17315. const idx = faceIndicesToRemove[i];
  17316. this.faces.splice(idx, 1);
  17317. for (let j = 0, jl = this.faceVertexUvs.length; j < jl; j++) {
  17318. this.faceVertexUvs[j].splice(idx, 1);
  17319. }
  17320. } // Use unique set of vertices
  17321. const diff = this.vertices.length - unique.length;
  17322. this.vertices = unique;
  17323. return diff;
  17324. },
  17325. setFromPoints: function (points) {
  17326. this.vertices = [];
  17327. for (let i = 0, l = points.length; i < l; i++) {
  17328. const point = points[i];
  17329. this.vertices.push(new Vector3(point.x, point.y, point.z || 0));
  17330. }
  17331. return this;
  17332. },
  17333. sortFacesByMaterialIndex: function () {
  17334. const faces = this.faces;
  17335. const length = faces.length; // tag faces
  17336. for (let i = 0; i < length; i++) {
  17337. faces[i]._id = i;
  17338. } // sort faces
  17339. function materialIndexSort(a, b) {
  17340. return a.materialIndex - b.materialIndex;
  17341. }
  17342. faces.sort(materialIndexSort); // sort uvs
  17343. const uvs1 = this.faceVertexUvs[0];
  17344. const uvs2 = this.faceVertexUvs[1];
  17345. let newUvs1, newUvs2;
  17346. if (uvs1 && uvs1.length === length) newUvs1 = [];
  17347. if (uvs2 && uvs2.length === length) newUvs2 = [];
  17348. for (let i = 0; i < length; i++) {
  17349. const id = faces[i]._id;
  17350. if (newUvs1) newUvs1.push(uvs1[id]);
  17351. if (newUvs2) newUvs2.push(uvs2[id]);
  17352. }
  17353. if (newUvs1) this.faceVertexUvs[0] = newUvs1;
  17354. if (newUvs2) this.faceVertexUvs[1] = newUvs2;
  17355. },
  17356. toJSON: function () {
  17357. const data = {
  17358. metadata: {
  17359. version: 4.5,
  17360. type: 'Geometry',
  17361. generator: 'Geometry.toJSON'
  17362. }
  17363. }; // standard Geometry serialization
  17364. data.uuid = this.uuid;
  17365. data.type = this.type;
  17366. if (this.name !== '') data.name = this.name;
  17367. if (this.parameters !== undefined) {
  17368. const parameters = this.parameters;
  17369. for (const key in parameters) {
  17370. if (parameters[key] !== undefined) data[key] = parameters[key];
  17371. }
  17372. return data;
  17373. }
  17374. const vertices = [];
  17375. for (let i = 0; i < this.vertices.length; i++) {
  17376. const vertex = this.vertices[i];
  17377. vertices.push(vertex.x, vertex.y, vertex.z);
  17378. }
  17379. const faces = [];
  17380. const normals = [];
  17381. const normalsHash = {};
  17382. const colors = [];
  17383. const colorsHash = {};
  17384. const uvs = [];
  17385. const uvsHash = {};
  17386. for (let i = 0; i < this.faces.length; i++) {
  17387. const face = this.faces[i];
  17388. const hasMaterial = true;
  17389. const hasFaceUv = false; // deprecated
  17390. const hasFaceVertexUv = this.faceVertexUvs[0][i] !== undefined;
  17391. const hasFaceNormal = face.normal.length() > 0;
  17392. const hasFaceVertexNormal = face.vertexNormals.length > 0;
  17393. const hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  17394. const hasFaceVertexColor = face.vertexColors.length > 0;
  17395. let faceType = 0;
  17396. faceType = setBit(faceType, 0, 0); // isQuad
  17397. faceType = setBit(faceType, 1, hasMaterial);
  17398. faceType = setBit(faceType, 2, hasFaceUv);
  17399. faceType = setBit(faceType, 3, hasFaceVertexUv);
  17400. faceType = setBit(faceType, 4, hasFaceNormal);
  17401. faceType = setBit(faceType, 5, hasFaceVertexNormal);
  17402. faceType = setBit(faceType, 6, hasFaceColor);
  17403. faceType = setBit(faceType, 7, hasFaceVertexColor);
  17404. faces.push(faceType);
  17405. faces.push(face.a, face.b, face.c);
  17406. faces.push(face.materialIndex);
  17407. if (hasFaceVertexUv) {
  17408. const faceVertexUvs = this.faceVertexUvs[0][i];
  17409. faces.push(getUvIndex(faceVertexUvs[0]), getUvIndex(faceVertexUvs[1]), getUvIndex(faceVertexUvs[2]));
  17410. }
  17411. if (hasFaceNormal) {
  17412. faces.push(getNormalIndex(face.normal));
  17413. }
  17414. if (hasFaceVertexNormal) {
  17415. const vertexNormals = face.vertexNormals;
  17416. faces.push(getNormalIndex(vertexNormals[0]), getNormalIndex(vertexNormals[1]), getNormalIndex(vertexNormals[2]));
  17417. }
  17418. if (hasFaceColor) {
  17419. faces.push(getColorIndex(face.color));
  17420. }
  17421. if (hasFaceVertexColor) {
  17422. const vertexColors = face.vertexColors;
  17423. faces.push(getColorIndex(vertexColors[0]), getColorIndex(vertexColors[1]), getColorIndex(vertexColors[2]));
  17424. }
  17425. }
  17426. function setBit(value, position, enabled) {
  17427. return enabled ? value | 1 << position : value & ~(1 << position);
  17428. }
  17429. function getNormalIndex(normal) {
  17430. const hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  17431. if (normalsHash[hash] !== undefined) {
  17432. return normalsHash[hash];
  17433. }
  17434. normalsHash[hash] = normals.length / 3;
  17435. normals.push(normal.x, normal.y, normal.z);
  17436. return normalsHash[hash];
  17437. }
  17438. function getColorIndex(color) {
  17439. const hash = color.r.toString() + color.g.toString() + color.b.toString();
  17440. if (colorsHash[hash] !== undefined) {
  17441. return colorsHash[hash];
  17442. }
  17443. colorsHash[hash] = colors.length;
  17444. colors.push(color.getHex());
  17445. return colorsHash[hash];
  17446. }
  17447. function getUvIndex(uv) {
  17448. const hash = uv.x.toString() + uv.y.toString();
  17449. if (uvsHash[hash] !== undefined) {
  17450. return uvsHash[hash];
  17451. }
  17452. uvsHash[hash] = uvs.length / 2;
  17453. uvs.push(uv.x, uv.y);
  17454. return uvsHash[hash];
  17455. }
  17456. data.data = {};
  17457. data.data.vertices = vertices;
  17458. data.data.normals = normals;
  17459. if (colors.length > 0) data.data.colors = colors;
  17460. if (uvs.length > 0) data.data.uvs = [uvs]; // temporal backward compatibility
  17461. data.data.faces = faces;
  17462. return data;
  17463. },
  17464. clone: function () {
  17465. /*
  17466. // Handle primitives
  17467. const parameters = this.parameters;
  17468. if ( parameters !== undefined ) {
  17469. const values = [];
  17470. for ( const key in parameters ) {
  17471. values.push( parameters[ key ] );
  17472. }
  17473. const geometry = Object.create( this.constructor.prototype );
  17474. this.constructor.apply( geometry, values );
  17475. return geometry;
  17476. }
  17477. return new this.constructor().copy( this );
  17478. */
  17479. return new Geometry().copy(this);
  17480. },
  17481. copy: function (source) {
  17482. // reset
  17483. this.vertices = [];
  17484. this.colors = [];
  17485. this.faces = [];
  17486. this.faceVertexUvs = [[]];
  17487. this.morphTargets = [];
  17488. this.morphNormals = [];
  17489. this.skinWeights = [];
  17490. this.skinIndices = [];
  17491. this.lineDistances = [];
  17492. this.boundingBox = null;
  17493. this.boundingSphere = null; // name
  17494. this.name = source.name; // vertices
  17495. const vertices = source.vertices;
  17496. for (let i = 0, il = vertices.length; i < il; i++) {
  17497. this.vertices.push(vertices[i].clone());
  17498. } // colors
  17499. const colors = source.colors;
  17500. for (let i = 0, il = colors.length; i < il; i++) {
  17501. this.colors.push(colors[i].clone());
  17502. } // faces
  17503. const faces = source.faces;
  17504. for (let i = 0, il = faces.length; i < il; i++) {
  17505. this.faces.push(faces[i].clone());
  17506. } // face vertex uvs
  17507. for (let i = 0, il = source.faceVertexUvs.length; i < il; i++) {
  17508. const faceVertexUvs = source.faceVertexUvs[i];
  17509. if (this.faceVertexUvs[i] === undefined) {
  17510. this.faceVertexUvs[i] = [];
  17511. }
  17512. for (let j = 0, jl = faceVertexUvs.length; j < jl; j++) {
  17513. const uvs = faceVertexUvs[j],
  17514. uvsCopy = [];
  17515. for (let k = 0, kl = uvs.length; k < kl; k++) {
  17516. const uv = uvs[k];
  17517. uvsCopy.push(uv.clone());
  17518. }
  17519. this.faceVertexUvs[i].push(uvsCopy);
  17520. }
  17521. } // morph targets
  17522. const morphTargets = source.morphTargets;
  17523. for (let i = 0, il = morphTargets.length; i < il; i++) {
  17524. const morphTarget = {};
  17525. morphTarget.name = morphTargets[i].name; // vertices
  17526. if (morphTargets[i].vertices !== undefined) {
  17527. morphTarget.vertices = [];
  17528. for (let j = 0, jl = morphTargets[i].vertices.length; j < jl; j++) {
  17529. morphTarget.vertices.push(morphTargets[i].vertices[j].clone());
  17530. }
  17531. } // normals
  17532. if (morphTargets[i].normals !== undefined) {
  17533. morphTarget.normals = [];
  17534. for (let j = 0, jl = morphTargets[i].normals.length; j < jl; j++) {
  17535. morphTarget.normals.push(morphTargets[i].normals[j].clone());
  17536. }
  17537. }
  17538. this.morphTargets.push(morphTarget);
  17539. } // morph normals
  17540. const morphNormals = source.morphNormals;
  17541. for (let i = 0, il = morphNormals.length; i < il; i++) {
  17542. const morphNormal = {}; // vertex normals
  17543. if (morphNormals[i].vertexNormals !== undefined) {
  17544. morphNormal.vertexNormals = [];
  17545. for (let j = 0, jl = morphNormals[i].vertexNormals.length; j < jl; j++) {
  17546. const srcVertexNormal = morphNormals[i].vertexNormals[j];
  17547. const destVertexNormal = {};
  17548. destVertexNormal.a = srcVertexNormal.a.clone();
  17549. destVertexNormal.b = srcVertexNormal.b.clone();
  17550. destVertexNormal.c = srcVertexNormal.c.clone();
  17551. morphNormal.vertexNormals.push(destVertexNormal);
  17552. }
  17553. } // face normals
  17554. if (morphNormals[i].faceNormals !== undefined) {
  17555. morphNormal.faceNormals = [];
  17556. for (let j = 0, jl = morphNormals[i].faceNormals.length; j < jl; j++) {
  17557. morphNormal.faceNormals.push(morphNormals[i].faceNormals[j].clone());
  17558. }
  17559. }
  17560. this.morphNormals.push(morphNormal);
  17561. } // skin weights
  17562. const skinWeights = source.skinWeights;
  17563. for (let i = 0, il = skinWeights.length; i < il; i++) {
  17564. this.skinWeights.push(skinWeights[i].clone());
  17565. } // skin indices
  17566. const skinIndices = source.skinIndices;
  17567. for (let i = 0, il = skinIndices.length; i < il; i++) {
  17568. this.skinIndices.push(skinIndices[i].clone());
  17569. } // line distances
  17570. const lineDistances = source.lineDistances;
  17571. for (let i = 0, il = lineDistances.length; i < il; i++) {
  17572. this.lineDistances.push(lineDistances[i]);
  17573. } // bounding box
  17574. const boundingBox = source.boundingBox;
  17575. if (boundingBox !== null) {
  17576. this.boundingBox = boundingBox.clone();
  17577. } // bounding sphere
  17578. const boundingSphere = source.boundingSphere;
  17579. if (boundingSphere !== null) {
  17580. this.boundingSphere = boundingSphere.clone();
  17581. } // update flags
  17582. this.elementsNeedUpdate = source.elementsNeedUpdate;
  17583. this.verticesNeedUpdate = source.verticesNeedUpdate;
  17584. this.uvsNeedUpdate = source.uvsNeedUpdate;
  17585. this.normalsNeedUpdate = source.normalsNeedUpdate;
  17586. this.colorsNeedUpdate = source.colorsNeedUpdate;
  17587. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  17588. this.groupsNeedUpdate = source.groupsNeedUpdate;
  17589. return this;
  17590. },
  17591. dispose: function () {
  17592. this.dispatchEvent({
  17593. type: 'dispose'
  17594. });
  17595. }
  17596. });
  17597. class BoxGeometry extends Geometry {
  17598. constructor(width, height, depth, widthSegments, heightSegments, depthSegments) {
  17599. super();
  17600. this.type = 'BoxGeometry';
  17601. this.parameters = {
  17602. width: width,
  17603. height: height,
  17604. depth: depth,
  17605. widthSegments: widthSegments,
  17606. heightSegments: heightSegments,
  17607. depthSegments: depthSegments
  17608. };
  17609. this.fromBufferGeometry(new BoxBufferGeometry(width, height, depth, widthSegments, heightSegments, depthSegments));
  17610. this.mergeVertices();
  17611. }
  17612. }
  17613. exports.CubeGeometry = exports.BoxGeometry = BoxGeometry;
  17614. class CircleBufferGeometry extends BufferGeometry {
  17615. constructor(radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2) {
  17616. super();
  17617. this.type = 'CircleBufferGeometry';
  17618. this.parameters = {
  17619. radius: radius,
  17620. segments: segments,
  17621. thetaStart: thetaStart,
  17622. thetaLength: thetaLength
  17623. };
  17624. segments = Math.max(3, segments); // buffers
  17625. const indices = [];
  17626. const vertices = [];
  17627. const normals = [];
  17628. const uvs = []; // helper variables
  17629. const vertex = new Vector3();
  17630. const uv = new Vector2(); // center point
  17631. vertices.push(0, 0, 0);
  17632. normals.push(0, 0, 1);
  17633. uvs.push(0.5, 0.5);
  17634. for (let s = 0, i = 3; s <= segments; s++, i += 3) {
  17635. const segment = thetaStart + s / segments * thetaLength; // vertex
  17636. vertex.x = radius * Math.cos(segment);
  17637. vertex.y = radius * Math.sin(segment);
  17638. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  17639. normals.push(0, 0, 1); // uvs
  17640. uv.x = (vertices[i] / radius + 1) / 2;
  17641. uv.y = (vertices[i + 1] / radius + 1) / 2;
  17642. uvs.push(uv.x, uv.y);
  17643. } // indices
  17644. for (let i = 1; i <= segments; i++) {
  17645. indices.push(i, i + 1, 0);
  17646. } // build geometry
  17647. this.setIndex(indices);
  17648. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17649. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  17650. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  17651. }
  17652. }
  17653. exports.CircleBufferGeometry = CircleBufferGeometry;
  17654. class CircleGeometry extends Geometry {
  17655. constructor(radius, segments, thetaStart, thetaLength) {
  17656. super();
  17657. this.type = 'CircleGeometry';
  17658. this.parameters = {
  17659. radius: radius,
  17660. segments: segments,
  17661. thetaStart: thetaStart,
  17662. thetaLength: thetaLength
  17663. };
  17664. this.fromBufferGeometry(new CircleBufferGeometry(radius, segments, thetaStart, thetaLength));
  17665. this.mergeVertices();
  17666. }
  17667. }
  17668. exports.CircleGeometry = CircleGeometry;
  17669. class CylinderBufferGeometry extends BufferGeometry {
  17670. constructor(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  17671. super();
  17672. this.type = 'CylinderBufferGeometry';
  17673. this.parameters = {
  17674. radiusTop: radiusTop,
  17675. radiusBottom: radiusBottom,
  17676. height: height,
  17677. radialSegments: radialSegments,
  17678. heightSegments: heightSegments,
  17679. openEnded: openEnded,
  17680. thetaStart: thetaStart,
  17681. thetaLength: thetaLength
  17682. };
  17683. const scope = this;
  17684. radialSegments = Math.floor(radialSegments);
  17685. heightSegments = Math.floor(heightSegments); // buffers
  17686. const indices = [];
  17687. const vertices = [];
  17688. const normals = [];
  17689. const uvs = []; // helper variables
  17690. let index = 0;
  17691. const indexArray = [];
  17692. const halfHeight = height / 2;
  17693. let groupStart = 0; // generate geometry
  17694. generateTorso();
  17695. if (openEnded === false) {
  17696. if (radiusTop > 0) generateCap(true);
  17697. if (radiusBottom > 0) generateCap(false);
  17698. } // build geometry
  17699. this.setIndex(indices);
  17700. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17701. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  17702. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  17703. function generateTorso() {
  17704. const normal = new Vector3();
  17705. const vertex = new Vector3();
  17706. let groupCount = 0; // this will be used to calculate the normal
  17707. const slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  17708. for (let y = 0; y <= heightSegments; y++) {
  17709. const indexRow = [];
  17710. const v = y / heightSegments; // calculate the radius of the current row
  17711. const radius = v * (radiusBottom - radiusTop) + radiusTop;
  17712. for (let x = 0; x <= radialSegments; x++) {
  17713. const u = x / radialSegments;
  17714. const theta = u * thetaLength + thetaStart;
  17715. const sinTheta = Math.sin(theta);
  17716. const cosTheta = Math.cos(theta); // vertex
  17717. vertex.x = radius * sinTheta;
  17718. vertex.y = -v * height + halfHeight;
  17719. vertex.z = radius * cosTheta;
  17720. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  17721. normal.set(sinTheta, slope, cosTheta).normalize();
  17722. normals.push(normal.x, normal.y, normal.z); // uv
  17723. uvs.push(u, 1 - v); // save index of vertex in respective row
  17724. indexRow.push(index++);
  17725. } // now save vertices of the row in our index array
  17726. indexArray.push(indexRow);
  17727. } // generate indices
  17728. for (let x = 0; x < radialSegments; x++) {
  17729. for (let y = 0; y < heightSegments; y++) {
  17730. // we use the index array to access the correct indices
  17731. const a = indexArray[y][x];
  17732. const b = indexArray[y + 1][x];
  17733. const c = indexArray[y + 1][x + 1];
  17734. const d = indexArray[y][x + 1]; // faces
  17735. indices.push(a, b, d);
  17736. indices.push(b, c, d); // update group counter
  17737. groupCount += 6;
  17738. }
  17739. } // add a group to the geometry. this will ensure multi material support
  17740. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  17741. groupStart += groupCount;
  17742. }
  17743. function generateCap(top) {
  17744. // save the index of the first center vertex
  17745. const centerIndexStart = index;
  17746. const uv = new Vector2();
  17747. const vertex = new Vector3();
  17748. let groupCount = 0;
  17749. const radius = top === true ? radiusTop : radiusBottom;
  17750. const sign = top === true ? 1 : -1; // first we generate the center vertex data of the cap.
  17751. // because the geometry needs one set of uvs per face,
  17752. // we must generate a center vertex per face/segment
  17753. for (let x = 1; x <= radialSegments; x++) {
  17754. // vertex
  17755. vertices.push(0, halfHeight * sign, 0); // normal
  17756. normals.push(0, sign, 0); // uv
  17757. uvs.push(0.5, 0.5); // increase index
  17758. index++;
  17759. } // save the index of the last center vertex
  17760. const centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  17761. for (let x = 0; x <= radialSegments; x++) {
  17762. const u = x / radialSegments;
  17763. const theta = u * thetaLength + thetaStart;
  17764. const cosTheta = Math.cos(theta);
  17765. const sinTheta = Math.sin(theta); // vertex
  17766. vertex.x = radius * sinTheta;
  17767. vertex.y = halfHeight * sign;
  17768. vertex.z = radius * cosTheta;
  17769. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  17770. normals.push(0, sign, 0); // uv
  17771. uv.x = cosTheta * 0.5 + 0.5;
  17772. uv.y = sinTheta * 0.5 * sign + 0.5;
  17773. uvs.push(uv.x, uv.y); // increase index
  17774. index++;
  17775. } // generate indices
  17776. for (let x = 0; x < radialSegments; x++) {
  17777. const c = centerIndexStart + x;
  17778. const i = centerIndexEnd + x;
  17779. if (top === true) {
  17780. // face top
  17781. indices.push(i, i + 1, c);
  17782. } else {
  17783. // face bottom
  17784. indices.push(i + 1, i, c);
  17785. }
  17786. groupCount += 3;
  17787. } // add a group to the geometry. this will ensure multi material support
  17788. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  17789. groupStart += groupCount;
  17790. }
  17791. }
  17792. }
  17793. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  17794. class CylinderGeometry extends Geometry {
  17795. constructor(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  17796. super();
  17797. this.type = 'CylinderGeometry';
  17798. this.parameters = {
  17799. radiusTop: radiusTop,
  17800. radiusBottom: radiusBottom,
  17801. height: height,
  17802. radialSegments: radialSegments,
  17803. heightSegments: heightSegments,
  17804. openEnded: openEnded,
  17805. thetaStart: thetaStart,
  17806. thetaLength: thetaLength
  17807. };
  17808. this.fromBufferGeometry(new CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength));
  17809. this.mergeVertices();
  17810. }
  17811. }
  17812. exports.CylinderGeometry = CylinderGeometry;
  17813. class ConeGeometry extends CylinderGeometry {
  17814. constructor(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  17815. super(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  17816. this.type = 'ConeGeometry';
  17817. this.parameters = {
  17818. radius: radius,
  17819. height: height,
  17820. radialSegments: radialSegments,
  17821. heightSegments: heightSegments,
  17822. openEnded: openEnded,
  17823. thetaStart: thetaStart,
  17824. thetaLength: thetaLength
  17825. };
  17826. }
  17827. }
  17828. exports.ConeGeometry = ConeGeometry;
  17829. class ConeBufferGeometry extends CylinderBufferGeometry {
  17830. constructor(radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  17831. super(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  17832. this.type = 'ConeBufferGeometry';
  17833. this.parameters = {
  17834. radius: radius,
  17835. height: height,
  17836. radialSegments: radialSegments,
  17837. heightSegments: heightSegments,
  17838. openEnded: openEnded,
  17839. thetaStart: thetaStart,
  17840. thetaLength: thetaLength
  17841. };
  17842. }
  17843. }
  17844. exports.ConeBufferGeometry = ConeBufferGeometry;
  17845. class PolyhedronBufferGeometry extends BufferGeometry {
  17846. constructor(vertices, indices, radius = 1, detail = 0) {
  17847. super();
  17848. this.type = 'PolyhedronBufferGeometry';
  17849. this.parameters = {
  17850. vertices: vertices,
  17851. indices: indices,
  17852. radius: radius,
  17853. detail: detail
  17854. }; // default buffer data
  17855. const vertexBuffer = [];
  17856. const uvBuffer = []; // the subdivision creates the vertex buffer data
  17857. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  17858. applyRadius(radius); // finally, create the uv data
  17859. generateUVs(); // build non-indexed geometry
  17860. this.setAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  17861. this.setAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  17862. this.setAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  17863. if (detail === 0) {
  17864. this.computeVertexNormals(); // flat normals
  17865. } else {
  17866. this.normalizeNormals(); // smooth normals
  17867. } // helper functions
  17868. function subdivide(detail) {
  17869. const a = new Vector3();
  17870. const b = new Vector3();
  17871. const c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  17872. for (let i = 0; i < indices.length; i += 3) {
  17873. // get the vertices of the face
  17874. getVertexByIndex(indices[i + 0], a);
  17875. getVertexByIndex(indices[i + 1], b);
  17876. getVertexByIndex(indices[i + 2], c); // perform subdivision
  17877. subdivideFace(a, b, c, detail);
  17878. }
  17879. }
  17880. function subdivideFace(a, b, c, detail) {
  17881. const cols = detail + 1; // we use this multidimensional array as a data structure for creating the subdivision
  17882. const v = []; // construct all of the vertices for this subdivision
  17883. for (let i = 0; i <= cols; i++) {
  17884. v[i] = [];
  17885. const aj = a.clone().lerp(c, i / cols);
  17886. const bj = b.clone().lerp(c, i / cols);
  17887. const rows = cols - i;
  17888. for (let j = 0; j <= rows; j++) {
  17889. if (j === 0 && i === cols) {
  17890. v[i][j] = aj;
  17891. } else {
  17892. v[i][j] = aj.clone().lerp(bj, j / rows);
  17893. }
  17894. }
  17895. } // construct all of the faces
  17896. for (let i = 0; i < cols; i++) {
  17897. for (let j = 0; j < 2 * (cols - i) - 1; j++) {
  17898. const k = Math.floor(j / 2);
  17899. if (j % 2 === 0) {
  17900. pushVertex(v[i][k + 1]);
  17901. pushVertex(v[i + 1][k]);
  17902. pushVertex(v[i][k]);
  17903. } else {
  17904. pushVertex(v[i][k + 1]);
  17905. pushVertex(v[i + 1][k + 1]);
  17906. pushVertex(v[i + 1][k]);
  17907. }
  17908. }
  17909. }
  17910. }
  17911. function applyRadius(radius) {
  17912. const vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  17913. for (let i = 0; i < vertexBuffer.length; i += 3) {
  17914. vertex.x = vertexBuffer[i + 0];
  17915. vertex.y = vertexBuffer[i + 1];
  17916. vertex.z = vertexBuffer[i + 2];
  17917. vertex.normalize().multiplyScalar(radius);
  17918. vertexBuffer[i + 0] = vertex.x;
  17919. vertexBuffer[i + 1] = vertex.y;
  17920. vertexBuffer[i + 2] = vertex.z;
  17921. }
  17922. }
  17923. function generateUVs() {
  17924. const vertex = new Vector3();
  17925. for (let i = 0; i < vertexBuffer.length; i += 3) {
  17926. vertex.x = vertexBuffer[i + 0];
  17927. vertex.y = vertexBuffer[i + 1];
  17928. vertex.z = vertexBuffer[i + 2];
  17929. const u = azimuth(vertex) / 2 / Math.PI + 0.5;
  17930. const v = inclination(vertex) / Math.PI + 0.5;
  17931. uvBuffer.push(u, 1 - v);
  17932. }
  17933. correctUVs();
  17934. correctSeam();
  17935. }
  17936. function correctSeam() {
  17937. // handle case when face straddles the seam, see #3269
  17938. for (let i = 0; i < uvBuffer.length; i += 6) {
  17939. // uv data of a single face
  17940. const x0 = uvBuffer[i + 0];
  17941. const x1 = uvBuffer[i + 2];
  17942. const x2 = uvBuffer[i + 4];
  17943. const max = Math.max(x0, x1, x2);
  17944. const min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  17945. if (max > 0.9 && min < 0.1) {
  17946. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  17947. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  17948. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  17949. }
  17950. }
  17951. }
  17952. function pushVertex(vertex) {
  17953. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  17954. }
  17955. function getVertexByIndex(index, vertex) {
  17956. const stride = index * 3;
  17957. vertex.x = vertices[stride + 0];
  17958. vertex.y = vertices[stride + 1];
  17959. vertex.z = vertices[stride + 2];
  17960. }
  17961. function correctUVs() {
  17962. const a = new Vector3();
  17963. const b = new Vector3();
  17964. const c = new Vector3();
  17965. const centroid = new Vector3();
  17966. const uvA = new Vector2();
  17967. const uvB = new Vector2();
  17968. const uvC = new Vector2();
  17969. for (let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  17970. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  17971. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  17972. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  17973. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  17974. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  17975. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  17976. centroid.copy(a).add(b).add(c).divideScalar(3);
  17977. const azi = azimuth(centroid);
  17978. correctUV(uvA, j + 0, a, azi);
  17979. correctUV(uvB, j + 2, b, azi);
  17980. correctUV(uvC, j + 4, c, azi);
  17981. }
  17982. }
  17983. function correctUV(uv, stride, vector, azimuth) {
  17984. if (azimuth < 0 && uv.x === 1) {
  17985. uvBuffer[stride] = uv.x - 1;
  17986. }
  17987. if (vector.x === 0 && vector.z === 0) {
  17988. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  17989. }
  17990. } // Angle around the Y axis, counter-clockwise when looking from above.
  17991. function azimuth(vector) {
  17992. return Math.atan2(vector.z, -vector.x);
  17993. } // Angle above the XZ plane.
  17994. function inclination(vector) {
  17995. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  17996. }
  17997. }
  17998. }
  17999. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  18000. class DodecahedronBufferGeometry extends PolyhedronBufferGeometry {
  18001. constructor(radius = 1, detail = 0) {
  18002. const t = (1 + Math.sqrt(5)) / 2;
  18003. const r = 1 / t;
  18004. const vertices = [// (±1, ±1, ±1)
  18005. -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/φ, ±φ)
  18006. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  18007. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  18008. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  18009. const 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];
  18010. super(vertices, indices, radius, detail);
  18011. this.type = 'DodecahedronBufferGeometry';
  18012. this.parameters = {
  18013. radius: radius,
  18014. detail: detail
  18015. };
  18016. }
  18017. }
  18018. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  18019. class DodecahedronGeometry extends Geometry {
  18020. constructor(radius, detail) {
  18021. super();
  18022. this.type = 'DodecahedronGeometry';
  18023. this.parameters = {
  18024. radius: radius,
  18025. detail: detail
  18026. };
  18027. this.fromBufferGeometry(new DodecahedronBufferGeometry(radius, detail));
  18028. this.mergeVertices();
  18029. }
  18030. }
  18031. exports.DodecahedronGeometry = DodecahedronGeometry;
  18032. const _v0$2 = new Vector3();
  18033. const _v1$5 = new Vector3();
  18034. const _normal$1 = new Vector3();
  18035. const _triangle = new Triangle();
  18036. class EdgesGeometry extends BufferGeometry {
  18037. constructor(geometry, thresholdAngle) {
  18038. super();
  18039. this.type = 'EdgesGeometry';
  18040. this.parameters = {
  18041. thresholdAngle: thresholdAngle
  18042. };
  18043. thresholdAngle = thresholdAngle !== undefined ? thresholdAngle : 1;
  18044. if (geometry.isGeometry) {
  18045. geometry = new BufferGeometry().fromGeometry(geometry);
  18046. }
  18047. const precisionPoints = 4;
  18048. const precision = Math.pow(10, precisionPoints);
  18049. const thresholdDot = Math.cos(MathUtils.DEG2RAD * thresholdAngle);
  18050. const indexAttr = geometry.getIndex();
  18051. const positionAttr = geometry.getAttribute('position');
  18052. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  18053. const indexArr = [0, 0, 0];
  18054. const vertKeys = ['a', 'b', 'c'];
  18055. const hashes = new Array(3);
  18056. const edgeData = {};
  18057. const vertices = [];
  18058. for (let i = 0; i < indexCount; i += 3) {
  18059. if (indexAttr) {
  18060. indexArr[0] = indexAttr.getX(i);
  18061. indexArr[1] = indexAttr.getX(i + 1);
  18062. indexArr[2] = indexAttr.getX(i + 2);
  18063. } else {
  18064. indexArr[0] = i;
  18065. indexArr[1] = i + 1;
  18066. indexArr[2] = i + 2;
  18067. }
  18068. const {
  18069. a,
  18070. b,
  18071. c
  18072. } = _triangle;
  18073. a.fromBufferAttribute(positionAttr, indexArr[0]);
  18074. b.fromBufferAttribute(positionAttr, indexArr[1]);
  18075. c.fromBufferAttribute(positionAttr, indexArr[2]);
  18076. _triangle.getNormal(_normal$1); // create hashes for the edge from the vertices
  18077. hashes[0] = `${Math.round(a.x * precision)},${Math.round(a.y * precision)},${Math.round(a.z * precision)}`;
  18078. hashes[1] = `${Math.round(b.x * precision)},${Math.round(b.y * precision)},${Math.round(b.z * precision)}`;
  18079. hashes[2] = `${Math.round(c.x * precision)},${Math.round(c.y * precision)},${Math.round(c.z * precision)}`; // skip degenerate triangles
  18080. if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) {
  18081. continue;
  18082. } // iterate over every edge
  18083. for (let j = 0; j < 3; j++) {
  18084. // get the first and next vertex making up the edge
  18085. const jNext = (j + 1) % 3;
  18086. const vecHash0 = hashes[j];
  18087. const vecHash1 = hashes[jNext];
  18088. const v0 = _triangle[vertKeys[j]];
  18089. const v1 = _triangle[vertKeys[jNext]];
  18090. const hash = `${vecHash0}_${vecHash1}`;
  18091. const reverseHash = `${vecHash1}_${vecHash0}`;
  18092. if (reverseHash in edgeData && edgeData[reverseHash]) {
  18093. // if we found a sibling edge add it into the vertex array if
  18094. // it meets the angle threshold and delete the edge from the map.
  18095. if (_normal$1.dot(edgeData[reverseHash].normal) <= thresholdDot) {
  18096. vertices.push(v0.x, v0.y, v0.z);
  18097. vertices.push(v1.x, v1.y, v1.z);
  18098. }
  18099. edgeData[reverseHash] = null;
  18100. } else if (!(hash in edgeData)) {
  18101. // if we've already got an edge here then skip adding a new one
  18102. edgeData[hash] = {
  18103. index0: indexArr[j],
  18104. index1: indexArr[jNext],
  18105. normal: _normal$1.clone()
  18106. };
  18107. }
  18108. }
  18109. } // iterate over all remaining, unmatched edges and add them to the vertex array
  18110. for (const key in edgeData) {
  18111. if (edgeData[key]) {
  18112. const {
  18113. index0,
  18114. index1
  18115. } = edgeData[key];
  18116. _v0$2.fromBufferAttribute(positionAttr, index0);
  18117. _v1$5.fromBufferAttribute(positionAttr, index1);
  18118. vertices.push(_v0$2.x, _v0$2.y, _v0$2.z);
  18119. vertices.push(_v1$5.x, _v1$5.y, _v1$5.z);
  18120. }
  18121. }
  18122. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18123. }
  18124. }
  18125. /**
  18126. * Port from https://github.com/mapbox/earcut (v2.2.2)
  18127. */
  18128. exports.EdgesGeometry = EdgesGeometry;
  18129. const Earcut = {
  18130. triangulate: function (data, holeIndices, dim) {
  18131. dim = dim || 2;
  18132. const hasHoles = holeIndices && holeIndices.length;
  18133. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  18134. let outerNode = linkedList(data, 0, outerLen, dim, true);
  18135. const triangles = [];
  18136. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  18137. let minX, minY, maxX, maxY, x, y, invSize;
  18138. 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
  18139. if (data.length > 80 * dim) {
  18140. minX = maxX = data[0];
  18141. minY = maxY = data[1];
  18142. for (let i = dim; i < outerLen; i += dim) {
  18143. x = data[i];
  18144. y = data[i + 1];
  18145. if (x < minX) minX = x;
  18146. if (y < minY) minY = y;
  18147. if (x > maxX) maxX = x;
  18148. if (y > maxY) maxY = y;
  18149. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  18150. invSize = Math.max(maxX - minX, maxY - minY);
  18151. invSize = invSize !== 0 ? 1 / invSize : 0;
  18152. }
  18153. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  18154. return triangles;
  18155. }
  18156. }; // create a circular doubly linked list from polygon points in the specified winding order
  18157. function linkedList(data, start, end, dim, clockwise) {
  18158. let i, last;
  18159. if (clockwise === signedArea(data, start, end, dim) > 0) {
  18160. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  18161. } else {
  18162. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  18163. }
  18164. if (last && equals(last, last.next)) {
  18165. removeNode(last);
  18166. last = last.next;
  18167. }
  18168. return last;
  18169. } // eliminate colinear or duplicate points
  18170. function filterPoints(start, end) {
  18171. if (!start) return start;
  18172. if (!end) end = start;
  18173. let p = start,
  18174. again;
  18175. do {
  18176. again = false;
  18177. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  18178. removeNode(p);
  18179. p = end = p.prev;
  18180. if (p === p.next) break;
  18181. again = true;
  18182. } else {
  18183. p = p.next;
  18184. }
  18185. } while (again || p !== end);
  18186. return end;
  18187. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  18188. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  18189. if (!ear) return; // interlink polygon nodes in z-order
  18190. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  18191. let stop = ear,
  18192. prev,
  18193. next; // iterate through ears, slicing them one by one
  18194. while (ear.prev !== ear.next) {
  18195. prev = ear.prev;
  18196. next = ear.next;
  18197. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  18198. // cut off the triangle
  18199. triangles.push(prev.i / dim);
  18200. triangles.push(ear.i / dim);
  18201. triangles.push(next.i / dim);
  18202. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  18203. ear = next.next;
  18204. stop = next.next;
  18205. continue;
  18206. }
  18207. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  18208. if (ear === stop) {
  18209. // try filtering points and slicing again
  18210. if (!pass) {
  18211. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  18212. } else if (pass === 1) {
  18213. ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
  18214. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  18215. } else if (pass === 2) {
  18216. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  18217. }
  18218. break;
  18219. }
  18220. }
  18221. } // check whether a polygon node forms a valid ear with adjacent nodes
  18222. function isEar(ear) {
  18223. const a = ear.prev,
  18224. b = ear,
  18225. c = ear.next;
  18226. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  18227. // now make sure we don't have other points inside the potential ear
  18228. let p = ear.next.next;
  18229. while (p !== ear.prev) {
  18230. 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;
  18231. p = p.next;
  18232. }
  18233. return true;
  18234. }
  18235. function isEarHashed(ear, minX, minY, invSize) {
  18236. const a = ear.prev,
  18237. b = ear,
  18238. c = ear.next;
  18239. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  18240. // triangle bbox; min & max are calculated like this for speed
  18241. const minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  18242. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  18243. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  18244. 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;
  18245. const minZ = zOrder(minTX, minTY, minX, minY, invSize),
  18246. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  18247. let p = ear.prevZ,
  18248. n = ear.nextZ; // look for points inside the triangle in both directions
  18249. while (p && p.z >= minZ && n && n.z <= maxZ) {
  18250. 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;
  18251. p = p.prevZ;
  18252. 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;
  18253. n = n.nextZ;
  18254. } // look for remaining points in decreasing z-order
  18255. while (p && p.z >= minZ) {
  18256. 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;
  18257. p = p.prevZ;
  18258. } // look for remaining points in increasing z-order
  18259. while (n && n.z <= maxZ) {
  18260. 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;
  18261. n = n.nextZ;
  18262. }
  18263. return true;
  18264. } // go through all polygon nodes and cure small local self-intersections
  18265. function cureLocalIntersections(start, triangles, dim) {
  18266. let p = start;
  18267. do {
  18268. const a = p.prev,
  18269. b = p.next.next;
  18270. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  18271. triangles.push(a.i / dim);
  18272. triangles.push(p.i / dim);
  18273. triangles.push(b.i / dim); // remove two nodes involved
  18274. removeNode(p);
  18275. removeNode(p.next);
  18276. p = start = b;
  18277. }
  18278. p = p.next;
  18279. } while (p !== start);
  18280. return filterPoints(p);
  18281. } // try splitting polygon into two and triangulate them independently
  18282. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  18283. // look for a valid diagonal that divides the polygon into two
  18284. let a = start;
  18285. do {
  18286. let b = a.next.next;
  18287. while (b !== a.prev) {
  18288. if (a.i !== b.i && isValidDiagonal(a, b)) {
  18289. // split the polygon in two by the diagonal
  18290. let c = splitPolygon(a, b); // filter colinear points around the cuts
  18291. a = filterPoints(a, a.next);
  18292. c = filterPoints(c, c.next); // run earcut on each half
  18293. earcutLinked(a, triangles, dim, minX, minY, invSize);
  18294. earcutLinked(c, triangles, dim, minX, minY, invSize);
  18295. return;
  18296. }
  18297. b = b.next;
  18298. }
  18299. a = a.next;
  18300. } while (a !== start);
  18301. } // link every hole into the outer loop, producing a single-ring polygon without holes
  18302. function eliminateHoles(data, holeIndices, outerNode, dim) {
  18303. const queue = [];
  18304. let i, len, start, end, list;
  18305. for (i = 0, len = holeIndices.length; i < len; i++) {
  18306. start = holeIndices[i] * dim;
  18307. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  18308. list = linkedList(data, start, end, dim, false);
  18309. if (list === list.next) list.steiner = true;
  18310. queue.push(getLeftmost(list));
  18311. }
  18312. queue.sort(compareX); // process holes from left to right
  18313. for (i = 0; i < queue.length; i++) {
  18314. eliminateHole(queue[i], outerNode);
  18315. outerNode = filterPoints(outerNode, outerNode.next);
  18316. }
  18317. return outerNode;
  18318. }
  18319. function compareX(a, b) {
  18320. return a.x - b.x;
  18321. } // find a bridge between vertices that connects hole with an outer ring and and link it
  18322. function eliminateHole(hole, outerNode) {
  18323. outerNode = findHoleBridge(hole, outerNode);
  18324. if (outerNode) {
  18325. const b = splitPolygon(outerNode, hole); // filter collinear points around the cuts
  18326. filterPoints(outerNode, outerNode.next);
  18327. filterPoints(b, b.next);
  18328. }
  18329. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  18330. function findHoleBridge(hole, outerNode) {
  18331. let p = outerNode;
  18332. const hx = hole.x;
  18333. const hy = hole.y;
  18334. let qx = -Infinity,
  18335. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  18336. // segment's endpoint with lesser x will be potential connection point
  18337. do {
  18338. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  18339. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  18340. if (x <= hx && x > qx) {
  18341. qx = x;
  18342. if (x === hx) {
  18343. if (hy === p.y) return p;
  18344. if (hy === p.next.y) return p.next;
  18345. }
  18346. m = p.x < p.next.x ? p : p.next;
  18347. }
  18348. }
  18349. p = p.next;
  18350. } while (p !== outerNode);
  18351. if (!m) return null;
  18352. if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint
  18353. // look for points inside the triangle of hole point, segment intersection and endpoint;
  18354. // if there are no points found, we have a valid connection;
  18355. // otherwise choose the point of the minimum angle with the ray as connection point
  18356. const stop = m,
  18357. mx = m.x,
  18358. my = m.y;
  18359. let tanMin = Infinity,
  18360. tan;
  18361. p = m;
  18362. do {
  18363. 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)) {
  18364. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  18365. if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) {
  18366. m = p;
  18367. tanMin = tan;
  18368. }
  18369. }
  18370. p = p.next;
  18371. } while (p !== stop);
  18372. return m;
  18373. } // whether sector in vertex m contains sector in vertex p in the same coordinates
  18374. function sectorContainsSector(m, p) {
  18375. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  18376. } // interlink polygon nodes in z-order
  18377. function indexCurve(start, minX, minY, invSize) {
  18378. let p = start;
  18379. do {
  18380. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  18381. p.prevZ = p.prev;
  18382. p.nextZ = p.next;
  18383. p = p.next;
  18384. } while (p !== start);
  18385. p.prevZ.nextZ = null;
  18386. p.prevZ = null;
  18387. sortLinked(p);
  18388. } // Simon Tatham's linked list merge sort algorithm
  18389. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  18390. function sortLinked(list) {
  18391. let i,
  18392. p,
  18393. q,
  18394. e,
  18395. tail,
  18396. numMerges,
  18397. pSize,
  18398. qSize,
  18399. inSize = 1;
  18400. do {
  18401. p = list;
  18402. list = null;
  18403. tail = null;
  18404. numMerges = 0;
  18405. while (p) {
  18406. numMerges++;
  18407. q = p;
  18408. pSize = 0;
  18409. for (i = 0; i < inSize; i++) {
  18410. pSize++;
  18411. q = q.nextZ;
  18412. if (!q) break;
  18413. }
  18414. qSize = inSize;
  18415. while (pSize > 0 || qSize > 0 && q) {
  18416. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  18417. e = p;
  18418. p = p.nextZ;
  18419. pSize--;
  18420. } else {
  18421. e = q;
  18422. q = q.nextZ;
  18423. qSize--;
  18424. }
  18425. if (tail) tail.nextZ = e;else list = e;
  18426. e.prevZ = tail;
  18427. tail = e;
  18428. }
  18429. p = q;
  18430. }
  18431. tail.nextZ = null;
  18432. inSize *= 2;
  18433. } while (numMerges > 1);
  18434. return list;
  18435. } // z-order of a point given coords and inverse of the longer side of data bbox
  18436. function zOrder(x, y, minX, minY, invSize) {
  18437. // coords are transformed into non-negative 15-bit integer range
  18438. x = 32767 * (x - minX) * invSize;
  18439. y = 32767 * (y - minY) * invSize;
  18440. x = (x | x << 8) & 0x00FF00FF;
  18441. x = (x | x << 4) & 0x0F0F0F0F;
  18442. x = (x | x << 2) & 0x33333333;
  18443. x = (x | x << 1) & 0x55555555;
  18444. y = (y | y << 8) & 0x00FF00FF;
  18445. y = (y | y << 4) & 0x0F0F0F0F;
  18446. y = (y | y << 2) & 0x33333333;
  18447. y = (y | y << 1) & 0x55555555;
  18448. return x | y << 1;
  18449. } // find the leftmost node of a polygon ring
  18450. function getLeftmost(start) {
  18451. let p = start,
  18452. leftmost = start;
  18453. do {
  18454. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  18455. p = p.next;
  18456. } while (p !== start);
  18457. return leftmost;
  18458. } // check if a point lies within a convex triangle
  18459. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  18460. 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;
  18461. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  18462. function isValidDiagonal(a, b) {
  18463. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && ( // dones't intersect other edges
  18464. locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && ( // locally visible
  18465. area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  18466. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  18467. } // signed area of a triangle
  18468. function area(p, q, r) {
  18469. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  18470. } // check if two points are equal
  18471. function equals(p1, p2) {
  18472. return p1.x === p2.x && p1.y === p2.y;
  18473. } // check if two segments intersect
  18474. function intersects(p1, q1, p2, q2) {
  18475. const o1 = sign(area(p1, q1, p2));
  18476. const o2 = sign(area(p1, q1, q2));
  18477. const o3 = sign(area(p2, q2, p1));
  18478. const o4 = sign(area(p2, q2, q1));
  18479. if (o1 !== o2 && o3 !== o4) return true; // general case
  18480. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  18481. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  18482. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  18483. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  18484. return false;
  18485. } // for collinear points p, q, r, check if point q lies on segment pr
  18486. function onSegment(p, q, r) {
  18487. return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y);
  18488. }
  18489. function sign(num) {
  18490. return num > 0 ? 1 : num < 0 ? -1 : 0;
  18491. } // check if a polygon diagonal intersects any polygon segments
  18492. function intersectsPolygon(a, b) {
  18493. let p = a;
  18494. do {
  18495. 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;
  18496. p = p.next;
  18497. } while (p !== a);
  18498. return false;
  18499. } // check if a polygon diagonal is locally inside the polygon
  18500. function locallyInside(a, b) {
  18501. 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;
  18502. } // check if the middle point of a polygon diagonal is inside the polygon
  18503. function middleInside(a, b) {
  18504. let p = a,
  18505. inside = false;
  18506. const px = (a.x + b.x) / 2,
  18507. py = (a.y + b.y) / 2;
  18508. do {
  18509. 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;
  18510. p = p.next;
  18511. } while (p !== a);
  18512. return inside;
  18513. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  18514. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  18515. function splitPolygon(a, b) {
  18516. const a2 = new Node(a.i, a.x, a.y),
  18517. b2 = new Node(b.i, b.x, b.y),
  18518. an = a.next,
  18519. bp = b.prev;
  18520. a.next = b;
  18521. b.prev = a;
  18522. a2.next = an;
  18523. an.prev = a2;
  18524. b2.next = a2;
  18525. a2.prev = b2;
  18526. bp.next = b2;
  18527. b2.prev = bp;
  18528. return b2;
  18529. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  18530. function insertNode(i, x, y, last) {
  18531. const p = new Node(i, x, y);
  18532. if (!last) {
  18533. p.prev = p;
  18534. p.next = p;
  18535. } else {
  18536. p.next = last.next;
  18537. p.prev = last;
  18538. last.next.prev = p;
  18539. last.next = p;
  18540. }
  18541. return p;
  18542. }
  18543. function removeNode(p) {
  18544. p.next.prev = p.prev;
  18545. p.prev.next = p.next;
  18546. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  18547. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  18548. }
  18549. function Node(i, x, y) {
  18550. // vertex index in coordinates array
  18551. this.i = i; // vertex coordinates
  18552. this.x = x;
  18553. this.y = y; // previous and next vertex nodes in a polygon ring
  18554. this.prev = null;
  18555. this.next = null; // z-order curve value
  18556. this.z = null; // previous and next nodes in z-order
  18557. this.prevZ = null;
  18558. this.nextZ = null; // indicates whether this is a steiner point
  18559. this.steiner = false;
  18560. }
  18561. function signedArea(data, start, end, dim) {
  18562. let sum = 0;
  18563. for (let i = start, j = end - dim; i < end; i += dim) {
  18564. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  18565. j = i;
  18566. }
  18567. return sum;
  18568. }
  18569. const ShapeUtils = {
  18570. // calculate area of the contour polygon
  18571. area: function (contour) {
  18572. const n = contour.length;
  18573. let a = 0.0;
  18574. for (let p = n - 1, q = 0; q < n; p = q++) {
  18575. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  18576. }
  18577. return a * 0.5;
  18578. },
  18579. isClockWise: function (pts) {
  18580. return ShapeUtils.area(pts) < 0;
  18581. },
  18582. triangulateShape: function (contour, holes) {
  18583. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  18584. const holeIndices = []; // array of hole indices
  18585. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  18586. removeDupEndPts(contour);
  18587. addContour(vertices, contour); //
  18588. let holeIndex = contour.length;
  18589. holes.forEach(removeDupEndPts);
  18590. for (let i = 0; i < holes.length; i++) {
  18591. holeIndices.push(holeIndex);
  18592. holeIndex += holes[i].length;
  18593. addContour(vertices, holes[i]);
  18594. } //
  18595. const triangles = Earcut.triangulate(vertices, holeIndices); //
  18596. for (let i = 0; i < triangles.length; i += 3) {
  18597. faces.push(triangles.slice(i, i + 3));
  18598. }
  18599. return faces;
  18600. }
  18601. };
  18602. exports.ShapeUtils = ShapeUtils;
  18603. function removeDupEndPts(points) {
  18604. const l = points.length;
  18605. if (l > 2 && points[l - 1].equals(points[0])) {
  18606. points.pop();
  18607. }
  18608. }
  18609. function addContour(vertices, contour) {
  18610. for (let i = 0; i < contour.length; i++) {
  18611. vertices.push(contour[i].x);
  18612. vertices.push(contour[i].y);
  18613. }
  18614. }
  18615. /**
  18616. * Creates extruded geometry from a path shape.
  18617. *
  18618. * parameters = {
  18619. *
  18620. * curveSegments: <int>, // number of points on the curves
  18621. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  18622. * depth: <float>, // Depth to extrude the shape
  18623. *
  18624. * bevelEnabled: <bool>, // turn on bevel
  18625. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18626. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  18627. * bevelOffset: <float>, // how far from shape outline does bevel start
  18628. * bevelSegments: <int>, // number of bevel layers
  18629. *
  18630. * extrudePath: <THREE.Curve> // curve to extrude shape along
  18631. *
  18632. * UVGenerator: <Object> // object that provides UV generator functions
  18633. *
  18634. * }
  18635. */
  18636. class ExtrudeBufferGeometry extends BufferGeometry {
  18637. constructor(shapes, options) {
  18638. super();
  18639. this.type = 'ExtrudeBufferGeometry';
  18640. this.parameters = {
  18641. shapes: shapes,
  18642. options: options
  18643. };
  18644. shapes = Array.isArray(shapes) ? shapes : [shapes];
  18645. const scope = this;
  18646. const verticesArray = [];
  18647. const uvArray = [];
  18648. for (let i = 0, l = shapes.length; i < l; i++) {
  18649. const shape = shapes[i];
  18650. addShape(shape);
  18651. } // build geometry
  18652. this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  18653. this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  18654. this.computeVertexNormals(); // functions
  18655. function addShape(shape) {
  18656. const placeholder = []; // options
  18657. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18658. const steps = options.steps !== undefined ? options.steps : 1;
  18659. let depth = options.depth !== undefined ? options.depth : 100;
  18660. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  18661. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  18662. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  18663. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  18664. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18665. const extrudePath = options.extrudePath;
  18666. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
  18667. if (options.amount !== undefined) {
  18668. console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
  18669. depth = options.amount;
  18670. } //
  18671. let extrudePts,
  18672. extrudeByPath = false;
  18673. let splineTube, binormal, normal, position2;
  18674. if (extrudePath) {
  18675. extrudePts = extrudePath.getSpacedPoints(steps);
  18676. extrudeByPath = true;
  18677. bevelEnabled = false; // bevels not supported for path extrusion
  18678. // SETUP TNB variables
  18679. // TODO1 - have a .isClosed in spline?
  18680. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18681. binormal = new Vector3();
  18682. normal = new Vector3();
  18683. position2 = new Vector3();
  18684. } // Safeguards if bevels are not enabled
  18685. if (!bevelEnabled) {
  18686. bevelSegments = 0;
  18687. bevelThickness = 0;
  18688. bevelSize = 0;
  18689. bevelOffset = 0;
  18690. } // Variables initialization
  18691. const shapePoints = shape.extractPoints(curveSegments);
  18692. let vertices = shapePoints.shape;
  18693. const holes = shapePoints.holes;
  18694. const reverse = !ShapeUtils.isClockWise(vertices);
  18695. if (reverse) {
  18696. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18697. for (let h = 0, hl = holes.length; h < hl; h++) {
  18698. const ahole = holes[h];
  18699. if (ShapeUtils.isClockWise(ahole)) {
  18700. holes[h] = ahole.reverse();
  18701. }
  18702. }
  18703. }
  18704. const faces = ShapeUtils.triangulateShape(vertices, holes);
  18705. /* Vertices */
  18706. const contour = vertices; // vertices has all points but contour has only points of circumference
  18707. for (let h = 0, hl = holes.length; h < hl; h++) {
  18708. const ahole = holes[h];
  18709. vertices = vertices.concat(ahole);
  18710. }
  18711. function scalePt2(pt, vec, size) {
  18712. if (!vec) console.error("THREE.ExtrudeGeometry: vec does not exist");
  18713. return vec.clone().multiplyScalar(size).add(pt);
  18714. }
  18715. const vlen = vertices.length,
  18716. flen = faces.length; // Find directions for point movement
  18717. function getBevelVec(inPt, inPrev, inNext) {
  18718. // computes for inPt the corresponding point inPt' on a new contour
  18719. // shifted by 1 unit (length of normalized vector) to the left
  18720. // if we walk along contour clockwise, this new contour is outside the old one
  18721. //
  18722. // inPt' is the intersection of the two lines parallel to the two
  18723. // adjacent edges of inPt at a distance of 1 unit on the left side.
  18724. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  18725. // good reading for geometry algorithms (here: line-line intersection)
  18726. // http://geomalgorithms.com/a05-_intersect-1.html
  18727. const v_prev_x = inPt.x - inPrev.x,
  18728. v_prev_y = inPt.y - inPrev.y;
  18729. const v_next_x = inNext.x - inPt.x,
  18730. v_next_y = inNext.y - inPt.y;
  18731. const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  18732. const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  18733. if (Math.abs(collinear0) > Number.EPSILON) {
  18734. // not collinear
  18735. // length of vectors for normalizing
  18736. const v_prev_len = Math.sqrt(v_prev_lensq);
  18737. const 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
  18738. const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  18739. const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  18740. const ptNextShift_x = inNext.x - v_next_y / v_next_len;
  18741. const ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  18742. const 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
  18743. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  18744. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  18745. // but prevent crazy spikes
  18746. const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  18747. if (v_trans_lensq <= 2) {
  18748. return new Vector2(v_trans_x, v_trans_y);
  18749. } else {
  18750. shrink_by = Math.sqrt(v_trans_lensq / 2);
  18751. }
  18752. } else {
  18753. // handle special case of collinear edges
  18754. let direction_eq = false; // assumes: opposite
  18755. if (v_prev_x > Number.EPSILON) {
  18756. if (v_next_x > Number.EPSILON) {
  18757. direction_eq = true;
  18758. }
  18759. } else {
  18760. if (v_prev_x < -Number.EPSILON) {
  18761. if (v_next_x < -Number.EPSILON) {
  18762. direction_eq = true;
  18763. }
  18764. } else {
  18765. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  18766. direction_eq = true;
  18767. }
  18768. }
  18769. }
  18770. if (direction_eq) {
  18771. // console.log("Warning: lines are a straight sequence");
  18772. v_trans_x = -v_prev_y;
  18773. v_trans_y = v_prev_x;
  18774. shrink_by = Math.sqrt(v_prev_lensq);
  18775. } else {
  18776. // console.log("Warning: lines are a straight spike");
  18777. v_trans_x = v_prev_x;
  18778. v_trans_y = v_prev_y;
  18779. shrink_by = Math.sqrt(v_prev_lensq / 2);
  18780. }
  18781. }
  18782. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  18783. }
  18784. const contourMovements = [];
  18785. for (let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  18786. if (j === il) j = 0;
  18787. if (k === il) k = 0; // (j)---(i)---(k)
  18788. // console.log('i,j,k', i, j , k)
  18789. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  18790. }
  18791. const holesMovements = [];
  18792. let oneHoleMovements,
  18793. verticesMovements = contourMovements.concat();
  18794. for (let h = 0, hl = holes.length; h < hl; h++) {
  18795. const ahole = holes[h];
  18796. oneHoleMovements = [];
  18797. for (let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  18798. if (j === il) j = 0;
  18799. if (k === il) k = 0; // (j)---(i)---(k)
  18800. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  18801. }
  18802. holesMovements.push(oneHoleMovements);
  18803. verticesMovements = verticesMovements.concat(oneHoleMovements);
  18804. } // Loop bevelSegments, 1 for the front, 1 for the back
  18805. for (let b = 0; b < bevelSegments; b++) {
  18806. //for ( b = bevelSegments; b > 0; b -- ) {
  18807. const t = b / bevelSegments;
  18808. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  18809. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  18810. for (let i = 0, il = contour.length; i < il; i++) {
  18811. const vert = scalePt2(contour[i], contourMovements[i], bs);
  18812. v(vert.x, vert.y, -z);
  18813. } // expand holes
  18814. for (let h = 0, hl = holes.length; h < hl; h++) {
  18815. const ahole = holes[h];
  18816. oneHoleMovements = holesMovements[h];
  18817. for (let i = 0, il = ahole.length; i < il; i++) {
  18818. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  18819. v(vert.x, vert.y, -z);
  18820. }
  18821. }
  18822. }
  18823. const bs = bevelSize + bevelOffset; // Back facing vertices
  18824. for (let i = 0; i < vlen; i++) {
  18825. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  18826. if (!extrudeByPath) {
  18827. v(vert.x, vert.y, 0);
  18828. } else {
  18829. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18830. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  18831. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  18832. position2.copy(extrudePts[0]).add(normal).add(binormal);
  18833. v(position2.x, position2.y, position2.z);
  18834. }
  18835. } // Add stepped vertices...
  18836. // Including front facing vertices
  18837. for (let s = 1; s <= steps; s++) {
  18838. for (let i = 0; i < vlen; i++) {
  18839. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  18840. if (!extrudeByPath) {
  18841. v(vert.x, vert.y, depth / steps * s);
  18842. } else {
  18843. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18844. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  18845. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  18846. position2.copy(extrudePts[s]).add(normal).add(binormal);
  18847. v(position2.x, position2.y, position2.z);
  18848. }
  18849. }
  18850. } // Add bevel segments planes
  18851. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18852. for (let b = bevelSegments - 1; b >= 0; b--) {
  18853. const t = b / bevelSegments;
  18854. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  18855. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  18856. for (let i = 0, il = contour.length; i < il; i++) {
  18857. const vert = scalePt2(contour[i], contourMovements[i], bs);
  18858. v(vert.x, vert.y, depth + z);
  18859. } // expand holes
  18860. for (let h = 0, hl = holes.length; h < hl; h++) {
  18861. const ahole = holes[h];
  18862. oneHoleMovements = holesMovements[h];
  18863. for (let i = 0, il = ahole.length; i < il; i++) {
  18864. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  18865. if (!extrudeByPath) {
  18866. v(vert.x, vert.y, depth + z);
  18867. } else {
  18868. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  18869. }
  18870. }
  18871. }
  18872. }
  18873. /* Faces */
  18874. // Top and bottom faces
  18875. buildLidFaces(); // Sides faces
  18876. buildSideFaces(); ///// Internal functions
  18877. function buildLidFaces() {
  18878. const start = verticesArray.length / 3;
  18879. if (bevelEnabled) {
  18880. let layer = 0; // steps + 1
  18881. let offset = vlen * layer; // Bottom faces
  18882. for (let i = 0; i < flen; i++) {
  18883. const face = faces[i];
  18884. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  18885. }
  18886. layer = steps + bevelSegments * 2;
  18887. offset = vlen * layer; // Top faces
  18888. for (let i = 0; i < flen; i++) {
  18889. const face = faces[i];
  18890. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  18891. }
  18892. } else {
  18893. // Bottom faces
  18894. for (let i = 0; i < flen; i++) {
  18895. const face = faces[i];
  18896. f3(face[2], face[1], face[0]);
  18897. } // Top faces
  18898. for (let i = 0; i < flen; i++) {
  18899. const face = faces[i];
  18900. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  18901. }
  18902. }
  18903. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  18904. } // Create faces for the z-sides of the shape
  18905. function buildSideFaces() {
  18906. const start = verticesArray.length / 3;
  18907. let layeroffset = 0;
  18908. sidewalls(contour, layeroffset);
  18909. layeroffset += contour.length;
  18910. for (let h = 0, hl = holes.length; h < hl; h++) {
  18911. const ahole = holes[h];
  18912. sidewalls(ahole, layeroffset); //, true
  18913. layeroffset += ahole.length;
  18914. }
  18915. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  18916. }
  18917. function sidewalls(contour, layeroffset) {
  18918. let i = contour.length;
  18919. while (--i >= 0) {
  18920. const j = i;
  18921. let k = i - 1;
  18922. if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  18923. for (let s = 0, sl = steps + bevelSegments * 2; s < sl; s++) {
  18924. const slen1 = vlen * s;
  18925. const slen2 = vlen * (s + 1);
  18926. const a = layeroffset + j + slen1,
  18927. b = layeroffset + k + slen1,
  18928. c = layeroffset + k + slen2,
  18929. d = layeroffset + j + slen2;
  18930. f4(a, b, c, d);
  18931. }
  18932. }
  18933. }
  18934. function v(x, y, z) {
  18935. placeholder.push(x);
  18936. placeholder.push(y);
  18937. placeholder.push(z);
  18938. }
  18939. function f3(a, b, c) {
  18940. addVertex(a);
  18941. addVertex(b);
  18942. addVertex(c);
  18943. const nextIndex = verticesArray.length / 3;
  18944. const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  18945. addUV(uvs[0]);
  18946. addUV(uvs[1]);
  18947. addUV(uvs[2]);
  18948. }
  18949. function f4(a, b, c, d) {
  18950. addVertex(a);
  18951. addVertex(b);
  18952. addVertex(d);
  18953. addVertex(b);
  18954. addVertex(c);
  18955. addVertex(d);
  18956. const nextIndex = verticesArray.length / 3;
  18957. const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  18958. addUV(uvs[0]);
  18959. addUV(uvs[1]);
  18960. addUV(uvs[3]);
  18961. addUV(uvs[1]);
  18962. addUV(uvs[2]);
  18963. addUV(uvs[3]);
  18964. }
  18965. function addVertex(index) {
  18966. verticesArray.push(placeholder[index * 3 + 0]);
  18967. verticesArray.push(placeholder[index * 3 + 1]);
  18968. verticesArray.push(placeholder[index * 3 + 2]);
  18969. }
  18970. function addUV(vector2) {
  18971. uvArray.push(vector2.x);
  18972. uvArray.push(vector2.y);
  18973. }
  18974. }
  18975. }
  18976. toJSON() {
  18977. const data = BufferGeometry.prototype.toJSON.call(this);
  18978. const shapes = this.parameters.shapes;
  18979. const options = this.parameters.options;
  18980. return toJSON(shapes, options, data);
  18981. }
  18982. }
  18983. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  18984. const WorldUVGenerator = {
  18985. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  18986. const a_x = vertices[indexA * 3];
  18987. const a_y = vertices[indexA * 3 + 1];
  18988. const b_x = vertices[indexB * 3];
  18989. const b_y = vertices[indexB * 3 + 1];
  18990. const c_x = vertices[indexC * 3];
  18991. const c_y = vertices[indexC * 3 + 1];
  18992. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  18993. },
  18994. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  18995. const a_x = vertices[indexA * 3];
  18996. const a_y = vertices[indexA * 3 + 1];
  18997. const a_z = vertices[indexA * 3 + 2];
  18998. const b_x = vertices[indexB * 3];
  18999. const b_y = vertices[indexB * 3 + 1];
  19000. const b_z = vertices[indexB * 3 + 2];
  19001. const c_x = vertices[indexC * 3];
  19002. const c_y = vertices[indexC * 3 + 1];
  19003. const c_z = vertices[indexC * 3 + 2];
  19004. const d_x = vertices[indexD * 3];
  19005. const d_y = vertices[indexD * 3 + 1];
  19006. const d_z = vertices[indexD * 3 + 2];
  19007. if (Math.abs(a_y - b_y) < 0.01) {
  19008. 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)];
  19009. } else {
  19010. 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)];
  19011. }
  19012. }
  19013. };
  19014. function toJSON(shapes, options, data) {
  19015. data.shapes = [];
  19016. if (Array.isArray(shapes)) {
  19017. for (let i = 0, l = shapes.length; i < l; i++) {
  19018. const shape = shapes[i];
  19019. data.shapes.push(shape.uuid);
  19020. }
  19021. } else {
  19022. data.shapes.push(shapes.uuid);
  19023. }
  19024. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  19025. return data;
  19026. }
  19027. /**
  19028. * Creates extruded geometry from a path shape.
  19029. *
  19030. * parameters = {
  19031. *
  19032. * curveSegments: <int>, // number of points on the curves
  19033. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  19034. * depth: <float>, // Depth to extrude the shape
  19035. *
  19036. * bevelEnabled: <bool>, // turn on bevel
  19037. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19038. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  19039. * bevelOffset: <float>, // how far from shape outline does bevel start
  19040. * bevelSegments: <int>, // number of bevel layers
  19041. *
  19042. * extrudePath: <THREE.Curve> // curve to extrude shape along
  19043. *
  19044. * UVGenerator: <Object> // object that provides UV generator functions
  19045. *
  19046. * }
  19047. */
  19048. class ExtrudeGeometry extends Geometry {
  19049. constructor(shapes, options) {
  19050. super();
  19051. this.type = 'ExtrudeGeometry';
  19052. this.parameters = {
  19053. shapes: shapes,
  19054. options: options
  19055. };
  19056. this.fromBufferGeometry(new ExtrudeBufferGeometry(shapes, options));
  19057. this.mergeVertices();
  19058. }
  19059. toJSON() {
  19060. const data = super.toJSON();
  19061. const shapes = this.parameters.shapes;
  19062. const options = this.parameters.options;
  19063. return toJSON$1(shapes, options, data);
  19064. }
  19065. }
  19066. exports.ExtrudeGeometry = ExtrudeGeometry;
  19067. function toJSON$1(shapes, options, data) {
  19068. data.shapes = [];
  19069. if (Array.isArray(shapes)) {
  19070. for (let i = 0, l = shapes.length; i < l; i++) {
  19071. const shape = shapes[i];
  19072. data.shapes.push(shape.uuid);
  19073. }
  19074. } else {
  19075. data.shapes.push(shapes.uuid);
  19076. }
  19077. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  19078. return data;
  19079. }
  19080. class IcosahedronBufferGeometry extends PolyhedronBufferGeometry {
  19081. constructor(radius = 1, detail = 0) {
  19082. const t = (1 + Math.sqrt(5)) / 2;
  19083. const 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];
  19084. const 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];
  19085. super(vertices, indices, radius, detail);
  19086. this.type = 'IcosahedronBufferGeometry';
  19087. this.parameters = {
  19088. radius: radius,
  19089. detail: detail
  19090. };
  19091. }
  19092. }
  19093. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  19094. class IcosahedronGeometry extends Geometry {
  19095. constructor(radius, detail) {
  19096. super();
  19097. this.type = 'IcosahedronGeometry';
  19098. this.parameters = {
  19099. radius: radius,
  19100. detail: detail
  19101. };
  19102. this.fromBufferGeometry(new IcosahedronBufferGeometry(radius, detail));
  19103. this.mergeVertices();
  19104. }
  19105. }
  19106. exports.IcosahedronGeometry = IcosahedronGeometry;
  19107. class LatheBufferGeometry extends BufferGeometry {
  19108. constructor(points, segments = 12, phiStart = 0, phiLength = Math.PI * 2) {
  19109. super();
  19110. this.type = 'LatheBufferGeometry';
  19111. this.parameters = {
  19112. points: points,
  19113. segments: segments,
  19114. phiStart: phiStart,
  19115. phiLength: phiLength
  19116. };
  19117. segments = Math.floor(segments); // clamp phiLength so it's in range of [ 0, 2PI ]
  19118. phiLength = MathUtils.clamp(phiLength, 0, Math.PI * 2); // buffers
  19119. const indices = [];
  19120. const vertices = [];
  19121. const uvs = []; // helper variables
  19122. const inverseSegments = 1.0 / segments;
  19123. const vertex = new Vector3();
  19124. const uv = new Vector2(); // generate vertices and uvs
  19125. for (let i = 0; i <= segments; i++) {
  19126. const phi = phiStart + i * inverseSegments * phiLength;
  19127. const sin = Math.sin(phi);
  19128. const cos = Math.cos(phi);
  19129. for (let j = 0; j <= points.length - 1; j++) {
  19130. // vertex
  19131. vertex.x = points[j].x * sin;
  19132. vertex.y = points[j].y;
  19133. vertex.z = points[j].x * cos;
  19134. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  19135. uv.x = i / segments;
  19136. uv.y = j / (points.length - 1);
  19137. uvs.push(uv.x, uv.y);
  19138. }
  19139. } // indices
  19140. for (let i = 0; i < segments; i++) {
  19141. for (let j = 0; j < points.length - 1; j++) {
  19142. const base = j + i * points.length;
  19143. const a = base;
  19144. const b = base + points.length;
  19145. const c = base + points.length + 1;
  19146. const d = base + 1; // faces
  19147. indices.push(a, b, d);
  19148. indices.push(b, c, d);
  19149. }
  19150. } // build geometry
  19151. this.setIndex(indices);
  19152. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19153. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // generate normals
  19154. this.computeVertexNormals(); // if the geometry is closed, we need to average the normals along the seam.
  19155. // because the corresponding vertices are identical (but still have different UVs).
  19156. if (phiLength === Math.PI * 2) {
  19157. const normals = this.attributes.normal.array;
  19158. const n1 = new Vector3();
  19159. const n2 = new Vector3();
  19160. const n = new Vector3(); // this is the buffer offset for the last line of vertices
  19161. const base = segments * points.length * 3;
  19162. for (let i = 0, j = 0; i < points.length; i++, j += 3) {
  19163. // select the normal of the vertex in the first line
  19164. n1.x = normals[j + 0];
  19165. n1.y = normals[j + 1];
  19166. n1.z = normals[j + 2]; // select the normal of the vertex in the last line
  19167. n2.x = normals[base + j + 0];
  19168. n2.y = normals[base + j + 1];
  19169. n2.z = normals[base + j + 2]; // average normals
  19170. n.addVectors(n1, n2).normalize(); // assign the new values to both normals
  19171. normals[j + 0] = normals[base + j + 0] = n.x;
  19172. normals[j + 1] = normals[base + j + 1] = n.y;
  19173. normals[j + 2] = normals[base + j + 2] = n.z;
  19174. }
  19175. }
  19176. }
  19177. }
  19178. exports.LatheBufferGeometry = LatheBufferGeometry;
  19179. class LatheGeometry extends Geometry {
  19180. constructor(points, segments, phiStart, phiLength) {
  19181. super();
  19182. this.type = 'LatheGeometry';
  19183. this.parameters = {
  19184. points: points,
  19185. segments: segments,
  19186. phiStart: phiStart,
  19187. phiLength: phiLength
  19188. };
  19189. this.fromBufferGeometry(new LatheBufferGeometry(points, segments, phiStart, phiLength));
  19190. this.mergeVertices();
  19191. }
  19192. }
  19193. exports.LatheGeometry = LatheGeometry;
  19194. class OctahedronBufferGeometry extends PolyhedronBufferGeometry {
  19195. constructor(radius = 1, detail = 0) {
  19196. const vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  19197. const 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];
  19198. super(vertices, indices, radius, detail);
  19199. this.type = 'OctahedronBufferGeometry';
  19200. this.parameters = {
  19201. radius: radius,
  19202. detail: detail
  19203. };
  19204. }
  19205. }
  19206. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  19207. class OctahedronGeometry extends Geometry {
  19208. constructor(radius, detail) {
  19209. super();
  19210. this.type = 'OctahedronGeometry';
  19211. this.parameters = {
  19212. radius: radius,
  19213. detail: detail
  19214. };
  19215. this.fromBufferGeometry(new OctahedronBufferGeometry(radius, detail));
  19216. this.mergeVertices();
  19217. }
  19218. }
  19219. /**
  19220. * Parametric Surfaces Geometry
  19221. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  19222. */
  19223. exports.OctahedronGeometry = OctahedronGeometry;
  19224. function ParametricBufferGeometry(func, slices, stacks) {
  19225. BufferGeometry.call(this);
  19226. this.type = 'ParametricBufferGeometry';
  19227. this.parameters = {
  19228. func: func,
  19229. slices: slices,
  19230. stacks: stacks
  19231. }; // buffers
  19232. const indices = [];
  19233. const vertices = [];
  19234. const normals = [];
  19235. const uvs = [];
  19236. const EPS = 0.00001;
  19237. const normal = new Vector3();
  19238. const p0 = new Vector3(),
  19239. p1 = new Vector3();
  19240. const pu = new Vector3(),
  19241. pv = new Vector3();
  19242. if (func.length < 3) {
  19243. console.error('THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.');
  19244. } // generate vertices, normals and uvs
  19245. const sliceCount = slices + 1;
  19246. for (let i = 0; i <= stacks; i++) {
  19247. const v = i / stacks;
  19248. for (let j = 0; j <= slices; j++) {
  19249. const u = j / slices; // vertex
  19250. func(u, v, p0);
  19251. vertices.push(p0.x, p0.y, p0.z); // normal
  19252. // approximate tangent vectors via finite differences
  19253. if (u - EPS >= 0) {
  19254. func(u - EPS, v, p1);
  19255. pu.subVectors(p0, p1);
  19256. } else {
  19257. func(u + EPS, v, p1);
  19258. pu.subVectors(p1, p0);
  19259. }
  19260. if (v - EPS >= 0) {
  19261. func(u, v - EPS, p1);
  19262. pv.subVectors(p0, p1);
  19263. } else {
  19264. func(u, v + EPS, p1);
  19265. pv.subVectors(p1, p0);
  19266. } // cross product of tangent vectors returns surface normal
  19267. normal.crossVectors(pu, pv).normalize();
  19268. normals.push(normal.x, normal.y, normal.z); // uv
  19269. uvs.push(u, v);
  19270. }
  19271. } // generate indices
  19272. for (let i = 0; i < stacks; i++) {
  19273. for (let j = 0; j < slices; j++) {
  19274. const a = i * sliceCount + j;
  19275. const b = i * sliceCount + j + 1;
  19276. const c = (i + 1) * sliceCount + j + 1;
  19277. const d = (i + 1) * sliceCount + j; // faces one and two
  19278. indices.push(a, b, d);
  19279. indices.push(b, c, d);
  19280. }
  19281. } // build geometry
  19282. this.setIndex(indices);
  19283. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19284. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19285. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19286. }
  19287. ParametricBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19288. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  19289. /**
  19290. * Parametric Surfaces Geometry
  19291. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  19292. */
  19293. function ParametricGeometry(func, slices, stacks) {
  19294. Geometry.call(this);
  19295. this.type = 'ParametricGeometry';
  19296. this.parameters = {
  19297. func: func,
  19298. slices: slices,
  19299. stacks: stacks
  19300. };
  19301. this.fromBufferGeometry(new ParametricBufferGeometry(func, slices, stacks));
  19302. this.mergeVertices();
  19303. }
  19304. ParametricGeometry.prototype = Object.create(Geometry.prototype);
  19305. ParametricGeometry.prototype.constructor = ParametricGeometry;
  19306. class PlaneGeometry extends Geometry {
  19307. constructor(width, height, widthSegments, heightSegments) {
  19308. super();
  19309. this.type = 'PlaneGeometry';
  19310. this.parameters = {
  19311. width: width,
  19312. height: height,
  19313. widthSegments: widthSegments,
  19314. heightSegments: heightSegments
  19315. };
  19316. this.fromBufferGeometry(new PlaneBufferGeometry(width, height, widthSegments, heightSegments));
  19317. this.mergeVertices();
  19318. }
  19319. }
  19320. exports.PlaneGeometry = PlaneGeometry;
  19321. class PolyhedronGeometry extends Geometry {
  19322. constructor(vertices, indices, radius, detail) {
  19323. super();
  19324. this.type = 'PolyhedronGeometry';
  19325. this.parameters = {
  19326. vertices: vertices,
  19327. indices: indices,
  19328. radius: radius,
  19329. detail: detail
  19330. };
  19331. this.fromBufferGeometry(new PolyhedronBufferGeometry(vertices, indices, radius, detail));
  19332. this.mergeVertices();
  19333. }
  19334. }
  19335. exports.PolyhedronGeometry = PolyhedronGeometry;
  19336. class RingBufferGeometry extends BufferGeometry {
  19337. constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) {
  19338. super();
  19339. this.type = 'RingBufferGeometry';
  19340. this.parameters = {
  19341. innerRadius: innerRadius,
  19342. outerRadius: outerRadius,
  19343. thetaSegments: thetaSegments,
  19344. phiSegments: phiSegments,
  19345. thetaStart: thetaStart,
  19346. thetaLength: thetaLength
  19347. };
  19348. thetaSegments = Math.max(3, thetaSegments);
  19349. phiSegments = Math.max(1, phiSegments); // buffers
  19350. const indices = [];
  19351. const vertices = [];
  19352. const normals = [];
  19353. const uvs = []; // some helper variables
  19354. let radius = innerRadius;
  19355. const radiusStep = (outerRadius - innerRadius) / phiSegments;
  19356. const vertex = new Vector3();
  19357. const uv = new Vector2(); // generate vertices, normals and uvs
  19358. for (let j = 0; j <= phiSegments; j++) {
  19359. for (let i = 0; i <= thetaSegments; i++) {
  19360. // values are generate from the inside of the ring to the outside
  19361. const segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  19362. vertex.x = radius * Math.cos(segment);
  19363. vertex.y = radius * Math.sin(segment);
  19364. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19365. normals.push(0, 0, 1); // uv
  19366. uv.x = (vertex.x / outerRadius + 1) / 2;
  19367. uv.y = (vertex.y / outerRadius + 1) / 2;
  19368. uvs.push(uv.x, uv.y);
  19369. } // increase the radius for next row of vertices
  19370. radius += radiusStep;
  19371. } // indices
  19372. for (let j = 0; j < phiSegments; j++) {
  19373. const thetaSegmentLevel = j * (thetaSegments + 1);
  19374. for (let i = 0; i < thetaSegments; i++) {
  19375. const segment = i + thetaSegmentLevel;
  19376. const a = segment;
  19377. const b = segment + thetaSegments + 1;
  19378. const c = segment + thetaSegments + 2;
  19379. const d = segment + 1; // faces
  19380. indices.push(a, b, d);
  19381. indices.push(b, c, d);
  19382. }
  19383. } // build geometry
  19384. this.setIndex(indices);
  19385. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19386. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19387. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19388. }
  19389. }
  19390. exports.RingBufferGeometry = RingBufferGeometry;
  19391. class RingGeometry extends Geometry {
  19392. constructor(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
  19393. super();
  19394. this.type = 'RingGeometry';
  19395. this.parameters = {
  19396. innerRadius: innerRadius,
  19397. outerRadius: outerRadius,
  19398. thetaSegments: thetaSegments,
  19399. phiSegments: phiSegments,
  19400. thetaStart: thetaStart,
  19401. thetaLength: thetaLength
  19402. };
  19403. this.fromBufferGeometry(new RingBufferGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength));
  19404. this.mergeVertices();
  19405. }
  19406. }
  19407. exports.RingGeometry = RingGeometry;
  19408. class ShapeBufferGeometry extends BufferGeometry {
  19409. constructor(shapes, curveSegments = 12) {
  19410. super();
  19411. this.type = 'ShapeBufferGeometry';
  19412. this.parameters = {
  19413. shapes: shapes,
  19414. curveSegments: curveSegments
  19415. }; // buffers
  19416. const indices = [];
  19417. const vertices = [];
  19418. const normals = [];
  19419. const uvs = []; // helper variables
  19420. let groupStart = 0;
  19421. let groupCount = 0; // allow single and array values for "shapes" parameter
  19422. if (Array.isArray(shapes) === false) {
  19423. addShape(shapes);
  19424. } else {
  19425. for (let i = 0; i < shapes.length; i++) {
  19426. addShape(shapes[i]);
  19427. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  19428. groupStart += groupCount;
  19429. groupCount = 0;
  19430. }
  19431. } // build geometry
  19432. this.setIndex(indices);
  19433. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19434. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19435. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  19436. function addShape(shape) {
  19437. const indexOffset = vertices.length / 3;
  19438. const points = shape.extractPoints(curveSegments);
  19439. let shapeVertices = points.shape;
  19440. const shapeHoles = points.holes; // check direction of vertices
  19441. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  19442. shapeVertices = shapeVertices.reverse();
  19443. }
  19444. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  19445. const shapeHole = shapeHoles[i];
  19446. if (ShapeUtils.isClockWise(shapeHole) === true) {
  19447. shapeHoles[i] = shapeHole.reverse();
  19448. }
  19449. }
  19450. const faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  19451. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  19452. const shapeHole = shapeHoles[i];
  19453. shapeVertices = shapeVertices.concat(shapeHole);
  19454. } // vertices, normals, uvs
  19455. for (let i = 0, l = shapeVertices.length; i < l; i++) {
  19456. const vertex = shapeVertices[i];
  19457. vertices.push(vertex.x, vertex.y, 0);
  19458. normals.push(0, 0, 1);
  19459. uvs.push(vertex.x, vertex.y); // world uvs
  19460. } // incides
  19461. for (let i = 0, l = faces.length; i < l; i++) {
  19462. const face = faces[i];
  19463. const a = face[0] + indexOffset;
  19464. const b = face[1] + indexOffset;
  19465. const c = face[2] + indexOffset;
  19466. indices.push(a, b, c);
  19467. groupCount += 3;
  19468. }
  19469. }
  19470. }
  19471. toJSON() {
  19472. const data = BufferGeometry.prototype.toJSON.call(this);
  19473. const shapes = this.parameters.shapes;
  19474. return toJSON$2(shapes, data);
  19475. }
  19476. }
  19477. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  19478. function toJSON$2(shapes, data) {
  19479. data.shapes = [];
  19480. if (Array.isArray(shapes)) {
  19481. for (let i = 0, l = shapes.length; i < l; i++) {
  19482. const shape = shapes[i];
  19483. data.shapes.push(shape.uuid);
  19484. }
  19485. } else {
  19486. data.shapes.push(shapes.uuid);
  19487. }
  19488. return data;
  19489. }
  19490. class ShapeGeometry extends Geometry {
  19491. constructor(shapes, curveSegments) {
  19492. super();
  19493. this.type = 'ShapeGeometry';
  19494. if (typeof curveSegments === 'object') {
  19495. console.warn('THREE.ShapeGeometry: Options parameter has been removed.');
  19496. curveSegments = curveSegments.curveSegments;
  19497. }
  19498. this.parameters = {
  19499. shapes: shapes,
  19500. curveSegments: curveSegments
  19501. };
  19502. this.fromBufferGeometry(new ShapeBufferGeometry(shapes, curveSegments));
  19503. this.mergeVertices();
  19504. }
  19505. toJSON() {
  19506. const data = Geometry.prototype.toJSON.call(this);
  19507. const shapes = this.parameters.shapes;
  19508. return toJSON$3(shapes, data);
  19509. }
  19510. }
  19511. exports.ShapeGeometry = ShapeGeometry;
  19512. function toJSON$3(shapes, data) {
  19513. data.shapes = [];
  19514. if (Array.isArray(shapes)) {
  19515. for (let i = 0, l = shapes.length; i < l; i++) {
  19516. const shape = shapes[i];
  19517. data.shapes.push(shape.uuid);
  19518. }
  19519. } else {
  19520. data.shapes.push(shapes.uuid);
  19521. }
  19522. return data;
  19523. }
  19524. class SphereBufferGeometry extends BufferGeometry {
  19525. constructor(radius = 1, widthSegments = 8, heightSegments = 6, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) {
  19526. super();
  19527. this.type = 'SphereBufferGeometry';
  19528. this.parameters = {
  19529. radius: radius,
  19530. widthSegments: widthSegments,
  19531. heightSegments: heightSegments,
  19532. phiStart: phiStart,
  19533. phiLength: phiLength,
  19534. thetaStart: thetaStart,
  19535. thetaLength: thetaLength
  19536. };
  19537. widthSegments = Math.max(3, Math.floor(widthSegments));
  19538. heightSegments = Math.max(2, Math.floor(heightSegments));
  19539. const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  19540. let index = 0;
  19541. const grid = [];
  19542. const vertex = new Vector3();
  19543. const normal = new Vector3(); // buffers
  19544. const indices = [];
  19545. const vertices = [];
  19546. const normals = [];
  19547. const uvs = []; // generate vertices, normals and uvs
  19548. for (let iy = 0; iy <= heightSegments; iy++) {
  19549. const verticesRow = [];
  19550. const v = iy / heightSegments; // special case for the poles
  19551. let uOffset = 0;
  19552. if (iy == 0 && thetaStart == 0) {
  19553. uOffset = 0.5 / widthSegments;
  19554. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  19555. uOffset = -0.5 / widthSegments;
  19556. }
  19557. for (let ix = 0; ix <= widthSegments; ix++) {
  19558. const u = ix / widthSegments; // vertex
  19559. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  19560. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  19561. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  19562. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19563. normal.copy(vertex).normalize();
  19564. normals.push(normal.x, normal.y, normal.z); // uv
  19565. uvs.push(u + uOffset, 1 - v);
  19566. verticesRow.push(index++);
  19567. }
  19568. grid.push(verticesRow);
  19569. } // indices
  19570. for (let iy = 0; iy < heightSegments; iy++) {
  19571. for (let ix = 0; ix < widthSegments; ix++) {
  19572. const a = grid[iy][ix + 1];
  19573. const b = grid[iy][ix];
  19574. const c = grid[iy + 1][ix];
  19575. const d = grid[iy + 1][ix + 1];
  19576. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  19577. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  19578. }
  19579. } // build geometry
  19580. this.setIndex(indices);
  19581. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19582. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19583. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19584. }
  19585. }
  19586. exports.SphereBufferGeometry = SphereBufferGeometry;
  19587. class SphereGeometry extends Geometry {
  19588. constructor(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
  19589. super();
  19590. this.type = 'SphereGeometry';
  19591. this.parameters = {
  19592. radius: radius,
  19593. widthSegments: widthSegments,
  19594. heightSegments: heightSegments,
  19595. phiStart: phiStart,
  19596. phiLength: phiLength,
  19597. thetaStart: thetaStart,
  19598. thetaLength: thetaLength
  19599. };
  19600. this.fromBufferGeometry(new SphereBufferGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength));
  19601. this.mergeVertices();
  19602. }
  19603. }
  19604. exports.SphereGeometry = SphereGeometry;
  19605. class TetrahedronBufferGeometry extends PolyhedronBufferGeometry {
  19606. constructor(radius = 1, detail = 0) {
  19607. const vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  19608. const indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  19609. super(vertices, indices, radius, detail);
  19610. this.type = 'TetrahedronBufferGeometry';
  19611. this.parameters = {
  19612. radius: radius,
  19613. detail: detail
  19614. };
  19615. }
  19616. }
  19617. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  19618. class TetrahedronGeometry extends Geometry {
  19619. constructor(radius, detail) {
  19620. super();
  19621. this.type = 'TetrahedronGeometry';
  19622. this.parameters = {
  19623. radius: radius,
  19624. detail: detail
  19625. };
  19626. this.fromBufferGeometry(new TetrahedronBufferGeometry(radius, detail));
  19627. this.mergeVertices();
  19628. }
  19629. }
  19630. /**
  19631. * Text = 3D Text
  19632. *
  19633. * parameters = {
  19634. * font: <THREE.Font>, // font
  19635. *
  19636. * size: <float>, // size of the text
  19637. * height: <float>, // thickness to extrude text
  19638. * curveSegments: <int>, // number of points on the curves
  19639. *
  19640. * bevelEnabled: <bool>, // turn on bevel
  19641. * bevelThickness: <float>, // how deep into text bevel goes
  19642. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  19643. * bevelOffset: <float> // how far from text outline does bevel start
  19644. * }
  19645. */
  19646. exports.TetrahedronGeometry = TetrahedronGeometry;
  19647. class TextBufferGeometry extends ExtrudeBufferGeometry {
  19648. constructor(text, parameters = {}) {
  19649. const font = parameters.font;
  19650. if (!(font && font.isFont)) {
  19651. console.error('THREE.TextGeometry: font parameter is not an instance of THREE.Font.');
  19652. return new BufferGeometry();
  19653. }
  19654. const shapes = font.generateShapes(text, parameters.size); // translate parameters to ExtrudeGeometry API
  19655. parameters.depth = parameters.height !== undefined ? parameters.height : 50; // defaults
  19656. if (parameters.bevelThickness === undefined) parameters.bevelThickness = 10;
  19657. if (parameters.bevelSize === undefined) parameters.bevelSize = 8;
  19658. if (parameters.bevelEnabled === undefined) parameters.bevelEnabled = false;
  19659. super(shapes, parameters);
  19660. this.type = 'TextBufferGeometry';
  19661. }
  19662. }
  19663. /**
  19664. * Text = 3D Text
  19665. *
  19666. * parameters = {
  19667. * font: <THREE.Font>, // font
  19668. *
  19669. * size: <float>, // size of the text
  19670. * height: <float>, // thickness to extrude text
  19671. * curveSegments: <int>, // number of points on the curves
  19672. *
  19673. * bevelEnabled: <bool>, // turn on bevel
  19674. * bevelThickness: <float>, // how deep into text bevel goes
  19675. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  19676. * bevelOffset: <float> // how far from text outline does bevel start
  19677. * }
  19678. */
  19679. exports.TextBufferGeometry = TextBufferGeometry;
  19680. class TextGeometry extends Geometry {
  19681. constructor(text, parameters) {
  19682. super();
  19683. this.type = 'TextGeometry';
  19684. this.parameters = {
  19685. text: text,
  19686. parameters: parameters
  19687. };
  19688. this.fromBufferGeometry(new TextBufferGeometry(text, parameters));
  19689. this.mergeVertices();
  19690. }
  19691. }
  19692. exports.TextGeometry = TextGeometry;
  19693. class TorusBufferGeometry extends BufferGeometry {
  19694. constructor(radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2) {
  19695. super();
  19696. this.type = 'TorusBufferGeometry';
  19697. this.parameters = {
  19698. radius: radius,
  19699. tube: tube,
  19700. radialSegments: radialSegments,
  19701. tubularSegments: tubularSegments,
  19702. arc: arc
  19703. };
  19704. radialSegments = Math.floor(radialSegments);
  19705. tubularSegments = Math.floor(tubularSegments); // buffers
  19706. const indices = [];
  19707. const vertices = [];
  19708. const normals = [];
  19709. const uvs = []; // helper variables
  19710. const center = new Vector3();
  19711. const vertex = new Vector3();
  19712. const normal = new Vector3(); // generate vertices, normals and uvs
  19713. for (let j = 0; j <= radialSegments; j++) {
  19714. for (let i = 0; i <= tubularSegments; i++) {
  19715. const u = i / tubularSegments * arc;
  19716. const v = j / radialSegments * Math.PI * 2; // vertex
  19717. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  19718. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  19719. vertex.z = tube * Math.sin(v);
  19720. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19721. center.x = radius * Math.cos(u);
  19722. center.y = radius * Math.sin(u);
  19723. normal.subVectors(vertex, center).normalize();
  19724. normals.push(normal.x, normal.y, normal.z); // uv
  19725. uvs.push(i / tubularSegments);
  19726. uvs.push(j / radialSegments);
  19727. }
  19728. } // generate indices
  19729. for (let j = 1; j <= radialSegments; j++) {
  19730. for (let i = 1; i <= tubularSegments; i++) {
  19731. // indices
  19732. const a = (tubularSegments + 1) * j + i - 1;
  19733. const b = (tubularSegments + 1) * (j - 1) + i - 1;
  19734. const c = (tubularSegments + 1) * (j - 1) + i;
  19735. const d = (tubularSegments + 1) * j + i; // faces
  19736. indices.push(a, b, d);
  19737. indices.push(b, c, d);
  19738. }
  19739. } // build geometry
  19740. this.setIndex(indices);
  19741. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19742. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19743. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19744. }
  19745. }
  19746. exports.TorusBufferGeometry = TorusBufferGeometry;
  19747. class TorusGeometry extends Geometry {
  19748. constructor(radius, tube, radialSegments, tubularSegments, arc) {
  19749. super();
  19750. this.type = 'TorusGeometry';
  19751. this.parameters = {
  19752. radius: radius,
  19753. tube: tube,
  19754. radialSegments: radialSegments,
  19755. tubularSegments: tubularSegments,
  19756. arc: arc
  19757. };
  19758. this.fromBufferGeometry(new TorusBufferGeometry(radius, tube, radialSegments, tubularSegments, arc));
  19759. this.mergeVertices();
  19760. }
  19761. }
  19762. exports.TorusGeometry = TorusGeometry;
  19763. class TorusKnotBufferGeometry extends BufferGeometry {
  19764. constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3) {
  19765. super();
  19766. this.type = 'TorusKnotBufferGeometry';
  19767. this.parameters = {
  19768. radius: radius,
  19769. tube: tube,
  19770. tubularSegments: tubularSegments,
  19771. radialSegments: radialSegments,
  19772. p: p,
  19773. q: q
  19774. };
  19775. tubularSegments = Math.floor(tubularSegments);
  19776. radialSegments = Math.floor(radialSegments); // buffers
  19777. const indices = [];
  19778. const vertices = [];
  19779. const normals = [];
  19780. const uvs = []; // helper variables
  19781. const vertex = new Vector3();
  19782. const normal = new Vector3();
  19783. const P1 = new Vector3();
  19784. const P2 = new Vector3();
  19785. const B = new Vector3();
  19786. const T = new Vector3();
  19787. const N = new Vector3(); // generate vertices, normals and uvs
  19788. for (let i = 0; i <= tubularSegments; ++i) {
  19789. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  19790. const 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.
  19791. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  19792. calculatePositionOnCurve(u, p, q, radius, P1);
  19793. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  19794. T.subVectors(P2, P1);
  19795. N.addVectors(P2, P1);
  19796. B.crossVectors(T, N);
  19797. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  19798. B.normalize();
  19799. N.normalize();
  19800. for (let j = 0; j <= radialSegments; ++j) {
  19801. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  19802. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  19803. const v = j / radialSegments * Math.PI * 2;
  19804. const cx = -tube * Math.cos(v);
  19805. const cy = tube * Math.sin(v); // now calculate the final vertex position.
  19806. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  19807. vertex.x = P1.x + (cx * N.x + cy * B.x);
  19808. vertex.y = P1.y + (cx * N.y + cy * B.y);
  19809. vertex.z = P1.z + (cx * N.z + cy * B.z);
  19810. 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)
  19811. normal.subVectors(vertex, P1).normalize();
  19812. normals.push(normal.x, normal.y, normal.z); // uv
  19813. uvs.push(i / tubularSegments);
  19814. uvs.push(j / radialSegments);
  19815. }
  19816. } // generate indices
  19817. for (let j = 1; j <= tubularSegments; j++) {
  19818. for (let i = 1; i <= radialSegments; i++) {
  19819. // indices
  19820. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  19821. const b = (radialSegments + 1) * j + (i - 1);
  19822. const c = (radialSegments + 1) * j + i;
  19823. const d = (radialSegments + 1) * (j - 1) + i; // faces
  19824. indices.push(a, b, d);
  19825. indices.push(b, c, d);
  19826. }
  19827. } // build geometry
  19828. this.setIndex(indices);
  19829. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19830. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19831. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  19832. function calculatePositionOnCurve(u, p, q, radius, position) {
  19833. const cu = Math.cos(u);
  19834. const su = Math.sin(u);
  19835. const quOverP = q / p * u;
  19836. const cs = Math.cos(quOverP);
  19837. position.x = radius * (2 + cs) * 0.5 * cu;
  19838. position.y = radius * (2 + cs) * su * 0.5;
  19839. position.z = radius * Math.sin(quOverP) * 0.5;
  19840. }
  19841. }
  19842. }
  19843. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  19844. class TorusKnotGeometry extends Geometry {
  19845. constructor(radius, tube, tubularSegments, radialSegments, p, q, heightScale) {
  19846. super();
  19847. this.type = 'TorusKnotGeometry';
  19848. this.parameters = {
  19849. radius: radius,
  19850. tube: tube,
  19851. tubularSegments: tubularSegments,
  19852. radialSegments: radialSegments,
  19853. p: p,
  19854. q: q
  19855. };
  19856. if (heightScale !== undefined) console.warn('THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.');
  19857. this.fromBufferGeometry(new TorusKnotBufferGeometry(radius, tube, tubularSegments, radialSegments, p, q));
  19858. this.mergeVertices();
  19859. }
  19860. }
  19861. exports.TorusKnotGeometry = TorusKnotGeometry;
  19862. class TubeBufferGeometry extends BufferGeometry {
  19863. constructor(path, tubularSegments = 64, radius = 1, radialSegments = 8, closed = false) {
  19864. super();
  19865. this.type = 'TubeBufferGeometry';
  19866. this.parameters = {
  19867. path: path,
  19868. tubularSegments: tubularSegments,
  19869. radius: radius,
  19870. radialSegments: radialSegments,
  19871. closed: closed
  19872. };
  19873. const frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  19874. this.tangents = frames.tangents;
  19875. this.normals = frames.normals;
  19876. this.binormals = frames.binormals; // helper variables
  19877. const vertex = new Vector3();
  19878. const normal = new Vector3();
  19879. const uv = new Vector2();
  19880. let P = new Vector3(); // buffer
  19881. const vertices = [];
  19882. const normals = [];
  19883. const uvs = [];
  19884. const indices = []; // create buffer data
  19885. generateBufferData(); // build geometry
  19886. this.setIndex(indices);
  19887. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19888. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19889. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  19890. function generateBufferData() {
  19891. for (let i = 0; i < tubularSegments; i++) {
  19892. generateSegment(i);
  19893. } // if the geometry is not closed, generate the last row of vertices and normals
  19894. // at the regular position on the given path
  19895. //
  19896. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  19897. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  19898. // this makes it easy compute correct values for closed geometries
  19899. generateUVs(); // finally create faces
  19900. generateIndices();
  19901. }
  19902. function generateSegment(i) {
  19903. // we use getPointAt to sample evenly distributed points from the given path
  19904. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  19905. const N = frames.normals[i];
  19906. const B = frames.binormals[i]; // generate normals and vertices for the current segment
  19907. for (let j = 0; j <= radialSegments; j++) {
  19908. const v = j / radialSegments * Math.PI * 2;
  19909. const sin = Math.sin(v);
  19910. const cos = -Math.cos(v); // normal
  19911. normal.x = cos * N.x + sin * B.x;
  19912. normal.y = cos * N.y + sin * B.y;
  19913. normal.z = cos * N.z + sin * B.z;
  19914. normal.normalize();
  19915. normals.push(normal.x, normal.y, normal.z); // vertex
  19916. vertex.x = P.x + radius * normal.x;
  19917. vertex.y = P.y + radius * normal.y;
  19918. vertex.z = P.z + radius * normal.z;
  19919. vertices.push(vertex.x, vertex.y, vertex.z);
  19920. }
  19921. }
  19922. function generateIndices() {
  19923. for (let j = 1; j <= tubularSegments; j++) {
  19924. for (let i = 1; i <= radialSegments; i++) {
  19925. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  19926. const b = (radialSegments + 1) * j + (i - 1);
  19927. const c = (radialSegments + 1) * j + i;
  19928. const d = (radialSegments + 1) * (j - 1) + i; // faces
  19929. indices.push(a, b, d);
  19930. indices.push(b, c, d);
  19931. }
  19932. }
  19933. }
  19934. function generateUVs() {
  19935. for (let i = 0; i <= tubularSegments; i++) {
  19936. for (let j = 0; j <= radialSegments; j++) {
  19937. uv.x = i / tubularSegments;
  19938. uv.y = j / radialSegments;
  19939. uvs.push(uv.x, uv.y);
  19940. }
  19941. }
  19942. }
  19943. }
  19944. toJSON() {
  19945. const data = BufferGeometry.prototype.toJSON.call(this);
  19946. data.path = this.parameters.path.toJSON();
  19947. return data;
  19948. }
  19949. }
  19950. exports.TubeBufferGeometry = TubeBufferGeometry;
  19951. class TubeGeometry extends Geometry {
  19952. constructor(path, tubularSegments, radius, radialSegments, closed, taper) {
  19953. super();
  19954. this.type = 'TubeGeometry';
  19955. this.parameters = {
  19956. path: path,
  19957. tubularSegments: tubularSegments,
  19958. radius: radius,
  19959. radialSegments: radialSegments,
  19960. closed: closed
  19961. };
  19962. if (taper !== undefined) console.warn('THREE.TubeGeometry: taper has been removed.');
  19963. const bufferGeometry = new TubeBufferGeometry(path, tubularSegments, radius, radialSegments, closed); // expose internals
  19964. this.tangents = bufferGeometry.tangents;
  19965. this.normals = bufferGeometry.normals;
  19966. this.binormals = bufferGeometry.binormals; // create geometry
  19967. this.fromBufferGeometry(bufferGeometry);
  19968. this.mergeVertices();
  19969. }
  19970. }
  19971. exports.TubeGeometry = TubeGeometry;
  19972. class WireframeGeometry extends BufferGeometry {
  19973. constructor(geometry) {
  19974. super();
  19975. this.type = 'WireframeGeometry'; // buffer
  19976. const vertices = []; // helper variables
  19977. const edge = [0, 0],
  19978. edges = {};
  19979. const keys = ['a', 'b', 'c']; // different logic for Geometry and BufferGeometry
  19980. if (geometry && geometry.isGeometry) {
  19981. // create a data structure that contains all edges without duplicates
  19982. const faces = geometry.faces;
  19983. for (let i = 0, l = faces.length; i < l; i++) {
  19984. const face = faces[i];
  19985. for (let j = 0; j < 3; j++) {
  19986. const edge1 = face[keys[j]];
  19987. const edge2 = face[keys[(j + 1) % 3]];
  19988. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  19989. edge[1] = Math.max(edge1, edge2);
  19990. const key = edge[0] + ',' + edge[1];
  19991. if (edges[key] === undefined) {
  19992. edges[key] = {
  19993. index1: edge[0],
  19994. index2: edge[1]
  19995. };
  19996. }
  19997. }
  19998. } // generate vertices
  19999. for (const key in edges) {
  20000. const e = edges[key];
  20001. let vertex = geometry.vertices[e.index1];
  20002. vertices.push(vertex.x, vertex.y, vertex.z);
  20003. vertex = geometry.vertices[e.index2];
  20004. vertices.push(vertex.x, vertex.y, vertex.z);
  20005. }
  20006. } else if (geometry && geometry.isBufferGeometry) {
  20007. const vertex = new Vector3();
  20008. if (geometry.index !== null) {
  20009. // indexed BufferGeometry
  20010. const position = geometry.attributes.position;
  20011. const indices = geometry.index;
  20012. let groups = geometry.groups;
  20013. if (groups.length === 0) {
  20014. groups = [{
  20015. start: 0,
  20016. count: indices.count,
  20017. materialIndex: 0
  20018. }];
  20019. } // create a data structure that contains all eges without duplicates
  20020. for (let o = 0, ol = groups.length; o < ol; ++o) {
  20021. const group = groups[o];
  20022. const start = group.start;
  20023. const count = group.count;
  20024. for (let i = start, l = start + count; i < l; i += 3) {
  20025. for (let j = 0; j < 3; j++) {
  20026. const edge1 = indices.getX(i + j);
  20027. const edge2 = indices.getX(i + (j + 1) % 3);
  20028. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  20029. edge[1] = Math.max(edge1, edge2);
  20030. const key = edge[0] + ',' + edge[1];
  20031. if (edges[key] === undefined) {
  20032. edges[key] = {
  20033. index1: edge[0],
  20034. index2: edge[1]
  20035. };
  20036. }
  20037. }
  20038. }
  20039. } // generate vertices
  20040. for (const key in edges) {
  20041. const e = edges[key];
  20042. vertex.fromBufferAttribute(position, e.index1);
  20043. vertices.push(vertex.x, vertex.y, vertex.z);
  20044. vertex.fromBufferAttribute(position, e.index2);
  20045. vertices.push(vertex.x, vertex.y, vertex.z);
  20046. }
  20047. } else {
  20048. // non-indexed BufferGeometry
  20049. const position = geometry.attributes.position;
  20050. for (let i = 0, l = position.count / 3; i < l; i++) {
  20051. for (let j = 0; j < 3; j++) {
  20052. // three edges per triangle, an edge is represented as (index1, index2)
  20053. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  20054. const index1 = 3 * i + j;
  20055. vertex.fromBufferAttribute(position, index1);
  20056. vertices.push(vertex.x, vertex.y, vertex.z);
  20057. const index2 = 3 * i + (j + 1) % 3;
  20058. vertex.fromBufferAttribute(position, index2);
  20059. vertices.push(vertex.x, vertex.y, vertex.z);
  20060. }
  20061. }
  20062. }
  20063. } // build geometry
  20064. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20065. }
  20066. }
  20067. exports.WireframeGeometry = WireframeGeometry;
  20068. var Geometries =
  20069. /*#__PURE__*/
  20070. Object.freeze({
  20071. __proto__: null,
  20072. BoxGeometry: BoxGeometry,
  20073. BoxBufferGeometry: BoxBufferGeometry,
  20074. CircleGeometry: CircleGeometry,
  20075. CircleBufferGeometry: CircleBufferGeometry,
  20076. ConeGeometry: ConeGeometry,
  20077. ConeBufferGeometry: ConeBufferGeometry,
  20078. CylinderGeometry: CylinderGeometry,
  20079. CylinderBufferGeometry: CylinderBufferGeometry,
  20080. DodecahedronGeometry: DodecahedronGeometry,
  20081. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  20082. EdgesGeometry: EdgesGeometry,
  20083. ExtrudeGeometry: ExtrudeGeometry,
  20084. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  20085. IcosahedronGeometry: IcosahedronGeometry,
  20086. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  20087. LatheGeometry: LatheGeometry,
  20088. LatheBufferGeometry: LatheBufferGeometry,
  20089. OctahedronGeometry: OctahedronGeometry,
  20090. OctahedronBufferGeometry: OctahedronBufferGeometry,
  20091. ParametricGeometry: ParametricGeometry,
  20092. ParametricBufferGeometry: ParametricBufferGeometry,
  20093. PlaneGeometry: PlaneGeometry,
  20094. PlaneBufferGeometry: PlaneBufferGeometry,
  20095. PolyhedronGeometry: PolyhedronGeometry,
  20096. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  20097. RingGeometry: RingGeometry,
  20098. RingBufferGeometry: RingBufferGeometry,
  20099. ShapeGeometry: ShapeGeometry,
  20100. ShapeBufferGeometry: ShapeBufferGeometry,
  20101. SphereGeometry: SphereGeometry,
  20102. SphereBufferGeometry: SphereBufferGeometry,
  20103. TetrahedronGeometry: TetrahedronGeometry,
  20104. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  20105. TextGeometry: TextGeometry,
  20106. TextBufferGeometry: TextBufferGeometry,
  20107. TorusGeometry: TorusGeometry,
  20108. TorusBufferGeometry: TorusBufferGeometry,
  20109. TorusKnotGeometry: TorusKnotGeometry,
  20110. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  20111. TubeGeometry: TubeGeometry,
  20112. TubeBufferGeometry: TubeBufferGeometry,
  20113. WireframeGeometry: WireframeGeometry
  20114. });
  20115. /**
  20116. * parameters = {
  20117. * color: <THREE.Color>
  20118. * }
  20119. */
  20120. function ShadowMaterial(parameters) {
  20121. Material.call(this);
  20122. this.type = 'ShadowMaterial';
  20123. this.color = new Color(0x000000);
  20124. this.transparent = true;
  20125. this.setValues(parameters);
  20126. }
  20127. ShadowMaterial.prototype = Object.create(Material.prototype);
  20128. ShadowMaterial.prototype.constructor = ShadowMaterial;
  20129. ShadowMaterial.prototype.isShadowMaterial = true;
  20130. ShadowMaterial.prototype.copy = function (source) {
  20131. Material.prototype.copy.call(this, source);
  20132. this.color.copy(source.color);
  20133. return this;
  20134. };
  20135. function RawShaderMaterial(parameters) {
  20136. ShaderMaterial.call(this, parameters);
  20137. this.type = 'RawShaderMaterial';
  20138. }
  20139. RawShaderMaterial.prototype = Object.create(ShaderMaterial.prototype);
  20140. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  20141. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  20142. /**
  20143. * parameters = {
  20144. * color: <hex>,
  20145. * roughness: <float>,
  20146. * metalness: <float>,
  20147. * opacity: <float>,
  20148. *
  20149. * map: new THREE.Texture( <Image> ),
  20150. *
  20151. * lightMap: new THREE.Texture( <Image> ),
  20152. * lightMapIntensity: <float>
  20153. *
  20154. * aoMap: new THREE.Texture( <Image> ),
  20155. * aoMapIntensity: <float>
  20156. *
  20157. * emissive: <hex>,
  20158. * emissiveIntensity: <float>
  20159. * emissiveMap: new THREE.Texture( <Image> ),
  20160. *
  20161. * bumpMap: new THREE.Texture( <Image> ),
  20162. * bumpScale: <float>,
  20163. *
  20164. * normalMap: new THREE.Texture( <Image> ),
  20165. * normalMapType: THREE.TangentSpaceNormalMap,
  20166. * normalScale: <Vector2>,
  20167. *
  20168. * displacementMap: new THREE.Texture( <Image> ),
  20169. * displacementScale: <float>,
  20170. * displacementBias: <float>,
  20171. *
  20172. * roughnessMap: new THREE.Texture( <Image> ),
  20173. *
  20174. * metalnessMap: new THREE.Texture( <Image> ),
  20175. *
  20176. * alphaMap: new THREE.Texture( <Image> ),
  20177. *
  20178. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20179. * envMapIntensity: <float>
  20180. *
  20181. * refractionRatio: <float>,
  20182. *
  20183. * wireframe: <boolean>,
  20184. * wireframeLinewidth: <float>,
  20185. *
  20186. * skinning: <bool>,
  20187. * morphTargets: <bool>,
  20188. * morphNormals: <bool>
  20189. * }
  20190. */
  20191. function MeshStandardMaterial(parameters) {
  20192. Material.call(this);
  20193. this.defines = {
  20194. 'STANDARD': ''
  20195. };
  20196. this.type = 'MeshStandardMaterial';
  20197. this.color = new Color(0xffffff); // diffuse
  20198. this.roughness = 1.0;
  20199. this.metalness = 0.0;
  20200. this.map = null;
  20201. this.lightMap = null;
  20202. this.lightMapIntensity = 1.0;
  20203. this.aoMap = null;
  20204. this.aoMapIntensity = 1.0;
  20205. this.emissive = new Color(0x000000);
  20206. this.emissiveIntensity = 1.0;
  20207. this.emissiveMap = null;
  20208. this.bumpMap = null;
  20209. this.bumpScale = 1;
  20210. this.normalMap = null;
  20211. this.normalMapType = TangentSpaceNormalMap;
  20212. this.normalScale = new Vector2(1, 1);
  20213. this.displacementMap = null;
  20214. this.displacementScale = 1;
  20215. this.displacementBias = 0;
  20216. this.roughnessMap = null;
  20217. this.metalnessMap = null;
  20218. this.alphaMap = null;
  20219. this.envMap = null;
  20220. this.envMapIntensity = 1.0;
  20221. this.refractionRatio = 0.98;
  20222. this.wireframe = false;
  20223. this.wireframeLinewidth = 1;
  20224. this.wireframeLinecap = 'round';
  20225. this.wireframeLinejoin = 'round';
  20226. this.skinning = false;
  20227. this.morphTargets = false;
  20228. this.morphNormals = false;
  20229. this.vertexTangents = false;
  20230. this.setValues(parameters);
  20231. }
  20232. MeshStandardMaterial.prototype = Object.create(Material.prototype);
  20233. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  20234. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  20235. MeshStandardMaterial.prototype.copy = function (source) {
  20236. Material.prototype.copy.call(this, source);
  20237. this.defines = {
  20238. 'STANDARD': ''
  20239. };
  20240. this.color.copy(source.color);
  20241. this.roughness = source.roughness;
  20242. this.metalness = source.metalness;
  20243. this.map = source.map;
  20244. this.lightMap = source.lightMap;
  20245. this.lightMapIntensity = source.lightMapIntensity;
  20246. this.aoMap = source.aoMap;
  20247. this.aoMapIntensity = source.aoMapIntensity;
  20248. this.emissive.copy(source.emissive);
  20249. this.emissiveMap = source.emissiveMap;
  20250. this.emissiveIntensity = source.emissiveIntensity;
  20251. this.bumpMap = source.bumpMap;
  20252. this.bumpScale = source.bumpScale;
  20253. this.normalMap = source.normalMap;
  20254. this.normalMapType = source.normalMapType;
  20255. this.normalScale.copy(source.normalScale);
  20256. this.displacementMap = source.displacementMap;
  20257. this.displacementScale = source.displacementScale;
  20258. this.displacementBias = source.displacementBias;
  20259. this.roughnessMap = source.roughnessMap;
  20260. this.metalnessMap = source.metalnessMap;
  20261. this.alphaMap = source.alphaMap;
  20262. this.envMap = source.envMap;
  20263. this.envMapIntensity = source.envMapIntensity;
  20264. this.refractionRatio = source.refractionRatio;
  20265. this.wireframe = source.wireframe;
  20266. this.wireframeLinewidth = source.wireframeLinewidth;
  20267. this.wireframeLinecap = source.wireframeLinecap;
  20268. this.wireframeLinejoin = source.wireframeLinejoin;
  20269. this.skinning = source.skinning;
  20270. this.morphTargets = source.morphTargets;
  20271. this.morphNormals = source.morphNormals;
  20272. this.vertexTangents = source.vertexTangents;
  20273. return this;
  20274. };
  20275. /**
  20276. * parameters = {
  20277. * clearcoat: <float>,
  20278. * clearcoatMap: new THREE.Texture( <Image> ),
  20279. * clearcoatRoughness: <float>,
  20280. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  20281. * clearcoatNormalScale: <Vector2>,
  20282. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  20283. *
  20284. * reflectivity: <float>,
  20285. * ior: <float>,
  20286. *
  20287. * sheen: <Color>,
  20288. *
  20289. * transmission: <float>,
  20290. * transmissionMap: new THREE.Texture( <Image> )
  20291. * }
  20292. */
  20293. function MeshPhysicalMaterial(parameters) {
  20294. MeshStandardMaterial.call(this);
  20295. this.defines = {
  20296. 'STANDARD': '',
  20297. 'PHYSICAL': ''
  20298. };
  20299. this.type = 'MeshPhysicalMaterial';
  20300. this.clearcoat = 0.0;
  20301. this.clearcoatMap = null;
  20302. this.clearcoatRoughness = 0.0;
  20303. this.clearcoatRoughnessMap = null;
  20304. this.clearcoatNormalScale = new Vector2(1, 1);
  20305. this.clearcoatNormalMap = null;
  20306. this.reflectivity = 0.5; // maps to F0 = 0.04
  20307. Object.defineProperty(this, 'ior', {
  20308. get: function () {
  20309. return (1 + 0.4 * this.reflectivity) / (1 - 0.4 * this.reflectivity);
  20310. },
  20311. set: function (ior) {
  20312. this.reflectivity = MathUtils.clamp(2.5 * (ior - 1) / (ior + 1), 0, 1);
  20313. }
  20314. });
  20315. this.sheen = null; // null will disable sheen bsdf
  20316. this.transmission = 0.0;
  20317. this.transmissionMap = null;
  20318. this.setValues(parameters);
  20319. }
  20320. MeshPhysicalMaterial.prototype = Object.create(MeshStandardMaterial.prototype);
  20321. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  20322. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  20323. MeshPhysicalMaterial.prototype.copy = function (source) {
  20324. MeshStandardMaterial.prototype.copy.call(this, source);
  20325. this.defines = {
  20326. 'STANDARD': '',
  20327. 'PHYSICAL': ''
  20328. };
  20329. this.clearcoat = source.clearcoat;
  20330. this.clearcoatMap = source.clearcoatMap;
  20331. this.clearcoatRoughness = source.clearcoatRoughness;
  20332. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  20333. this.clearcoatNormalMap = source.clearcoatNormalMap;
  20334. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  20335. this.reflectivity = source.reflectivity;
  20336. if (source.sheen) {
  20337. this.sheen = (this.sheen || new Color()).copy(source.sheen);
  20338. } else {
  20339. this.sheen = null;
  20340. }
  20341. this.transmission = source.transmission;
  20342. this.transmissionMap = source.transmissionMap;
  20343. return this;
  20344. };
  20345. /**
  20346. * parameters = {
  20347. * color: <hex>,
  20348. * specular: <hex>,
  20349. * shininess: <float>,
  20350. * opacity: <float>,
  20351. *
  20352. * map: new THREE.Texture( <Image> ),
  20353. *
  20354. * lightMap: new THREE.Texture( <Image> ),
  20355. * lightMapIntensity: <float>
  20356. *
  20357. * aoMap: new THREE.Texture( <Image> ),
  20358. * aoMapIntensity: <float>
  20359. *
  20360. * emissive: <hex>,
  20361. * emissiveIntensity: <float>
  20362. * emissiveMap: new THREE.Texture( <Image> ),
  20363. *
  20364. * bumpMap: new THREE.Texture( <Image> ),
  20365. * bumpScale: <float>,
  20366. *
  20367. * normalMap: new THREE.Texture( <Image> ),
  20368. * normalMapType: THREE.TangentSpaceNormalMap,
  20369. * normalScale: <Vector2>,
  20370. *
  20371. * displacementMap: new THREE.Texture( <Image> ),
  20372. * displacementScale: <float>,
  20373. * displacementBias: <float>,
  20374. *
  20375. * specularMap: new THREE.Texture( <Image> ),
  20376. *
  20377. * alphaMap: new THREE.Texture( <Image> ),
  20378. *
  20379. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20380. * combine: THREE.MultiplyOperation,
  20381. * reflectivity: <float>,
  20382. * refractionRatio: <float>,
  20383. *
  20384. * wireframe: <boolean>,
  20385. * wireframeLinewidth: <float>,
  20386. *
  20387. * skinning: <bool>,
  20388. * morphTargets: <bool>,
  20389. * morphNormals: <bool>
  20390. * }
  20391. */
  20392. function MeshPhongMaterial(parameters) {
  20393. Material.call(this);
  20394. this.type = 'MeshPhongMaterial';
  20395. this.color = new Color(0xffffff); // diffuse
  20396. this.specular = new Color(0x111111);
  20397. this.shininess = 30;
  20398. this.map = null;
  20399. this.lightMap = null;
  20400. this.lightMapIntensity = 1.0;
  20401. this.aoMap = null;
  20402. this.aoMapIntensity = 1.0;
  20403. this.emissive = new Color(0x000000);
  20404. this.emissiveIntensity = 1.0;
  20405. this.emissiveMap = null;
  20406. this.bumpMap = null;
  20407. this.bumpScale = 1;
  20408. this.normalMap = null;
  20409. this.normalMapType = TangentSpaceNormalMap;
  20410. this.normalScale = new Vector2(1, 1);
  20411. this.displacementMap = null;
  20412. this.displacementScale = 1;
  20413. this.displacementBias = 0;
  20414. this.specularMap = null;
  20415. this.alphaMap = null;
  20416. this.envMap = null;
  20417. this.combine = MultiplyOperation;
  20418. this.reflectivity = 1;
  20419. this.refractionRatio = 0.98;
  20420. this.wireframe = false;
  20421. this.wireframeLinewidth = 1;
  20422. this.wireframeLinecap = 'round';
  20423. this.wireframeLinejoin = 'round';
  20424. this.skinning = false;
  20425. this.morphTargets = false;
  20426. this.morphNormals = false;
  20427. this.setValues(parameters);
  20428. }
  20429. MeshPhongMaterial.prototype = Object.create(Material.prototype);
  20430. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  20431. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  20432. MeshPhongMaterial.prototype.copy = function (source) {
  20433. Material.prototype.copy.call(this, source);
  20434. this.color.copy(source.color);
  20435. this.specular.copy(source.specular);
  20436. this.shininess = source.shininess;
  20437. this.map = source.map;
  20438. this.lightMap = source.lightMap;
  20439. this.lightMapIntensity = source.lightMapIntensity;
  20440. this.aoMap = source.aoMap;
  20441. this.aoMapIntensity = source.aoMapIntensity;
  20442. this.emissive.copy(source.emissive);
  20443. this.emissiveMap = source.emissiveMap;
  20444. this.emissiveIntensity = source.emissiveIntensity;
  20445. this.bumpMap = source.bumpMap;
  20446. this.bumpScale = source.bumpScale;
  20447. this.normalMap = source.normalMap;
  20448. this.normalMapType = source.normalMapType;
  20449. this.normalScale.copy(source.normalScale);
  20450. this.displacementMap = source.displacementMap;
  20451. this.displacementScale = source.displacementScale;
  20452. this.displacementBias = source.displacementBias;
  20453. this.specularMap = source.specularMap;
  20454. this.alphaMap = source.alphaMap;
  20455. this.envMap = source.envMap;
  20456. this.combine = source.combine;
  20457. this.reflectivity = source.reflectivity;
  20458. this.refractionRatio = source.refractionRatio;
  20459. this.wireframe = source.wireframe;
  20460. this.wireframeLinewidth = source.wireframeLinewidth;
  20461. this.wireframeLinecap = source.wireframeLinecap;
  20462. this.wireframeLinejoin = source.wireframeLinejoin;
  20463. this.skinning = source.skinning;
  20464. this.morphTargets = source.morphTargets;
  20465. this.morphNormals = source.morphNormals;
  20466. return this;
  20467. };
  20468. /**
  20469. * parameters = {
  20470. * color: <hex>,
  20471. *
  20472. * map: new THREE.Texture( <Image> ),
  20473. * gradientMap: new THREE.Texture( <Image> ),
  20474. *
  20475. * lightMap: new THREE.Texture( <Image> ),
  20476. * lightMapIntensity: <float>
  20477. *
  20478. * aoMap: new THREE.Texture( <Image> ),
  20479. * aoMapIntensity: <float>
  20480. *
  20481. * emissive: <hex>,
  20482. * emissiveIntensity: <float>
  20483. * emissiveMap: new THREE.Texture( <Image> ),
  20484. *
  20485. * bumpMap: new THREE.Texture( <Image> ),
  20486. * bumpScale: <float>,
  20487. *
  20488. * normalMap: new THREE.Texture( <Image> ),
  20489. * normalMapType: THREE.TangentSpaceNormalMap,
  20490. * normalScale: <Vector2>,
  20491. *
  20492. * displacementMap: new THREE.Texture( <Image> ),
  20493. * displacementScale: <float>,
  20494. * displacementBias: <float>,
  20495. *
  20496. * alphaMap: new THREE.Texture( <Image> ),
  20497. *
  20498. * wireframe: <boolean>,
  20499. * wireframeLinewidth: <float>,
  20500. *
  20501. * skinning: <bool>,
  20502. * morphTargets: <bool>,
  20503. * morphNormals: <bool>
  20504. * }
  20505. */
  20506. function MeshToonMaterial(parameters) {
  20507. Material.call(this);
  20508. this.defines = {
  20509. 'TOON': ''
  20510. };
  20511. this.type = 'MeshToonMaterial';
  20512. this.color = new Color(0xffffff);
  20513. this.map = null;
  20514. this.gradientMap = null;
  20515. this.lightMap = null;
  20516. this.lightMapIntensity = 1.0;
  20517. this.aoMap = null;
  20518. this.aoMapIntensity = 1.0;
  20519. this.emissive = new Color(0x000000);
  20520. this.emissiveIntensity = 1.0;
  20521. this.emissiveMap = null;
  20522. this.bumpMap = null;
  20523. this.bumpScale = 1;
  20524. this.normalMap = null;
  20525. this.normalMapType = TangentSpaceNormalMap;
  20526. this.normalScale = new Vector2(1, 1);
  20527. this.displacementMap = null;
  20528. this.displacementScale = 1;
  20529. this.displacementBias = 0;
  20530. this.alphaMap = null;
  20531. this.wireframe = false;
  20532. this.wireframeLinewidth = 1;
  20533. this.wireframeLinecap = 'round';
  20534. this.wireframeLinejoin = 'round';
  20535. this.skinning = false;
  20536. this.morphTargets = false;
  20537. this.morphNormals = false;
  20538. this.setValues(parameters);
  20539. }
  20540. MeshToonMaterial.prototype = Object.create(Material.prototype);
  20541. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  20542. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  20543. MeshToonMaterial.prototype.copy = function (source) {
  20544. Material.prototype.copy.call(this, source);
  20545. this.color.copy(source.color);
  20546. this.map = source.map;
  20547. this.gradientMap = source.gradientMap;
  20548. this.lightMap = source.lightMap;
  20549. this.lightMapIntensity = source.lightMapIntensity;
  20550. this.aoMap = source.aoMap;
  20551. this.aoMapIntensity = source.aoMapIntensity;
  20552. this.emissive.copy(source.emissive);
  20553. this.emissiveMap = source.emissiveMap;
  20554. this.emissiveIntensity = source.emissiveIntensity;
  20555. this.bumpMap = source.bumpMap;
  20556. this.bumpScale = source.bumpScale;
  20557. this.normalMap = source.normalMap;
  20558. this.normalMapType = source.normalMapType;
  20559. this.normalScale.copy(source.normalScale);
  20560. this.displacementMap = source.displacementMap;
  20561. this.displacementScale = source.displacementScale;
  20562. this.displacementBias = source.displacementBias;
  20563. this.alphaMap = source.alphaMap;
  20564. this.wireframe = source.wireframe;
  20565. this.wireframeLinewidth = source.wireframeLinewidth;
  20566. this.wireframeLinecap = source.wireframeLinecap;
  20567. this.wireframeLinejoin = source.wireframeLinejoin;
  20568. this.skinning = source.skinning;
  20569. this.morphTargets = source.morphTargets;
  20570. this.morphNormals = source.morphNormals;
  20571. return this;
  20572. };
  20573. /**
  20574. * parameters = {
  20575. * opacity: <float>,
  20576. *
  20577. * bumpMap: new THREE.Texture( <Image> ),
  20578. * bumpScale: <float>,
  20579. *
  20580. * normalMap: new THREE.Texture( <Image> ),
  20581. * normalMapType: THREE.TangentSpaceNormalMap,
  20582. * normalScale: <Vector2>,
  20583. *
  20584. * displacementMap: new THREE.Texture( <Image> ),
  20585. * displacementScale: <float>,
  20586. * displacementBias: <float>,
  20587. *
  20588. * wireframe: <boolean>,
  20589. * wireframeLinewidth: <float>
  20590. *
  20591. * skinning: <bool>,
  20592. * morphTargets: <bool>,
  20593. * morphNormals: <bool>
  20594. * }
  20595. */
  20596. function MeshNormalMaterial(parameters) {
  20597. Material.call(this);
  20598. this.type = 'MeshNormalMaterial';
  20599. this.bumpMap = null;
  20600. this.bumpScale = 1;
  20601. this.normalMap = null;
  20602. this.normalMapType = TangentSpaceNormalMap;
  20603. this.normalScale = new Vector2(1, 1);
  20604. this.displacementMap = null;
  20605. this.displacementScale = 1;
  20606. this.displacementBias = 0;
  20607. this.wireframe = false;
  20608. this.wireframeLinewidth = 1;
  20609. this.fog = false;
  20610. this.skinning = false;
  20611. this.morphTargets = false;
  20612. this.morphNormals = false;
  20613. this.setValues(parameters);
  20614. }
  20615. MeshNormalMaterial.prototype = Object.create(Material.prototype);
  20616. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  20617. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  20618. MeshNormalMaterial.prototype.copy = function (source) {
  20619. Material.prototype.copy.call(this, source);
  20620. this.bumpMap = source.bumpMap;
  20621. this.bumpScale = source.bumpScale;
  20622. this.normalMap = source.normalMap;
  20623. this.normalMapType = source.normalMapType;
  20624. this.normalScale.copy(source.normalScale);
  20625. this.displacementMap = source.displacementMap;
  20626. this.displacementScale = source.displacementScale;
  20627. this.displacementBias = source.displacementBias;
  20628. this.wireframe = source.wireframe;
  20629. this.wireframeLinewidth = source.wireframeLinewidth;
  20630. this.skinning = source.skinning;
  20631. this.morphTargets = source.morphTargets;
  20632. this.morphNormals = source.morphNormals;
  20633. return this;
  20634. };
  20635. /**
  20636. * parameters = {
  20637. * color: <hex>,
  20638. * opacity: <float>,
  20639. *
  20640. * map: new THREE.Texture( <Image> ),
  20641. *
  20642. * lightMap: new THREE.Texture( <Image> ),
  20643. * lightMapIntensity: <float>
  20644. *
  20645. * aoMap: new THREE.Texture( <Image> ),
  20646. * aoMapIntensity: <float>
  20647. *
  20648. * emissive: <hex>,
  20649. * emissiveIntensity: <float>
  20650. * emissiveMap: new THREE.Texture( <Image> ),
  20651. *
  20652. * specularMap: new THREE.Texture( <Image> ),
  20653. *
  20654. * alphaMap: new THREE.Texture( <Image> ),
  20655. *
  20656. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20657. * combine: THREE.Multiply,
  20658. * reflectivity: <float>,
  20659. * refractionRatio: <float>,
  20660. *
  20661. * wireframe: <boolean>,
  20662. * wireframeLinewidth: <float>,
  20663. *
  20664. * skinning: <bool>,
  20665. * morphTargets: <bool>,
  20666. * morphNormals: <bool>
  20667. * }
  20668. */
  20669. function MeshLambertMaterial(parameters) {
  20670. Material.call(this);
  20671. this.type = 'MeshLambertMaterial';
  20672. this.color = new Color(0xffffff); // diffuse
  20673. this.map = null;
  20674. this.lightMap = null;
  20675. this.lightMapIntensity = 1.0;
  20676. this.aoMap = null;
  20677. this.aoMapIntensity = 1.0;
  20678. this.emissive = new Color(0x000000);
  20679. this.emissiveIntensity = 1.0;
  20680. this.emissiveMap = null;
  20681. this.specularMap = null;
  20682. this.alphaMap = null;
  20683. this.envMap = null;
  20684. this.combine = MultiplyOperation;
  20685. this.reflectivity = 1;
  20686. this.refractionRatio = 0.98;
  20687. this.wireframe = false;
  20688. this.wireframeLinewidth = 1;
  20689. this.wireframeLinecap = 'round';
  20690. this.wireframeLinejoin = 'round';
  20691. this.skinning = false;
  20692. this.morphTargets = false;
  20693. this.morphNormals = false;
  20694. this.setValues(parameters);
  20695. }
  20696. MeshLambertMaterial.prototype = Object.create(Material.prototype);
  20697. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  20698. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  20699. MeshLambertMaterial.prototype.copy = function (source) {
  20700. Material.prototype.copy.call(this, source);
  20701. this.color.copy(source.color);
  20702. this.map = source.map;
  20703. this.lightMap = source.lightMap;
  20704. this.lightMapIntensity = source.lightMapIntensity;
  20705. this.aoMap = source.aoMap;
  20706. this.aoMapIntensity = source.aoMapIntensity;
  20707. this.emissive.copy(source.emissive);
  20708. this.emissiveMap = source.emissiveMap;
  20709. this.emissiveIntensity = source.emissiveIntensity;
  20710. this.specularMap = source.specularMap;
  20711. this.alphaMap = source.alphaMap;
  20712. this.envMap = source.envMap;
  20713. this.combine = source.combine;
  20714. this.reflectivity = source.reflectivity;
  20715. this.refractionRatio = source.refractionRatio;
  20716. this.wireframe = source.wireframe;
  20717. this.wireframeLinewidth = source.wireframeLinewidth;
  20718. this.wireframeLinecap = source.wireframeLinecap;
  20719. this.wireframeLinejoin = source.wireframeLinejoin;
  20720. this.skinning = source.skinning;
  20721. this.morphTargets = source.morphTargets;
  20722. this.morphNormals = source.morphNormals;
  20723. return this;
  20724. };
  20725. /**
  20726. * parameters = {
  20727. * color: <hex>,
  20728. * opacity: <float>,
  20729. *
  20730. * matcap: new THREE.Texture( <Image> ),
  20731. *
  20732. * map: new THREE.Texture( <Image> ),
  20733. *
  20734. * bumpMap: new THREE.Texture( <Image> ),
  20735. * bumpScale: <float>,
  20736. *
  20737. * normalMap: new THREE.Texture( <Image> ),
  20738. * normalMapType: THREE.TangentSpaceNormalMap,
  20739. * normalScale: <Vector2>,
  20740. *
  20741. * displacementMap: new THREE.Texture( <Image> ),
  20742. * displacementScale: <float>,
  20743. * displacementBias: <float>,
  20744. *
  20745. * alphaMap: new THREE.Texture( <Image> ),
  20746. *
  20747. * skinning: <bool>,
  20748. * morphTargets: <bool>,
  20749. * morphNormals: <bool>
  20750. * }
  20751. */
  20752. function MeshMatcapMaterial(parameters) {
  20753. Material.call(this);
  20754. this.defines = {
  20755. 'MATCAP': ''
  20756. };
  20757. this.type = 'MeshMatcapMaterial';
  20758. this.color = new Color(0xffffff); // diffuse
  20759. this.matcap = null;
  20760. this.map = null;
  20761. this.bumpMap = null;
  20762. this.bumpScale = 1;
  20763. this.normalMap = null;
  20764. this.normalMapType = TangentSpaceNormalMap;
  20765. this.normalScale = new Vector2(1, 1);
  20766. this.displacementMap = null;
  20767. this.displacementScale = 1;
  20768. this.displacementBias = 0;
  20769. this.alphaMap = null;
  20770. this.skinning = false;
  20771. this.morphTargets = false;
  20772. this.morphNormals = false;
  20773. this.setValues(parameters);
  20774. }
  20775. MeshMatcapMaterial.prototype = Object.create(Material.prototype);
  20776. MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial;
  20777. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  20778. MeshMatcapMaterial.prototype.copy = function (source) {
  20779. Material.prototype.copy.call(this, source);
  20780. this.defines = {
  20781. 'MATCAP': ''
  20782. };
  20783. this.color.copy(source.color);
  20784. this.matcap = source.matcap;
  20785. this.map = source.map;
  20786. this.bumpMap = source.bumpMap;
  20787. this.bumpScale = source.bumpScale;
  20788. this.normalMap = source.normalMap;
  20789. this.normalMapType = source.normalMapType;
  20790. this.normalScale.copy(source.normalScale);
  20791. this.displacementMap = source.displacementMap;
  20792. this.displacementScale = source.displacementScale;
  20793. this.displacementBias = source.displacementBias;
  20794. this.alphaMap = source.alphaMap;
  20795. this.skinning = source.skinning;
  20796. this.morphTargets = source.morphTargets;
  20797. this.morphNormals = source.morphNormals;
  20798. return this;
  20799. };
  20800. /**
  20801. * parameters = {
  20802. * color: <hex>,
  20803. * opacity: <float>,
  20804. *
  20805. * linewidth: <float>,
  20806. *
  20807. * scale: <float>,
  20808. * dashSize: <float>,
  20809. * gapSize: <float>
  20810. * }
  20811. */
  20812. function LineDashedMaterial(parameters) {
  20813. LineBasicMaterial.call(this);
  20814. this.type = 'LineDashedMaterial';
  20815. this.scale = 1;
  20816. this.dashSize = 3;
  20817. this.gapSize = 1;
  20818. this.setValues(parameters);
  20819. }
  20820. LineDashedMaterial.prototype = Object.create(LineBasicMaterial.prototype);
  20821. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  20822. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  20823. LineDashedMaterial.prototype.copy = function (source) {
  20824. LineBasicMaterial.prototype.copy.call(this, source);
  20825. this.scale = source.scale;
  20826. this.dashSize = source.dashSize;
  20827. this.gapSize = source.gapSize;
  20828. return this;
  20829. };
  20830. var Materials =
  20831. /*#__PURE__*/
  20832. Object.freeze({
  20833. __proto__: null,
  20834. ShadowMaterial: ShadowMaterial,
  20835. SpriteMaterial: SpriteMaterial,
  20836. RawShaderMaterial: RawShaderMaterial,
  20837. ShaderMaterial: ShaderMaterial,
  20838. PointsMaterial: PointsMaterial,
  20839. MeshPhysicalMaterial: MeshPhysicalMaterial,
  20840. MeshStandardMaterial: MeshStandardMaterial,
  20841. MeshPhongMaterial: MeshPhongMaterial,
  20842. MeshToonMaterial: MeshToonMaterial,
  20843. MeshNormalMaterial: MeshNormalMaterial,
  20844. MeshLambertMaterial: MeshLambertMaterial,
  20845. MeshDepthMaterial: MeshDepthMaterial,
  20846. MeshDistanceMaterial: MeshDistanceMaterial,
  20847. MeshBasicMaterial: MeshBasicMaterial,
  20848. MeshMatcapMaterial: MeshMatcapMaterial,
  20849. LineDashedMaterial: LineDashedMaterial,
  20850. LineBasicMaterial: LineBasicMaterial,
  20851. Material: Material
  20852. });
  20853. const AnimationUtils = {
  20854. // same as Array.prototype.slice, but also works on typed arrays
  20855. arraySlice: function (array, from, to) {
  20856. if (AnimationUtils.isTypedArray(array)) {
  20857. // in ios9 array.subarray(from, undefined) will return empty array
  20858. // but array.subarray(from) or array.subarray(from, len) is correct
  20859. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  20860. }
  20861. return array.slice(from, to);
  20862. },
  20863. // converts an array to a specific type
  20864. convertArray: function (array, type, forceClone) {
  20865. if (!array || // let 'undefined' and 'null' pass
  20866. !forceClone && array.constructor === type) return array;
  20867. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  20868. return new type(array); // create typed array
  20869. }
  20870. return Array.prototype.slice.call(array); // create Array
  20871. },
  20872. isTypedArray: function (object) {
  20873. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  20874. },
  20875. // returns an array by which times and values can be sorted
  20876. getKeyframeOrder: function (times) {
  20877. function compareTime(i, j) {
  20878. return times[i] - times[j];
  20879. }
  20880. const n = times.length;
  20881. const result = new Array(n);
  20882. for (let i = 0; i !== n; ++i) result[i] = i;
  20883. result.sort(compareTime);
  20884. return result;
  20885. },
  20886. // uses the array previously returned by 'getKeyframeOrder' to sort data
  20887. sortedArray: function (values, stride, order) {
  20888. const nValues = values.length;
  20889. const result = new values.constructor(nValues);
  20890. for (let i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  20891. const srcOffset = order[i] * stride;
  20892. for (let j = 0; j !== stride; ++j) {
  20893. result[dstOffset++] = values[srcOffset + j];
  20894. }
  20895. }
  20896. return result;
  20897. },
  20898. // function for parsing AOS keyframe formats
  20899. flattenJSON: function (jsonKeys, times, values, valuePropertyName) {
  20900. let i = 1,
  20901. key = jsonKeys[0];
  20902. while (key !== undefined && key[valuePropertyName] === undefined) {
  20903. key = jsonKeys[i++];
  20904. }
  20905. if (key === undefined) return; // no data
  20906. let value = key[valuePropertyName];
  20907. if (value === undefined) return; // no data
  20908. if (Array.isArray(value)) {
  20909. do {
  20910. value = key[valuePropertyName];
  20911. if (value !== undefined) {
  20912. times.push(key.time);
  20913. values.push.apply(values, value); // push all elements
  20914. }
  20915. key = jsonKeys[i++];
  20916. } while (key !== undefined);
  20917. } else if (value.toArray !== undefined) {
  20918. // ...assume THREE.Math-ish
  20919. do {
  20920. value = key[valuePropertyName];
  20921. if (value !== undefined) {
  20922. times.push(key.time);
  20923. value.toArray(values, values.length);
  20924. }
  20925. key = jsonKeys[i++];
  20926. } while (key !== undefined);
  20927. } else {
  20928. // otherwise push as-is
  20929. do {
  20930. value = key[valuePropertyName];
  20931. if (value !== undefined) {
  20932. times.push(key.time);
  20933. values.push(value);
  20934. }
  20935. key = jsonKeys[i++];
  20936. } while (key !== undefined);
  20937. }
  20938. },
  20939. subclip: function (sourceClip, name, startFrame, endFrame, fps = 30) {
  20940. const clip = sourceClip.clone();
  20941. clip.name = name;
  20942. const tracks = [];
  20943. for (let i = 0; i < clip.tracks.length; ++i) {
  20944. const track = clip.tracks[i];
  20945. const valueSize = track.getValueSize();
  20946. const times = [];
  20947. const values = [];
  20948. for (let j = 0; j < track.times.length; ++j) {
  20949. const frame = track.times[j] * fps;
  20950. if (frame < startFrame || frame >= endFrame) continue;
  20951. times.push(track.times[j]);
  20952. for (let k = 0; k < valueSize; ++k) {
  20953. values.push(track.values[j * valueSize + k]);
  20954. }
  20955. }
  20956. if (times.length === 0) continue;
  20957. track.times = AnimationUtils.convertArray(times, track.times.constructor);
  20958. track.values = AnimationUtils.convertArray(values, track.values.constructor);
  20959. tracks.push(track);
  20960. }
  20961. clip.tracks = tracks; // find minimum .times value across all tracks in the trimmed clip
  20962. let minStartTime = Infinity;
  20963. for (let i = 0; i < clip.tracks.length; ++i) {
  20964. if (minStartTime > clip.tracks[i].times[0]) {
  20965. minStartTime = clip.tracks[i].times[0];
  20966. }
  20967. } // shift all tracks such that clip begins at t=0
  20968. for (let i = 0; i < clip.tracks.length; ++i) {
  20969. clip.tracks[i].shift(-1 * minStartTime);
  20970. }
  20971. clip.resetDuration();
  20972. return clip;
  20973. },
  20974. makeClipAdditive: function (targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) {
  20975. if (fps <= 0) fps = 30;
  20976. const numTracks = referenceClip.tracks.length;
  20977. const referenceTime = referenceFrame / fps; // Make each track's values relative to the values at the reference frame
  20978. for (let i = 0; i < numTracks; ++i) {
  20979. const referenceTrack = referenceClip.tracks[i];
  20980. const referenceTrackType = referenceTrack.ValueTypeName; // Skip this track if it's non-numeric
  20981. if (referenceTrackType === 'bool' || referenceTrackType === 'string') continue; // Find the track in the target clip whose name and type matches the reference track
  20982. const targetTrack = targetClip.tracks.find(function (track) {
  20983. return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType;
  20984. });
  20985. if (targetTrack === undefined) continue;
  20986. let referenceOffset = 0;
  20987. const referenceValueSize = referenceTrack.getValueSize();
  20988. if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  20989. referenceOffset = referenceValueSize / 3;
  20990. }
  20991. let targetOffset = 0;
  20992. const targetValueSize = targetTrack.getValueSize();
  20993. if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  20994. targetOffset = targetValueSize / 3;
  20995. }
  20996. const lastIndex = referenceTrack.times.length - 1;
  20997. let referenceValue; // Find the value to subtract out of the track
  20998. if (referenceTime <= referenceTrack.times[0]) {
  20999. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  21000. const startIndex = referenceOffset;
  21001. const endIndex = referenceValueSize - referenceOffset;
  21002. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  21003. } else if (referenceTime >= referenceTrack.times[lastIndex]) {
  21004. // Reference frame is after the last keyframe, so just use the last keyframe
  21005. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  21006. const endIndex = startIndex + referenceValueSize - referenceOffset;
  21007. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  21008. } else {
  21009. // Interpolate to the reference value
  21010. const interpolant = referenceTrack.createInterpolant();
  21011. const startIndex = referenceOffset;
  21012. const endIndex = referenceValueSize - referenceOffset;
  21013. interpolant.evaluate(referenceTime);
  21014. referenceValue = AnimationUtils.arraySlice(interpolant.resultBuffer, startIndex, endIndex);
  21015. } // Conjugate the quaternion
  21016. if (referenceTrackType === 'quaternion') {
  21017. const referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate();
  21018. referenceQuat.toArray(referenceValue);
  21019. } // Subtract the reference value from all of the track values
  21020. const numTimes = targetTrack.times.length;
  21021. for (let j = 0; j < numTimes; ++j) {
  21022. const valueStart = j * targetValueSize + targetOffset;
  21023. if (referenceTrackType === 'quaternion') {
  21024. // Multiply the conjugate for quaternion track types
  21025. Quaternion.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart);
  21026. } else {
  21027. const valueEnd = targetValueSize - targetOffset * 2; // Subtract each value for all other numeric track types
  21028. for (let k = 0; k < valueEnd; ++k) {
  21029. targetTrack.values[valueStart + k] -= referenceValue[k];
  21030. }
  21031. }
  21032. }
  21033. }
  21034. targetClip.blendMode = AdditiveAnimationBlendMode;
  21035. return targetClip;
  21036. }
  21037. };
  21038. /**
  21039. * Abstract base class of interpolants over parametric samples.
  21040. *
  21041. * The parameter domain is one dimensional, typically the time or a path
  21042. * along a curve defined by the data.
  21043. *
  21044. * The sample values can have any dimensionality and derived classes may
  21045. * apply special interpretations to the data.
  21046. *
  21047. * This class provides the interval seek in a Template Method, deferring
  21048. * the actual interpolation to derived classes.
  21049. *
  21050. * Time complexity is O(1) for linear access crossing at most two points
  21051. * and O(log N) for random access, where N is the number of positions.
  21052. *
  21053. * References:
  21054. *
  21055. * http://www.oodesign.com/template-method-pattern.html
  21056. *
  21057. */
  21058. exports.AnimationUtils = AnimationUtils;
  21059. function Interpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21060. this.parameterPositions = parameterPositions;
  21061. this._cachedIndex = 0;
  21062. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  21063. this.sampleValues = sampleValues;
  21064. this.valueSize = sampleSize;
  21065. }
  21066. Object.assign(Interpolant.prototype, {
  21067. evaluate: function (t) {
  21068. const pp = this.parameterPositions;
  21069. let i1 = this._cachedIndex,
  21070. t1 = pp[i1],
  21071. t0 = pp[i1 - 1];
  21072. validate_interval: {
  21073. seek: {
  21074. let right;
  21075. linear_scan: {
  21076. //- See http://jsperf.com/comparison-to-undefined/3
  21077. //- slower code:
  21078. //-
  21079. //- if ( t >= t1 || t1 === undefined ) {
  21080. forward_scan: if (!(t < t1)) {
  21081. for (let giveUpAt = i1 + 2;;) {
  21082. if (t1 === undefined) {
  21083. if (t < t0) break forward_scan; // after end
  21084. i1 = pp.length;
  21085. this._cachedIndex = i1;
  21086. return this.afterEnd_(i1 - 1, t, t0);
  21087. }
  21088. if (i1 === giveUpAt) break; // this loop
  21089. t0 = t1;
  21090. t1 = pp[++i1];
  21091. if (t < t1) {
  21092. // we have arrived at the sought interval
  21093. break seek;
  21094. }
  21095. } // prepare binary search on the right side of the index
  21096. right = pp.length;
  21097. break linear_scan;
  21098. } //- slower code:
  21099. //- if ( t < t0 || t0 === undefined ) {
  21100. if (!(t >= t0)) {
  21101. // looping?
  21102. const t1global = pp[1];
  21103. if (t < t1global) {
  21104. i1 = 2; // + 1, using the scan for the details
  21105. t0 = t1global;
  21106. } // linear reverse scan
  21107. for (let giveUpAt = i1 - 2;;) {
  21108. if (t0 === undefined) {
  21109. // before start
  21110. this._cachedIndex = 0;
  21111. return this.beforeStart_(0, t, t1);
  21112. }
  21113. if (i1 === giveUpAt) break; // this loop
  21114. t1 = t0;
  21115. t0 = pp[--i1 - 1];
  21116. if (t >= t0) {
  21117. // we have arrived at the sought interval
  21118. break seek;
  21119. }
  21120. } // prepare binary search on the left side of the index
  21121. right = i1;
  21122. i1 = 0;
  21123. break linear_scan;
  21124. } // the interval is valid
  21125. break validate_interval;
  21126. } // linear scan
  21127. // binary search
  21128. while (i1 < right) {
  21129. const mid = i1 + right >>> 1;
  21130. if (t < pp[mid]) {
  21131. right = mid;
  21132. } else {
  21133. i1 = mid + 1;
  21134. }
  21135. }
  21136. t1 = pp[i1];
  21137. t0 = pp[i1 - 1]; // check boundary cases, again
  21138. if (t0 === undefined) {
  21139. this._cachedIndex = 0;
  21140. return this.beforeStart_(0, t, t1);
  21141. }
  21142. if (t1 === undefined) {
  21143. i1 = pp.length;
  21144. this._cachedIndex = i1;
  21145. return this.afterEnd_(i1 - 1, t0, t);
  21146. }
  21147. } // seek
  21148. this._cachedIndex = i1;
  21149. this.intervalChanged_(i1, t0, t1);
  21150. } // validate_interval
  21151. return this.interpolate_(i1, t0, t, t1);
  21152. },
  21153. settings: null,
  21154. // optional, subclass-specific settings structure
  21155. // Note: The indirection allows central control of many interpolants.
  21156. // --- Protected interface
  21157. DefaultSettings_: {},
  21158. getSettings_: function () {
  21159. return this.settings || this.DefaultSettings_;
  21160. },
  21161. copySampleValue_: function (index) {
  21162. // copies a sample value to the result buffer
  21163. const result = this.resultBuffer,
  21164. values = this.sampleValues,
  21165. stride = this.valueSize,
  21166. offset = index * stride;
  21167. for (let i = 0; i !== stride; ++i) {
  21168. result[i] = values[offset + i];
  21169. }
  21170. return result;
  21171. },
  21172. // Template methods for derived classes:
  21173. interpolate_: function ()
  21174. /* i1, t0, t, t1 */
  21175. {
  21176. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  21177. },
  21178. intervalChanged_: function ()
  21179. /* i1, t0, t1 */
  21180. {// empty
  21181. }
  21182. }); // DECLARE ALIAS AFTER assign prototype
  21183. Object.assign(Interpolant.prototype, {
  21184. //( 0, t, t0 ), returns this.resultBuffer
  21185. beforeStart_: Interpolant.prototype.copySampleValue_,
  21186. //( N-1, tN-1, t ), returns this.resultBuffer
  21187. afterEnd_: Interpolant.prototype.copySampleValue_
  21188. });
  21189. /**
  21190. * Fast and simple cubic spline interpolant.
  21191. *
  21192. * It was derived from a Hermitian construction setting the first derivative
  21193. * at each sample position to the linear slope between neighboring positions
  21194. * over their parameter interval.
  21195. */
  21196. function CubicInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21197. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21198. this._weightPrev = -0;
  21199. this._offsetPrev = -0;
  21200. this._weightNext = -0;
  21201. this._offsetNext = -0;
  21202. }
  21203. CubicInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21204. constructor: CubicInterpolant,
  21205. DefaultSettings_: {
  21206. endingStart: ZeroCurvatureEnding,
  21207. endingEnd: ZeroCurvatureEnding
  21208. },
  21209. intervalChanged_: function (i1, t0, t1) {
  21210. const pp = this.parameterPositions;
  21211. let iPrev = i1 - 2,
  21212. iNext = i1 + 1,
  21213. tPrev = pp[iPrev],
  21214. tNext = pp[iNext];
  21215. if (tPrev === undefined) {
  21216. switch (this.getSettings_().endingStart) {
  21217. case ZeroSlopeEnding:
  21218. // f'(t0) = 0
  21219. iPrev = i1;
  21220. tPrev = 2 * t0 - t1;
  21221. break;
  21222. case WrapAroundEnding:
  21223. // use the other end of the curve
  21224. iPrev = pp.length - 2;
  21225. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  21226. break;
  21227. default:
  21228. // ZeroCurvatureEnding
  21229. // f''(t0) = 0 a.k.a. Natural Spline
  21230. iPrev = i1;
  21231. tPrev = t1;
  21232. }
  21233. }
  21234. if (tNext === undefined) {
  21235. switch (this.getSettings_().endingEnd) {
  21236. case ZeroSlopeEnding:
  21237. // f'(tN) = 0
  21238. iNext = i1;
  21239. tNext = 2 * t1 - t0;
  21240. break;
  21241. case WrapAroundEnding:
  21242. // use the other end of the curve
  21243. iNext = 1;
  21244. tNext = t1 + pp[1] - pp[0];
  21245. break;
  21246. default:
  21247. // ZeroCurvatureEnding
  21248. // f''(tN) = 0, a.k.a. Natural Spline
  21249. iNext = i1 - 1;
  21250. tNext = t0;
  21251. }
  21252. }
  21253. const halfDt = (t1 - t0) * 0.5,
  21254. stride = this.valueSize;
  21255. this._weightPrev = halfDt / (t0 - tPrev);
  21256. this._weightNext = halfDt / (tNext - t1);
  21257. this._offsetPrev = iPrev * stride;
  21258. this._offsetNext = iNext * stride;
  21259. },
  21260. interpolate_: function (i1, t0, t, t1) {
  21261. const result = this.resultBuffer,
  21262. values = this.sampleValues,
  21263. stride = this.valueSize,
  21264. o1 = i1 * stride,
  21265. o0 = o1 - stride,
  21266. oP = this._offsetPrev,
  21267. oN = this._offsetNext,
  21268. wP = this._weightPrev,
  21269. wN = this._weightNext,
  21270. p = (t - t0) / (t1 - t0),
  21271. pp = p * p,
  21272. ppp = pp * p; // evaluate polynomials
  21273. const sP = -wP * ppp + 2 * wP * pp - wP * p;
  21274. const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  21275. const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  21276. const sN = wN * ppp - wN * pp; // combine data linearly
  21277. for (let i = 0; i !== stride; ++i) {
  21278. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  21279. }
  21280. return result;
  21281. }
  21282. });
  21283. function LinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21284. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21285. }
  21286. LinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21287. constructor: LinearInterpolant,
  21288. interpolate_: function (i1, t0, t, t1) {
  21289. const result = this.resultBuffer,
  21290. values = this.sampleValues,
  21291. stride = this.valueSize,
  21292. offset1 = i1 * stride,
  21293. offset0 = offset1 - stride,
  21294. weight1 = (t - t0) / (t1 - t0),
  21295. weight0 = 1 - weight1;
  21296. for (let i = 0; i !== stride; ++i) {
  21297. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  21298. }
  21299. return result;
  21300. }
  21301. });
  21302. /**
  21303. *
  21304. * Interpolant that evaluates to the sample value at the position preceeding
  21305. * the parameter.
  21306. */
  21307. function DiscreteInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21308. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21309. }
  21310. DiscreteInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21311. constructor: DiscreteInterpolant,
  21312. interpolate_: function (i1
  21313. /*, t0, t, t1 */
  21314. ) {
  21315. return this.copySampleValue_(i1 - 1);
  21316. }
  21317. });
  21318. function KeyframeTrack(name, times, values, interpolation) {
  21319. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  21320. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  21321. this.name = name;
  21322. this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
  21323. this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
  21324. this.setInterpolation(interpolation || this.DefaultInterpolation);
  21325. } // Static methods
  21326. Object.assign(KeyframeTrack, {
  21327. // Serialization (in static context, because of constructor invocation
  21328. // and automatic invocation of .toJSON):
  21329. toJSON: function (track) {
  21330. const trackType = track.constructor;
  21331. let json; // derived classes can define a static toJSON method
  21332. if (trackType.toJSON !== undefined) {
  21333. json = trackType.toJSON(track);
  21334. } else {
  21335. // by default, we assume the data can be serialized as-is
  21336. json = {
  21337. 'name': track.name,
  21338. 'times': AnimationUtils.convertArray(track.times, Array),
  21339. 'values': AnimationUtils.convertArray(track.values, Array)
  21340. };
  21341. const interpolation = track.getInterpolation();
  21342. if (interpolation !== track.DefaultInterpolation) {
  21343. json.interpolation = interpolation;
  21344. }
  21345. }
  21346. json.type = track.ValueTypeName; // mandatory
  21347. return json;
  21348. }
  21349. });
  21350. Object.assign(KeyframeTrack.prototype, {
  21351. constructor: KeyframeTrack,
  21352. TimeBufferType: Float32Array,
  21353. ValueBufferType: Float32Array,
  21354. DefaultInterpolation: InterpolateLinear,
  21355. InterpolantFactoryMethodDiscrete: function (result) {
  21356. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  21357. },
  21358. InterpolantFactoryMethodLinear: function (result) {
  21359. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  21360. },
  21361. InterpolantFactoryMethodSmooth: function (result) {
  21362. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  21363. },
  21364. setInterpolation: function (interpolation) {
  21365. let factoryMethod;
  21366. switch (interpolation) {
  21367. case InterpolateDiscrete:
  21368. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  21369. break;
  21370. case InterpolateLinear:
  21371. factoryMethod = this.InterpolantFactoryMethodLinear;
  21372. break;
  21373. case InterpolateSmooth:
  21374. factoryMethod = this.InterpolantFactoryMethodSmooth;
  21375. break;
  21376. }
  21377. if (factoryMethod === undefined) {
  21378. const message = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name;
  21379. if (this.createInterpolant === undefined) {
  21380. // fall back to default, unless the default itself is messed up
  21381. if (interpolation !== this.DefaultInterpolation) {
  21382. this.setInterpolation(this.DefaultInterpolation);
  21383. } else {
  21384. throw new Error(message); // fatal, in this case
  21385. }
  21386. }
  21387. console.warn('THREE.KeyframeTrack:', message);
  21388. return this;
  21389. }
  21390. this.createInterpolant = factoryMethod;
  21391. return this;
  21392. },
  21393. getInterpolation: function () {
  21394. switch (this.createInterpolant) {
  21395. case this.InterpolantFactoryMethodDiscrete:
  21396. return InterpolateDiscrete;
  21397. case this.InterpolantFactoryMethodLinear:
  21398. return InterpolateLinear;
  21399. case this.InterpolantFactoryMethodSmooth:
  21400. return InterpolateSmooth;
  21401. }
  21402. },
  21403. getValueSize: function () {
  21404. return this.values.length / this.times.length;
  21405. },
  21406. // move all keyframes either forwards or backwards in time
  21407. shift: function (timeOffset) {
  21408. if (timeOffset !== 0.0) {
  21409. const times = this.times;
  21410. for (let i = 0, n = times.length; i !== n; ++i) {
  21411. times[i] += timeOffset;
  21412. }
  21413. }
  21414. return this;
  21415. },
  21416. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  21417. scale: function (timeScale) {
  21418. if (timeScale !== 1.0) {
  21419. const times = this.times;
  21420. for (let i = 0, n = times.length; i !== n; ++i) {
  21421. times[i] *= timeScale;
  21422. }
  21423. }
  21424. return this;
  21425. },
  21426. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  21427. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  21428. trim: function (startTime, endTime) {
  21429. const times = this.times,
  21430. nKeys = times.length;
  21431. let from = 0,
  21432. to = nKeys - 1;
  21433. while (from !== nKeys && times[from] < startTime) {
  21434. ++from;
  21435. }
  21436. while (to !== -1 && times[to] > endTime) {
  21437. --to;
  21438. }
  21439. ++to; // inclusive -> exclusive bound
  21440. if (from !== 0 || to !== nKeys) {
  21441. // empty tracks are forbidden, so keep at least one keyframe
  21442. if (from >= to) {
  21443. to = Math.max(to, 1);
  21444. from = to - 1;
  21445. }
  21446. const stride = this.getValueSize();
  21447. this.times = AnimationUtils.arraySlice(times, from, to);
  21448. this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
  21449. }
  21450. return this;
  21451. },
  21452. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  21453. validate: function () {
  21454. let valid = true;
  21455. const valueSize = this.getValueSize();
  21456. if (valueSize - Math.floor(valueSize) !== 0) {
  21457. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  21458. valid = false;
  21459. }
  21460. const times = this.times,
  21461. values = this.values,
  21462. nKeys = times.length;
  21463. if (nKeys === 0) {
  21464. console.error('THREE.KeyframeTrack: Track is empty.', this);
  21465. valid = false;
  21466. }
  21467. let prevTime = null;
  21468. for (let i = 0; i !== nKeys; i++) {
  21469. const currTime = times[i];
  21470. if (typeof currTime === 'number' && isNaN(currTime)) {
  21471. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  21472. valid = false;
  21473. break;
  21474. }
  21475. if (prevTime !== null && prevTime > currTime) {
  21476. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  21477. valid = false;
  21478. break;
  21479. }
  21480. prevTime = currTime;
  21481. }
  21482. if (values !== undefined) {
  21483. if (AnimationUtils.isTypedArray(values)) {
  21484. for (let i = 0, n = values.length; i !== n; ++i) {
  21485. const value = values[i];
  21486. if (isNaN(value)) {
  21487. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  21488. valid = false;
  21489. break;
  21490. }
  21491. }
  21492. }
  21493. }
  21494. return valid;
  21495. },
  21496. // removes equivalent sequential keys as common in morph target sequences
  21497. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  21498. optimize: function () {
  21499. // times or values may be shared with other tracks, so overwriting is unsafe
  21500. const times = AnimationUtils.arraySlice(this.times),
  21501. values = AnimationUtils.arraySlice(this.values),
  21502. stride = this.getValueSize(),
  21503. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  21504. lastIndex = times.length - 1;
  21505. let writeIndex = 1;
  21506. for (let i = 1; i < lastIndex; ++i) {
  21507. let keep = false;
  21508. const time = times[i];
  21509. const timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  21510. if (time !== timeNext && (i !== 1 || time !== time[0])) {
  21511. if (!smoothInterpolation) {
  21512. // remove unnecessary keyframes same as their neighbors
  21513. const offset = i * stride,
  21514. offsetP = offset - stride,
  21515. offsetN = offset + stride;
  21516. for (let j = 0; j !== stride; ++j) {
  21517. const value = values[offset + j];
  21518. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  21519. keep = true;
  21520. break;
  21521. }
  21522. }
  21523. } else {
  21524. keep = true;
  21525. }
  21526. } // in-place compaction
  21527. if (keep) {
  21528. if (i !== writeIndex) {
  21529. times[writeIndex] = times[i];
  21530. const readOffset = i * stride,
  21531. writeOffset = writeIndex * stride;
  21532. for (let j = 0; j !== stride; ++j) {
  21533. values[writeOffset + j] = values[readOffset + j];
  21534. }
  21535. }
  21536. ++writeIndex;
  21537. }
  21538. } // flush last keyframe (compaction looks ahead)
  21539. if (lastIndex > 0) {
  21540. times[writeIndex] = times[lastIndex];
  21541. for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  21542. values[writeOffset + j] = values[readOffset + j];
  21543. }
  21544. ++writeIndex;
  21545. }
  21546. if (writeIndex !== times.length) {
  21547. this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
  21548. this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
  21549. } else {
  21550. this.times = times;
  21551. this.values = values;
  21552. }
  21553. return this;
  21554. },
  21555. clone: function () {
  21556. const times = AnimationUtils.arraySlice(this.times, 0);
  21557. const values = AnimationUtils.arraySlice(this.values, 0);
  21558. const TypedKeyframeTrack = this.constructor;
  21559. const track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  21560. track.createInterpolant = this.createInterpolant;
  21561. return track;
  21562. }
  21563. });
  21564. /**
  21565. * A Track of Boolean keyframe values.
  21566. */
  21567. function BooleanKeyframeTrack(name, times, values) {
  21568. KeyframeTrack.call(this, name, times, values);
  21569. }
  21570. BooleanKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21571. constructor: BooleanKeyframeTrack,
  21572. ValueTypeName: 'bool',
  21573. ValueBufferType: Array,
  21574. DefaultInterpolation: InterpolateDiscrete,
  21575. InterpolantFactoryMethodLinear: undefined,
  21576. InterpolantFactoryMethodSmooth: undefined // Note: Actually this track could have a optimized / compressed
  21577. // representation of a single value and a custom interpolant that
  21578. // computes "firstValue ^ isOdd( index )".
  21579. });
  21580. /**
  21581. * A Track of keyframe values that represent color.
  21582. */
  21583. function ColorKeyframeTrack(name, times, values, interpolation) {
  21584. KeyframeTrack.call(this, name, times, values, interpolation);
  21585. }
  21586. ColorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21587. constructor: ColorKeyframeTrack,
  21588. ValueTypeName: 'color' // ValueBufferType is inherited
  21589. // DefaultInterpolation is inherited
  21590. // Note: Very basic implementation and nothing special yet.
  21591. // However, this is the place for color space parameterization.
  21592. });
  21593. /**
  21594. * A Track of numeric keyframe values.
  21595. */
  21596. function NumberKeyframeTrack(name, times, values, interpolation) {
  21597. KeyframeTrack.call(this, name, times, values, interpolation);
  21598. }
  21599. NumberKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21600. constructor: NumberKeyframeTrack,
  21601. ValueTypeName: 'number' // ValueBufferType is inherited
  21602. // DefaultInterpolation is inherited
  21603. });
  21604. /**
  21605. * Spherical linear unit quaternion interpolant.
  21606. */
  21607. function QuaternionLinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21608. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21609. }
  21610. QuaternionLinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21611. constructor: QuaternionLinearInterpolant,
  21612. interpolate_: function (i1, t0, t, t1) {
  21613. const result = this.resultBuffer,
  21614. values = this.sampleValues,
  21615. stride = this.valueSize,
  21616. alpha = (t - t0) / (t1 - t0);
  21617. let offset = i1 * stride;
  21618. for (let end = offset + stride; offset !== end; offset += 4) {
  21619. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  21620. }
  21621. return result;
  21622. }
  21623. });
  21624. /**
  21625. * A Track of quaternion keyframe values.
  21626. */
  21627. function QuaternionKeyframeTrack(name, times, values, interpolation) {
  21628. KeyframeTrack.call(this, name, times, values, interpolation);
  21629. }
  21630. QuaternionKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21631. constructor: QuaternionKeyframeTrack,
  21632. ValueTypeName: 'quaternion',
  21633. // ValueBufferType is inherited
  21634. DefaultInterpolation: InterpolateLinear,
  21635. InterpolantFactoryMethodLinear: function (result) {
  21636. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  21637. },
  21638. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  21639. });
  21640. /**
  21641. * A Track that interpolates Strings
  21642. */
  21643. function StringKeyframeTrack(name, times, values, interpolation) {
  21644. KeyframeTrack.call(this, name, times, values, interpolation);
  21645. }
  21646. StringKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21647. constructor: StringKeyframeTrack,
  21648. ValueTypeName: 'string',
  21649. ValueBufferType: Array,
  21650. DefaultInterpolation: InterpolateDiscrete,
  21651. InterpolantFactoryMethodLinear: undefined,
  21652. InterpolantFactoryMethodSmooth: undefined
  21653. });
  21654. /**
  21655. * A Track of vectored keyframe values.
  21656. */
  21657. function VectorKeyframeTrack(name, times, values, interpolation) {
  21658. KeyframeTrack.call(this, name, times, values, interpolation);
  21659. }
  21660. VectorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21661. constructor: VectorKeyframeTrack,
  21662. ValueTypeName: 'vector' // ValueBufferType is inherited
  21663. // DefaultInterpolation is inherited
  21664. });
  21665. function AnimationClip(name, duration, tracks, blendMode) {
  21666. this.name = name;
  21667. this.tracks = tracks;
  21668. this.duration = duration !== undefined ? duration : -1;
  21669. this.blendMode = blendMode !== undefined ? blendMode : NormalAnimationBlendMode;
  21670. this.uuid = MathUtils.generateUUID(); // this means it should figure out its duration by scanning the tracks
  21671. if (this.duration < 0) {
  21672. this.resetDuration();
  21673. }
  21674. }
  21675. function getTrackTypeForValueTypeName(typeName) {
  21676. switch (typeName.toLowerCase()) {
  21677. case 'scalar':
  21678. case 'double':
  21679. case 'float':
  21680. case 'number':
  21681. case 'integer':
  21682. return NumberKeyframeTrack;
  21683. case 'vector':
  21684. case 'vector2':
  21685. case 'vector3':
  21686. case 'vector4':
  21687. return VectorKeyframeTrack;
  21688. case 'color':
  21689. return ColorKeyframeTrack;
  21690. case 'quaternion':
  21691. return QuaternionKeyframeTrack;
  21692. case 'bool':
  21693. case 'boolean':
  21694. return BooleanKeyframeTrack;
  21695. case 'string':
  21696. return StringKeyframeTrack;
  21697. }
  21698. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  21699. }
  21700. function parseKeyframeTrack(json) {
  21701. if (json.type === undefined) {
  21702. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  21703. }
  21704. const trackType = getTrackTypeForValueTypeName(json.type);
  21705. if (json.times === undefined) {
  21706. const times = [],
  21707. values = [];
  21708. AnimationUtils.flattenJSON(json.keys, times, values, 'value');
  21709. json.times = times;
  21710. json.values = values;
  21711. } // derived classes can define a static parse method
  21712. if (trackType.parse !== undefined) {
  21713. return trackType.parse(json);
  21714. } else {
  21715. // by default, we assume a constructor compatible with the base
  21716. return new trackType(json.name, json.times, json.values, json.interpolation);
  21717. }
  21718. }
  21719. Object.assign(AnimationClip, {
  21720. parse: function (json) {
  21721. const tracks = [],
  21722. jsonTracks = json.tracks,
  21723. frameTime = 1.0 / (json.fps || 1.0);
  21724. for (let i = 0, n = jsonTracks.length; i !== n; ++i) {
  21725. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  21726. }
  21727. const clip = new AnimationClip(json.name, json.duration, tracks, json.blendMode);
  21728. clip.uuid = json.uuid;
  21729. return clip;
  21730. },
  21731. toJSON: function (clip) {
  21732. const tracks = [],
  21733. clipTracks = clip.tracks;
  21734. const json = {
  21735. 'name': clip.name,
  21736. 'duration': clip.duration,
  21737. 'tracks': tracks,
  21738. 'uuid': clip.uuid,
  21739. 'blendMode': clip.blendMode
  21740. };
  21741. for (let i = 0, n = clipTracks.length; i !== n; ++i) {
  21742. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  21743. }
  21744. return json;
  21745. },
  21746. CreateFromMorphTargetSequence: function (name, morphTargetSequence, fps, noLoop) {
  21747. const numMorphTargets = morphTargetSequence.length;
  21748. const tracks = [];
  21749. for (let i = 0; i < numMorphTargets; i++) {
  21750. let times = [];
  21751. let values = [];
  21752. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  21753. values.push(0, 1, 0);
  21754. const order = AnimationUtils.getKeyframeOrder(times);
  21755. times = AnimationUtils.sortedArray(times, 1, order);
  21756. values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  21757. // last frame as well for perfect loop.
  21758. if (!noLoop && times[0] === 0) {
  21759. times.push(numMorphTargets);
  21760. values.push(values[0]);
  21761. }
  21762. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  21763. }
  21764. return new AnimationClip(name, -1, tracks);
  21765. },
  21766. findByName: function (objectOrClipArray, name) {
  21767. let clipArray = objectOrClipArray;
  21768. if (!Array.isArray(objectOrClipArray)) {
  21769. const o = objectOrClipArray;
  21770. clipArray = o.geometry && o.geometry.animations || o.animations;
  21771. }
  21772. for (let i = 0; i < clipArray.length; i++) {
  21773. if (clipArray[i].name === name) {
  21774. return clipArray[i];
  21775. }
  21776. }
  21777. return null;
  21778. },
  21779. CreateClipsFromMorphTargetSequences: function (morphTargets, fps, noLoop) {
  21780. const animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  21781. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  21782. const pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  21783. // patterns like Walk_001, Walk_002, Run_001, Run_002
  21784. for (let i = 0, il = morphTargets.length; i < il; i++) {
  21785. const morphTarget = morphTargets[i];
  21786. const parts = morphTarget.name.match(pattern);
  21787. if (parts && parts.length > 1) {
  21788. const name = parts[1];
  21789. let animationMorphTargets = animationToMorphTargets[name];
  21790. if (!animationMorphTargets) {
  21791. animationToMorphTargets[name] = animationMorphTargets = [];
  21792. }
  21793. animationMorphTargets.push(morphTarget);
  21794. }
  21795. }
  21796. const clips = [];
  21797. for (const name in animationToMorphTargets) {
  21798. clips.push(AnimationClip.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  21799. }
  21800. return clips;
  21801. },
  21802. // parse the animation.hierarchy format
  21803. parseAnimation: function (animation, bones) {
  21804. if (!animation) {
  21805. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  21806. return null;
  21807. }
  21808. const addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  21809. // only return track if there are actually keys.
  21810. if (animationKeys.length !== 0) {
  21811. const times = [];
  21812. const values = [];
  21813. AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  21814. if (times.length !== 0) {
  21815. destTracks.push(new trackType(trackName, times, values));
  21816. }
  21817. }
  21818. };
  21819. const tracks = [];
  21820. const clipName = animation.name || 'default';
  21821. const fps = animation.fps || 30;
  21822. const blendMode = animation.blendMode; // automatic length determination in AnimationClip.
  21823. let duration = animation.length || -1;
  21824. const hierarchyTracks = animation.hierarchy || [];
  21825. for (let h = 0; h < hierarchyTracks.length; h++) {
  21826. const animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  21827. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  21828. if (animationKeys[0].morphTargets) {
  21829. // figure out all morph targets used in this track
  21830. const morphTargetNames = {};
  21831. let k;
  21832. for (k = 0; k < animationKeys.length; k++) {
  21833. if (animationKeys[k].morphTargets) {
  21834. for (let m = 0; m < animationKeys[k].morphTargets.length; m++) {
  21835. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  21836. }
  21837. }
  21838. } // create a track for each morph target with all zero
  21839. // morphTargetInfluences except for the keys in which
  21840. // the morphTarget is named.
  21841. for (const morphTargetName in morphTargetNames) {
  21842. const times = [];
  21843. const values = [];
  21844. for (let m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  21845. const animationKey = animationKeys[k];
  21846. times.push(animationKey.time);
  21847. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  21848. }
  21849. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  21850. }
  21851. duration = morphTargetNames.length * (fps || 1.0);
  21852. } else {
  21853. // ...assume skeletal animation
  21854. const boneName = '.bones[' + bones[h].name + ']';
  21855. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  21856. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  21857. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  21858. }
  21859. }
  21860. if (tracks.length === 0) {
  21861. return null;
  21862. }
  21863. const clip = new AnimationClip(clipName, duration, tracks, blendMode);
  21864. return clip;
  21865. }
  21866. });
  21867. Object.assign(AnimationClip.prototype, {
  21868. resetDuration: function () {
  21869. const tracks = this.tracks;
  21870. let duration = 0;
  21871. for (let i = 0, n = tracks.length; i !== n; ++i) {
  21872. const track = this.tracks[i];
  21873. duration = Math.max(duration, track.times[track.times.length - 1]);
  21874. }
  21875. this.duration = duration;
  21876. return this;
  21877. },
  21878. trim: function () {
  21879. for (let i = 0; i < this.tracks.length; i++) {
  21880. this.tracks[i].trim(0, this.duration);
  21881. }
  21882. return this;
  21883. },
  21884. validate: function () {
  21885. let valid = true;
  21886. for (let i = 0; i < this.tracks.length; i++) {
  21887. valid = valid && this.tracks[i].validate();
  21888. }
  21889. return valid;
  21890. },
  21891. optimize: function () {
  21892. for (let i = 0; i < this.tracks.length; i++) {
  21893. this.tracks[i].optimize();
  21894. }
  21895. return this;
  21896. },
  21897. clone: function () {
  21898. const tracks = [];
  21899. for (let i = 0; i < this.tracks.length; i++) {
  21900. tracks.push(this.tracks[i].clone());
  21901. }
  21902. return new AnimationClip(this.name, this.duration, tracks, this.blendMode);
  21903. },
  21904. toJSON: function () {
  21905. return AnimationClip.toJSON(this);
  21906. }
  21907. });
  21908. const Cache = {
  21909. enabled: false,
  21910. files: {},
  21911. add: function (key, file) {
  21912. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  21913. this.files[key] = file;
  21914. },
  21915. get: function (key) {
  21916. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  21917. return this.files[key];
  21918. },
  21919. remove: function (key) {
  21920. delete this.files[key];
  21921. },
  21922. clear: function () {
  21923. this.files = {};
  21924. }
  21925. };
  21926. exports.Cache = Cache;
  21927. function LoadingManager(onLoad, onProgress, onError) {
  21928. const scope = this;
  21929. let isLoading = false;
  21930. let itemsLoaded = 0;
  21931. let itemsTotal = 0;
  21932. let urlModifier = undefined;
  21933. const handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  21934. // in the constructor
  21935. this.onStart = undefined;
  21936. this.onLoad = onLoad;
  21937. this.onProgress = onProgress;
  21938. this.onError = onError;
  21939. this.itemStart = function (url) {
  21940. itemsTotal++;
  21941. if (isLoading === false) {
  21942. if (scope.onStart !== undefined) {
  21943. scope.onStart(url, itemsLoaded, itemsTotal);
  21944. }
  21945. }
  21946. isLoading = true;
  21947. };
  21948. this.itemEnd = function (url) {
  21949. itemsLoaded++;
  21950. if (scope.onProgress !== undefined) {
  21951. scope.onProgress(url, itemsLoaded, itemsTotal);
  21952. }
  21953. if (itemsLoaded === itemsTotal) {
  21954. isLoading = false;
  21955. if (scope.onLoad !== undefined) {
  21956. scope.onLoad();
  21957. }
  21958. }
  21959. };
  21960. this.itemError = function (url) {
  21961. if (scope.onError !== undefined) {
  21962. scope.onError(url);
  21963. }
  21964. };
  21965. this.resolveURL = function (url) {
  21966. if (urlModifier) {
  21967. return urlModifier(url);
  21968. }
  21969. return url;
  21970. };
  21971. this.setURLModifier = function (transform) {
  21972. urlModifier = transform;
  21973. return this;
  21974. };
  21975. this.addHandler = function (regex, loader) {
  21976. handlers.push(regex, loader);
  21977. return this;
  21978. };
  21979. this.removeHandler = function (regex) {
  21980. const index = handlers.indexOf(regex);
  21981. if (index !== -1) {
  21982. handlers.splice(index, 2);
  21983. }
  21984. return this;
  21985. };
  21986. this.getHandler = function (file) {
  21987. for (let i = 0, l = handlers.length; i < l; i += 2) {
  21988. const regex = handlers[i];
  21989. const loader = handlers[i + 1];
  21990. if (regex.global) regex.lastIndex = 0; // see #17920
  21991. if (regex.test(file)) {
  21992. return loader;
  21993. }
  21994. }
  21995. return null;
  21996. };
  21997. }
  21998. const DefaultLoadingManager = new LoadingManager();
  21999. exports.DefaultLoadingManager = DefaultLoadingManager;
  22000. function Loader(manager) {
  22001. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  22002. this.crossOrigin = 'anonymous';
  22003. this.withCredentials = false;
  22004. this.path = '';
  22005. this.resourcePath = '';
  22006. this.requestHeader = {};
  22007. }
  22008. Object.assign(Loader.prototype, {
  22009. load: function ()
  22010. /* url, onLoad, onProgress, onError */
  22011. {},
  22012. loadAsync: function (url, onProgress) {
  22013. const scope = this;
  22014. return new Promise(function (resolve, reject) {
  22015. scope.load(url, resolve, onProgress, reject);
  22016. });
  22017. },
  22018. parse: function ()
  22019. /* data */
  22020. {},
  22021. setCrossOrigin: function (crossOrigin) {
  22022. this.crossOrigin = crossOrigin;
  22023. return this;
  22024. },
  22025. setWithCredentials: function (value) {
  22026. this.withCredentials = value;
  22027. return this;
  22028. },
  22029. setPath: function (path) {
  22030. this.path = path;
  22031. return this;
  22032. },
  22033. setResourcePath: function (resourcePath) {
  22034. this.resourcePath = resourcePath;
  22035. return this;
  22036. },
  22037. setRequestHeader: function (requestHeader) {
  22038. this.requestHeader = requestHeader;
  22039. return this;
  22040. }
  22041. });
  22042. const loading = {};
  22043. function FileLoader(manager) {
  22044. Loader.call(this, manager);
  22045. }
  22046. FileLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22047. constructor: FileLoader,
  22048. load: function (url, onLoad, onProgress, onError) {
  22049. if (url === undefined) url = '';
  22050. if (this.path !== undefined) url = this.path + url;
  22051. url = this.manager.resolveURL(url);
  22052. const scope = this;
  22053. const cached = Cache.get(url);
  22054. if (cached !== undefined) {
  22055. scope.manager.itemStart(url);
  22056. setTimeout(function () {
  22057. if (onLoad) onLoad(cached);
  22058. scope.manager.itemEnd(url);
  22059. }, 0);
  22060. return cached;
  22061. } // Check if request is duplicate
  22062. if (loading[url] !== undefined) {
  22063. loading[url].push({
  22064. onLoad: onLoad,
  22065. onProgress: onProgress,
  22066. onError: onError
  22067. });
  22068. return;
  22069. } // Check for data: URI
  22070. const dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  22071. const dataUriRegexResult = url.match(dataUriRegex);
  22072. let request; // Safari can not handle Data URIs through XMLHttpRequest so process manually
  22073. if (dataUriRegexResult) {
  22074. const mimeType = dataUriRegexResult[1];
  22075. const isBase64 = !!dataUriRegexResult[2];
  22076. let data = dataUriRegexResult[3];
  22077. data = decodeURIComponent(data);
  22078. if (isBase64) data = atob(data);
  22079. try {
  22080. let response;
  22081. const responseType = (this.responseType || '').toLowerCase();
  22082. switch (responseType) {
  22083. case 'arraybuffer':
  22084. case 'blob':
  22085. const view = new Uint8Array(data.length);
  22086. for (let i = 0; i < data.length; i++) {
  22087. view[i] = data.charCodeAt(i);
  22088. }
  22089. if (responseType === 'blob') {
  22090. response = new Blob([view.buffer], {
  22091. type: mimeType
  22092. });
  22093. } else {
  22094. response = view.buffer;
  22095. }
  22096. break;
  22097. case 'document':
  22098. const parser = new DOMParser();
  22099. response = parser.parseFromString(data, mimeType);
  22100. break;
  22101. case 'json':
  22102. response = JSON.parse(data);
  22103. break;
  22104. default:
  22105. // 'text' or other
  22106. response = data;
  22107. break;
  22108. } // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22109. setTimeout(function () {
  22110. if (onLoad) onLoad(response);
  22111. scope.manager.itemEnd(url);
  22112. }, 0);
  22113. } catch (error) {
  22114. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22115. setTimeout(function () {
  22116. if (onError) onError(error);
  22117. scope.manager.itemError(url);
  22118. scope.manager.itemEnd(url);
  22119. }, 0);
  22120. }
  22121. } else {
  22122. // Initialise array for duplicate requests
  22123. loading[url] = [];
  22124. loading[url].push({
  22125. onLoad: onLoad,
  22126. onProgress: onProgress,
  22127. onError: onError
  22128. });
  22129. request = new XMLHttpRequest();
  22130. request.open('GET', url, true);
  22131. request.addEventListener('load', function (event) {
  22132. const response = this.response;
  22133. const callbacks = loading[url];
  22134. delete loading[url];
  22135. if (this.status === 200 || this.status === 0) {
  22136. // Some browsers return HTTP Status 0 when using non-http protocol
  22137. // e.g. 'file://' or 'data://'. Handle as success.
  22138. if (this.status === 0) console.warn('THREE.FileLoader: HTTP Status 0 received.'); // Add to cache only on HTTP success, so that we do not cache
  22139. // error response bodies as proper responses to requests.
  22140. Cache.add(url, response);
  22141. for (let i = 0, il = callbacks.length; i < il; i++) {
  22142. const callback = callbacks[i];
  22143. if (callback.onLoad) callback.onLoad(response);
  22144. }
  22145. scope.manager.itemEnd(url);
  22146. } else {
  22147. for (let i = 0, il = callbacks.length; i < il; i++) {
  22148. const callback = callbacks[i];
  22149. if (callback.onError) callback.onError(event);
  22150. }
  22151. scope.manager.itemError(url);
  22152. scope.manager.itemEnd(url);
  22153. }
  22154. }, false);
  22155. request.addEventListener('progress', function (event) {
  22156. const callbacks = loading[url];
  22157. for (let i = 0, il = callbacks.length; i < il; i++) {
  22158. const callback = callbacks[i];
  22159. if (callback.onProgress) callback.onProgress(event);
  22160. }
  22161. }, false);
  22162. request.addEventListener('error', function (event) {
  22163. const callbacks = loading[url];
  22164. delete loading[url];
  22165. for (let i = 0, il = callbacks.length; i < il; i++) {
  22166. const callback = callbacks[i];
  22167. if (callback.onError) callback.onError(event);
  22168. }
  22169. scope.manager.itemError(url);
  22170. scope.manager.itemEnd(url);
  22171. }, false);
  22172. request.addEventListener('abort', function (event) {
  22173. const callbacks = loading[url];
  22174. delete loading[url];
  22175. for (let i = 0, il = callbacks.length; i < il; i++) {
  22176. const callback = callbacks[i];
  22177. if (callback.onError) callback.onError(event);
  22178. }
  22179. scope.manager.itemError(url);
  22180. scope.manager.itemEnd(url);
  22181. }, false);
  22182. if (this.responseType !== undefined) request.responseType = this.responseType;
  22183. if (this.withCredentials !== undefined) request.withCredentials = this.withCredentials;
  22184. if (request.overrideMimeType) request.overrideMimeType(this.mimeType !== undefined ? this.mimeType : 'text/plain');
  22185. for (const header in this.requestHeader) {
  22186. request.setRequestHeader(header, this.requestHeader[header]);
  22187. }
  22188. request.send(null);
  22189. }
  22190. scope.manager.itemStart(url);
  22191. return request;
  22192. },
  22193. setResponseType: function (value) {
  22194. this.responseType = value;
  22195. return this;
  22196. },
  22197. setMimeType: function (value) {
  22198. this.mimeType = value;
  22199. return this;
  22200. }
  22201. });
  22202. function AnimationLoader(manager) {
  22203. Loader.call(this, manager);
  22204. }
  22205. AnimationLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22206. constructor: AnimationLoader,
  22207. load: function (url, onLoad, onProgress, onError) {
  22208. const scope = this;
  22209. const loader = new FileLoader(scope.manager);
  22210. loader.setPath(scope.path);
  22211. loader.setRequestHeader(scope.requestHeader);
  22212. loader.setWithCredentials(scope.withCredentials);
  22213. loader.load(url, function (text) {
  22214. try {
  22215. onLoad(scope.parse(JSON.parse(text)));
  22216. } catch (e) {
  22217. if (onError) {
  22218. onError(e);
  22219. } else {
  22220. console.error(e);
  22221. }
  22222. scope.manager.itemError(url);
  22223. }
  22224. }, onProgress, onError);
  22225. },
  22226. parse: function (json) {
  22227. const animations = [];
  22228. for (let i = 0; i < json.length; i++) {
  22229. const clip = AnimationClip.parse(json[i]);
  22230. animations.push(clip);
  22231. }
  22232. return animations;
  22233. }
  22234. });
  22235. /**
  22236. * Abstract Base class to block based textures loader (dds, pvr, ...)
  22237. *
  22238. * Sub classes have to implement the parse() method which will be used in load().
  22239. */
  22240. function CompressedTextureLoader(manager) {
  22241. Loader.call(this, manager);
  22242. }
  22243. CompressedTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22244. constructor: CompressedTextureLoader,
  22245. load: function (url, onLoad, onProgress, onError) {
  22246. const scope = this;
  22247. const images = [];
  22248. const texture = new CompressedTexture();
  22249. texture.image = images;
  22250. const loader = new FileLoader(this.manager);
  22251. loader.setPath(this.path);
  22252. loader.setResponseType('arraybuffer');
  22253. loader.setRequestHeader(this.requestHeader);
  22254. loader.setWithCredentials(scope.withCredentials);
  22255. let loaded = 0;
  22256. function loadTexture(i) {
  22257. loader.load(url[i], function (buffer) {
  22258. const texDatas = scope.parse(buffer, true);
  22259. images[i] = {
  22260. width: texDatas.width,
  22261. height: texDatas.height,
  22262. format: texDatas.format,
  22263. mipmaps: texDatas.mipmaps
  22264. };
  22265. loaded += 1;
  22266. if (loaded === 6) {
  22267. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  22268. texture.format = texDatas.format;
  22269. texture.needsUpdate = true;
  22270. if (onLoad) onLoad(texture);
  22271. }
  22272. }, onProgress, onError);
  22273. }
  22274. if (Array.isArray(url)) {
  22275. for (let i = 0, il = url.length; i < il; ++i) {
  22276. loadTexture(i);
  22277. }
  22278. } else {
  22279. // compressed cubemap texture stored in a single DDS file
  22280. loader.load(url, function (buffer) {
  22281. const texDatas = scope.parse(buffer, true);
  22282. if (texDatas.isCubemap) {
  22283. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  22284. for (let f = 0; f < faces; f++) {
  22285. images[f] = {
  22286. mipmaps: []
  22287. };
  22288. for (let i = 0; i < texDatas.mipmapCount; i++) {
  22289. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  22290. images[f].format = texDatas.format;
  22291. images[f].width = texDatas.width;
  22292. images[f].height = texDatas.height;
  22293. }
  22294. }
  22295. } else {
  22296. texture.image.width = texDatas.width;
  22297. texture.image.height = texDatas.height;
  22298. texture.mipmaps = texDatas.mipmaps;
  22299. }
  22300. if (texDatas.mipmapCount === 1) {
  22301. texture.minFilter = LinearFilter;
  22302. }
  22303. texture.format = texDatas.format;
  22304. texture.needsUpdate = true;
  22305. if (onLoad) onLoad(texture);
  22306. }, onProgress, onError);
  22307. }
  22308. return texture;
  22309. }
  22310. });
  22311. function ImageLoader(manager) {
  22312. Loader.call(this, manager);
  22313. }
  22314. ImageLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22315. constructor: ImageLoader,
  22316. load: function (url, onLoad, onProgress, onError) {
  22317. if (this.path !== undefined) url = this.path + url;
  22318. url = this.manager.resolveURL(url);
  22319. const scope = this;
  22320. const cached = Cache.get(url);
  22321. if (cached !== undefined) {
  22322. scope.manager.itemStart(url);
  22323. setTimeout(function () {
  22324. if (onLoad) onLoad(cached);
  22325. scope.manager.itemEnd(url);
  22326. }, 0);
  22327. return cached;
  22328. }
  22329. const image = document.createElementNS('http://www.w3.org/1999/xhtml', 'img');
  22330. function onImageLoad() {
  22331. image.removeEventListener('load', onImageLoad, false);
  22332. image.removeEventListener('error', onImageError, false);
  22333. Cache.add(url, this);
  22334. if (onLoad) onLoad(this);
  22335. scope.manager.itemEnd(url);
  22336. }
  22337. function onImageError(event) {
  22338. image.removeEventListener('load', onImageLoad, false);
  22339. image.removeEventListener('error', onImageError, false);
  22340. if (onError) onError(event);
  22341. scope.manager.itemError(url);
  22342. scope.manager.itemEnd(url);
  22343. }
  22344. image.addEventListener('load', onImageLoad, false);
  22345. image.addEventListener('error', onImageError, false);
  22346. if (url.substr(0, 5) !== 'data:') {
  22347. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  22348. }
  22349. scope.manager.itemStart(url);
  22350. image.src = url;
  22351. return image;
  22352. }
  22353. });
  22354. function CubeTextureLoader(manager) {
  22355. Loader.call(this, manager);
  22356. }
  22357. CubeTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22358. constructor: CubeTextureLoader,
  22359. load: function (urls, onLoad, onProgress, onError) {
  22360. const texture = new CubeTexture();
  22361. const loader = new ImageLoader(this.manager);
  22362. loader.setCrossOrigin(this.crossOrigin);
  22363. loader.setPath(this.path);
  22364. let loaded = 0;
  22365. function loadTexture(i) {
  22366. loader.load(urls[i], function (image) {
  22367. texture.images[i] = image;
  22368. loaded++;
  22369. if (loaded === 6) {
  22370. texture.needsUpdate = true;
  22371. if (onLoad) onLoad(texture);
  22372. }
  22373. }, undefined, onError);
  22374. }
  22375. for (let i = 0; i < urls.length; ++i) {
  22376. loadTexture(i);
  22377. }
  22378. return texture;
  22379. }
  22380. });
  22381. /**
  22382. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  22383. *
  22384. * Sub classes have to implement the parse() method which will be used in load().
  22385. */
  22386. function DataTextureLoader(manager) {
  22387. Loader.call(this, manager);
  22388. }
  22389. DataTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22390. constructor: DataTextureLoader,
  22391. load: function (url, onLoad, onProgress, onError) {
  22392. const scope = this;
  22393. const texture = new DataTexture();
  22394. const loader = new FileLoader(this.manager);
  22395. loader.setResponseType('arraybuffer');
  22396. loader.setRequestHeader(this.requestHeader);
  22397. loader.setPath(this.path);
  22398. loader.setWithCredentials(scope.withCredentials);
  22399. loader.load(url, function (buffer) {
  22400. const texData = scope.parse(buffer);
  22401. if (!texData) return;
  22402. if (texData.image !== undefined) {
  22403. texture.image = texData.image;
  22404. } else if (texData.data !== undefined) {
  22405. texture.image.width = texData.width;
  22406. texture.image.height = texData.height;
  22407. texture.image.data = texData.data;
  22408. }
  22409. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  22410. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  22411. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  22412. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  22413. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  22414. if (texData.format !== undefined) {
  22415. texture.format = texData.format;
  22416. }
  22417. if (texData.type !== undefined) {
  22418. texture.type = texData.type;
  22419. }
  22420. if (texData.mipmaps !== undefined) {
  22421. texture.mipmaps = texData.mipmaps;
  22422. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  22423. }
  22424. if (texData.mipmapCount === 1) {
  22425. texture.minFilter = LinearFilter;
  22426. }
  22427. texture.needsUpdate = true;
  22428. if (onLoad) onLoad(texture, texData);
  22429. }, onProgress, onError);
  22430. return texture;
  22431. }
  22432. });
  22433. function TextureLoader(manager) {
  22434. Loader.call(this, manager);
  22435. }
  22436. TextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22437. constructor: TextureLoader,
  22438. load: function (url, onLoad, onProgress, onError) {
  22439. const texture = new Texture();
  22440. const loader = new ImageLoader(this.manager);
  22441. loader.setCrossOrigin(this.crossOrigin);
  22442. loader.setPath(this.path);
  22443. loader.load(url, function (image) {
  22444. texture.image = image; // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  22445. const isJPEG = url.search(/\.jpe?g($|\?)/i) > 0 || url.search(/^data\:image\/jpeg/) === 0;
  22446. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  22447. texture.needsUpdate = true;
  22448. if (onLoad !== undefined) {
  22449. onLoad(texture);
  22450. }
  22451. }, onProgress, onError);
  22452. return texture;
  22453. }
  22454. });
  22455. /**
  22456. * Extensible curve object.
  22457. *
  22458. * Some common of curve methods:
  22459. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  22460. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  22461. * .getPoints(), .getSpacedPoints()
  22462. * .getLength()
  22463. * .updateArcLengths()
  22464. *
  22465. * This following curves inherit from THREE.Curve:
  22466. *
  22467. * -- 2D curves --
  22468. * THREE.ArcCurve
  22469. * THREE.CubicBezierCurve
  22470. * THREE.EllipseCurve
  22471. * THREE.LineCurve
  22472. * THREE.QuadraticBezierCurve
  22473. * THREE.SplineCurve
  22474. *
  22475. * -- 3D curves --
  22476. * THREE.CatmullRomCurve3
  22477. * THREE.CubicBezierCurve3
  22478. * THREE.LineCurve3
  22479. * THREE.QuadraticBezierCurve3
  22480. *
  22481. * A series of curves can be represented as a THREE.CurvePath.
  22482. *
  22483. **/
  22484. function Curve() {
  22485. this.type = 'Curve';
  22486. this.arcLengthDivisions = 200;
  22487. }
  22488. Object.assign(Curve.prototype, {
  22489. // Virtual base class method to overwrite and implement in subclasses
  22490. // - t [0 .. 1]
  22491. getPoint: function ()
  22492. /* t, optionalTarget */
  22493. {
  22494. console.warn('THREE.Curve: .getPoint() not implemented.');
  22495. return null;
  22496. },
  22497. // Get point at relative position in curve according to arc length
  22498. // - u [0 .. 1]
  22499. getPointAt: function (u, optionalTarget) {
  22500. const t = this.getUtoTmapping(u);
  22501. return this.getPoint(t, optionalTarget);
  22502. },
  22503. // Get sequence of points using getPoint( t )
  22504. getPoints: function (divisions = 5) {
  22505. const points = [];
  22506. for (let d = 0; d <= divisions; d++) {
  22507. points.push(this.getPoint(d / divisions));
  22508. }
  22509. return points;
  22510. },
  22511. // Get sequence of points using getPointAt( u )
  22512. getSpacedPoints: function (divisions = 5) {
  22513. const points = [];
  22514. for (let d = 0; d <= divisions; d++) {
  22515. points.push(this.getPointAt(d / divisions));
  22516. }
  22517. return points;
  22518. },
  22519. // Get total curve arc length
  22520. getLength: function () {
  22521. const lengths = this.getLengths();
  22522. return lengths[lengths.length - 1];
  22523. },
  22524. // Get list of cumulative segment lengths
  22525. getLengths: function (divisions) {
  22526. if (divisions === undefined) divisions = this.arcLengthDivisions;
  22527. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  22528. return this.cacheArcLengths;
  22529. }
  22530. this.needsUpdate = false;
  22531. const cache = [];
  22532. let current,
  22533. last = this.getPoint(0);
  22534. let sum = 0;
  22535. cache.push(0);
  22536. for (let p = 1; p <= divisions; p++) {
  22537. current = this.getPoint(p / divisions);
  22538. sum += current.distanceTo(last);
  22539. cache.push(sum);
  22540. last = current;
  22541. }
  22542. this.cacheArcLengths = cache;
  22543. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  22544. },
  22545. updateArcLengths: function () {
  22546. this.needsUpdate = true;
  22547. this.getLengths();
  22548. },
  22549. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  22550. getUtoTmapping: function (u, distance) {
  22551. const arcLengths = this.getLengths();
  22552. let i = 0;
  22553. const il = arcLengths.length;
  22554. let targetArcLength; // The targeted u distance value to get
  22555. if (distance) {
  22556. targetArcLength = distance;
  22557. } else {
  22558. targetArcLength = u * arcLengths[il - 1];
  22559. } // binary search for the index with largest value smaller than target u distance
  22560. let low = 0,
  22561. high = il - 1,
  22562. comparison;
  22563. while (low <= high) {
  22564. 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
  22565. comparison = arcLengths[i] - targetArcLength;
  22566. if (comparison < 0) {
  22567. low = i + 1;
  22568. } else if (comparison > 0) {
  22569. high = i - 1;
  22570. } else {
  22571. high = i;
  22572. break; // DONE
  22573. }
  22574. }
  22575. i = high;
  22576. if (arcLengths[i] === targetArcLength) {
  22577. return i / (il - 1);
  22578. } // we could get finer grain at lengths, or use simple interpolation between two points
  22579. const lengthBefore = arcLengths[i];
  22580. const lengthAfter = arcLengths[i + 1];
  22581. const segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  22582. const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  22583. const t = (i + segmentFraction) / (il - 1);
  22584. return t;
  22585. },
  22586. // Returns a unit vector tangent at t
  22587. // In case any sub curve does not implement its tangent derivation,
  22588. // 2 points a small delta apart will be used to find its gradient
  22589. // which seems to give a reasonable approximation
  22590. getTangent: function (t, optionalTarget) {
  22591. const delta = 0.0001;
  22592. let t1 = t - delta;
  22593. let t2 = t + delta; // Capping in case of danger
  22594. if (t1 < 0) t1 = 0;
  22595. if (t2 > 1) t2 = 1;
  22596. const pt1 = this.getPoint(t1);
  22597. const pt2 = this.getPoint(t2);
  22598. const tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3());
  22599. tangent.copy(pt2).sub(pt1).normalize();
  22600. return tangent;
  22601. },
  22602. getTangentAt: function (u, optionalTarget) {
  22603. const t = this.getUtoTmapping(u);
  22604. return this.getTangent(t, optionalTarget);
  22605. },
  22606. computeFrenetFrames: function (segments, closed) {
  22607. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  22608. const normal = new Vector3();
  22609. const tangents = [];
  22610. const normals = [];
  22611. const binormals = [];
  22612. const vec = new Vector3();
  22613. const mat = new Matrix4(); // compute the tangent vectors for each segment on the curve
  22614. for (let i = 0; i <= segments; i++) {
  22615. const u = i / segments;
  22616. tangents[i] = this.getTangentAt(u, new Vector3());
  22617. tangents[i].normalize();
  22618. } // select an initial normal vector perpendicular to the first tangent vector,
  22619. // and in the direction of the minimum tangent xyz component
  22620. normals[0] = new Vector3();
  22621. binormals[0] = new Vector3();
  22622. let min = Number.MAX_VALUE;
  22623. const tx = Math.abs(tangents[0].x);
  22624. const ty = Math.abs(tangents[0].y);
  22625. const tz = Math.abs(tangents[0].z);
  22626. if (tx <= min) {
  22627. min = tx;
  22628. normal.set(1, 0, 0);
  22629. }
  22630. if (ty <= min) {
  22631. min = ty;
  22632. normal.set(0, 1, 0);
  22633. }
  22634. if (tz <= min) {
  22635. normal.set(0, 0, 1);
  22636. }
  22637. vec.crossVectors(tangents[0], normal).normalize();
  22638. normals[0].crossVectors(tangents[0], vec);
  22639. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  22640. for (let i = 1; i <= segments; i++) {
  22641. normals[i] = normals[i - 1].clone();
  22642. binormals[i] = binormals[i - 1].clone();
  22643. vec.crossVectors(tangents[i - 1], tangents[i]);
  22644. if (vec.length() > Number.EPSILON) {
  22645. vec.normalize();
  22646. const theta = Math.acos(MathUtils.clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  22647. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  22648. }
  22649. binormals[i].crossVectors(tangents[i], normals[i]);
  22650. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  22651. if (closed === true) {
  22652. let theta = Math.acos(MathUtils.clamp(normals[0].dot(normals[segments]), -1, 1));
  22653. theta /= segments;
  22654. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  22655. theta = -theta;
  22656. }
  22657. for (let i = 1; i <= segments; i++) {
  22658. // twist a little...
  22659. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  22660. binormals[i].crossVectors(tangents[i], normals[i]);
  22661. }
  22662. }
  22663. return {
  22664. tangents: tangents,
  22665. normals: normals,
  22666. binormals: binormals
  22667. };
  22668. },
  22669. clone: function () {
  22670. return new this.constructor().copy(this);
  22671. },
  22672. copy: function (source) {
  22673. this.arcLengthDivisions = source.arcLengthDivisions;
  22674. return this;
  22675. },
  22676. toJSON: function () {
  22677. const data = {
  22678. metadata: {
  22679. version: 4.5,
  22680. type: 'Curve',
  22681. generator: 'Curve.toJSON'
  22682. }
  22683. };
  22684. data.arcLengthDivisions = this.arcLengthDivisions;
  22685. data.type = this.type;
  22686. return data;
  22687. },
  22688. fromJSON: function (json) {
  22689. this.arcLengthDivisions = json.arcLengthDivisions;
  22690. return this;
  22691. }
  22692. });
  22693. function EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  22694. Curve.call(this);
  22695. this.type = 'EllipseCurve';
  22696. this.aX = aX || 0;
  22697. this.aY = aY || 0;
  22698. this.xRadius = xRadius || 1;
  22699. this.yRadius = yRadius || 1;
  22700. this.aStartAngle = aStartAngle || 0;
  22701. this.aEndAngle = aEndAngle || 2 * Math.PI;
  22702. this.aClockwise = aClockwise || false;
  22703. this.aRotation = aRotation || 0;
  22704. }
  22705. EllipseCurve.prototype = Object.create(Curve.prototype);
  22706. EllipseCurve.prototype.constructor = EllipseCurve;
  22707. EllipseCurve.prototype.isEllipseCurve = true;
  22708. EllipseCurve.prototype.getPoint = function (t, optionalTarget) {
  22709. const point = optionalTarget || new Vector2();
  22710. const twoPi = Math.PI * 2;
  22711. let deltaAngle = this.aEndAngle - this.aStartAngle;
  22712. const samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  22713. while (deltaAngle < 0) deltaAngle += twoPi;
  22714. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  22715. if (deltaAngle < Number.EPSILON) {
  22716. if (samePoints) {
  22717. deltaAngle = 0;
  22718. } else {
  22719. deltaAngle = twoPi;
  22720. }
  22721. }
  22722. if (this.aClockwise === true && !samePoints) {
  22723. if (deltaAngle === twoPi) {
  22724. deltaAngle = -twoPi;
  22725. } else {
  22726. deltaAngle = deltaAngle - twoPi;
  22727. }
  22728. }
  22729. const angle = this.aStartAngle + t * deltaAngle;
  22730. let x = this.aX + this.xRadius * Math.cos(angle);
  22731. let y = this.aY + this.yRadius * Math.sin(angle);
  22732. if (this.aRotation !== 0) {
  22733. const cos = Math.cos(this.aRotation);
  22734. const sin = Math.sin(this.aRotation);
  22735. const tx = x - this.aX;
  22736. const ty = y - this.aY; // Rotate the point about the center of the ellipse.
  22737. x = tx * cos - ty * sin + this.aX;
  22738. y = tx * sin + ty * cos + this.aY;
  22739. }
  22740. return point.set(x, y);
  22741. };
  22742. EllipseCurve.prototype.copy = function (source) {
  22743. Curve.prototype.copy.call(this, source);
  22744. this.aX = source.aX;
  22745. this.aY = source.aY;
  22746. this.xRadius = source.xRadius;
  22747. this.yRadius = source.yRadius;
  22748. this.aStartAngle = source.aStartAngle;
  22749. this.aEndAngle = source.aEndAngle;
  22750. this.aClockwise = source.aClockwise;
  22751. this.aRotation = source.aRotation;
  22752. return this;
  22753. };
  22754. EllipseCurve.prototype.toJSON = function () {
  22755. const data = Curve.prototype.toJSON.call(this);
  22756. data.aX = this.aX;
  22757. data.aY = this.aY;
  22758. data.xRadius = this.xRadius;
  22759. data.yRadius = this.yRadius;
  22760. data.aStartAngle = this.aStartAngle;
  22761. data.aEndAngle = this.aEndAngle;
  22762. data.aClockwise = this.aClockwise;
  22763. data.aRotation = this.aRotation;
  22764. return data;
  22765. };
  22766. EllipseCurve.prototype.fromJSON = function (json) {
  22767. Curve.prototype.fromJSON.call(this, json);
  22768. this.aX = json.aX;
  22769. this.aY = json.aY;
  22770. this.xRadius = json.xRadius;
  22771. this.yRadius = json.yRadius;
  22772. this.aStartAngle = json.aStartAngle;
  22773. this.aEndAngle = json.aEndAngle;
  22774. this.aClockwise = json.aClockwise;
  22775. this.aRotation = json.aRotation;
  22776. return this;
  22777. };
  22778. function ArcCurve(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  22779. EllipseCurve.call(this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  22780. this.type = 'ArcCurve';
  22781. }
  22782. ArcCurve.prototype = Object.create(EllipseCurve.prototype);
  22783. ArcCurve.prototype.constructor = ArcCurve;
  22784. ArcCurve.prototype.isArcCurve = true;
  22785. /**
  22786. * Centripetal CatmullRom Curve - which is useful for avoiding
  22787. * cusps and self-intersections in non-uniform catmull rom curves.
  22788. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  22789. *
  22790. * curve.type accepts centripetal(default), chordal and catmullrom
  22791. * curve.tension is used for catmullrom which defaults to 0.5
  22792. */
  22793. /*
  22794. Based on an optimized c++ solution in
  22795. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  22796. - http://ideone.com/NoEbVM
  22797. This CubicPoly class could be used for reusing some variables and calculations,
  22798. but for three.js curve use, it could be possible inlined and flatten into a single function call
  22799. which can be placed in CurveUtils.
  22800. */
  22801. function CubicPoly() {
  22802. let c0 = 0,
  22803. c1 = 0,
  22804. c2 = 0,
  22805. c3 = 0;
  22806. /*
  22807. * Compute coefficients for a cubic polynomial
  22808. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  22809. * such that
  22810. * p(0) = x0, p(1) = x1
  22811. * and
  22812. * p'(0) = t0, p'(1) = t1.
  22813. */
  22814. function init(x0, x1, t0, t1) {
  22815. c0 = x0;
  22816. c1 = t0;
  22817. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  22818. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  22819. }
  22820. return {
  22821. initCatmullRom: function (x0, x1, x2, x3, tension) {
  22822. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  22823. },
  22824. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  22825. // compute tangents when parameterized in [t1,t2]
  22826. let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  22827. let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  22828. t1 *= dt1;
  22829. t2 *= dt1;
  22830. init(x1, x2, t1, t2);
  22831. },
  22832. calc: function (t) {
  22833. const t2 = t * t;
  22834. const t3 = t2 * t;
  22835. return c0 + c1 * t + c2 * t2 + c3 * t3;
  22836. }
  22837. };
  22838. } //
  22839. const tmp = new Vector3();
  22840. const px = new CubicPoly(),
  22841. py = new CubicPoly(),
  22842. pz = new CubicPoly();
  22843. function CatmullRomCurve3(points = [], closed = false, curveType = 'centripetal', tension = 0.5) {
  22844. Curve.call(this);
  22845. this.type = 'CatmullRomCurve3';
  22846. this.points = points;
  22847. this.closed = closed;
  22848. this.curveType = curveType;
  22849. this.tension = tension;
  22850. }
  22851. CatmullRomCurve3.prototype = Object.create(Curve.prototype);
  22852. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  22853. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  22854. CatmullRomCurve3.prototype.getPoint = function (t, optionalTarget = new Vector3()) {
  22855. const point = optionalTarget;
  22856. const points = this.points;
  22857. const l = points.length;
  22858. const p = (l - (this.closed ? 0 : 1)) * t;
  22859. let intPoint = Math.floor(p);
  22860. let weight = p - intPoint;
  22861. if (this.closed) {
  22862. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  22863. } else if (weight === 0 && intPoint === l - 1) {
  22864. intPoint = l - 2;
  22865. weight = 1;
  22866. }
  22867. let p0, p3; // 4 points (p1 & p2 defined below)
  22868. if (this.closed || intPoint > 0) {
  22869. p0 = points[(intPoint - 1) % l];
  22870. } else {
  22871. // extrapolate first point
  22872. tmp.subVectors(points[0], points[1]).add(points[0]);
  22873. p0 = tmp;
  22874. }
  22875. const p1 = points[intPoint % l];
  22876. const p2 = points[(intPoint + 1) % l];
  22877. if (this.closed || intPoint + 2 < l) {
  22878. p3 = points[(intPoint + 2) % l];
  22879. } else {
  22880. // extrapolate last point
  22881. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  22882. p3 = tmp;
  22883. }
  22884. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  22885. // init Centripetal / Chordal Catmull-Rom
  22886. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  22887. let dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  22888. let dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  22889. let dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  22890. if (dt1 < 1e-4) dt1 = 1.0;
  22891. if (dt0 < 1e-4) dt0 = dt1;
  22892. if (dt2 < 1e-4) dt2 = dt1;
  22893. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  22894. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  22895. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  22896. } else if (this.curveType === 'catmullrom') {
  22897. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  22898. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  22899. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  22900. }
  22901. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  22902. return point;
  22903. };
  22904. CatmullRomCurve3.prototype.copy = function (source) {
  22905. Curve.prototype.copy.call(this, source);
  22906. this.points = [];
  22907. for (let i = 0, l = source.points.length; i < l; i++) {
  22908. const point = source.points[i];
  22909. this.points.push(point.clone());
  22910. }
  22911. this.closed = source.closed;
  22912. this.curveType = source.curveType;
  22913. this.tension = source.tension;
  22914. return this;
  22915. };
  22916. CatmullRomCurve3.prototype.toJSON = function () {
  22917. const data = Curve.prototype.toJSON.call(this);
  22918. data.points = [];
  22919. for (let i = 0, l = this.points.length; i < l; i++) {
  22920. const point = this.points[i];
  22921. data.points.push(point.toArray());
  22922. }
  22923. data.closed = this.closed;
  22924. data.curveType = this.curveType;
  22925. data.tension = this.tension;
  22926. return data;
  22927. };
  22928. CatmullRomCurve3.prototype.fromJSON = function (json) {
  22929. Curve.prototype.fromJSON.call(this, json);
  22930. this.points = [];
  22931. for (let i = 0, l = json.points.length; i < l; i++) {
  22932. const point = json.points[i];
  22933. this.points.push(new Vector3().fromArray(point));
  22934. }
  22935. this.closed = json.closed;
  22936. this.curveType = json.curveType;
  22937. this.tension = json.tension;
  22938. return this;
  22939. };
  22940. /**
  22941. * Bezier Curves formulas obtained from
  22942. * http://en.wikipedia.org/wiki/Bézier_curve
  22943. */
  22944. function CatmullRom(t, p0, p1, p2, p3) {
  22945. const v0 = (p2 - p0) * 0.5;
  22946. const v1 = (p3 - p1) * 0.5;
  22947. const t2 = t * t;
  22948. const t3 = t * t2;
  22949. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  22950. } //
  22951. function QuadraticBezierP0(t, p) {
  22952. const k = 1 - t;
  22953. return k * k * p;
  22954. }
  22955. function QuadraticBezierP1(t, p) {
  22956. return 2 * (1 - t) * t * p;
  22957. }
  22958. function QuadraticBezierP2(t, p) {
  22959. return t * t * p;
  22960. }
  22961. function QuadraticBezier(t, p0, p1, p2) {
  22962. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  22963. } //
  22964. function CubicBezierP0(t, p) {
  22965. const k = 1 - t;
  22966. return k * k * k * p;
  22967. }
  22968. function CubicBezierP1(t, p) {
  22969. const k = 1 - t;
  22970. return 3 * k * k * t * p;
  22971. }
  22972. function CubicBezierP2(t, p) {
  22973. return 3 * (1 - t) * t * t * p;
  22974. }
  22975. function CubicBezierP3(t, p) {
  22976. return t * t * t * p;
  22977. }
  22978. function CubicBezier(t, p0, p1, p2, p3) {
  22979. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  22980. }
  22981. function CubicBezierCurve(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2()) {
  22982. Curve.call(this);
  22983. this.type = 'CubicBezierCurve';
  22984. this.v0 = v0;
  22985. this.v1 = v1;
  22986. this.v2 = v2;
  22987. this.v3 = v3;
  22988. }
  22989. CubicBezierCurve.prototype = Object.create(Curve.prototype);
  22990. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  22991. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  22992. CubicBezierCurve.prototype.getPoint = function (t, optionalTarget = new Vector2()) {
  22993. const point = optionalTarget;
  22994. const v0 = this.v0,
  22995. v1 = this.v1,
  22996. v2 = this.v2,
  22997. v3 = this.v3;
  22998. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  22999. return point;
  23000. };
  23001. CubicBezierCurve.prototype.copy = function (source) {
  23002. Curve.prototype.copy.call(this, source);
  23003. this.v0.copy(source.v0);
  23004. this.v1.copy(source.v1);
  23005. this.v2.copy(source.v2);
  23006. this.v3.copy(source.v3);
  23007. return this;
  23008. };
  23009. CubicBezierCurve.prototype.toJSON = function () {
  23010. const data = Curve.prototype.toJSON.call(this);
  23011. data.v0 = this.v0.toArray();
  23012. data.v1 = this.v1.toArray();
  23013. data.v2 = this.v2.toArray();
  23014. data.v3 = this.v3.toArray();
  23015. return data;
  23016. };
  23017. CubicBezierCurve.prototype.fromJSON = function (json) {
  23018. Curve.prototype.fromJSON.call(this, json);
  23019. this.v0.fromArray(json.v0);
  23020. this.v1.fromArray(json.v1);
  23021. this.v2.fromArray(json.v2);
  23022. this.v3.fromArray(json.v3);
  23023. return this;
  23024. };
  23025. function CubicBezierCurve3(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3()) {
  23026. Curve.call(this);
  23027. this.type = 'CubicBezierCurve3';
  23028. this.v0 = v0;
  23029. this.v1 = v1;
  23030. this.v2 = v2;
  23031. this.v3 = v3;
  23032. }
  23033. CubicBezierCurve3.prototype = Object.create(Curve.prototype);
  23034. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  23035. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  23036. CubicBezierCurve3.prototype.getPoint = function (t, optionalTarget = new Vector3()) {
  23037. const point = optionalTarget;
  23038. const v0 = this.v0,
  23039. v1 = this.v1,
  23040. v2 = this.v2,
  23041. v3 = this.v3;
  23042. 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));
  23043. return point;
  23044. };
  23045. CubicBezierCurve3.prototype.copy = function (source) {
  23046. Curve.prototype.copy.call(this, source);
  23047. this.v0.copy(source.v0);
  23048. this.v1.copy(source.v1);
  23049. this.v2.copy(source.v2);
  23050. this.v3.copy(source.v3);
  23051. return this;
  23052. };
  23053. CubicBezierCurve3.prototype.toJSON = function () {
  23054. const data = Curve.prototype.toJSON.call(this);
  23055. data.v0 = this.v0.toArray();
  23056. data.v1 = this.v1.toArray();
  23057. data.v2 = this.v2.toArray();
  23058. data.v3 = this.v3.toArray();
  23059. return data;
  23060. };
  23061. CubicBezierCurve3.prototype.fromJSON = function (json) {
  23062. Curve.prototype.fromJSON.call(this, json);
  23063. this.v0.fromArray(json.v0);
  23064. this.v1.fromArray(json.v1);
  23065. this.v2.fromArray(json.v2);
  23066. this.v3.fromArray(json.v3);
  23067. return this;
  23068. };
  23069. function LineCurve(v1 = new Vector2(), v2 = new Vector2()) {
  23070. Curve.call(this);
  23071. this.type = 'LineCurve';
  23072. this.v1 = v1;
  23073. this.v2 = v2;
  23074. }
  23075. LineCurve.prototype = Object.create(Curve.prototype);
  23076. LineCurve.prototype.constructor = LineCurve;
  23077. LineCurve.prototype.isLineCurve = true;
  23078. LineCurve.prototype.getPoint = function (t, optionalTarget = new Vector2()) {
  23079. const point = optionalTarget;
  23080. if (t === 1) {
  23081. point.copy(this.v2);
  23082. } else {
  23083. point.copy(this.v2).sub(this.v1);
  23084. point.multiplyScalar(t).add(this.v1);
  23085. }
  23086. return point;
  23087. }; // Line curve is linear, so we can overwrite default getPointAt
  23088. LineCurve.prototype.getPointAt = function (u, optionalTarget) {
  23089. return this.getPoint(u, optionalTarget);
  23090. };
  23091. LineCurve.prototype.getTangent = function (t, optionalTarget) {
  23092. const tangent = optionalTarget || new Vector2();
  23093. tangent.copy(this.v2).sub(this.v1).normalize();
  23094. return tangent;
  23095. };
  23096. LineCurve.prototype.copy = function (source) {
  23097. Curve.prototype.copy.call(this, source);
  23098. this.v1.copy(source.v1);
  23099. this.v2.copy(source.v2);
  23100. return this;
  23101. };
  23102. LineCurve.prototype.toJSON = function () {
  23103. const data = Curve.prototype.toJSON.call(this);
  23104. data.v1 = this.v1.toArray();
  23105. data.v2 = this.v2.toArray();
  23106. return data;
  23107. };
  23108. LineCurve.prototype.fromJSON = function (json) {
  23109. Curve.prototype.fromJSON.call(this, json);
  23110. this.v1.fromArray(json.v1);
  23111. this.v2.fromArray(json.v2);
  23112. return this;
  23113. };
  23114. function LineCurve3(v1 = new Vector3(), v2 = new Vector3()) {
  23115. Curve.call(this);
  23116. this.type = 'LineCurve3';
  23117. this.v1 = v1;
  23118. this.v2 = v2;
  23119. }
  23120. LineCurve3.prototype = Object.create(Curve.prototype);
  23121. LineCurve3.prototype.constructor = LineCurve3;
  23122. LineCurve3.prototype.isLineCurve3 = true;
  23123. LineCurve3.prototype.getPoint = function (t, optionalTarget = new Vector3()) {
  23124. const point = optionalTarget;
  23125. if (t === 1) {
  23126. point.copy(this.v2);
  23127. } else {
  23128. point.copy(this.v2).sub(this.v1);
  23129. point.multiplyScalar(t).add(this.v1);
  23130. }
  23131. return point;
  23132. }; // Line curve is linear, so we can overwrite default getPointAt
  23133. LineCurve3.prototype.getPointAt = function (u, optionalTarget) {
  23134. return this.getPoint(u, optionalTarget);
  23135. };
  23136. LineCurve3.prototype.copy = function (source) {
  23137. Curve.prototype.copy.call(this, source);
  23138. this.v1.copy(source.v1);
  23139. this.v2.copy(source.v2);
  23140. return this;
  23141. };
  23142. LineCurve3.prototype.toJSON = function () {
  23143. const data = Curve.prototype.toJSON.call(this);
  23144. data.v1 = this.v1.toArray();
  23145. data.v2 = this.v2.toArray();
  23146. return data;
  23147. };
  23148. LineCurve3.prototype.fromJSON = function (json) {
  23149. Curve.prototype.fromJSON.call(this, json);
  23150. this.v1.fromArray(json.v1);
  23151. this.v2.fromArray(json.v2);
  23152. return this;
  23153. };
  23154. function QuadraticBezierCurve(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2()) {
  23155. Curve.call(this);
  23156. this.type = 'QuadraticBezierCurve';
  23157. this.v0 = v0;
  23158. this.v1 = v1;
  23159. this.v2 = v2;
  23160. }
  23161. QuadraticBezierCurve.prototype = Object.create(Curve.prototype);
  23162. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  23163. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  23164. QuadraticBezierCurve.prototype.getPoint = function (t, optionalTarget = new Vector2()) {
  23165. const point = optionalTarget;
  23166. const v0 = this.v0,
  23167. v1 = this.v1,
  23168. v2 = this.v2;
  23169. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  23170. return point;
  23171. };
  23172. QuadraticBezierCurve.prototype.copy = function (source) {
  23173. Curve.prototype.copy.call(this, source);
  23174. this.v0.copy(source.v0);
  23175. this.v1.copy(source.v1);
  23176. this.v2.copy(source.v2);
  23177. return this;
  23178. };
  23179. QuadraticBezierCurve.prototype.toJSON = function () {
  23180. const data = Curve.prototype.toJSON.call(this);
  23181. data.v0 = this.v0.toArray();
  23182. data.v1 = this.v1.toArray();
  23183. data.v2 = this.v2.toArray();
  23184. return data;
  23185. };
  23186. QuadraticBezierCurve.prototype.fromJSON = function (json) {
  23187. Curve.prototype.fromJSON.call(this, json);
  23188. this.v0.fromArray(json.v0);
  23189. this.v1.fromArray(json.v1);
  23190. this.v2.fromArray(json.v2);
  23191. return this;
  23192. };
  23193. function QuadraticBezierCurve3(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3()) {
  23194. Curve.call(this);
  23195. this.type = 'QuadraticBezierCurve3';
  23196. this.v0 = v0;
  23197. this.v1 = v1;
  23198. this.v2 = v2;
  23199. }
  23200. QuadraticBezierCurve3.prototype = Object.create(Curve.prototype);
  23201. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  23202. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  23203. QuadraticBezierCurve3.prototype.getPoint = function (t, optionalTarget = new Vector3()) {
  23204. const point = optionalTarget;
  23205. const v0 = this.v0,
  23206. v1 = this.v1,
  23207. v2 = this.v2;
  23208. 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));
  23209. return point;
  23210. };
  23211. QuadraticBezierCurve3.prototype.copy = function (source) {
  23212. Curve.prototype.copy.call(this, source);
  23213. this.v0.copy(source.v0);
  23214. this.v1.copy(source.v1);
  23215. this.v2.copy(source.v2);
  23216. return this;
  23217. };
  23218. QuadraticBezierCurve3.prototype.toJSON = function () {
  23219. const data = Curve.prototype.toJSON.call(this);
  23220. data.v0 = this.v0.toArray();
  23221. data.v1 = this.v1.toArray();
  23222. data.v2 = this.v2.toArray();
  23223. return data;
  23224. };
  23225. QuadraticBezierCurve3.prototype.fromJSON = function (json) {
  23226. Curve.prototype.fromJSON.call(this, json);
  23227. this.v0.fromArray(json.v0);
  23228. this.v1.fromArray(json.v1);
  23229. this.v2.fromArray(json.v2);
  23230. return this;
  23231. };
  23232. function SplineCurve(points = []) {
  23233. Curve.call(this);
  23234. this.type = 'SplineCurve';
  23235. this.points = points;
  23236. }
  23237. SplineCurve.prototype = Object.create(Curve.prototype);
  23238. SplineCurve.prototype.constructor = SplineCurve;
  23239. SplineCurve.prototype.isSplineCurve = true;
  23240. SplineCurve.prototype.getPoint = function (t, optionalTarget = new Vector2()) {
  23241. const point = optionalTarget;
  23242. const points = this.points;
  23243. const p = (points.length - 1) * t;
  23244. const intPoint = Math.floor(p);
  23245. const weight = p - intPoint;
  23246. const p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  23247. const p1 = points[intPoint];
  23248. const p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  23249. const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  23250. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  23251. return point;
  23252. };
  23253. SplineCurve.prototype.copy = function (source) {
  23254. Curve.prototype.copy.call(this, source);
  23255. this.points = [];
  23256. for (let i = 0, l = source.points.length; i < l; i++) {
  23257. const point = source.points[i];
  23258. this.points.push(point.clone());
  23259. }
  23260. return this;
  23261. };
  23262. SplineCurve.prototype.toJSON = function () {
  23263. const data = Curve.prototype.toJSON.call(this);
  23264. data.points = [];
  23265. for (let i = 0, l = this.points.length; i < l; i++) {
  23266. const point = this.points[i];
  23267. data.points.push(point.toArray());
  23268. }
  23269. return data;
  23270. };
  23271. SplineCurve.prototype.fromJSON = function (json) {
  23272. Curve.prototype.fromJSON.call(this, json);
  23273. this.points = [];
  23274. for (let i = 0, l = json.points.length; i < l; i++) {
  23275. const point = json.points[i];
  23276. this.points.push(new Vector2().fromArray(point));
  23277. }
  23278. return this;
  23279. };
  23280. var Curves =
  23281. /*#__PURE__*/
  23282. Object.freeze({
  23283. __proto__: null,
  23284. ArcCurve: ArcCurve,
  23285. CatmullRomCurve3: CatmullRomCurve3,
  23286. CubicBezierCurve: CubicBezierCurve,
  23287. CubicBezierCurve3: CubicBezierCurve3,
  23288. EllipseCurve: EllipseCurve,
  23289. LineCurve: LineCurve,
  23290. LineCurve3: LineCurve3,
  23291. QuadraticBezierCurve: QuadraticBezierCurve,
  23292. QuadraticBezierCurve3: QuadraticBezierCurve3,
  23293. SplineCurve: SplineCurve
  23294. });
  23295. /**************************************************************
  23296. * Curved Path - a curve path is simply a array of connected
  23297. * curves, but retains the api of a curve
  23298. **************************************************************/
  23299. function CurvePath() {
  23300. Curve.call(this);
  23301. this.type = 'CurvePath';
  23302. this.curves = [];
  23303. this.autoClose = false; // Automatically closes the path
  23304. }
  23305. CurvePath.prototype = Object.assign(Object.create(Curve.prototype), {
  23306. constructor: CurvePath,
  23307. add: function (curve) {
  23308. this.curves.push(curve);
  23309. },
  23310. closePath: function () {
  23311. // Add a line curve if start and end of lines are not connected
  23312. const startPoint = this.curves[0].getPoint(0);
  23313. const endPoint = this.curves[this.curves.length - 1].getPoint(1);
  23314. if (!startPoint.equals(endPoint)) {
  23315. this.curves.push(new LineCurve(endPoint, startPoint));
  23316. }
  23317. },
  23318. // To get accurate point with reference to
  23319. // entire path distance at time t,
  23320. // following has to be done:
  23321. // 1. Length of each sub path have to be known
  23322. // 2. Locate and identify type of curve
  23323. // 3. Get t for the curve
  23324. // 4. Return curve.getPointAt(t')
  23325. getPoint: function (t) {
  23326. const d = t * this.getLength();
  23327. const curveLengths = this.getCurveLengths();
  23328. let i = 0; // To think about boundaries points.
  23329. while (i < curveLengths.length) {
  23330. if (curveLengths[i] >= d) {
  23331. const diff = curveLengths[i] - d;
  23332. const curve = this.curves[i];
  23333. const segmentLength = curve.getLength();
  23334. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  23335. return curve.getPointAt(u);
  23336. }
  23337. i++;
  23338. }
  23339. return null; // loop where sum != 0, sum > d , sum+1 <d
  23340. },
  23341. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  23342. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  23343. // getPoint() depends on getLength
  23344. getLength: function () {
  23345. const lens = this.getCurveLengths();
  23346. return lens[lens.length - 1];
  23347. },
  23348. // cacheLengths must be recalculated.
  23349. updateArcLengths: function () {
  23350. this.needsUpdate = true;
  23351. this.cacheLengths = null;
  23352. this.getCurveLengths();
  23353. },
  23354. // Compute lengths and cache them
  23355. // We cannot overwrite getLengths() because UtoT mapping uses it.
  23356. getCurveLengths: function () {
  23357. // We use cache values if curves and cache array are same length
  23358. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  23359. return this.cacheLengths;
  23360. } // Get length of sub-curve
  23361. // Push sums into cached array
  23362. const lengths = [];
  23363. let sums = 0;
  23364. for (let i = 0, l = this.curves.length; i < l; i++) {
  23365. sums += this.curves[i].getLength();
  23366. lengths.push(sums);
  23367. }
  23368. this.cacheLengths = lengths;
  23369. return lengths;
  23370. },
  23371. getSpacedPoints: function (divisions = 40) {
  23372. const points = [];
  23373. for (let i = 0; i <= divisions; i++) {
  23374. points.push(this.getPoint(i / divisions));
  23375. }
  23376. if (this.autoClose) {
  23377. points.push(points[0]);
  23378. }
  23379. return points;
  23380. },
  23381. getPoints: function (divisions = 12) {
  23382. const points = [];
  23383. let last;
  23384. for (let i = 0, curves = this.curves; i < curves.length; i++) {
  23385. const curve = curves[i];
  23386. const resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
  23387. const pts = curve.getPoints(resolution);
  23388. for (let j = 0; j < pts.length; j++) {
  23389. const point = pts[j];
  23390. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  23391. points.push(point);
  23392. last = point;
  23393. }
  23394. }
  23395. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  23396. points.push(points[0]);
  23397. }
  23398. return points;
  23399. },
  23400. copy: function (source) {
  23401. Curve.prototype.copy.call(this, source);
  23402. this.curves = [];
  23403. for (let i = 0, l = source.curves.length; i < l; i++) {
  23404. const curve = source.curves[i];
  23405. this.curves.push(curve.clone());
  23406. }
  23407. this.autoClose = source.autoClose;
  23408. return this;
  23409. },
  23410. toJSON: function () {
  23411. const data = Curve.prototype.toJSON.call(this);
  23412. data.autoClose = this.autoClose;
  23413. data.curves = [];
  23414. for (let i = 0, l = this.curves.length; i < l; i++) {
  23415. const curve = this.curves[i];
  23416. data.curves.push(curve.toJSON());
  23417. }
  23418. return data;
  23419. },
  23420. fromJSON: function (json) {
  23421. Curve.prototype.fromJSON.call(this, json);
  23422. this.autoClose = json.autoClose;
  23423. this.curves = [];
  23424. for (let i = 0, l = json.curves.length; i < l; i++) {
  23425. const curve = json.curves[i];
  23426. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  23427. }
  23428. return this;
  23429. }
  23430. });
  23431. function Path(points) {
  23432. CurvePath.call(this);
  23433. this.type = 'Path';
  23434. this.currentPoint = new Vector2();
  23435. if (points) {
  23436. this.setFromPoints(points);
  23437. }
  23438. }
  23439. Path.prototype = Object.assign(Object.create(CurvePath.prototype), {
  23440. constructor: Path,
  23441. setFromPoints: function (points) {
  23442. this.moveTo(points[0].x, points[0].y);
  23443. for (let i = 1, l = points.length; i < l; i++) {
  23444. this.lineTo(points[i].x, points[i].y);
  23445. }
  23446. return this;
  23447. },
  23448. moveTo: function (x, y) {
  23449. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  23450. return this;
  23451. },
  23452. lineTo: function (x, y) {
  23453. const curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  23454. this.curves.push(curve);
  23455. this.currentPoint.set(x, y);
  23456. return this;
  23457. },
  23458. quadraticCurveTo: function (aCPx, aCPy, aX, aY) {
  23459. const curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  23460. this.curves.push(curve);
  23461. this.currentPoint.set(aX, aY);
  23462. return this;
  23463. },
  23464. bezierCurveTo: function (aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  23465. const curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  23466. this.curves.push(curve);
  23467. this.currentPoint.set(aX, aY);
  23468. return this;
  23469. },
  23470. splineThru: function (pts
  23471. /*Array of Vector*/
  23472. ) {
  23473. const npts = [this.currentPoint.clone()].concat(pts);
  23474. const curve = new SplineCurve(npts);
  23475. this.curves.push(curve);
  23476. this.currentPoint.copy(pts[pts.length - 1]);
  23477. return this;
  23478. },
  23479. arc: function (aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  23480. const x0 = this.currentPoint.x;
  23481. const y0 = this.currentPoint.y;
  23482. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  23483. return this;
  23484. },
  23485. absarc: function (aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  23486. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  23487. return this;
  23488. },
  23489. ellipse: function (aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  23490. const x0 = this.currentPoint.x;
  23491. const y0 = this.currentPoint.y;
  23492. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  23493. return this;
  23494. },
  23495. absellipse: function (aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  23496. const curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  23497. if (this.curves.length > 0) {
  23498. // if a previous curve is present, attempt to join
  23499. const firstPoint = curve.getPoint(0);
  23500. if (!firstPoint.equals(this.currentPoint)) {
  23501. this.lineTo(firstPoint.x, firstPoint.y);
  23502. }
  23503. }
  23504. this.curves.push(curve);
  23505. const lastPoint = curve.getPoint(1);
  23506. this.currentPoint.copy(lastPoint);
  23507. return this;
  23508. },
  23509. copy: function (source) {
  23510. CurvePath.prototype.copy.call(this, source);
  23511. this.currentPoint.copy(source.currentPoint);
  23512. return this;
  23513. },
  23514. toJSON: function () {
  23515. const data = CurvePath.prototype.toJSON.call(this);
  23516. data.currentPoint = this.currentPoint.toArray();
  23517. return data;
  23518. },
  23519. fromJSON: function (json) {
  23520. CurvePath.prototype.fromJSON.call(this, json);
  23521. this.currentPoint.fromArray(json.currentPoint);
  23522. return this;
  23523. }
  23524. });
  23525. function Shape(points) {
  23526. Path.call(this, points);
  23527. this.uuid = MathUtils.generateUUID();
  23528. this.type = 'Shape';
  23529. this.holes = [];
  23530. }
  23531. Shape.prototype = Object.assign(Object.create(Path.prototype), {
  23532. constructor: Shape,
  23533. getPointsHoles: function (divisions) {
  23534. const holesPts = [];
  23535. for (let i = 0, l = this.holes.length; i < l; i++) {
  23536. holesPts[i] = this.holes[i].getPoints(divisions);
  23537. }
  23538. return holesPts;
  23539. },
  23540. // get points of shape and holes (keypoints based on segments parameter)
  23541. extractPoints: function (divisions) {
  23542. return {
  23543. shape: this.getPoints(divisions),
  23544. holes: this.getPointsHoles(divisions)
  23545. };
  23546. },
  23547. copy: function (source) {
  23548. Path.prototype.copy.call(this, source);
  23549. this.holes = [];
  23550. for (let i = 0, l = source.holes.length; i < l; i++) {
  23551. const hole = source.holes[i];
  23552. this.holes.push(hole.clone());
  23553. }
  23554. return this;
  23555. },
  23556. toJSON: function () {
  23557. const data = Path.prototype.toJSON.call(this);
  23558. data.uuid = this.uuid;
  23559. data.holes = [];
  23560. for (let i = 0, l = this.holes.length; i < l; i++) {
  23561. const hole = this.holes[i];
  23562. data.holes.push(hole.toJSON());
  23563. }
  23564. return data;
  23565. },
  23566. fromJSON: function (json) {
  23567. Path.prototype.fromJSON.call(this, json);
  23568. this.uuid = json.uuid;
  23569. this.holes = [];
  23570. for (let i = 0, l = json.holes.length; i < l; i++) {
  23571. const hole = json.holes[i];
  23572. this.holes.push(new Path().fromJSON(hole));
  23573. }
  23574. return this;
  23575. }
  23576. });
  23577. function Light(color, intensity = 1) {
  23578. Object3D.call(this);
  23579. this.type = 'Light';
  23580. this.color = new Color(color);
  23581. this.intensity = intensity;
  23582. }
  23583. Light.prototype = Object.assign(Object.create(Object3D.prototype), {
  23584. constructor: Light,
  23585. isLight: true,
  23586. copy: function (source) {
  23587. Object3D.prototype.copy.call(this, source);
  23588. this.color.copy(source.color);
  23589. this.intensity = source.intensity;
  23590. return this;
  23591. },
  23592. toJSON: function (meta) {
  23593. const data = Object3D.prototype.toJSON.call(this, meta);
  23594. data.object.color = this.color.getHex();
  23595. data.object.intensity = this.intensity;
  23596. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  23597. if (this.distance !== undefined) data.object.distance = this.distance;
  23598. if (this.angle !== undefined) data.object.angle = this.angle;
  23599. if (this.decay !== undefined) data.object.decay = this.decay;
  23600. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  23601. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  23602. return data;
  23603. }
  23604. });
  23605. function HemisphereLight(skyColor, groundColor, intensity) {
  23606. Light.call(this, skyColor, intensity);
  23607. this.type = 'HemisphereLight';
  23608. this.position.copy(Object3D.DefaultUp);
  23609. this.updateMatrix();
  23610. this.groundColor = new Color(groundColor);
  23611. }
  23612. HemisphereLight.prototype = Object.assign(Object.create(Light.prototype), {
  23613. constructor: HemisphereLight,
  23614. isHemisphereLight: true,
  23615. copy: function (source) {
  23616. Light.prototype.copy.call(this, source);
  23617. this.groundColor.copy(source.groundColor);
  23618. return this;
  23619. }
  23620. });
  23621. function LightShadow(camera) {
  23622. this.camera = camera;
  23623. this.bias = 0;
  23624. this.normalBias = 0;
  23625. this.radius = 1;
  23626. this.mapSize = new Vector2(512, 512);
  23627. this.map = null;
  23628. this.mapPass = null;
  23629. this.matrix = new Matrix4();
  23630. this.autoUpdate = true;
  23631. this.needsUpdate = false;
  23632. this._frustum = new Frustum();
  23633. this._frameExtents = new Vector2(1, 1);
  23634. this._viewportCount = 1;
  23635. this._viewports = [new Vector4(0, 0, 1, 1)];
  23636. }
  23637. Object.assign(LightShadow.prototype, {
  23638. _projScreenMatrix: new Matrix4(),
  23639. _lightPositionWorld: new Vector3(),
  23640. _lookTarget: new Vector3(),
  23641. getViewportCount: function () {
  23642. return this._viewportCount;
  23643. },
  23644. getFrustum: function () {
  23645. return this._frustum;
  23646. },
  23647. updateMatrices: function (light) {
  23648. const shadowCamera = this.camera,
  23649. shadowMatrix = this.matrix,
  23650. projScreenMatrix = this._projScreenMatrix,
  23651. lookTarget = this._lookTarget,
  23652. lightPositionWorld = this._lightPositionWorld;
  23653. lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  23654. shadowCamera.position.copy(lightPositionWorld);
  23655. lookTarget.setFromMatrixPosition(light.target.matrixWorld);
  23656. shadowCamera.lookAt(lookTarget);
  23657. shadowCamera.updateMatrixWorld();
  23658. projScreenMatrix.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  23659. this._frustum.setFromProjectionMatrix(projScreenMatrix);
  23660. 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);
  23661. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  23662. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  23663. },
  23664. getViewport: function (viewportIndex) {
  23665. return this._viewports[viewportIndex];
  23666. },
  23667. getFrameExtents: function () {
  23668. return this._frameExtents;
  23669. },
  23670. copy: function (source) {
  23671. this.camera = source.camera.clone();
  23672. this.bias = source.bias;
  23673. this.radius = source.radius;
  23674. this.mapSize.copy(source.mapSize);
  23675. return this;
  23676. },
  23677. clone: function () {
  23678. return new this.constructor().copy(this);
  23679. },
  23680. toJSON: function () {
  23681. const object = {};
  23682. if (this.bias !== 0) object.bias = this.bias;
  23683. if (this.normalBias !== 0) object.normalBias = this.normalBias;
  23684. if (this.radius !== 1) object.radius = this.radius;
  23685. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  23686. object.camera = this.camera.toJSON(false).object;
  23687. delete object.camera.matrix;
  23688. return object;
  23689. }
  23690. });
  23691. function SpotLightShadow() {
  23692. LightShadow.call(this, new PerspectiveCamera(50, 1, 0.5, 500));
  23693. this.focus = 1;
  23694. }
  23695. SpotLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  23696. constructor: SpotLightShadow,
  23697. isSpotLightShadow: true,
  23698. updateMatrices: function (light) {
  23699. const camera = this.camera;
  23700. const fov = MathUtils.RAD2DEG * 2 * light.angle * this.focus;
  23701. const aspect = this.mapSize.width / this.mapSize.height;
  23702. const far = light.distance || camera.far;
  23703. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  23704. camera.fov = fov;
  23705. camera.aspect = aspect;
  23706. camera.far = far;
  23707. camera.updateProjectionMatrix();
  23708. }
  23709. LightShadow.prototype.updateMatrices.call(this, light);
  23710. }
  23711. });
  23712. function SpotLight(color, intensity, distance, angle, penumbra, decay) {
  23713. Light.call(this, color, intensity);
  23714. this.type = 'SpotLight';
  23715. this.position.copy(Object3D.DefaultUp);
  23716. this.updateMatrix();
  23717. this.target = new Object3D();
  23718. Object.defineProperty(this, 'power', {
  23719. get: function () {
  23720. // intensity = power per solid angle.
  23721. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23722. return this.intensity * Math.PI;
  23723. },
  23724. set: function (power) {
  23725. // intensity = power per solid angle.
  23726. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23727. this.intensity = power / Math.PI;
  23728. }
  23729. });
  23730. this.distance = distance !== undefined ? distance : 0;
  23731. this.angle = angle !== undefined ? angle : Math.PI / 3;
  23732. this.penumbra = penumbra !== undefined ? penumbra : 0;
  23733. this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
  23734. this.shadow = new SpotLightShadow();
  23735. }
  23736. SpotLight.prototype = Object.assign(Object.create(Light.prototype), {
  23737. constructor: SpotLight,
  23738. isSpotLight: true,
  23739. copy: function (source) {
  23740. Light.prototype.copy.call(this, source);
  23741. this.distance = source.distance;
  23742. this.angle = source.angle;
  23743. this.penumbra = source.penumbra;
  23744. this.decay = source.decay;
  23745. this.target = source.target.clone();
  23746. this.shadow = source.shadow.clone();
  23747. return this;
  23748. }
  23749. });
  23750. function PointLightShadow() {
  23751. LightShadow.call(this, new PerspectiveCamera(90, 1, 0.5, 500));
  23752. this._frameExtents = new Vector2(4, 2);
  23753. this._viewportCount = 6;
  23754. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  23755. // following orientation:
  23756. //
  23757. // xzXZ
  23758. // y Y
  23759. //
  23760. // X - Positive x direction
  23761. // x - Negative x direction
  23762. // Y - Positive y direction
  23763. // y - Negative y direction
  23764. // Z - Positive z direction
  23765. // z - Negative z direction
  23766. // positive X
  23767. new Vector4(2, 1, 1, 1), // negative X
  23768. new Vector4(0, 1, 1, 1), // positive Z
  23769. new Vector4(3, 1, 1, 1), // negative Z
  23770. new Vector4(1, 1, 1, 1), // positive Y
  23771. new Vector4(3, 0, 1, 1), // negative Y
  23772. new Vector4(1, 0, 1, 1)];
  23773. 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)];
  23774. 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)];
  23775. }
  23776. PointLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  23777. constructor: PointLightShadow,
  23778. isPointLightShadow: true,
  23779. updateMatrices: function (light, viewportIndex = 0) {
  23780. const camera = this.camera,
  23781. shadowMatrix = this.matrix,
  23782. lightPositionWorld = this._lightPositionWorld,
  23783. lookTarget = this._lookTarget,
  23784. projScreenMatrix = this._projScreenMatrix;
  23785. lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  23786. camera.position.copy(lightPositionWorld);
  23787. lookTarget.copy(camera.position);
  23788. lookTarget.add(this._cubeDirections[viewportIndex]);
  23789. camera.up.copy(this._cubeUps[viewportIndex]);
  23790. camera.lookAt(lookTarget);
  23791. camera.updateMatrixWorld();
  23792. shadowMatrix.makeTranslation(-lightPositionWorld.x, -lightPositionWorld.y, -lightPositionWorld.z);
  23793. projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  23794. this._frustum.setFromProjectionMatrix(projScreenMatrix);
  23795. }
  23796. });
  23797. function PointLight(color, intensity, distance, decay) {
  23798. Light.call(this, color, intensity);
  23799. this.type = 'PointLight';
  23800. Object.defineProperty(this, 'power', {
  23801. get: function () {
  23802. // intensity = power per solid angle.
  23803. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23804. return this.intensity * 4 * Math.PI;
  23805. },
  23806. set: function (power) {
  23807. // intensity = power per solid angle.
  23808. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23809. this.intensity = power / (4 * Math.PI);
  23810. }
  23811. });
  23812. this.distance = distance !== undefined ? distance : 0;
  23813. this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
  23814. this.shadow = new PointLightShadow();
  23815. }
  23816. PointLight.prototype = Object.assign(Object.create(Light.prototype), {
  23817. constructor: PointLight,
  23818. isPointLight: true,
  23819. copy: function (source) {
  23820. Light.prototype.copy.call(this, source);
  23821. this.distance = source.distance;
  23822. this.decay = source.decay;
  23823. this.shadow = source.shadow.clone();
  23824. return this;
  23825. }
  23826. });
  23827. function OrthographicCamera(left, right, top, bottom, near, far) {
  23828. Camera.call(this);
  23829. this.type = 'OrthographicCamera';
  23830. this.zoom = 1;
  23831. this.view = null;
  23832. this.left = left !== undefined ? left : -1;
  23833. this.right = right !== undefined ? right : 1;
  23834. this.top = top !== undefined ? top : 1;
  23835. this.bottom = bottom !== undefined ? bottom : -1;
  23836. this.near = near !== undefined ? near : 0.1;
  23837. this.far = far !== undefined ? far : 2000;
  23838. this.updateProjectionMatrix();
  23839. }
  23840. OrthographicCamera.prototype = Object.assign(Object.create(Camera.prototype), {
  23841. constructor: OrthographicCamera,
  23842. isOrthographicCamera: true,
  23843. copy: function (source, recursive) {
  23844. Camera.prototype.copy.call(this, source, recursive);
  23845. this.left = source.left;
  23846. this.right = source.right;
  23847. this.top = source.top;
  23848. this.bottom = source.bottom;
  23849. this.near = source.near;
  23850. this.far = source.far;
  23851. this.zoom = source.zoom;
  23852. this.view = source.view === null ? null : Object.assign({}, source.view);
  23853. return this;
  23854. },
  23855. setViewOffset: function (fullWidth, fullHeight, x, y, width, height) {
  23856. if (this.view === null) {
  23857. this.view = {
  23858. enabled: true,
  23859. fullWidth: 1,
  23860. fullHeight: 1,
  23861. offsetX: 0,
  23862. offsetY: 0,
  23863. width: 1,
  23864. height: 1
  23865. };
  23866. }
  23867. this.view.enabled = true;
  23868. this.view.fullWidth = fullWidth;
  23869. this.view.fullHeight = fullHeight;
  23870. this.view.offsetX = x;
  23871. this.view.offsetY = y;
  23872. this.view.width = width;
  23873. this.view.height = height;
  23874. this.updateProjectionMatrix();
  23875. },
  23876. clearViewOffset: function () {
  23877. if (this.view !== null) {
  23878. this.view.enabled = false;
  23879. }
  23880. this.updateProjectionMatrix();
  23881. },
  23882. updateProjectionMatrix: function () {
  23883. const dx = (this.right - this.left) / (2 * this.zoom);
  23884. const dy = (this.top - this.bottom) / (2 * this.zoom);
  23885. const cx = (this.right + this.left) / 2;
  23886. const cy = (this.top + this.bottom) / 2;
  23887. let left = cx - dx;
  23888. let right = cx + dx;
  23889. let top = cy + dy;
  23890. let bottom = cy - dy;
  23891. if (this.view !== null && this.view.enabled) {
  23892. const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom;
  23893. const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
  23894. left += scaleW * this.view.offsetX;
  23895. right = left + scaleW * this.view.width;
  23896. top -= scaleH * this.view.offsetY;
  23897. bottom = top - scaleH * this.view.height;
  23898. }
  23899. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  23900. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  23901. },
  23902. toJSON: function (meta) {
  23903. const data = Object3D.prototype.toJSON.call(this, meta);
  23904. data.object.zoom = this.zoom;
  23905. data.object.left = this.left;
  23906. data.object.right = this.right;
  23907. data.object.top = this.top;
  23908. data.object.bottom = this.bottom;
  23909. data.object.near = this.near;
  23910. data.object.far = this.far;
  23911. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  23912. return data;
  23913. }
  23914. });
  23915. function DirectionalLightShadow() {
  23916. LightShadow.call(this, new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  23917. }
  23918. DirectionalLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  23919. constructor: DirectionalLightShadow,
  23920. isDirectionalLightShadow: true,
  23921. updateMatrices: function (light) {
  23922. LightShadow.prototype.updateMatrices.call(this, light);
  23923. }
  23924. });
  23925. function DirectionalLight(color, intensity) {
  23926. Light.call(this, color, intensity);
  23927. this.type = 'DirectionalLight';
  23928. this.position.copy(Object3D.DefaultUp);
  23929. this.updateMatrix();
  23930. this.target = new Object3D();
  23931. this.shadow = new DirectionalLightShadow();
  23932. }
  23933. DirectionalLight.prototype = Object.assign(Object.create(Light.prototype), {
  23934. constructor: DirectionalLight,
  23935. isDirectionalLight: true,
  23936. copy: function (source) {
  23937. Light.prototype.copy.call(this, source);
  23938. this.target = source.target.clone();
  23939. this.shadow = source.shadow.clone();
  23940. return this;
  23941. }
  23942. });
  23943. function AmbientLight(color, intensity) {
  23944. Light.call(this, color, intensity);
  23945. this.type = 'AmbientLight';
  23946. }
  23947. AmbientLight.prototype = Object.assign(Object.create(Light.prototype), {
  23948. constructor: AmbientLight,
  23949. isAmbientLight: true
  23950. });
  23951. function RectAreaLight(color, intensity, width, height) {
  23952. Light.call(this, color, intensity);
  23953. this.type = 'RectAreaLight';
  23954. this.width = width !== undefined ? width : 10;
  23955. this.height = height !== undefined ? height : 10;
  23956. }
  23957. RectAreaLight.prototype = Object.assign(Object.create(Light.prototype), {
  23958. constructor: RectAreaLight,
  23959. isRectAreaLight: true,
  23960. copy: function (source) {
  23961. Light.prototype.copy.call(this, source);
  23962. this.width = source.width;
  23963. this.height = source.height;
  23964. return this;
  23965. },
  23966. toJSON: function (meta) {
  23967. const data = Light.prototype.toJSON.call(this, meta);
  23968. data.object.width = this.width;
  23969. data.object.height = this.height;
  23970. return data;
  23971. }
  23972. });
  23973. /**
  23974. * Primary reference:
  23975. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23976. *
  23977. * Secondary reference:
  23978. * https://www.ppsloan.org/publications/StupidSH36.pdf
  23979. */
  23980. // 3-band SH defined by 9 coefficients
  23981. class SphericalHarmonics3 {
  23982. constructor() {
  23983. Object.defineProperty(this, 'isSphericalHarmonics3', {
  23984. value: true
  23985. });
  23986. this.coefficients = [];
  23987. for (let i = 0; i < 9; i++) {
  23988. this.coefficients.push(new Vector3());
  23989. }
  23990. }
  23991. set(coefficients) {
  23992. for (let i = 0; i < 9; i++) {
  23993. this.coefficients[i].copy(coefficients[i]);
  23994. }
  23995. return this;
  23996. }
  23997. zero() {
  23998. for (let i = 0; i < 9; i++) {
  23999. this.coefficients[i].set(0, 0, 0);
  24000. }
  24001. return this;
  24002. } // get the radiance in the direction of the normal
  24003. // target is a Vector3
  24004. getAt(normal, target) {
  24005. // normal is assumed to be unit length
  24006. const x = normal.x,
  24007. y = normal.y,
  24008. z = normal.z;
  24009. const coeff = this.coefficients; // band 0
  24010. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  24011. target.addScaledVector(coeff[1], 0.488603 * y);
  24012. target.addScaledVector(coeff[2], 0.488603 * z);
  24013. target.addScaledVector(coeff[3], 0.488603 * x); // band 2
  24014. target.addScaledVector(coeff[4], 1.092548 * (x * y));
  24015. target.addScaledVector(coeff[5], 1.092548 * (y * z));
  24016. target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  24017. target.addScaledVector(coeff[7], 1.092548 * (x * z));
  24018. target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
  24019. return target;
  24020. } // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  24021. // target is a Vector3
  24022. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24023. getIrradianceAt(normal, target) {
  24024. // normal is assumed to be unit length
  24025. const x = normal.x,
  24026. y = normal.y,
  24027. z = normal.z;
  24028. const coeff = this.coefficients; // band 0
  24029. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  24030. // band 1
  24031. target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  24032. target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
  24033. target.addScaledVector(coeff[3], 2.0 * 0.511664 * x); // band 2
  24034. target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  24035. target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
  24036. target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  24037. target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
  24038. target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  24039. return target;
  24040. }
  24041. add(sh) {
  24042. for (let i = 0; i < 9; i++) {
  24043. this.coefficients[i].add(sh.coefficients[i]);
  24044. }
  24045. return this;
  24046. }
  24047. addScaledSH(sh, s) {
  24048. for (let i = 0; i < 9; i++) {
  24049. this.coefficients[i].addScaledVector(sh.coefficients[i], s);
  24050. }
  24051. return this;
  24052. }
  24053. scale(s) {
  24054. for (let i = 0; i < 9; i++) {
  24055. this.coefficients[i].multiplyScalar(s);
  24056. }
  24057. return this;
  24058. }
  24059. lerp(sh, alpha) {
  24060. for (let i = 0; i < 9; i++) {
  24061. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  24062. }
  24063. return this;
  24064. }
  24065. equals(sh) {
  24066. for (let i = 0; i < 9; i++) {
  24067. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  24068. return false;
  24069. }
  24070. }
  24071. return true;
  24072. }
  24073. copy(sh) {
  24074. return this.set(sh.coefficients);
  24075. }
  24076. clone() {
  24077. return new this.constructor().copy(this);
  24078. }
  24079. fromArray(array, offset = 0) {
  24080. const coefficients = this.coefficients;
  24081. for (let i = 0; i < 9; i++) {
  24082. coefficients[i].fromArray(array, offset + i * 3);
  24083. }
  24084. return this;
  24085. }
  24086. toArray(array = [], offset = 0) {
  24087. const coefficients = this.coefficients;
  24088. for (let i = 0; i < 9; i++) {
  24089. coefficients[i].toArray(array, offset + i * 3);
  24090. }
  24091. return array;
  24092. } // evaluate the basis functions
  24093. // shBasis is an Array[ 9 ]
  24094. static getBasisAt(normal, shBasis) {
  24095. // normal is assumed to be unit length
  24096. const x = normal.x,
  24097. y = normal.y,
  24098. z = normal.z; // band 0
  24099. shBasis[0] = 0.282095; // band 1
  24100. shBasis[1] = 0.488603 * y;
  24101. shBasis[2] = 0.488603 * z;
  24102. shBasis[3] = 0.488603 * x; // band 2
  24103. shBasis[4] = 1.092548 * x * y;
  24104. shBasis[5] = 1.092548 * y * z;
  24105. shBasis[6] = 0.315392 * (3 * z * z - 1);
  24106. shBasis[7] = 1.092548 * x * z;
  24107. shBasis[8] = 0.546274 * (x * x - y * y);
  24108. }
  24109. }
  24110. exports.SphericalHarmonics3 = SphericalHarmonics3;
  24111. function LightProbe(sh, intensity) {
  24112. Light.call(this, undefined, intensity);
  24113. this.type = 'LightProbe';
  24114. this.sh = sh !== undefined ? sh : new SphericalHarmonics3();
  24115. }
  24116. LightProbe.prototype = Object.assign(Object.create(Light.prototype), {
  24117. constructor: LightProbe,
  24118. isLightProbe: true,
  24119. copy: function (source) {
  24120. Light.prototype.copy.call(this, source);
  24121. this.sh.copy(source.sh);
  24122. return this;
  24123. },
  24124. fromJSON: function (json) {
  24125. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  24126. this.sh.fromArray(json.sh);
  24127. return this;
  24128. },
  24129. toJSON: function (meta) {
  24130. const data = Light.prototype.toJSON.call(this, meta);
  24131. data.object.sh = this.sh.toArray();
  24132. return data;
  24133. }
  24134. });
  24135. function MaterialLoader(manager) {
  24136. Loader.call(this, manager);
  24137. this.textures = {};
  24138. }
  24139. MaterialLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24140. constructor: MaterialLoader,
  24141. load: function (url, onLoad, onProgress, onError) {
  24142. const scope = this;
  24143. const loader = new FileLoader(scope.manager);
  24144. loader.setPath(scope.path);
  24145. loader.setRequestHeader(scope.requestHeader);
  24146. loader.setWithCredentials(scope.withCredentials);
  24147. loader.load(url, function (text) {
  24148. try {
  24149. onLoad(scope.parse(JSON.parse(text)));
  24150. } catch (e) {
  24151. if (onError) {
  24152. onError(e);
  24153. } else {
  24154. console.error(e);
  24155. }
  24156. scope.manager.itemError(url);
  24157. }
  24158. }, onProgress, onError);
  24159. },
  24160. parse: function (json) {
  24161. const textures = this.textures;
  24162. function getTexture(name) {
  24163. if (textures[name] === undefined) {
  24164. console.warn('THREE.MaterialLoader: Undefined texture', name);
  24165. }
  24166. return textures[name];
  24167. }
  24168. const material = new Materials[json.type]();
  24169. if (json.uuid !== undefined) material.uuid = json.uuid;
  24170. if (json.name !== undefined) material.name = json.name;
  24171. if (json.color !== undefined && material.color !== undefined) material.color.setHex(json.color);
  24172. if (json.roughness !== undefined) material.roughness = json.roughness;
  24173. if (json.metalness !== undefined) material.metalness = json.metalness;
  24174. if (json.sheen !== undefined) material.sheen = new Color().setHex(json.sheen);
  24175. if (json.emissive !== undefined && material.emissive !== undefined) material.emissive.setHex(json.emissive);
  24176. if (json.specular !== undefined && material.specular !== undefined) material.specular.setHex(json.specular);
  24177. if (json.shininess !== undefined) material.shininess = json.shininess;
  24178. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  24179. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  24180. if (json.fog !== undefined) material.fog = json.fog;
  24181. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  24182. if (json.blending !== undefined) material.blending = json.blending;
  24183. if (json.combine !== undefined) material.combine = json.combine;
  24184. if (json.side !== undefined) material.side = json.side;
  24185. if (json.opacity !== undefined) material.opacity = json.opacity;
  24186. if (json.transparent !== undefined) material.transparent = json.transparent;
  24187. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  24188. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  24189. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  24190. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  24191. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  24192. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  24193. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  24194. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  24195. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  24196. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  24197. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  24198. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  24199. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  24200. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  24201. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  24202. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  24203. if (json.rotation !== undefined) material.rotation = json.rotation;
  24204. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  24205. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  24206. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  24207. if (json.scale !== undefined) material.scale = json.scale;
  24208. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  24209. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  24210. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  24211. if (json.skinning !== undefined) material.skinning = json.skinning;
  24212. if (json.morphTargets !== undefined) material.morphTargets = json.morphTargets;
  24213. if (json.morphNormals !== undefined) material.morphNormals = json.morphNormals;
  24214. if (json.dithering !== undefined) material.dithering = json.dithering;
  24215. if (json.vertexTangents !== undefined) material.vertexTangents = json.vertexTangents;
  24216. if (json.visible !== undefined) material.visible = json.visible;
  24217. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  24218. if (json.userData !== undefined) material.userData = json.userData;
  24219. if (json.vertexColors !== undefined) {
  24220. if (typeof json.vertexColors === 'number') {
  24221. material.vertexColors = json.vertexColors > 0 ? true : false;
  24222. } else {
  24223. material.vertexColors = json.vertexColors;
  24224. }
  24225. } // Shader Material
  24226. if (json.uniforms !== undefined) {
  24227. for (const name in json.uniforms) {
  24228. const uniform = json.uniforms[name];
  24229. material.uniforms[name] = {};
  24230. switch (uniform.type) {
  24231. case 't':
  24232. material.uniforms[name].value = getTexture(uniform.value);
  24233. break;
  24234. case 'c':
  24235. material.uniforms[name].value = new Color().setHex(uniform.value);
  24236. break;
  24237. case 'v2':
  24238. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  24239. break;
  24240. case 'v3':
  24241. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  24242. break;
  24243. case 'v4':
  24244. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  24245. break;
  24246. case 'm3':
  24247. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  24248. break;
  24249. case 'm4':
  24250. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  24251. break;
  24252. default:
  24253. material.uniforms[name].value = uniform.value;
  24254. }
  24255. }
  24256. }
  24257. if (json.defines !== undefined) material.defines = json.defines;
  24258. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  24259. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  24260. if (json.extensions !== undefined) {
  24261. for (const key in json.extensions) {
  24262. material.extensions[key] = json.extensions[key];
  24263. }
  24264. } // Deprecated
  24265. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  24266. // for PointsMaterial
  24267. if (json.size !== undefined) material.size = json.size;
  24268. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  24269. if (json.map !== undefined) material.map = getTexture(json.map);
  24270. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  24271. if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
  24272. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  24273. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  24274. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  24275. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  24276. if (json.normalScale !== undefined) {
  24277. let normalScale = json.normalScale;
  24278. if (Array.isArray(normalScale) === false) {
  24279. // Blender exporter used to export a scalar. See #7459
  24280. normalScale = [normalScale, normalScale];
  24281. }
  24282. material.normalScale = new Vector2().fromArray(normalScale);
  24283. }
  24284. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  24285. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  24286. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  24287. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  24288. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  24289. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  24290. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  24291. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  24292. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  24293. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  24294. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  24295. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  24296. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  24297. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  24298. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  24299. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  24300. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  24301. if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
  24302. if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
  24303. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  24304. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  24305. if (json.transmission !== undefined) material.transmission = json.transmission;
  24306. if (json.transmissionMap !== undefined) material.transmissionMap = getTexture(json.transmissionMap);
  24307. return material;
  24308. },
  24309. setTextures: function (value) {
  24310. this.textures = value;
  24311. return this;
  24312. }
  24313. });
  24314. const LoaderUtils = {
  24315. decodeText: function (array) {
  24316. if (typeof TextDecoder !== 'undefined') {
  24317. return new TextDecoder().decode(array);
  24318. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  24319. // throws a "maximum call stack size exceeded" error for large arrays.
  24320. let s = '';
  24321. for (let i = 0, il = array.length; i < il; i++) {
  24322. // Implicitly assumes little-endian.
  24323. s += String.fromCharCode(array[i]);
  24324. }
  24325. try {
  24326. // merges multi-byte utf-8 characters.
  24327. return decodeURIComponent(escape(s));
  24328. } catch (e) {
  24329. // see #16358
  24330. return s;
  24331. }
  24332. },
  24333. extractUrlBase: function (url) {
  24334. const index = url.lastIndexOf('/');
  24335. if (index === -1) return './';
  24336. return url.substr(0, index + 1);
  24337. }
  24338. };
  24339. exports.LoaderUtils = LoaderUtils;
  24340. function InstancedBufferGeometry() {
  24341. BufferGeometry.call(this);
  24342. this.type = 'InstancedBufferGeometry';
  24343. this.instanceCount = Infinity;
  24344. }
  24345. InstancedBufferGeometry.prototype = Object.assign(Object.create(BufferGeometry.prototype), {
  24346. constructor: InstancedBufferGeometry,
  24347. isInstancedBufferGeometry: true,
  24348. copy: function (source) {
  24349. BufferGeometry.prototype.copy.call(this, source);
  24350. this.instanceCount = source.instanceCount;
  24351. return this;
  24352. },
  24353. clone: function () {
  24354. return new this.constructor().copy(this);
  24355. },
  24356. toJSON: function () {
  24357. const data = BufferGeometry.prototype.toJSON.call(this);
  24358. data.instanceCount = this.instanceCount;
  24359. data.isInstancedBufferGeometry = true;
  24360. return data;
  24361. }
  24362. });
  24363. function InstancedBufferAttribute(array, itemSize, normalized, meshPerAttribute) {
  24364. if (typeof normalized === 'number') {
  24365. meshPerAttribute = normalized;
  24366. normalized = false;
  24367. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  24368. }
  24369. BufferAttribute.call(this, array, itemSize, normalized);
  24370. this.meshPerAttribute = meshPerAttribute || 1;
  24371. }
  24372. InstancedBufferAttribute.prototype = Object.assign(Object.create(BufferAttribute.prototype), {
  24373. constructor: InstancedBufferAttribute,
  24374. isInstancedBufferAttribute: true,
  24375. copy: function (source) {
  24376. BufferAttribute.prototype.copy.call(this, source);
  24377. this.meshPerAttribute = source.meshPerAttribute;
  24378. return this;
  24379. },
  24380. toJSON: function () {
  24381. const data = BufferAttribute.prototype.toJSON.call(this);
  24382. data.meshPerAttribute = this.meshPerAttribute;
  24383. data.isInstancedBufferAttribute = true;
  24384. return data;
  24385. }
  24386. });
  24387. function BufferGeometryLoader(manager) {
  24388. Loader.call(this, manager);
  24389. }
  24390. BufferGeometryLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24391. constructor: BufferGeometryLoader,
  24392. load: function (url, onLoad, onProgress, onError) {
  24393. const scope = this;
  24394. const loader = new FileLoader(scope.manager);
  24395. loader.setPath(scope.path);
  24396. loader.setRequestHeader(scope.requestHeader);
  24397. loader.setWithCredentials(scope.withCredentials);
  24398. loader.load(url, function (text) {
  24399. try {
  24400. onLoad(scope.parse(JSON.parse(text)));
  24401. } catch (e) {
  24402. if (onError) {
  24403. onError(e);
  24404. } else {
  24405. console.error(e);
  24406. }
  24407. scope.manager.itemError(url);
  24408. }
  24409. }, onProgress, onError);
  24410. },
  24411. parse: function (json) {
  24412. const interleavedBufferMap = {};
  24413. const arrayBufferMap = {};
  24414. function getInterleavedBuffer(json, uuid) {
  24415. if (interleavedBufferMap[uuid] !== undefined) return interleavedBufferMap[uuid];
  24416. const interleavedBuffers = json.interleavedBuffers;
  24417. const interleavedBuffer = interleavedBuffers[uuid];
  24418. const buffer = getArrayBuffer(json, interleavedBuffer.buffer);
  24419. const array = getTypedArray(interleavedBuffer.type, buffer);
  24420. const ib = new InterleavedBuffer(array, interleavedBuffer.stride);
  24421. ib.uuid = interleavedBuffer.uuid;
  24422. interleavedBufferMap[uuid] = ib;
  24423. return ib;
  24424. }
  24425. function getArrayBuffer(json, uuid) {
  24426. if (arrayBufferMap[uuid] !== undefined) return arrayBufferMap[uuid];
  24427. const arrayBuffers = json.arrayBuffers;
  24428. const arrayBuffer = arrayBuffers[uuid];
  24429. const ab = new Uint32Array(arrayBuffer).buffer;
  24430. arrayBufferMap[uuid] = ab;
  24431. return ab;
  24432. }
  24433. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  24434. const index = json.data.index;
  24435. if (index !== undefined) {
  24436. const typedArray = getTypedArray(index.type, index.array);
  24437. geometry.setIndex(new BufferAttribute(typedArray, 1));
  24438. }
  24439. const attributes = json.data.attributes;
  24440. for (const key in attributes) {
  24441. const attribute = attributes[key];
  24442. let bufferAttribute;
  24443. if (attribute.isInterleavedBufferAttribute) {
  24444. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  24445. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  24446. } else {
  24447. const typedArray = getTypedArray(attribute.type, attribute.array);
  24448. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  24449. bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  24450. }
  24451. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  24452. geometry.setAttribute(key, bufferAttribute);
  24453. }
  24454. const morphAttributes = json.data.morphAttributes;
  24455. if (morphAttributes) {
  24456. for (const key in morphAttributes) {
  24457. const attributeArray = morphAttributes[key];
  24458. const array = [];
  24459. for (let i = 0, il = attributeArray.length; i < il; i++) {
  24460. const attribute = attributeArray[i];
  24461. let bufferAttribute;
  24462. if (attribute.isInterleavedBufferAttribute) {
  24463. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  24464. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  24465. } else {
  24466. const typedArray = getTypedArray(attribute.type, attribute.array);
  24467. bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  24468. }
  24469. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  24470. array.push(bufferAttribute);
  24471. }
  24472. geometry.morphAttributes[key] = array;
  24473. }
  24474. }
  24475. const morphTargetsRelative = json.data.morphTargetsRelative;
  24476. if (morphTargetsRelative) {
  24477. geometry.morphTargetsRelative = true;
  24478. }
  24479. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  24480. if (groups !== undefined) {
  24481. for (let i = 0, n = groups.length; i !== n; ++i) {
  24482. const group = groups[i];
  24483. geometry.addGroup(group.start, group.count, group.materialIndex);
  24484. }
  24485. }
  24486. const boundingSphere = json.data.boundingSphere;
  24487. if (boundingSphere !== undefined) {
  24488. const center = new Vector3();
  24489. if (boundingSphere.center !== undefined) {
  24490. center.fromArray(boundingSphere.center);
  24491. }
  24492. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  24493. }
  24494. if (json.name) geometry.name = json.name;
  24495. if (json.userData) geometry.userData = json.userData;
  24496. return geometry;
  24497. }
  24498. });
  24499. class ObjectLoader extends Loader {
  24500. constructor(manager) {
  24501. super(manager);
  24502. }
  24503. load(url, onLoad, onProgress, onError) {
  24504. const scope = this;
  24505. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  24506. this.resourcePath = this.resourcePath || path;
  24507. const loader = new FileLoader(this.manager);
  24508. loader.setPath(this.path);
  24509. loader.setRequestHeader(this.requestHeader);
  24510. loader.setWithCredentials(this.withCredentials);
  24511. loader.load(url, function (text) {
  24512. let json = null;
  24513. try {
  24514. json = JSON.parse(text);
  24515. } catch (error) {
  24516. if (onError !== undefined) onError(error);
  24517. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  24518. return;
  24519. }
  24520. const metadata = json.metadata;
  24521. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  24522. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  24523. return;
  24524. }
  24525. scope.parse(json, onLoad);
  24526. }, onProgress, onError);
  24527. }
  24528. parse(json, onLoad) {
  24529. const animations = this.parseAnimations(json.animations);
  24530. const shapes = this.parseShapes(json.shapes);
  24531. const geometries = this.parseGeometries(json.geometries, shapes);
  24532. const images = this.parseImages(json.images, function () {
  24533. if (onLoad !== undefined) onLoad(object);
  24534. });
  24535. const textures = this.parseTextures(json.textures, images);
  24536. const materials = this.parseMaterials(json.materials, textures);
  24537. const object = this.parseObject(json.object, geometries, materials, animations);
  24538. const skeletons = this.parseSkeletons(json.skeletons, object);
  24539. this.bindSkeletons(object, skeletons); //
  24540. if (onLoad !== undefined) {
  24541. let hasImages = false;
  24542. for (const uuid in images) {
  24543. if (images[uuid] instanceof HTMLImageElement) {
  24544. hasImages = true;
  24545. break;
  24546. }
  24547. }
  24548. if (hasImages === false) onLoad(object);
  24549. }
  24550. return object;
  24551. }
  24552. parseShapes(json) {
  24553. const shapes = {};
  24554. if (json !== undefined) {
  24555. for (let i = 0, l = json.length; i < l; i++) {
  24556. const shape = new Shape().fromJSON(json[i]);
  24557. shapes[shape.uuid] = shape;
  24558. }
  24559. }
  24560. return shapes;
  24561. }
  24562. parseSkeletons(json, object) {
  24563. const skeletons = {};
  24564. const bones = {}; // generate bone lookup table
  24565. object.traverse(function (child) {
  24566. if (child.isBone) bones[child.uuid] = child;
  24567. }); // create skeletons
  24568. if (json !== undefined) {
  24569. for (let i = 0, l = json.length; i < l; i++) {
  24570. const skeleton = new Skeleton().fromJSON(json[i], bones);
  24571. skeletons[skeleton.uuid] = skeleton;
  24572. }
  24573. }
  24574. return skeletons;
  24575. }
  24576. parseGeometries(json, shapes) {
  24577. const geometries = {};
  24578. let geometryShapes;
  24579. if (json !== undefined) {
  24580. const bufferGeometryLoader = new BufferGeometryLoader();
  24581. for (let i = 0, l = json.length; i < l; i++) {
  24582. let geometry;
  24583. const data = json[i];
  24584. switch (data.type) {
  24585. case 'PlaneGeometry':
  24586. case 'PlaneBufferGeometry':
  24587. geometry = new Geometries[data.type](data.width, data.height, data.widthSegments, data.heightSegments);
  24588. break;
  24589. case 'BoxGeometry':
  24590. case 'BoxBufferGeometry':
  24591. case 'CubeGeometry':
  24592. // backwards compatible
  24593. geometry = new Geometries[data.type](data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  24594. break;
  24595. case 'CircleGeometry':
  24596. case 'CircleBufferGeometry':
  24597. geometry = new Geometries[data.type](data.radius, data.segments, data.thetaStart, data.thetaLength);
  24598. break;
  24599. case 'CylinderGeometry':
  24600. case 'CylinderBufferGeometry':
  24601. geometry = new Geometries[data.type](data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  24602. break;
  24603. case 'ConeGeometry':
  24604. case 'ConeBufferGeometry':
  24605. geometry = new Geometries[data.type](data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  24606. break;
  24607. case 'SphereGeometry':
  24608. case 'SphereBufferGeometry':
  24609. geometry = new Geometries[data.type](data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  24610. break;
  24611. case 'DodecahedronGeometry':
  24612. case 'DodecahedronBufferGeometry':
  24613. case 'IcosahedronGeometry':
  24614. case 'IcosahedronBufferGeometry':
  24615. case 'OctahedronGeometry':
  24616. case 'OctahedronBufferGeometry':
  24617. case 'TetrahedronGeometry':
  24618. case 'TetrahedronBufferGeometry':
  24619. geometry = new Geometries[data.type](data.radius, data.detail);
  24620. break;
  24621. case 'RingGeometry':
  24622. case 'RingBufferGeometry':
  24623. geometry = new Geometries[data.type](data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  24624. break;
  24625. case 'TorusGeometry':
  24626. case 'TorusBufferGeometry':
  24627. geometry = new Geometries[data.type](data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  24628. break;
  24629. case 'TorusKnotGeometry':
  24630. case 'TorusKnotBufferGeometry':
  24631. geometry = new Geometries[data.type](data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  24632. break;
  24633. case 'TubeGeometry':
  24634. case 'TubeBufferGeometry':
  24635. // This only works for built-in curves (e.g. CatmullRomCurve3).
  24636. // User defined curves or instances of CurvePath will not be deserialized.
  24637. geometry = new Geometries[data.type](new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  24638. break;
  24639. case 'LatheGeometry':
  24640. case 'LatheBufferGeometry':
  24641. geometry = new Geometries[data.type](data.points, data.segments, data.phiStart, data.phiLength);
  24642. break;
  24643. case 'PolyhedronGeometry':
  24644. case 'PolyhedronBufferGeometry':
  24645. geometry = new Geometries[data.type](data.vertices, data.indices, data.radius, data.details);
  24646. break;
  24647. case 'ShapeGeometry':
  24648. case 'ShapeBufferGeometry':
  24649. geometryShapes = [];
  24650. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  24651. const shape = shapes[data.shapes[j]];
  24652. geometryShapes.push(shape);
  24653. }
  24654. geometry = new Geometries[data.type](geometryShapes, data.curveSegments);
  24655. break;
  24656. case 'ExtrudeGeometry':
  24657. case 'ExtrudeBufferGeometry':
  24658. geometryShapes = [];
  24659. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  24660. const shape = shapes[data.shapes[j]];
  24661. geometryShapes.push(shape);
  24662. }
  24663. const extrudePath = data.options.extrudePath;
  24664. if (extrudePath !== undefined) {
  24665. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  24666. }
  24667. geometry = new Geometries[data.type](geometryShapes, data.options);
  24668. break;
  24669. case 'BufferGeometry':
  24670. case 'InstancedBufferGeometry':
  24671. geometry = bufferGeometryLoader.parse(data);
  24672. break;
  24673. case 'Geometry':
  24674. console.error('THREE.ObjectLoader: Loading "Geometry" is not supported anymore.');
  24675. break;
  24676. default:
  24677. console.warn('THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"');
  24678. continue;
  24679. }
  24680. geometry.uuid = data.uuid;
  24681. if (data.name !== undefined) geometry.name = data.name;
  24682. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  24683. geometries[data.uuid] = geometry;
  24684. }
  24685. }
  24686. return geometries;
  24687. }
  24688. parseMaterials(json, textures) {
  24689. const cache = {}; // MultiMaterial
  24690. const materials = {};
  24691. if (json !== undefined) {
  24692. const loader = new MaterialLoader();
  24693. loader.setTextures(textures);
  24694. for (let i = 0, l = json.length; i < l; i++) {
  24695. const data = json[i];
  24696. if (data.type === 'MultiMaterial') {
  24697. // Deprecated
  24698. const array = [];
  24699. for (let j = 0; j < data.materials.length; j++) {
  24700. const material = data.materials[j];
  24701. if (cache[material.uuid] === undefined) {
  24702. cache[material.uuid] = loader.parse(material);
  24703. }
  24704. array.push(cache[material.uuid]);
  24705. }
  24706. materials[data.uuid] = array;
  24707. } else {
  24708. if (cache[data.uuid] === undefined) {
  24709. cache[data.uuid] = loader.parse(data);
  24710. }
  24711. materials[data.uuid] = cache[data.uuid];
  24712. }
  24713. }
  24714. }
  24715. return materials;
  24716. }
  24717. parseAnimations(json) {
  24718. const animations = {};
  24719. if (json !== undefined) {
  24720. for (let i = 0; i < json.length; i++) {
  24721. const data = json[i];
  24722. const clip = AnimationClip.parse(data);
  24723. animations[clip.uuid] = clip;
  24724. }
  24725. }
  24726. return animations;
  24727. }
  24728. parseImages(json, onLoad) {
  24729. const scope = this;
  24730. const images = {};
  24731. let loader;
  24732. function loadImage(url) {
  24733. scope.manager.itemStart(url);
  24734. return loader.load(url, function () {
  24735. scope.manager.itemEnd(url);
  24736. }, undefined, function () {
  24737. scope.manager.itemError(url);
  24738. scope.manager.itemEnd(url);
  24739. });
  24740. }
  24741. function deserializeImage(image) {
  24742. if (typeof image === 'string') {
  24743. const url = image;
  24744. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  24745. return loadImage(path);
  24746. } else {
  24747. if (image.data) {
  24748. return {
  24749. data: getTypedArray(image.type, image.data),
  24750. width: image.width,
  24751. height: image.height
  24752. };
  24753. } else {
  24754. return null;
  24755. }
  24756. }
  24757. }
  24758. if (json !== undefined && json.length > 0) {
  24759. const manager = new LoadingManager(onLoad);
  24760. loader = new ImageLoader(manager);
  24761. loader.setCrossOrigin(this.crossOrigin);
  24762. for (let i = 0, il = json.length; i < il; i++) {
  24763. const image = json[i];
  24764. const url = image.url;
  24765. if (Array.isArray(url)) {
  24766. // load array of images e.g CubeTexture
  24767. images[image.uuid] = [];
  24768. for (let j = 0, jl = url.length; j < jl; j++) {
  24769. const currentUrl = url[j];
  24770. const deserializedImage = deserializeImage(currentUrl);
  24771. if (deserializedImage !== null) {
  24772. if (deserializedImage instanceof HTMLImageElement) {
  24773. images[image.uuid].push(deserializedImage);
  24774. } else {
  24775. // special case: handle array of data textures for cube textures
  24776. images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  24777. }
  24778. }
  24779. }
  24780. } else {
  24781. // load single image
  24782. const deserializedImage = deserializeImage(image.url);
  24783. if (deserializedImage !== null) {
  24784. images[image.uuid] = deserializedImage;
  24785. }
  24786. }
  24787. }
  24788. }
  24789. return images;
  24790. }
  24791. parseTextures(json, images) {
  24792. function parseConstant(value, type) {
  24793. if (typeof value === 'number') return value;
  24794. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  24795. return type[value];
  24796. }
  24797. const textures = {};
  24798. if (json !== undefined) {
  24799. for (let i = 0, l = json.length; i < l; i++) {
  24800. const data = json[i];
  24801. if (data.image === undefined) {
  24802. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  24803. }
  24804. if (images[data.image] === undefined) {
  24805. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  24806. }
  24807. let texture;
  24808. const image = images[data.image];
  24809. if (Array.isArray(image)) {
  24810. texture = new CubeTexture(image);
  24811. if (image.length === 6) texture.needsUpdate = true;
  24812. } else {
  24813. if (image && image.data) {
  24814. texture = new DataTexture(image.data, image.width, image.height);
  24815. } else {
  24816. texture = new Texture(image);
  24817. }
  24818. if (image) texture.needsUpdate = true; // textures can have undefined image data
  24819. }
  24820. texture.uuid = data.uuid;
  24821. if (data.name !== undefined) texture.name = data.name;
  24822. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  24823. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  24824. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  24825. if (data.center !== undefined) texture.center.fromArray(data.center);
  24826. if (data.rotation !== undefined) texture.rotation = data.rotation;
  24827. if (data.wrap !== undefined) {
  24828. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  24829. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  24830. }
  24831. if (data.format !== undefined) texture.format = data.format;
  24832. if (data.type !== undefined) texture.type = data.type;
  24833. if (data.encoding !== undefined) texture.encoding = data.encoding;
  24834. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  24835. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  24836. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  24837. if (data.flipY !== undefined) texture.flipY = data.flipY;
  24838. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  24839. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  24840. textures[data.uuid] = texture;
  24841. }
  24842. }
  24843. return textures;
  24844. }
  24845. parseObject(data, geometries, materials, animations) {
  24846. let object;
  24847. function getGeometry(name) {
  24848. if (geometries[name] === undefined) {
  24849. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  24850. }
  24851. return geometries[name];
  24852. }
  24853. function getMaterial(name) {
  24854. if (name === undefined) return undefined;
  24855. if (Array.isArray(name)) {
  24856. const array = [];
  24857. for (let i = 0, l = name.length; i < l; i++) {
  24858. const uuid = name[i];
  24859. if (materials[uuid] === undefined) {
  24860. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  24861. }
  24862. array.push(materials[uuid]);
  24863. }
  24864. return array;
  24865. }
  24866. if (materials[name] === undefined) {
  24867. console.warn('THREE.ObjectLoader: Undefined material', name);
  24868. }
  24869. return materials[name];
  24870. }
  24871. let geometry, material;
  24872. switch (data.type) {
  24873. case 'Scene':
  24874. object = new Scene();
  24875. if (data.background !== undefined) {
  24876. if (Number.isInteger(data.background)) {
  24877. object.background = new Color(data.background);
  24878. }
  24879. }
  24880. if (data.fog !== undefined) {
  24881. if (data.fog.type === 'Fog') {
  24882. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  24883. } else if (data.fog.type === 'FogExp2') {
  24884. object.fog = new FogExp2(data.fog.color, data.fog.density);
  24885. }
  24886. }
  24887. break;
  24888. case 'PerspectiveCamera':
  24889. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  24890. if (data.focus !== undefined) object.focus = data.focus;
  24891. if (data.zoom !== undefined) object.zoom = data.zoom;
  24892. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  24893. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  24894. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24895. break;
  24896. case 'OrthographicCamera':
  24897. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  24898. if (data.zoom !== undefined) object.zoom = data.zoom;
  24899. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24900. break;
  24901. case 'AmbientLight':
  24902. object = new AmbientLight(data.color, data.intensity);
  24903. break;
  24904. case 'DirectionalLight':
  24905. object = new DirectionalLight(data.color, data.intensity);
  24906. break;
  24907. case 'PointLight':
  24908. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  24909. break;
  24910. case 'RectAreaLight':
  24911. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  24912. break;
  24913. case 'SpotLight':
  24914. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  24915. break;
  24916. case 'HemisphereLight':
  24917. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  24918. break;
  24919. case 'LightProbe':
  24920. object = new LightProbe().fromJSON(data);
  24921. break;
  24922. case 'SkinnedMesh':
  24923. geometry = getGeometry(data.geometry);
  24924. material = getMaterial(data.material);
  24925. object = new SkinnedMesh(geometry, material);
  24926. if (data.bindMode !== undefined) object.bindMode = data.bindMode;
  24927. if (data.bindMatrix !== undefined) object.bindMatrix.fromArray(data.bindMatrix);
  24928. if (data.skeleton !== undefined) object.skeleton = data.skeleton;
  24929. break;
  24930. case 'Mesh':
  24931. geometry = getGeometry(data.geometry);
  24932. material = getMaterial(data.material);
  24933. object = new Mesh(geometry, material);
  24934. break;
  24935. case 'InstancedMesh':
  24936. geometry = getGeometry(data.geometry);
  24937. material = getMaterial(data.material);
  24938. const count = data.count;
  24939. const instanceMatrix = data.instanceMatrix;
  24940. object = new InstancedMesh(geometry, material, count);
  24941. object.instanceMatrix = new BufferAttribute(new Float32Array(instanceMatrix.array), 16);
  24942. break;
  24943. case 'LOD':
  24944. object = new LOD();
  24945. break;
  24946. case 'Line':
  24947. object = new Line(getGeometry(data.geometry), getMaterial(data.material), data.mode);
  24948. break;
  24949. case 'LineLoop':
  24950. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  24951. break;
  24952. case 'LineSegments':
  24953. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  24954. break;
  24955. case 'PointCloud':
  24956. case 'Points':
  24957. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  24958. break;
  24959. case 'Sprite':
  24960. object = new Sprite(getMaterial(data.material));
  24961. break;
  24962. case 'Group':
  24963. object = new Group();
  24964. break;
  24965. case 'Bone':
  24966. object = new Bone();
  24967. break;
  24968. default:
  24969. object = new Object3D();
  24970. }
  24971. object.uuid = data.uuid;
  24972. if (data.name !== undefined) object.name = data.name;
  24973. if (data.matrix !== undefined) {
  24974. object.matrix.fromArray(data.matrix);
  24975. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  24976. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  24977. } else {
  24978. if (data.position !== undefined) object.position.fromArray(data.position);
  24979. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  24980. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  24981. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  24982. }
  24983. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  24984. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  24985. if (data.shadow) {
  24986. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  24987. if (data.shadow.normalBias !== undefined) object.shadow.normalBias = data.shadow.normalBias;
  24988. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  24989. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  24990. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  24991. }
  24992. if (data.visible !== undefined) object.visible = data.visible;
  24993. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  24994. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  24995. if (data.userData !== undefined) object.userData = data.userData;
  24996. if (data.layers !== undefined) object.layers.mask = data.layers;
  24997. if (data.children !== undefined) {
  24998. const children = data.children;
  24999. for (let i = 0; i < children.length; i++) {
  25000. object.add(this.parseObject(children[i], geometries, materials, animations));
  25001. }
  25002. }
  25003. if (data.animations !== undefined) {
  25004. const objectAnimations = data.animations;
  25005. for (let i = 0; i < objectAnimations.length; i++) {
  25006. const uuid = objectAnimations[i];
  25007. object.animations.push(animations[uuid]);
  25008. }
  25009. }
  25010. if (data.type === 'LOD') {
  25011. if (data.autoUpdate !== undefined) object.autoUpdate = data.autoUpdate;
  25012. const levels = data.levels;
  25013. for (let l = 0; l < levels.length; l++) {
  25014. const level = levels[l];
  25015. const child = object.getObjectByProperty('uuid', level.object);
  25016. if (child !== undefined) {
  25017. object.addLevel(child, level.distance);
  25018. }
  25019. }
  25020. }
  25021. return object;
  25022. }
  25023. bindSkeletons(object, skeletons) {
  25024. if (Object.keys(skeletons).length === 0) return;
  25025. object.traverse(function (child) {
  25026. if (child.isSkinnedMesh === true && child.skeleton !== undefined) {
  25027. const skeleton = skeletons[child.skeleton];
  25028. if (skeleton === undefined) {
  25029. console.warn('THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton);
  25030. } else {
  25031. child.bind(skeleton, child.bindMatrix);
  25032. }
  25033. }
  25034. });
  25035. }
  25036. /* DEPRECATED */
  25037. setTexturePath(value) {
  25038. console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
  25039. return this.setResourcePath(value);
  25040. }
  25041. }
  25042. exports.ObjectLoader = ObjectLoader;
  25043. const TEXTURE_MAPPING = {
  25044. UVMapping: UVMapping,
  25045. CubeReflectionMapping: CubeReflectionMapping,
  25046. CubeRefractionMapping: CubeRefractionMapping,
  25047. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  25048. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  25049. CubeUVReflectionMapping: CubeUVReflectionMapping,
  25050. CubeUVRefractionMapping: CubeUVRefractionMapping
  25051. };
  25052. const TEXTURE_WRAPPING = {
  25053. RepeatWrapping: RepeatWrapping,
  25054. ClampToEdgeWrapping: ClampToEdgeWrapping,
  25055. MirroredRepeatWrapping: MirroredRepeatWrapping
  25056. };
  25057. const TEXTURE_FILTER = {
  25058. NearestFilter: NearestFilter,
  25059. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  25060. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  25061. LinearFilter: LinearFilter,
  25062. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  25063. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  25064. };
  25065. function ImageBitmapLoader(manager) {
  25066. if (typeof createImageBitmap === 'undefined') {
  25067. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  25068. }
  25069. if (typeof fetch === 'undefined') {
  25070. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  25071. }
  25072. Loader.call(this, manager);
  25073. this.options = {
  25074. premultiplyAlpha: 'none'
  25075. };
  25076. }
  25077. ImageBitmapLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  25078. constructor: ImageBitmapLoader,
  25079. isImageBitmapLoader: true,
  25080. setOptions: function setOptions(options) {
  25081. this.options = options;
  25082. return this;
  25083. },
  25084. load: function (url, onLoad, onProgress, onError) {
  25085. if (url === undefined) url = '';
  25086. if (this.path !== undefined) url = this.path + url;
  25087. url = this.manager.resolveURL(url);
  25088. const scope = this;
  25089. const cached = Cache.get(url);
  25090. if (cached !== undefined) {
  25091. scope.manager.itemStart(url);
  25092. setTimeout(function () {
  25093. if (onLoad) onLoad(cached);
  25094. scope.manager.itemEnd(url);
  25095. }, 0);
  25096. return cached;
  25097. }
  25098. const fetchOptions = {};
  25099. fetchOptions.credentials = this.crossOrigin === 'anonymous' ? 'same-origin' : 'include';
  25100. fetch(url, fetchOptions).then(function (res) {
  25101. return res.blob();
  25102. }).then(function (blob) {
  25103. return createImageBitmap(blob, scope.options);
  25104. }).then(function (imageBitmap) {
  25105. Cache.add(url, imageBitmap);
  25106. if (onLoad) onLoad(imageBitmap);
  25107. scope.manager.itemEnd(url);
  25108. }).catch(function (e) {
  25109. if (onError) onError(e);
  25110. scope.manager.itemError(url);
  25111. scope.manager.itemEnd(url);
  25112. });
  25113. scope.manager.itemStart(url);
  25114. }
  25115. });
  25116. function ShapePath() {
  25117. this.type = 'ShapePath';
  25118. this.color = new Color();
  25119. this.subPaths = [];
  25120. this.currentPath = null;
  25121. }
  25122. Object.assign(ShapePath.prototype, {
  25123. moveTo: function (x, y) {
  25124. this.currentPath = new Path();
  25125. this.subPaths.push(this.currentPath);
  25126. this.currentPath.moveTo(x, y);
  25127. return this;
  25128. },
  25129. lineTo: function (x, y) {
  25130. this.currentPath.lineTo(x, y);
  25131. return this;
  25132. },
  25133. quadraticCurveTo: function (aCPx, aCPy, aX, aY) {
  25134. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  25135. return this;
  25136. },
  25137. bezierCurveTo: function (aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  25138. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  25139. return this;
  25140. },
  25141. splineThru: function (pts) {
  25142. this.currentPath.splineThru(pts);
  25143. return this;
  25144. },
  25145. toShapes: function (isCCW, noHoles) {
  25146. function toShapesNoHoles(inSubpaths) {
  25147. const shapes = [];
  25148. for (let i = 0, l = inSubpaths.length; i < l; i++) {
  25149. const tmpPath = inSubpaths[i];
  25150. const tmpShape = new Shape();
  25151. tmpShape.curves = tmpPath.curves;
  25152. shapes.push(tmpShape);
  25153. }
  25154. return shapes;
  25155. }
  25156. function isPointInsidePolygon(inPt, inPolygon) {
  25157. const polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  25158. // toggling of inside/outside at every single! intersection point of an edge
  25159. // with the horizontal line through inPt, left of inPt
  25160. // not counting lowerY endpoints of edges and whole edges on that line
  25161. let inside = false;
  25162. for (let p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  25163. let edgeLowPt = inPolygon[p];
  25164. let edgeHighPt = inPolygon[q];
  25165. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  25166. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  25167. if (Math.abs(edgeDy) > Number.EPSILON) {
  25168. // not parallel
  25169. if (edgeDy < 0) {
  25170. edgeLowPt = inPolygon[q];
  25171. edgeDx = -edgeDx;
  25172. edgeHighPt = inPolygon[p];
  25173. edgeDy = -edgeDy;
  25174. }
  25175. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  25176. if (inPt.y === edgeLowPt.y) {
  25177. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  25178. // continue; // no intersection or edgeLowPt => doesn't count !!!
  25179. } else {
  25180. const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  25181. if (perpEdge === 0) return true; // inPt is on contour ?
  25182. if (perpEdge < 0) continue;
  25183. inside = !inside; // true intersection left of inPt
  25184. }
  25185. } else {
  25186. // parallel or collinear
  25187. if (inPt.y !== edgeLowPt.y) continue; // parallel
  25188. // edge lies on the same horizontal line as inPt
  25189. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  25190. // continue;
  25191. }
  25192. }
  25193. return inside;
  25194. }
  25195. const isClockWise = ShapeUtils.isClockWise;
  25196. const subPaths = this.subPaths;
  25197. if (subPaths.length === 0) return [];
  25198. if (noHoles === true) return toShapesNoHoles(subPaths);
  25199. let solid, tmpPath, tmpShape;
  25200. const shapes = [];
  25201. if (subPaths.length === 1) {
  25202. tmpPath = subPaths[0];
  25203. tmpShape = new Shape();
  25204. tmpShape.curves = tmpPath.curves;
  25205. shapes.push(tmpShape);
  25206. return shapes;
  25207. }
  25208. let holesFirst = !isClockWise(subPaths[0].getPoints());
  25209. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  25210. const betterShapeHoles = [];
  25211. const newShapes = [];
  25212. let newShapeHoles = [];
  25213. let mainIdx = 0;
  25214. let tmpPoints;
  25215. newShapes[mainIdx] = undefined;
  25216. newShapeHoles[mainIdx] = [];
  25217. for (let i = 0, l = subPaths.length; i < l; i++) {
  25218. tmpPath = subPaths[i];
  25219. tmpPoints = tmpPath.getPoints();
  25220. solid = isClockWise(tmpPoints);
  25221. solid = isCCW ? !solid : solid;
  25222. if (solid) {
  25223. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  25224. newShapes[mainIdx] = {
  25225. s: new Shape(),
  25226. p: tmpPoints
  25227. };
  25228. newShapes[mainIdx].s.curves = tmpPath.curves;
  25229. if (holesFirst) mainIdx++;
  25230. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  25231. } else {
  25232. newShapeHoles[mainIdx].push({
  25233. h: tmpPath,
  25234. p: tmpPoints[0]
  25235. }); //console.log('ccw', i);
  25236. }
  25237. } // only Holes? -> probably all Shapes with wrong orientation
  25238. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  25239. if (newShapes.length > 1) {
  25240. let ambiguous = false;
  25241. const toChange = [];
  25242. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  25243. betterShapeHoles[sIdx] = [];
  25244. }
  25245. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  25246. const sho = newShapeHoles[sIdx];
  25247. for (let hIdx = 0; hIdx < sho.length; hIdx++) {
  25248. const ho = sho[hIdx];
  25249. let hole_unassigned = true;
  25250. for (let s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  25251. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  25252. if (sIdx !== s2Idx) toChange.push({
  25253. froms: sIdx,
  25254. tos: s2Idx,
  25255. hole: hIdx
  25256. });
  25257. if (hole_unassigned) {
  25258. hole_unassigned = false;
  25259. betterShapeHoles[s2Idx].push(ho);
  25260. } else {
  25261. ambiguous = true;
  25262. }
  25263. }
  25264. }
  25265. if (hole_unassigned) {
  25266. betterShapeHoles[sIdx].push(ho);
  25267. }
  25268. }
  25269. } // console.log("ambiguous: ", ambiguous);
  25270. if (toChange.length > 0) {
  25271. // console.log("to change: ", toChange);
  25272. if (!ambiguous) newShapeHoles = betterShapeHoles;
  25273. }
  25274. }
  25275. let tmpHoles;
  25276. for (let i = 0, il = newShapes.length; i < il; i++) {
  25277. tmpShape = newShapes[i].s;
  25278. shapes.push(tmpShape);
  25279. tmpHoles = newShapeHoles[i];
  25280. for (let j = 0, jl = tmpHoles.length; j < jl; j++) {
  25281. tmpShape.holes.push(tmpHoles[j].h);
  25282. }
  25283. } //console.log("shape", shapes);
  25284. return shapes;
  25285. }
  25286. });
  25287. function Font(data) {
  25288. this.type = 'Font';
  25289. this.data = data;
  25290. }
  25291. Object.assign(Font.prototype, {
  25292. isFont: true,
  25293. generateShapes: function (text, size = 100) {
  25294. const shapes = [];
  25295. const paths = createPaths(text, size, this.data);
  25296. for (let p = 0, pl = paths.length; p < pl; p++) {
  25297. Array.prototype.push.apply(shapes, paths[p].toShapes());
  25298. }
  25299. return shapes;
  25300. }
  25301. });
  25302. function createPaths(text, size, data) {
  25303. const chars = Array.from ? Array.from(text) : String(text).split(''); // workaround for IE11, see #13988
  25304. const scale = size / data.resolution;
  25305. const line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale;
  25306. const paths = [];
  25307. let offsetX = 0,
  25308. offsetY = 0;
  25309. for (let i = 0; i < chars.length; i++) {
  25310. const char = chars[i];
  25311. if (char === '\n') {
  25312. offsetX = 0;
  25313. offsetY -= line_height;
  25314. } else {
  25315. const ret = createPath(char, scale, offsetX, offsetY, data);
  25316. offsetX += ret.offsetX;
  25317. paths.push(ret.path);
  25318. }
  25319. }
  25320. return paths;
  25321. }
  25322. function createPath(char, scale, offsetX, offsetY, data) {
  25323. const glyph = data.glyphs[char] || data.glyphs['?'];
  25324. if (!glyph) {
  25325. console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.');
  25326. return;
  25327. }
  25328. const path = new ShapePath();
  25329. let x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  25330. if (glyph.o) {
  25331. const outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(' '));
  25332. for (let i = 0, l = outline.length; i < l;) {
  25333. const action = outline[i++];
  25334. switch (action) {
  25335. case 'm':
  25336. // moveTo
  25337. x = outline[i++] * scale + offsetX;
  25338. y = outline[i++] * scale + offsetY;
  25339. path.moveTo(x, y);
  25340. break;
  25341. case 'l':
  25342. // lineTo
  25343. x = outline[i++] * scale + offsetX;
  25344. y = outline[i++] * scale + offsetY;
  25345. path.lineTo(x, y);
  25346. break;
  25347. case 'q':
  25348. // quadraticCurveTo
  25349. cpx = outline[i++] * scale + offsetX;
  25350. cpy = outline[i++] * scale + offsetY;
  25351. cpx1 = outline[i++] * scale + offsetX;
  25352. cpy1 = outline[i++] * scale + offsetY;
  25353. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  25354. break;
  25355. case 'b':
  25356. // bezierCurveTo
  25357. cpx = outline[i++] * scale + offsetX;
  25358. cpy = outline[i++] * scale + offsetY;
  25359. cpx1 = outline[i++] * scale + offsetX;
  25360. cpy1 = outline[i++] * scale + offsetY;
  25361. cpx2 = outline[i++] * scale + offsetX;
  25362. cpy2 = outline[i++] * scale + offsetY;
  25363. path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);
  25364. break;
  25365. }
  25366. }
  25367. }
  25368. return {
  25369. offsetX: glyph.ha * scale,
  25370. path: path
  25371. };
  25372. }
  25373. function FontLoader(manager) {
  25374. Loader.call(this, manager);
  25375. }
  25376. FontLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  25377. constructor: FontLoader,
  25378. load: function (url, onLoad, onProgress, onError) {
  25379. const scope = this;
  25380. const loader = new FileLoader(this.manager);
  25381. loader.setPath(this.path);
  25382. loader.setRequestHeader(this.requestHeader);
  25383. loader.setWithCredentials(scope.withCredentials);
  25384. loader.load(url, function (text) {
  25385. let json;
  25386. try {
  25387. json = JSON.parse(text);
  25388. } catch (e) {
  25389. console.warn('THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.');
  25390. json = JSON.parse(text.substring(65, text.length - 2));
  25391. }
  25392. const font = scope.parse(json);
  25393. if (onLoad) onLoad(font);
  25394. }, onProgress, onError);
  25395. },
  25396. parse: function (json) {
  25397. return new Font(json);
  25398. }
  25399. });
  25400. let _context;
  25401. const AudioContext = {
  25402. getContext: function () {
  25403. if (_context === undefined) {
  25404. _context = new (window.AudioContext || window.webkitAudioContext)();
  25405. }
  25406. return _context;
  25407. },
  25408. setContext: function (value) {
  25409. _context = value;
  25410. }
  25411. };
  25412. exports.AudioContext = AudioContext;
  25413. function AudioLoader(manager) {
  25414. Loader.call(this, manager);
  25415. }
  25416. AudioLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  25417. constructor: AudioLoader,
  25418. load: function (url, onLoad, onProgress, onError) {
  25419. const scope = this;
  25420. const loader = new FileLoader(scope.manager);
  25421. loader.setResponseType('arraybuffer');
  25422. loader.setPath(scope.path);
  25423. loader.setRequestHeader(scope.requestHeader);
  25424. loader.setWithCredentials(scope.withCredentials);
  25425. loader.load(url, function (buffer) {
  25426. try {
  25427. // Create a copy of the buffer. The `decodeAudioData` method
  25428. // detaches the buffer when complete, preventing reuse.
  25429. const bufferCopy = buffer.slice(0);
  25430. const context = AudioContext.getContext();
  25431. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  25432. onLoad(audioBuffer);
  25433. });
  25434. } catch (e) {
  25435. if (onError) {
  25436. onError(e);
  25437. } else {
  25438. console.error(e);
  25439. }
  25440. scope.manager.itemError(url);
  25441. }
  25442. }, onProgress, onError);
  25443. }
  25444. });
  25445. function HemisphereLightProbe(skyColor, groundColor, intensity) {
  25446. LightProbe.call(this, undefined, intensity);
  25447. const color1 = new Color().set(skyColor);
  25448. const color2 = new Color().set(groundColor);
  25449. const sky = new Vector3(color1.r, color1.g, color1.b);
  25450. const ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  25451. const c0 = Math.sqrt(Math.PI);
  25452. const c1 = c0 * Math.sqrt(0.75);
  25453. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  25454. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  25455. }
  25456. HemisphereLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
  25457. constructor: HemisphereLightProbe,
  25458. isHemisphereLightProbe: true,
  25459. copy: function (source) {
  25460. // modifying colors not currently supported
  25461. LightProbe.prototype.copy.call(this, source);
  25462. return this;
  25463. },
  25464. toJSON: function (meta) {
  25465. const data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  25466. return data;
  25467. }
  25468. });
  25469. function AmbientLightProbe(color, intensity) {
  25470. LightProbe.call(this, undefined, intensity);
  25471. const color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  25472. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  25473. }
  25474. AmbientLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
  25475. constructor: AmbientLightProbe,
  25476. isAmbientLightProbe: true,
  25477. copy: function (source) {
  25478. // modifying color not currently supported
  25479. LightProbe.prototype.copy.call(this, source);
  25480. return this;
  25481. },
  25482. toJSON: function (meta) {
  25483. const data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  25484. return data;
  25485. }
  25486. });
  25487. const _eyeRight = new Matrix4();
  25488. const _eyeLeft = new Matrix4();
  25489. function StereoCamera() {
  25490. this.type = 'StereoCamera';
  25491. this.aspect = 1;
  25492. this.eyeSep = 0.064;
  25493. this.cameraL = new PerspectiveCamera();
  25494. this.cameraL.layers.enable(1);
  25495. this.cameraL.matrixAutoUpdate = false;
  25496. this.cameraR = new PerspectiveCamera();
  25497. this.cameraR.layers.enable(2);
  25498. this.cameraR.matrixAutoUpdate = false;
  25499. this._cache = {
  25500. focus: null,
  25501. fov: null,
  25502. aspect: null,
  25503. near: null,
  25504. far: null,
  25505. zoom: null,
  25506. eyeSep: null
  25507. };
  25508. }
  25509. Object.assign(StereoCamera.prototype, {
  25510. update: function (camera) {
  25511. const cache = this._cache;
  25512. const 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;
  25513. if (needsUpdate) {
  25514. cache.focus = camera.focus;
  25515. cache.fov = camera.fov;
  25516. cache.aspect = camera.aspect * this.aspect;
  25517. cache.near = camera.near;
  25518. cache.far = camera.far;
  25519. cache.zoom = camera.zoom;
  25520. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  25521. // http://paulbourke.net/stereographics/stereorender/
  25522. const projectionMatrix = camera.projectionMatrix.clone();
  25523. const eyeSepHalf = cache.eyeSep / 2;
  25524. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  25525. const ymax = cache.near * Math.tan(MathUtils.DEG2RAD * cache.fov * 0.5) / cache.zoom;
  25526. let xmin, xmax; // translate xOffset
  25527. _eyeLeft.elements[12] = -eyeSepHalf;
  25528. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  25529. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  25530. xmax = ymax * cache.aspect + eyeSepOnProjection;
  25531. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  25532. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  25533. this.cameraL.projectionMatrix.copy(projectionMatrix); // for right eye
  25534. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  25535. xmax = ymax * cache.aspect - eyeSepOnProjection;
  25536. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  25537. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  25538. this.cameraR.projectionMatrix.copy(projectionMatrix);
  25539. }
  25540. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  25541. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  25542. }
  25543. });
  25544. class Clock {
  25545. constructor(autoStart) {
  25546. this.autoStart = autoStart !== undefined ? autoStart : true;
  25547. this.startTime = 0;
  25548. this.oldTime = 0;
  25549. this.elapsedTime = 0;
  25550. this.running = false;
  25551. }
  25552. start() {
  25553. this.startTime = now();
  25554. this.oldTime = this.startTime;
  25555. this.elapsedTime = 0;
  25556. this.running = true;
  25557. }
  25558. stop() {
  25559. this.getElapsedTime();
  25560. this.running = false;
  25561. this.autoStart = false;
  25562. }
  25563. getElapsedTime() {
  25564. this.getDelta();
  25565. return this.elapsedTime;
  25566. }
  25567. getDelta() {
  25568. let diff = 0;
  25569. if (this.autoStart && !this.running) {
  25570. this.start();
  25571. return 0;
  25572. }
  25573. if (this.running) {
  25574. const newTime = now();
  25575. diff = (newTime - this.oldTime) / 1000;
  25576. this.oldTime = newTime;
  25577. this.elapsedTime += diff;
  25578. }
  25579. return diff;
  25580. }
  25581. }
  25582. exports.Clock = Clock;
  25583. function now() {
  25584. return (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  25585. }
  25586. const _position$2 =
  25587. /*@__PURE__*/
  25588. new Vector3();
  25589. const _quaternion$3 =
  25590. /*@__PURE__*/
  25591. new Quaternion();
  25592. const _scale$1 =
  25593. /*@__PURE__*/
  25594. new Vector3();
  25595. const _orientation =
  25596. /*@__PURE__*/
  25597. new Vector3();
  25598. class AudioListener extends Object3D {
  25599. constructor() {
  25600. super();
  25601. this.type = 'AudioListener';
  25602. this.context = AudioContext.getContext();
  25603. this.gain = this.context.createGain();
  25604. this.gain.connect(this.context.destination);
  25605. this.filter = null;
  25606. this.timeDelta = 0; // private
  25607. this._clock = new Clock();
  25608. }
  25609. getInput() {
  25610. return this.gain;
  25611. }
  25612. removeFilter() {
  25613. if (this.filter !== null) {
  25614. this.gain.disconnect(this.filter);
  25615. this.filter.disconnect(this.context.destination);
  25616. this.gain.connect(this.context.destination);
  25617. this.filter = null;
  25618. }
  25619. return this;
  25620. }
  25621. getFilter() {
  25622. return this.filter;
  25623. }
  25624. setFilter(value) {
  25625. if (this.filter !== null) {
  25626. this.gain.disconnect(this.filter);
  25627. this.filter.disconnect(this.context.destination);
  25628. } else {
  25629. this.gain.disconnect(this.context.destination);
  25630. }
  25631. this.filter = value;
  25632. this.gain.connect(this.filter);
  25633. this.filter.connect(this.context.destination);
  25634. return this;
  25635. }
  25636. getMasterVolume() {
  25637. return this.gain.gain.value;
  25638. }
  25639. setMasterVolume(value) {
  25640. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25641. return this;
  25642. }
  25643. updateMatrixWorld(force) {
  25644. super.updateMatrixWorld(force);
  25645. const listener = this.context.listener;
  25646. const up = this.up;
  25647. this.timeDelta = this._clock.getDelta();
  25648. this.matrixWorld.decompose(_position$2, _quaternion$3, _scale$1);
  25649. _orientation.set(0, 0, -1).applyQuaternion(_quaternion$3);
  25650. if (listener.positionX) {
  25651. // code path for Chrome (see #14393)
  25652. const endTime = this.context.currentTime + this.timeDelta;
  25653. listener.positionX.linearRampToValueAtTime(_position$2.x, endTime);
  25654. listener.positionY.linearRampToValueAtTime(_position$2.y, endTime);
  25655. listener.positionZ.linearRampToValueAtTime(_position$2.z, endTime);
  25656. listener.forwardX.linearRampToValueAtTime(_orientation.x, endTime);
  25657. listener.forwardY.linearRampToValueAtTime(_orientation.y, endTime);
  25658. listener.forwardZ.linearRampToValueAtTime(_orientation.z, endTime);
  25659. listener.upX.linearRampToValueAtTime(up.x, endTime);
  25660. listener.upY.linearRampToValueAtTime(up.y, endTime);
  25661. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  25662. } else {
  25663. listener.setPosition(_position$2.x, _position$2.y, _position$2.z);
  25664. listener.setOrientation(_orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z);
  25665. }
  25666. }
  25667. }
  25668. exports.AudioListener = AudioListener;
  25669. class Audio extends Object3D {
  25670. constructor(listener) {
  25671. super();
  25672. this.type = 'Audio';
  25673. this.listener = listener;
  25674. this.context = listener.context;
  25675. this.gain = this.context.createGain();
  25676. this.gain.connect(listener.getInput());
  25677. this.autoplay = false;
  25678. this.buffer = null;
  25679. this.detune = 0;
  25680. this.loop = false;
  25681. this.loopStart = 0;
  25682. this.loopEnd = 0;
  25683. this.offset = 0;
  25684. this.duration = undefined;
  25685. this.playbackRate = 1;
  25686. this.isPlaying = false;
  25687. this.hasPlaybackControl = true;
  25688. this.source = null;
  25689. this.sourceType = 'empty';
  25690. this._startedAt = 0;
  25691. this._progress = 0;
  25692. this._connected = false;
  25693. this.filters = [];
  25694. }
  25695. getOutput() {
  25696. return this.gain;
  25697. }
  25698. setNodeSource(audioNode) {
  25699. this.hasPlaybackControl = false;
  25700. this.sourceType = 'audioNode';
  25701. this.source = audioNode;
  25702. this.connect();
  25703. return this;
  25704. }
  25705. setMediaElementSource(mediaElement) {
  25706. this.hasPlaybackControl = false;
  25707. this.sourceType = 'mediaNode';
  25708. this.source = this.context.createMediaElementSource(mediaElement);
  25709. this.connect();
  25710. return this;
  25711. }
  25712. setMediaStreamSource(mediaStream) {
  25713. this.hasPlaybackControl = false;
  25714. this.sourceType = 'mediaStreamNode';
  25715. this.source = this.context.createMediaStreamSource(mediaStream);
  25716. this.connect();
  25717. return this;
  25718. }
  25719. setBuffer(audioBuffer) {
  25720. this.buffer = audioBuffer;
  25721. this.sourceType = 'buffer';
  25722. if (this.autoplay) this.play();
  25723. return this;
  25724. }
  25725. play(delay = 0) {
  25726. if (this.isPlaying === true) {
  25727. console.warn('THREE.Audio: Audio is already playing.');
  25728. return;
  25729. }
  25730. if (this.hasPlaybackControl === false) {
  25731. console.warn('THREE.Audio: this Audio has no playback control.');
  25732. return;
  25733. }
  25734. this._startedAt = this.context.currentTime + delay;
  25735. const source = this.context.createBufferSource();
  25736. source.buffer = this.buffer;
  25737. source.loop = this.loop;
  25738. source.loopStart = this.loopStart;
  25739. source.loopEnd = this.loopEnd;
  25740. source.onended = this.onEnded.bind(this);
  25741. source.start(this._startedAt, this._progress + this.offset, this.duration);
  25742. this.isPlaying = true;
  25743. this.source = source;
  25744. this.setDetune(this.detune);
  25745. this.setPlaybackRate(this.playbackRate);
  25746. return this.connect();
  25747. }
  25748. pause() {
  25749. if (this.hasPlaybackControl === false) {
  25750. console.warn('THREE.Audio: this Audio has no playback control.');
  25751. return;
  25752. }
  25753. if (this.isPlaying === true) {
  25754. // update current progress
  25755. this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
  25756. if (this.loop === true) {
  25757. // ensure _progress does not exceed duration with looped audios
  25758. this._progress = this._progress % (this.duration || this.buffer.duration);
  25759. }
  25760. this.source.stop();
  25761. this.source.onended = null;
  25762. this.isPlaying = false;
  25763. }
  25764. return this;
  25765. }
  25766. stop() {
  25767. if (this.hasPlaybackControl === false) {
  25768. console.warn('THREE.Audio: this Audio has no playback control.');
  25769. return;
  25770. }
  25771. this._progress = 0;
  25772. this.source.stop();
  25773. this.source.onended = null;
  25774. this.isPlaying = false;
  25775. return this;
  25776. }
  25777. connect() {
  25778. if (this.filters.length > 0) {
  25779. this.source.connect(this.filters[0]);
  25780. for (let i = 1, l = this.filters.length; i < l; i++) {
  25781. this.filters[i - 1].connect(this.filters[i]);
  25782. }
  25783. this.filters[this.filters.length - 1].connect(this.getOutput());
  25784. } else {
  25785. this.source.connect(this.getOutput());
  25786. }
  25787. this._connected = true;
  25788. return this;
  25789. }
  25790. disconnect() {
  25791. if (this.filters.length > 0) {
  25792. this.source.disconnect(this.filters[0]);
  25793. for (let i = 1, l = this.filters.length; i < l; i++) {
  25794. this.filters[i - 1].disconnect(this.filters[i]);
  25795. }
  25796. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  25797. } else {
  25798. this.source.disconnect(this.getOutput());
  25799. }
  25800. this._connected = false;
  25801. return this;
  25802. }
  25803. getFilters() {
  25804. return this.filters;
  25805. }
  25806. setFilters(value) {
  25807. if (!value) value = [];
  25808. if (this._connected === true) {
  25809. this.disconnect();
  25810. this.filters = value.slice();
  25811. this.connect();
  25812. } else {
  25813. this.filters = value.slice();
  25814. }
  25815. return this;
  25816. }
  25817. setDetune(value) {
  25818. this.detune = value;
  25819. if (this.source.detune === undefined) return; // only set detune when available
  25820. if (this.isPlaying === true) {
  25821. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  25822. }
  25823. return this;
  25824. }
  25825. getDetune() {
  25826. return this.detune;
  25827. }
  25828. getFilter() {
  25829. return this.getFilters()[0];
  25830. }
  25831. setFilter(filter) {
  25832. return this.setFilters(filter ? [filter] : []);
  25833. }
  25834. setPlaybackRate(value) {
  25835. if (this.hasPlaybackControl === false) {
  25836. console.warn('THREE.Audio: this Audio has no playback control.');
  25837. return;
  25838. }
  25839. this.playbackRate = value;
  25840. if (this.isPlaying === true) {
  25841. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  25842. }
  25843. return this;
  25844. }
  25845. getPlaybackRate() {
  25846. return this.playbackRate;
  25847. }
  25848. onEnded() {
  25849. this.isPlaying = false;
  25850. }
  25851. getLoop() {
  25852. if (this.hasPlaybackControl === false) {
  25853. console.warn('THREE.Audio: this Audio has no playback control.');
  25854. return false;
  25855. }
  25856. return this.loop;
  25857. }
  25858. setLoop(value) {
  25859. if (this.hasPlaybackControl === false) {
  25860. console.warn('THREE.Audio: this Audio has no playback control.');
  25861. return;
  25862. }
  25863. this.loop = value;
  25864. if (this.isPlaying === true) {
  25865. this.source.loop = this.loop;
  25866. }
  25867. return this;
  25868. }
  25869. setLoopStart(value) {
  25870. this.loopStart = value;
  25871. return this;
  25872. }
  25873. setLoopEnd(value) {
  25874. this.loopEnd = value;
  25875. return this;
  25876. }
  25877. getVolume() {
  25878. return this.gain.gain.value;
  25879. }
  25880. setVolume(value) {
  25881. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25882. return this;
  25883. }
  25884. }
  25885. exports.Audio = Audio;
  25886. const _position$3 =
  25887. /*@__PURE__*/
  25888. new Vector3();
  25889. const _quaternion$4 =
  25890. /*@__PURE__*/
  25891. new Quaternion();
  25892. const _scale$2 =
  25893. /*@__PURE__*/
  25894. new Vector3();
  25895. const _orientation$1 =
  25896. /*@__PURE__*/
  25897. new Vector3();
  25898. class PositionalAudio extends Audio {
  25899. constructor(listener) {
  25900. super(listener);
  25901. this.panner = this.context.createPanner();
  25902. this.panner.panningModel = 'HRTF';
  25903. this.panner.connect(this.gain);
  25904. }
  25905. getOutput() {
  25906. return this.panner;
  25907. }
  25908. getRefDistance() {
  25909. return this.panner.refDistance;
  25910. }
  25911. setRefDistance(value) {
  25912. this.panner.refDistance = value;
  25913. return this;
  25914. }
  25915. getRolloffFactor() {
  25916. return this.panner.rolloffFactor;
  25917. }
  25918. setRolloffFactor(value) {
  25919. this.panner.rolloffFactor = value;
  25920. return this;
  25921. }
  25922. getDistanceModel() {
  25923. return this.panner.distanceModel;
  25924. }
  25925. setDistanceModel(value) {
  25926. this.panner.distanceModel = value;
  25927. return this;
  25928. }
  25929. getMaxDistance() {
  25930. return this.panner.maxDistance;
  25931. }
  25932. setMaxDistance(value) {
  25933. this.panner.maxDistance = value;
  25934. return this;
  25935. }
  25936. setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {
  25937. this.panner.coneInnerAngle = coneInnerAngle;
  25938. this.panner.coneOuterAngle = coneOuterAngle;
  25939. this.panner.coneOuterGain = coneOuterGain;
  25940. return this;
  25941. }
  25942. updateMatrixWorld(force) {
  25943. super.updateMatrixWorld(force);
  25944. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  25945. this.matrixWorld.decompose(_position$3, _quaternion$4, _scale$2);
  25946. _orientation$1.set(0, 0, 1).applyQuaternion(_quaternion$4);
  25947. const panner = this.panner;
  25948. if (panner.positionX) {
  25949. // code path for Chrome and Firefox (see #14393)
  25950. const endTime = this.context.currentTime + this.listener.timeDelta;
  25951. panner.positionX.linearRampToValueAtTime(_position$3.x, endTime);
  25952. panner.positionY.linearRampToValueAtTime(_position$3.y, endTime);
  25953. panner.positionZ.linearRampToValueAtTime(_position$3.z, endTime);
  25954. panner.orientationX.linearRampToValueAtTime(_orientation$1.x, endTime);
  25955. panner.orientationY.linearRampToValueAtTime(_orientation$1.y, endTime);
  25956. panner.orientationZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  25957. } else {
  25958. panner.setPosition(_position$3.x, _position$3.y, _position$3.z);
  25959. panner.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z);
  25960. }
  25961. }
  25962. }
  25963. exports.PositionalAudio = PositionalAudio;
  25964. class AudioAnalyser {
  25965. constructor(audio, fftSize = 2048) {
  25966. this.analyser = audio.context.createAnalyser();
  25967. this.analyser.fftSize = fftSize;
  25968. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  25969. audio.getOutput().connect(this.analyser);
  25970. }
  25971. getFrequencyData() {
  25972. this.analyser.getByteFrequencyData(this.data);
  25973. return this.data;
  25974. }
  25975. getAverageFrequency() {
  25976. let value = 0;
  25977. const data = this.getFrequencyData();
  25978. for (let i = 0; i < data.length; i++) {
  25979. value += data[i];
  25980. }
  25981. return value / data.length;
  25982. }
  25983. }
  25984. exports.AudioAnalyser = AudioAnalyser;
  25985. function PropertyMixer(binding, typeName, valueSize) {
  25986. this.binding = binding;
  25987. this.valueSize = valueSize;
  25988. let mixFunction, mixFunctionAdditive, setIdentity; // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  25989. //
  25990. // interpolators can use .buffer as their .result
  25991. // the data then goes to 'incoming'
  25992. //
  25993. // 'accu0' and 'accu1' are used frame-interleaved for
  25994. // the cumulative result and are compared to detect
  25995. // changes
  25996. //
  25997. // 'orig' stores the original state of the property
  25998. //
  25999. // 'add' is used for additive cumulative results
  26000. //
  26001. // 'work' is optional and is only present for quaternion types. It is used
  26002. // to store intermediate quaternion multiplication results
  26003. switch (typeName) {
  26004. case 'quaternion':
  26005. mixFunction = this._slerp;
  26006. mixFunctionAdditive = this._slerpAdditive;
  26007. setIdentity = this._setAdditiveIdentityQuaternion;
  26008. this.buffer = new Float64Array(valueSize * 6);
  26009. this._workIndex = 5;
  26010. break;
  26011. case 'string':
  26012. case 'bool':
  26013. mixFunction = this._select; // Use the regular mix function and for additive on these types,
  26014. // additive is not relevant for non-numeric types
  26015. mixFunctionAdditive = this._select;
  26016. setIdentity = this._setAdditiveIdentityOther;
  26017. this.buffer = new Array(valueSize * 5);
  26018. break;
  26019. default:
  26020. mixFunction = this._lerp;
  26021. mixFunctionAdditive = this._lerpAdditive;
  26022. setIdentity = this._setAdditiveIdentityNumeric;
  26023. this.buffer = new Float64Array(valueSize * 5);
  26024. }
  26025. this._mixBufferRegion = mixFunction;
  26026. this._mixBufferRegionAdditive = mixFunctionAdditive;
  26027. this._setIdentity = setIdentity;
  26028. this._origIndex = 3;
  26029. this._addIndex = 4;
  26030. this.cumulativeWeight = 0;
  26031. this.cumulativeWeightAdditive = 0;
  26032. this.useCount = 0;
  26033. this.referenceCount = 0;
  26034. }
  26035. Object.assign(PropertyMixer.prototype, {
  26036. // accumulate data in the 'incoming' region into 'accu<i>'
  26037. accumulate: function (accuIndex, weight) {
  26038. // note: happily accumulating nothing when weight = 0, the caller knows
  26039. // the weight and shouldn't have made the call in the first place
  26040. const buffer = this.buffer,
  26041. stride = this.valueSize,
  26042. offset = accuIndex * stride + stride;
  26043. let currentWeight = this.cumulativeWeight;
  26044. if (currentWeight === 0) {
  26045. // accuN := incoming * weight
  26046. for (let i = 0; i !== stride; ++i) {
  26047. buffer[offset + i] = buffer[i];
  26048. }
  26049. currentWeight = weight;
  26050. } else {
  26051. // accuN := accuN + incoming * weight
  26052. currentWeight += weight;
  26053. const mix = weight / currentWeight;
  26054. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  26055. }
  26056. this.cumulativeWeight = currentWeight;
  26057. },
  26058. // accumulate data in the 'incoming' region into 'add'
  26059. accumulateAdditive: function (weight) {
  26060. const buffer = this.buffer,
  26061. stride = this.valueSize,
  26062. offset = stride * this._addIndex;
  26063. if (this.cumulativeWeightAdditive === 0) {
  26064. // add = identity
  26065. this._setIdentity();
  26066. } // add := add + incoming * weight
  26067. this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride);
  26068. this.cumulativeWeightAdditive += weight;
  26069. },
  26070. // apply the state of 'accu<i>' to the binding when accus differ
  26071. apply: function (accuIndex) {
  26072. const stride = this.valueSize,
  26073. buffer = this.buffer,
  26074. offset = accuIndex * stride + stride,
  26075. weight = this.cumulativeWeight,
  26076. weightAdditive = this.cumulativeWeightAdditive,
  26077. binding = this.binding;
  26078. this.cumulativeWeight = 0;
  26079. this.cumulativeWeightAdditive = 0;
  26080. if (weight < 1) {
  26081. // accuN := accuN + original * ( 1 - cumulativeWeight )
  26082. const originalValueOffset = stride * this._origIndex;
  26083. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  26084. }
  26085. if (weightAdditive > 0) {
  26086. // accuN := accuN + additive accuN
  26087. this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride);
  26088. }
  26089. for (let i = stride, e = stride + stride; i !== e; ++i) {
  26090. if (buffer[i] !== buffer[i + stride]) {
  26091. // value has changed -> update scene graph
  26092. binding.setValue(buffer, offset);
  26093. break;
  26094. }
  26095. }
  26096. },
  26097. // remember the state of the bound property and copy it to both accus
  26098. saveOriginalState: function () {
  26099. const binding = this.binding;
  26100. const buffer = this.buffer,
  26101. stride = this.valueSize,
  26102. originalValueOffset = stride * this._origIndex;
  26103. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  26104. for (let i = stride, e = originalValueOffset; i !== e; ++i) {
  26105. buffer[i] = buffer[originalValueOffset + i % stride];
  26106. } // Add to identity for additive
  26107. this._setIdentity();
  26108. this.cumulativeWeight = 0;
  26109. this.cumulativeWeightAdditive = 0;
  26110. },
  26111. // apply the state previously taken via 'saveOriginalState' to the binding
  26112. restoreOriginalState: function () {
  26113. const originalValueOffset = this.valueSize * 3;
  26114. this.binding.setValue(this.buffer, originalValueOffset);
  26115. },
  26116. _setAdditiveIdentityNumeric: function () {
  26117. const startIndex = this._addIndex * this.valueSize;
  26118. const endIndex = startIndex + this.valueSize;
  26119. for (let i = startIndex; i < endIndex; i++) {
  26120. this.buffer[i] = 0;
  26121. }
  26122. },
  26123. _setAdditiveIdentityQuaternion: function () {
  26124. this._setAdditiveIdentityNumeric();
  26125. this.buffer[this._addIndex * this.valueSize + 3] = 1;
  26126. },
  26127. _setAdditiveIdentityOther: function () {
  26128. const startIndex = this._origIndex * this.valueSize;
  26129. const targetIndex = this._addIndex * this.valueSize;
  26130. for (let i = 0; i < this.valueSize; i++) {
  26131. this.buffer[targetIndex + i] = this.buffer[startIndex + i];
  26132. }
  26133. },
  26134. // mix functions
  26135. _select: function (buffer, dstOffset, srcOffset, t, stride) {
  26136. if (t >= 0.5) {
  26137. for (let i = 0; i !== stride; ++i) {
  26138. buffer[dstOffset + i] = buffer[srcOffset + i];
  26139. }
  26140. }
  26141. },
  26142. _slerp: function (buffer, dstOffset, srcOffset, t) {
  26143. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  26144. },
  26145. _slerpAdditive: function (buffer, dstOffset, srcOffset, t, stride) {
  26146. const workOffset = this._workIndex * stride; // Store result in intermediate buffer offset
  26147. Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); // Slerp to the intermediate result
  26148. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t);
  26149. },
  26150. _lerp: function (buffer, dstOffset, srcOffset, t, stride) {
  26151. const s = 1 - t;
  26152. for (let i = 0; i !== stride; ++i) {
  26153. const j = dstOffset + i;
  26154. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  26155. }
  26156. },
  26157. _lerpAdditive: function (buffer, dstOffset, srcOffset, t, stride) {
  26158. for (let i = 0; i !== stride; ++i) {
  26159. const j = dstOffset + i;
  26160. buffer[j] = buffer[j] + buffer[srcOffset + i] * t;
  26161. }
  26162. }
  26163. }); // Characters [].:/ are reserved for track binding syntax.
  26164. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  26165. const _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  26166. // only latin characters, and the unicode \p{L} is not yet supported. So
  26167. // instead, we exclude reserved characters and match everything else.
  26168. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  26169. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  26170. // be matched to parse the rest of the track name.
  26171. const _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  26172. const _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  26173. // characters. Accessor may contain any character except closing bracket.
  26174. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  26175. // contain any non-bracket characters.
  26176. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  26177. const _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  26178. const _supportedObjectNames = ['material', 'materials', 'bones'];
  26179. function Composite(targetGroup, path, optionalParsedPath) {
  26180. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  26181. this._targetGroup = targetGroup;
  26182. this._bindings = targetGroup.subscribe_(path, parsedPath);
  26183. }
  26184. Object.assign(Composite.prototype, {
  26185. getValue: function (array, offset) {
  26186. this.bind(); // bind all binding
  26187. const firstValidIndex = this._targetGroup.nCachedObjects_,
  26188. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  26189. if (binding !== undefined) binding.getValue(array, offset);
  26190. },
  26191. setValue: function (array, offset) {
  26192. const bindings = this._bindings;
  26193. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  26194. bindings[i].setValue(array, offset);
  26195. }
  26196. },
  26197. bind: function () {
  26198. const bindings = this._bindings;
  26199. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  26200. bindings[i].bind();
  26201. }
  26202. },
  26203. unbind: function () {
  26204. const bindings = this._bindings;
  26205. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  26206. bindings[i].unbind();
  26207. }
  26208. }
  26209. });
  26210. function PropertyBinding(rootNode, path, parsedPath) {
  26211. this.path = path;
  26212. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  26213. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  26214. this.rootNode = rootNode;
  26215. }
  26216. Object.assign(PropertyBinding, {
  26217. Composite: Composite,
  26218. create: function (root, path, parsedPath) {
  26219. if (!(root && root.isAnimationObjectGroup)) {
  26220. return new PropertyBinding(root, path, parsedPath);
  26221. } else {
  26222. return new PropertyBinding.Composite(root, path, parsedPath);
  26223. }
  26224. },
  26225. /**
  26226. * Replaces spaces with underscores and removes unsupported characters from
  26227. * node names, to ensure compatibility with parseTrackName().
  26228. *
  26229. * @param {string} name Node name to be sanitized.
  26230. * @return {string}
  26231. */
  26232. sanitizeNodeName: function (name) {
  26233. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  26234. },
  26235. parseTrackName: function (trackName) {
  26236. const matches = _trackRe.exec(trackName);
  26237. if (!matches) {
  26238. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  26239. }
  26240. const results = {
  26241. // directoryName: matches[ 1 ], // (tschw) currently unused
  26242. nodeName: matches[2],
  26243. objectName: matches[3],
  26244. objectIndex: matches[4],
  26245. propertyName: matches[5],
  26246. // required
  26247. propertyIndex: matches[6]
  26248. };
  26249. const lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  26250. if (lastDot !== undefined && lastDot !== -1) {
  26251. const objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against an allowlist. Otherwise, there
  26252. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  26253. // 'bar' could be the objectName, or part of a nodeName (which can
  26254. // include '.' characters).
  26255. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  26256. results.nodeName = results.nodeName.substring(0, lastDot);
  26257. results.objectName = objectName;
  26258. }
  26259. }
  26260. if (results.propertyName === null || results.propertyName.length === 0) {
  26261. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  26262. }
  26263. return results;
  26264. },
  26265. findNode: function (root, nodeName) {
  26266. if (!nodeName || nodeName === "" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  26267. return root;
  26268. } // search into skeleton bones.
  26269. if (root.skeleton) {
  26270. const bone = root.skeleton.getBoneByName(nodeName);
  26271. if (bone !== undefined) {
  26272. return bone;
  26273. }
  26274. } // search into node subtree.
  26275. if (root.children) {
  26276. const searchNodeSubtree = function (children) {
  26277. for (let i = 0; i < children.length; i++) {
  26278. const childNode = children[i];
  26279. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  26280. return childNode;
  26281. }
  26282. const result = searchNodeSubtree(childNode.children);
  26283. if (result) return result;
  26284. }
  26285. return null;
  26286. };
  26287. const subTreeNode = searchNodeSubtree(root.children);
  26288. if (subTreeNode) {
  26289. return subTreeNode;
  26290. }
  26291. }
  26292. return null;
  26293. }
  26294. });
  26295. Object.assign(PropertyBinding.prototype, {
  26296. // prototype, continued
  26297. // these are used to "bind" a nonexistent property
  26298. _getValue_unavailable: function () {},
  26299. _setValue_unavailable: function () {},
  26300. BindingType: {
  26301. Direct: 0,
  26302. EntireArray: 1,
  26303. ArrayElement: 2,
  26304. HasFromToArray: 3
  26305. },
  26306. Versioning: {
  26307. None: 0,
  26308. NeedsUpdate: 1,
  26309. MatrixWorldNeedsUpdate: 2
  26310. },
  26311. GetterByBindingType: [function getValue_direct(buffer, offset) {
  26312. buffer[offset] = this.node[this.propertyName];
  26313. }, function getValue_array(buffer, offset) {
  26314. const source = this.resolvedProperty;
  26315. for (let i = 0, n = source.length; i !== n; ++i) {
  26316. buffer[offset++] = source[i];
  26317. }
  26318. }, function getValue_arrayElement(buffer, offset) {
  26319. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  26320. }, function getValue_toArray(buffer, offset) {
  26321. this.resolvedProperty.toArray(buffer, offset);
  26322. }],
  26323. SetterByBindingTypeAndVersioning: [[// Direct
  26324. function setValue_direct(buffer, offset) {
  26325. this.targetObject[this.propertyName] = buffer[offset];
  26326. }, function setValue_direct_setNeedsUpdate(buffer, offset) {
  26327. this.targetObject[this.propertyName] = buffer[offset];
  26328. this.targetObject.needsUpdate = true;
  26329. }, function setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  26330. this.targetObject[this.propertyName] = buffer[offset];
  26331. this.targetObject.matrixWorldNeedsUpdate = true;
  26332. }], [// EntireArray
  26333. function setValue_array(buffer, offset) {
  26334. const dest = this.resolvedProperty;
  26335. for (let i = 0, n = dest.length; i !== n; ++i) {
  26336. dest[i] = buffer[offset++];
  26337. }
  26338. }, function setValue_array_setNeedsUpdate(buffer, offset) {
  26339. const dest = this.resolvedProperty;
  26340. for (let i = 0, n = dest.length; i !== n; ++i) {
  26341. dest[i] = buffer[offset++];
  26342. }
  26343. this.targetObject.needsUpdate = true;
  26344. }, function setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  26345. const dest = this.resolvedProperty;
  26346. for (let i = 0, n = dest.length; i !== n; ++i) {
  26347. dest[i] = buffer[offset++];
  26348. }
  26349. this.targetObject.matrixWorldNeedsUpdate = true;
  26350. }], [// ArrayElement
  26351. function setValue_arrayElement(buffer, offset) {
  26352. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  26353. }, function setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  26354. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  26355. this.targetObject.needsUpdate = true;
  26356. }, function setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  26357. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  26358. this.targetObject.matrixWorldNeedsUpdate = true;
  26359. }], [// HasToFromArray
  26360. function setValue_fromArray(buffer, offset) {
  26361. this.resolvedProperty.fromArray(buffer, offset);
  26362. }, function setValue_fromArray_setNeedsUpdate(buffer, offset) {
  26363. this.resolvedProperty.fromArray(buffer, offset);
  26364. this.targetObject.needsUpdate = true;
  26365. }, function setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  26366. this.resolvedProperty.fromArray(buffer, offset);
  26367. this.targetObject.matrixWorldNeedsUpdate = true;
  26368. }]],
  26369. getValue: function getValue_unbound(targetArray, offset) {
  26370. this.bind();
  26371. this.getValue(targetArray, offset); // Note: This class uses a State pattern on a per-method basis:
  26372. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  26373. // prototype version of these methods with one that represents
  26374. // the bound state. When the property is not found, the methods
  26375. // become no-ops.
  26376. },
  26377. setValue: function getValue_unbound(sourceArray, offset) {
  26378. this.bind();
  26379. this.setValue(sourceArray, offset);
  26380. },
  26381. // create getter / setter pair for a property in the scene graph
  26382. bind: function () {
  26383. let targetObject = this.node;
  26384. const parsedPath = this.parsedPath;
  26385. const objectName = parsedPath.objectName;
  26386. const propertyName = parsedPath.propertyName;
  26387. let propertyIndex = parsedPath.propertyIndex;
  26388. if (!targetObject) {
  26389. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  26390. this.node = targetObject;
  26391. } // set fail state so we can just 'return' on error
  26392. this.getValue = this._getValue_unavailable;
  26393. this.setValue = this._setValue_unavailable; // ensure there is a value node
  26394. if (!targetObject) {
  26395. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  26396. return;
  26397. }
  26398. if (objectName) {
  26399. let objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  26400. switch (objectName) {
  26401. case 'materials':
  26402. if (!targetObject.material) {
  26403. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  26404. return;
  26405. }
  26406. if (!targetObject.material.materials) {
  26407. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  26408. return;
  26409. }
  26410. targetObject = targetObject.material.materials;
  26411. break;
  26412. case 'bones':
  26413. if (!targetObject.skeleton) {
  26414. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  26415. return;
  26416. } // potential future optimization: skip this if propertyIndex is already an integer
  26417. // and convert the integer string to a true integer.
  26418. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  26419. for (let i = 0; i < targetObject.length; i++) {
  26420. if (targetObject[i].name === objectIndex) {
  26421. objectIndex = i;
  26422. break;
  26423. }
  26424. }
  26425. break;
  26426. default:
  26427. if (targetObject[objectName] === undefined) {
  26428. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  26429. return;
  26430. }
  26431. targetObject = targetObject[objectName];
  26432. }
  26433. if (objectIndex !== undefined) {
  26434. if (targetObject[objectIndex] === undefined) {
  26435. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  26436. return;
  26437. }
  26438. targetObject = targetObject[objectIndex];
  26439. }
  26440. } // resolve property
  26441. const nodeProperty = targetObject[propertyName];
  26442. if (nodeProperty === undefined) {
  26443. const nodeName = parsedPath.nodeName;
  26444. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  26445. return;
  26446. } // determine versioning scheme
  26447. let versioning = this.Versioning.None;
  26448. this.targetObject = targetObject;
  26449. if (targetObject.needsUpdate !== undefined) {
  26450. // material
  26451. versioning = this.Versioning.NeedsUpdate;
  26452. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  26453. // node transform
  26454. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  26455. } // determine how the property gets bound
  26456. let bindingType = this.BindingType.Direct;
  26457. if (propertyIndex !== undefined) {
  26458. // access a sub element of the property array (only primitives are supported right now)
  26459. if (propertyName === "morphTargetInfluences") {
  26460. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  26461. // support resolving morphTarget names into indices.
  26462. if (!targetObject.geometry) {
  26463. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  26464. return;
  26465. }
  26466. if (targetObject.geometry.isBufferGeometry) {
  26467. if (!targetObject.geometry.morphAttributes) {
  26468. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  26469. return;
  26470. }
  26471. if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) {
  26472. propertyIndex = targetObject.morphTargetDictionary[propertyIndex];
  26473. }
  26474. } else {
  26475. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this);
  26476. return;
  26477. }
  26478. }
  26479. bindingType = this.BindingType.ArrayElement;
  26480. this.resolvedProperty = nodeProperty;
  26481. this.propertyIndex = propertyIndex;
  26482. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  26483. // must use copy for Object3D.Euler/Quaternion
  26484. bindingType = this.BindingType.HasFromToArray;
  26485. this.resolvedProperty = nodeProperty;
  26486. } else if (Array.isArray(nodeProperty)) {
  26487. bindingType = this.BindingType.EntireArray;
  26488. this.resolvedProperty = nodeProperty;
  26489. } else {
  26490. this.propertyName = propertyName;
  26491. } // select getter / setter
  26492. this.getValue = this.GetterByBindingType[bindingType];
  26493. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  26494. },
  26495. unbind: function () {
  26496. this.node = null; // back to the prototype version of getValue / setValue
  26497. // note: avoiding to mutate the shape of 'this' via 'delete'
  26498. this.getValue = this._getValue_unbound;
  26499. this.setValue = this._setValue_unbound;
  26500. }
  26501. }); // DECLARE ALIAS AFTER assign prototype
  26502. Object.assign(PropertyBinding.prototype, {
  26503. // initial state of these methods that calls 'bind'
  26504. _getValue_unbound: PropertyBinding.prototype.getValue,
  26505. _setValue_unbound: PropertyBinding.prototype.setValue
  26506. });
  26507. /**
  26508. *
  26509. * A group of objects that receives a shared animation state.
  26510. *
  26511. * Usage:
  26512. *
  26513. * - Add objects you would otherwise pass as 'root' to the
  26514. * constructor or the .clipAction method of AnimationMixer.
  26515. *
  26516. * - Instead pass this object as 'root'.
  26517. *
  26518. * - You can also add and remove objects later when the mixer
  26519. * is running.
  26520. *
  26521. * Note:
  26522. *
  26523. * Objects of this class appear as one object to the mixer,
  26524. * so cache control of the individual objects must be done
  26525. * on the group.
  26526. *
  26527. * Limitation:
  26528. *
  26529. * - The animated properties must be compatible among the
  26530. * all objects in the group.
  26531. *
  26532. * - A single property can either be controlled through a
  26533. * target group or directly, but not both.
  26534. */
  26535. function AnimationObjectGroup() {
  26536. this.uuid = MathUtils.generateUUID(); // cached objects followed by the active ones
  26537. this._objects = Array.prototype.slice.call(arguments);
  26538. this.nCachedObjects_ = 0; // threshold
  26539. // note: read by PropertyBinding.Composite
  26540. const indices = {};
  26541. this._indicesByUUID = indices; // for bookkeeping
  26542. for (let i = 0, n = arguments.length; i !== n; ++i) {
  26543. indices[arguments[i].uuid] = i;
  26544. }
  26545. this._paths = []; // inside: string
  26546. this._parsedPaths = []; // inside: { we don't care, here }
  26547. this._bindings = []; // inside: Array< PropertyBinding >
  26548. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  26549. const scope = this;
  26550. this.stats = {
  26551. objects: {
  26552. get total() {
  26553. return scope._objects.length;
  26554. },
  26555. get inUse() {
  26556. return this.total - scope.nCachedObjects_;
  26557. }
  26558. },
  26559. get bindingsPerObject() {
  26560. return scope._bindings.length;
  26561. }
  26562. };
  26563. }
  26564. Object.assign(AnimationObjectGroup.prototype, {
  26565. isAnimationObjectGroup: true,
  26566. add: function () {
  26567. const objects = this._objects,
  26568. indicesByUUID = this._indicesByUUID,
  26569. paths = this._paths,
  26570. parsedPaths = this._parsedPaths,
  26571. bindings = this._bindings,
  26572. nBindings = bindings.length;
  26573. let knownObject = undefined,
  26574. nObjects = objects.length,
  26575. nCachedObjects = this.nCachedObjects_;
  26576. for (let i = 0, n = arguments.length; i !== n; ++i) {
  26577. const object = arguments[i],
  26578. uuid = object.uuid;
  26579. let index = indicesByUUID[uuid];
  26580. if (index === undefined) {
  26581. // unknown object -> add it to the ACTIVE region
  26582. index = nObjects++;
  26583. indicesByUUID[uuid] = index;
  26584. objects.push(object); // accounting is done, now do the same for all bindings
  26585. for (let j = 0, m = nBindings; j !== m; ++j) {
  26586. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  26587. }
  26588. } else if (index < nCachedObjects) {
  26589. knownObject = objects[index]; // move existing object to the ACTIVE region
  26590. const firstActiveIndex = --nCachedObjects,
  26591. lastCachedObject = objects[firstActiveIndex];
  26592. indicesByUUID[lastCachedObject.uuid] = index;
  26593. objects[index] = lastCachedObject;
  26594. indicesByUUID[uuid] = firstActiveIndex;
  26595. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  26596. for (let j = 0, m = nBindings; j !== m; ++j) {
  26597. const bindingsForPath = bindings[j],
  26598. lastCached = bindingsForPath[firstActiveIndex];
  26599. let binding = bindingsForPath[index];
  26600. bindingsForPath[index] = lastCached;
  26601. if (binding === undefined) {
  26602. // since we do not bother to create new bindings
  26603. // for objects that are cached, the binding may
  26604. // or may not exist
  26605. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  26606. }
  26607. bindingsForPath[firstActiveIndex] = binding;
  26608. }
  26609. } else if (objects[index] !== knownObject) {
  26610. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  26611. } // else the object is already where we want it to be
  26612. } // for arguments
  26613. this.nCachedObjects_ = nCachedObjects;
  26614. },
  26615. remove: function () {
  26616. const objects = this._objects,
  26617. indicesByUUID = this._indicesByUUID,
  26618. bindings = this._bindings,
  26619. nBindings = bindings.length;
  26620. let nCachedObjects = this.nCachedObjects_;
  26621. for (let i = 0, n = arguments.length; i !== n; ++i) {
  26622. const object = arguments[i],
  26623. uuid = object.uuid,
  26624. index = indicesByUUID[uuid];
  26625. if (index !== undefined && index >= nCachedObjects) {
  26626. // move existing object into the CACHED region
  26627. const lastCachedIndex = nCachedObjects++,
  26628. firstActiveObject = objects[lastCachedIndex];
  26629. indicesByUUID[firstActiveObject.uuid] = index;
  26630. objects[index] = firstActiveObject;
  26631. indicesByUUID[uuid] = lastCachedIndex;
  26632. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  26633. for (let j = 0, m = nBindings; j !== m; ++j) {
  26634. const bindingsForPath = bindings[j],
  26635. firstActive = bindingsForPath[lastCachedIndex],
  26636. binding = bindingsForPath[index];
  26637. bindingsForPath[index] = firstActive;
  26638. bindingsForPath[lastCachedIndex] = binding;
  26639. }
  26640. }
  26641. } // for arguments
  26642. this.nCachedObjects_ = nCachedObjects;
  26643. },
  26644. // remove & forget
  26645. uncache: function () {
  26646. const objects = this._objects,
  26647. indicesByUUID = this._indicesByUUID,
  26648. bindings = this._bindings,
  26649. nBindings = bindings.length;
  26650. let nCachedObjects = this.nCachedObjects_,
  26651. nObjects = objects.length;
  26652. for (let i = 0, n = arguments.length; i !== n; ++i) {
  26653. const object = arguments[i],
  26654. uuid = object.uuid,
  26655. index = indicesByUUID[uuid];
  26656. if (index !== undefined) {
  26657. delete indicesByUUID[uuid];
  26658. if (index < nCachedObjects) {
  26659. // object is cached, shrink the CACHED region
  26660. const firstActiveIndex = --nCachedObjects,
  26661. lastCachedObject = objects[firstActiveIndex],
  26662. lastIndex = --nObjects,
  26663. lastObject = objects[lastIndex]; // last cached object takes this object's place
  26664. indicesByUUID[lastCachedObject.uuid] = index;
  26665. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  26666. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  26667. objects[firstActiveIndex] = lastObject;
  26668. objects.pop(); // accounting is done, now do the same for all bindings
  26669. for (let j = 0, m = nBindings; j !== m; ++j) {
  26670. const bindingsForPath = bindings[j],
  26671. lastCached = bindingsForPath[firstActiveIndex],
  26672. last = bindingsForPath[lastIndex];
  26673. bindingsForPath[index] = lastCached;
  26674. bindingsForPath[firstActiveIndex] = last;
  26675. bindingsForPath.pop();
  26676. }
  26677. } else {
  26678. // object is active, just swap with the last and pop
  26679. const lastIndex = --nObjects,
  26680. lastObject = objects[lastIndex];
  26681. if (lastIndex > 0) {
  26682. indicesByUUID[lastObject.uuid] = index;
  26683. }
  26684. objects[index] = lastObject;
  26685. objects.pop(); // accounting is done, now do the same for all bindings
  26686. for (let j = 0, m = nBindings; j !== m; ++j) {
  26687. const bindingsForPath = bindings[j];
  26688. bindingsForPath[index] = bindingsForPath[lastIndex];
  26689. bindingsForPath.pop();
  26690. }
  26691. } // cached or active
  26692. } // if object is known
  26693. } // for arguments
  26694. this.nCachedObjects_ = nCachedObjects;
  26695. },
  26696. // Internal interface used by befriended PropertyBinding.Composite:
  26697. subscribe_: function (path, parsedPath) {
  26698. // returns an array of bindings for the given path that is changed
  26699. // according to the contained objects in the group
  26700. const indicesByPath = this._bindingsIndicesByPath;
  26701. let index = indicesByPath[path];
  26702. const bindings = this._bindings;
  26703. if (index !== undefined) return bindings[index];
  26704. const paths = this._paths,
  26705. parsedPaths = this._parsedPaths,
  26706. objects = this._objects,
  26707. nObjects = objects.length,
  26708. nCachedObjects = this.nCachedObjects_,
  26709. bindingsForPath = new Array(nObjects);
  26710. index = bindings.length;
  26711. indicesByPath[path] = index;
  26712. paths.push(path);
  26713. parsedPaths.push(parsedPath);
  26714. bindings.push(bindingsForPath);
  26715. for (let i = nCachedObjects, n = objects.length; i !== n; ++i) {
  26716. const object = objects[i];
  26717. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  26718. }
  26719. return bindingsForPath;
  26720. },
  26721. unsubscribe_: function (path) {
  26722. // tells the group to forget about a property path and no longer
  26723. // update the array previously obtained with 'subscribe_'
  26724. const indicesByPath = this._bindingsIndicesByPath,
  26725. index = indicesByPath[path];
  26726. if (index !== undefined) {
  26727. const paths = this._paths,
  26728. parsedPaths = this._parsedPaths,
  26729. bindings = this._bindings,
  26730. lastBindingsIndex = bindings.length - 1,
  26731. lastBindings = bindings[lastBindingsIndex],
  26732. lastBindingsPath = path[lastBindingsIndex];
  26733. indicesByPath[lastBindingsPath] = index;
  26734. bindings[index] = lastBindings;
  26735. bindings.pop();
  26736. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  26737. parsedPaths.pop();
  26738. paths[index] = paths[lastBindingsIndex];
  26739. paths.pop();
  26740. }
  26741. }
  26742. });
  26743. class AnimationAction {
  26744. constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) {
  26745. this._mixer = mixer;
  26746. this._clip = clip;
  26747. this._localRoot = localRoot;
  26748. this.blendMode = blendMode;
  26749. const tracks = clip.tracks,
  26750. nTracks = tracks.length,
  26751. interpolants = new Array(nTracks);
  26752. const interpolantSettings = {
  26753. endingStart: ZeroCurvatureEnding,
  26754. endingEnd: ZeroCurvatureEnding
  26755. };
  26756. for (let i = 0; i !== nTracks; ++i) {
  26757. const interpolant = tracks[i].createInterpolant(null);
  26758. interpolants[i] = interpolant;
  26759. interpolant.settings = interpolantSettings;
  26760. }
  26761. this._interpolantSettings = interpolantSettings;
  26762. this._interpolants = interpolants; // bound by the mixer
  26763. // inside: PropertyMixer (managed by the mixer)
  26764. this._propertyBindings = new Array(nTracks);
  26765. this._cacheIndex = null; // for the memory manager
  26766. this._byClipCacheIndex = null; // for the memory manager
  26767. this._timeScaleInterpolant = null;
  26768. this._weightInterpolant = null;
  26769. this.loop = LoopRepeat;
  26770. this._loopCount = -1; // global mixer time when the action is to be started
  26771. // it's set back to 'null' upon start of the action
  26772. this._startTime = null; // scaled local time of the action
  26773. // gets clamped or wrapped to 0..clip.duration according to loop
  26774. this.time = 0;
  26775. this.timeScale = 1;
  26776. this._effectiveTimeScale = 1;
  26777. this.weight = 1;
  26778. this._effectiveWeight = 1;
  26779. this.repetitions = Infinity; // no. of repetitions when looping
  26780. this.paused = false; // true -> zero effective time scale
  26781. this.enabled = true; // false -> zero effective weight
  26782. this.clampWhenFinished = false; // keep feeding the last frame?
  26783. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  26784. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  26785. } // State & Scheduling
  26786. play() {
  26787. this._mixer._activateAction(this);
  26788. return this;
  26789. }
  26790. stop() {
  26791. this._mixer._deactivateAction(this);
  26792. return this.reset();
  26793. }
  26794. reset() {
  26795. this.paused = false;
  26796. this.enabled = true;
  26797. this.time = 0; // restart clip
  26798. this._loopCount = -1; // forget previous loops
  26799. this._startTime = null; // forget scheduling
  26800. return this.stopFading().stopWarping();
  26801. }
  26802. isRunning() {
  26803. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  26804. } // return true when play has been called
  26805. isScheduled() {
  26806. return this._mixer._isActiveAction(this);
  26807. }
  26808. startAt(time) {
  26809. this._startTime = time;
  26810. return this;
  26811. }
  26812. setLoop(mode, repetitions) {
  26813. this.loop = mode;
  26814. this.repetitions = repetitions;
  26815. return this;
  26816. } // Weight
  26817. // set the weight stopping any scheduled fading
  26818. // although .enabled = false yields an effective weight of zero, this
  26819. // method does *not* change .enabled, because it would be confusing
  26820. setEffectiveWeight(weight) {
  26821. this.weight = weight; // note: same logic as when updated at runtime
  26822. this._effectiveWeight = this.enabled ? weight : 0;
  26823. return this.stopFading();
  26824. } // return the weight considering fading and .enabled
  26825. getEffectiveWeight() {
  26826. return this._effectiveWeight;
  26827. }
  26828. fadeIn(duration) {
  26829. return this._scheduleFading(duration, 0, 1);
  26830. }
  26831. fadeOut(duration) {
  26832. return this._scheduleFading(duration, 1, 0);
  26833. }
  26834. crossFadeFrom(fadeOutAction, duration, warp) {
  26835. fadeOutAction.fadeOut(duration);
  26836. this.fadeIn(duration);
  26837. if (warp) {
  26838. const fadeInDuration = this._clip.duration,
  26839. fadeOutDuration = fadeOutAction._clip.duration,
  26840. startEndRatio = fadeOutDuration / fadeInDuration,
  26841. endStartRatio = fadeInDuration / fadeOutDuration;
  26842. fadeOutAction.warp(1.0, startEndRatio, duration);
  26843. this.warp(endStartRatio, 1.0, duration);
  26844. }
  26845. return this;
  26846. }
  26847. crossFadeTo(fadeInAction, duration, warp) {
  26848. return fadeInAction.crossFadeFrom(this, duration, warp);
  26849. }
  26850. stopFading() {
  26851. const weightInterpolant = this._weightInterpolant;
  26852. if (weightInterpolant !== null) {
  26853. this._weightInterpolant = null;
  26854. this._mixer._takeBackControlInterpolant(weightInterpolant);
  26855. }
  26856. return this;
  26857. } // Time Scale Control
  26858. // set the time scale stopping any scheduled warping
  26859. // although .paused = true yields an effective time scale of zero, this
  26860. // method does *not* change .paused, because it would be confusing
  26861. setEffectiveTimeScale(timeScale) {
  26862. this.timeScale = timeScale;
  26863. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  26864. return this.stopWarping();
  26865. } // return the time scale considering warping and .paused
  26866. getEffectiveTimeScale() {
  26867. return this._effectiveTimeScale;
  26868. }
  26869. setDuration(duration) {
  26870. this.timeScale = this._clip.duration / duration;
  26871. return this.stopWarping();
  26872. }
  26873. syncWith(action) {
  26874. this.time = action.time;
  26875. this.timeScale = action.timeScale;
  26876. return this.stopWarping();
  26877. }
  26878. halt(duration) {
  26879. return this.warp(this._effectiveTimeScale, 0, duration);
  26880. }
  26881. warp(startTimeScale, endTimeScale, duration) {
  26882. const mixer = this._mixer,
  26883. now = mixer.time,
  26884. timeScale = this.timeScale;
  26885. let interpolant = this._timeScaleInterpolant;
  26886. if (interpolant === null) {
  26887. interpolant = mixer._lendControlInterpolant();
  26888. this._timeScaleInterpolant = interpolant;
  26889. }
  26890. const times = interpolant.parameterPositions,
  26891. values = interpolant.sampleValues;
  26892. times[0] = now;
  26893. times[1] = now + duration;
  26894. values[0] = startTimeScale / timeScale;
  26895. values[1] = endTimeScale / timeScale;
  26896. return this;
  26897. }
  26898. stopWarping() {
  26899. const timeScaleInterpolant = this._timeScaleInterpolant;
  26900. if (timeScaleInterpolant !== null) {
  26901. this._timeScaleInterpolant = null;
  26902. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  26903. }
  26904. return this;
  26905. } // Object Accessors
  26906. getMixer() {
  26907. return this._mixer;
  26908. }
  26909. getClip() {
  26910. return this._clip;
  26911. }
  26912. getRoot() {
  26913. return this._localRoot || this._mixer._root;
  26914. } // Interna
  26915. _update(time, deltaTime, timeDirection, accuIndex) {
  26916. // called by the mixer
  26917. if (!this.enabled) {
  26918. // call ._updateWeight() to update ._effectiveWeight
  26919. this._updateWeight(time);
  26920. return;
  26921. }
  26922. const startTime = this._startTime;
  26923. if (startTime !== null) {
  26924. // check for scheduled start of action
  26925. const timeRunning = (time - startTime) * timeDirection;
  26926. if (timeRunning < 0 || timeDirection === 0) {
  26927. return; // yet to come / don't decide when delta = 0
  26928. } // start
  26929. this._startTime = null; // unschedule
  26930. deltaTime = timeDirection * timeRunning;
  26931. } // apply time scale and advance time
  26932. deltaTime *= this._updateTimeScale(time);
  26933. const clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  26934. // an effective weight of 0
  26935. const weight = this._updateWeight(time);
  26936. if (weight > 0) {
  26937. const interpolants = this._interpolants;
  26938. const propertyMixers = this._propertyBindings;
  26939. switch (this.blendMode) {
  26940. case AdditiveAnimationBlendMode:
  26941. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  26942. interpolants[j].evaluate(clipTime);
  26943. propertyMixers[j].accumulateAdditive(weight);
  26944. }
  26945. break;
  26946. case NormalAnimationBlendMode:
  26947. default:
  26948. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  26949. interpolants[j].evaluate(clipTime);
  26950. propertyMixers[j].accumulate(accuIndex, weight);
  26951. }
  26952. }
  26953. }
  26954. }
  26955. _updateWeight(time) {
  26956. let weight = 0;
  26957. if (this.enabled) {
  26958. weight = this.weight;
  26959. const interpolant = this._weightInterpolant;
  26960. if (interpolant !== null) {
  26961. const interpolantValue = interpolant.evaluate(time)[0];
  26962. weight *= interpolantValue;
  26963. if (time > interpolant.parameterPositions[1]) {
  26964. this.stopFading();
  26965. if (interpolantValue === 0) {
  26966. // faded out, disable
  26967. this.enabled = false;
  26968. }
  26969. }
  26970. }
  26971. }
  26972. this._effectiveWeight = weight;
  26973. return weight;
  26974. }
  26975. _updateTimeScale(time) {
  26976. let timeScale = 0;
  26977. if (!this.paused) {
  26978. timeScale = this.timeScale;
  26979. const interpolant = this._timeScaleInterpolant;
  26980. if (interpolant !== null) {
  26981. const interpolantValue = interpolant.evaluate(time)[0];
  26982. timeScale *= interpolantValue;
  26983. if (time > interpolant.parameterPositions[1]) {
  26984. this.stopWarping();
  26985. if (timeScale === 0) {
  26986. // motion has halted, pause
  26987. this.paused = true;
  26988. } else {
  26989. // warp done - apply final time scale
  26990. this.timeScale = timeScale;
  26991. }
  26992. }
  26993. }
  26994. }
  26995. this._effectiveTimeScale = timeScale;
  26996. return timeScale;
  26997. }
  26998. _updateTime(deltaTime) {
  26999. const duration = this._clip.duration;
  27000. const loop = this.loop;
  27001. let time = this.time + deltaTime;
  27002. let loopCount = this._loopCount;
  27003. const pingPong = loop === LoopPingPong;
  27004. if (deltaTime === 0) {
  27005. if (loopCount === -1) return time;
  27006. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  27007. }
  27008. if (loop === LoopOnce) {
  27009. if (loopCount === -1) {
  27010. // just started
  27011. this._loopCount = 0;
  27012. this._setEndings(true, true, false);
  27013. }
  27014. handle_stop: {
  27015. if (time >= duration) {
  27016. time = duration;
  27017. } else if (time < 0) {
  27018. time = 0;
  27019. } else {
  27020. this.time = time;
  27021. break handle_stop;
  27022. }
  27023. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  27024. this.time = time;
  27025. this._mixer.dispatchEvent({
  27026. type: 'finished',
  27027. action: this,
  27028. direction: deltaTime < 0 ? -1 : 1
  27029. });
  27030. }
  27031. } else {
  27032. // repetitive Repeat or PingPong
  27033. if (loopCount === -1) {
  27034. // just started
  27035. if (deltaTime >= 0) {
  27036. loopCount = 0;
  27037. this._setEndings(true, this.repetitions === 0, pingPong);
  27038. } else {
  27039. // when looping in reverse direction, the initial
  27040. // transition through zero counts as a repetition,
  27041. // so leave loopCount at -1
  27042. this._setEndings(this.repetitions === 0, true, pingPong);
  27043. }
  27044. }
  27045. if (time >= duration || time < 0) {
  27046. // wrap around
  27047. const loopDelta = Math.floor(time / duration); // signed
  27048. time -= duration * loopDelta;
  27049. loopCount += Math.abs(loopDelta);
  27050. const pending = this.repetitions - loopCount;
  27051. if (pending <= 0) {
  27052. // have to stop (switch state, clamp time, fire event)
  27053. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  27054. time = deltaTime > 0 ? duration : 0;
  27055. this.time = time;
  27056. this._mixer.dispatchEvent({
  27057. type: 'finished',
  27058. action: this,
  27059. direction: deltaTime > 0 ? 1 : -1
  27060. });
  27061. } else {
  27062. // keep running
  27063. if (pending === 1) {
  27064. // entering the last round
  27065. const atStart = deltaTime < 0;
  27066. this._setEndings(atStart, !atStart, pingPong);
  27067. } else {
  27068. this._setEndings(false, false, pingPong);
  27069. }
  27070. this._loopCount = loopCount;
  27071. this.time = time;
  27072. this._mixer.dispatchEvent({
  27073. type: 'loop',
  27074. action: this,
  27075. loopDelta: loopDelta
  27076. });
  27077. }
  27078. } else {
  27079. this.time = time;
  27080. }
  27081. if (pingPong && (loopCount & 1) === 1) {
  27082. // invert time for the "pong round"
  27083. return duration - time;
  27084. }
  27085. }
  27086. return time;
  27087. }
  27088. _setEndings(atStart, atEnd, pingPong) {
  27089. const settings = this._interpolantSettings;
  27090. if (pingPong) {
  27091. settings.endingStart = ZeroSlopeEnding;
  27092. settings.endingEnd = ZeroSlopeEnding;
  27093. } else {
  27094. // assuming for LoopOnce atStart == atEnd == true
  27095. if (atStart) {
  27096. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27097. } else {
  27098. settings.endingStart = WrapAroundEnding;
  27099. }
  27100. if (atEnd) {
  27101. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27102. } else {
  27103. settings.endingEnd = WrapAroundEnding;
  27104. }
  27105. }
  27106. }
  27107. _scheduleFading(duration, weightNow, weightThen) {
  27108. const mixer = this._mixer,
  27109. now = mixer.time;
  27110. let interpolant = this._weightInterpolant;
  27111. if (interpolant === null) {
  27112. interpolant = mixer._lendControlInterpolant();
  27113. this._weightInterpolant = interpolant;
  27114. }
  27115. const times = interpolant.parameterPositions,
  27116. values = interpolant.sampleValues;
  27117. times[0] = now;
  27118. values[0] = weightNow;
  27119. times[1] = now + duration;
  27120. values[1] = weightThen;
  27121. return this;
  27122. }
  27123. }
  27124. function AnimationMixer(root) {
  27125. this._root = root;
  27126. this._initMemoryManager();
  27127. this._accuIndex = 0;
  27128. this.time = 0;
  27129. this.timeScale = 1.0;
  27130. }
  27131. AnimationMixer.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  27132. constructor: AnimationMixer,
  27133. _bindAction: function (action, prototypeAction) {
  27134. const root = action._localRoot || this._root,
  27135. tracks = action._clip.tracks,
  27136. nTracks = tracks.length,
  27137. bindings = action._propertyBindings,
  27138. interpolants = action._interpolants,
  27139. rootUuid = root.uuid,
  27140. bindingsByRoot = this._bindingsByRootAndName;
  27141. let bindingsByName = bindingsByRoot[rootUuid];
  27142. if (bindingsByName === undefined) {
  27143. bindingsByName = {};
  27144. bindingsByRoot[rootUuid] = bindingsByName;
  27145. }
  27146. for (let i = 0; i !== nTracks; ++i) {
  27147. const track = tracks[i],
  27148. trackName = track.name;
  27149. let binding = bindingsByName[trackName];
  27150. if (binding !== undefined) {
  27151. bindings[i] = binding;
  27152. } else {
  27153. binding = bindings[i];
  27154. if (binding !== undefined) {
  27155. // existing binding, make sure the cache knows
  27156. if (binding._cacheIndex === null) {
  27157. ++binding.referenceCount;
  27158. this._addInactiveBinding(binding, rootUuid, trackName);
  27159. }
  27160. continue;
  27161. }
  27162. const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  27163. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  27164. ++binding.referenceCount;
  27165. this._addInactiveBinding(binding, rootUuid, trackName);
  27166. bindings[i] = binding;
  27167. }
  27168. interpolants[i].resultBuffer = binding.buffer;
  27169. }
  27170. },
  27171. _activateAction: function (action) {
  27172. if (!this._isActiveAction(action)) {
  27173. if (action._cacheIndex === null) {
  27174. // this action has been forgotten by the cache, but the user
  27175. // appears to be still using it -> rebind
  27176. const rootUuid = (action._localRoot || this._root).uuid,
  27177. clipUuid = action._clip.uuid,
  27178. actionsForClip = this._actionsByClip[clipUuid];
  27179. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  27180. this._addInactiveAction(action, clipUuid, rootUuid);
  27181. }
  27182. const bindings = action._propertyBindings; // increment reference counts / sort out state
  27183. for (let i = 0, n = bindings.length; i !== n; ++i) {
  27184. const binding = bindings[i];
  27185. if (binding.useCount++ === 0) {
  27186. this._lendBinding(binding);
  27187. binding.saveOriginalState();
  27188. }
  27189. }
  27190. this._lendAction(action);
  27191. }
  27192. },
  27193. _deactivateAction: function (action) {
  27194. if (this._isActiveAction(action)) {
  27195. const bindings = action._propertyBindings; // decrement reference counts / sort out state
  27196. for (let i = 0, n = bindings.length; i !== n; ++i) {
  27197. const binding = bindings[i];
  27198. if (--binding.useCount === 0) {
  27199. binding.restoreOriginalState();
  27200. this._takeBackBinding(binding);
  27201. }
  27202. }
  27203. this._takeBackAction(action);
  27204. }
  27205. },
  27206. // Memory manager
  27207. _initMemoryManager: function () {
  27208. this._actions = []; // 'nActiveActions' followed by inactive ones
  27209. this._nActiveActions = 0;
  27210. this._actionsByClip = {}; // inside:
  27211. // {
  27212. // knownActions: Array< AnimationAction > - used as prototypes
  27213. // actionByRoot: AnimationAction - lookup
  27214. // }
  27215. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  27216. this._nActiveBindings = 0;
  27217. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  27218. this._controlInterpolants = []; // same game as above
  27219. this._nActiveControlInterpolants = 0;
  27220. const scope = this;
  27221. this.stats = {
  27222. actions: {
  27223. get total() {
  27224. return scope._actions.length;
  27225. },
  27226. get inUse() {
  27227. return scope._nActiveActions;
  27228. }
  27229. },
  27230. bindings: {
  27231. get total() {
  27232. return scope._bindings.length;
  27233. },
  27234. get inUse() {
  27235. return scope._nActiveBindings;
  27236. }
  27237. },
  27238. controlInterpolants: {
  27239. get total() {
  27240. return scope._controlInterpolants.length;
  27241. },
  27242. get inUse() {
  27243. return scope._nActiveControlInterpolants;
  27244. }
  27245. }
  27246. };
  27247. },
  27248. // Memory management for AnimationAction objects
  27249. _isActiveAction: function (action) {
  27250. const index = action._cacheIndex;
  27251. return index !== null && index < this._nActiveActions;
  27252. },
  27253. _addInactiveAction: function (action, clipUuid, rootUuid) {
  27254. const actions = this._actions,
  27255. actionsByClip = this._actionsByClip;
  27256. let actionsForClip = actionsByClip[clipUuid];
  27257. if (actionsForClip === undefined) {
  27258. actionsForClip = {
  27259. knownActions: [action],
  27260. actionByRoot: {}
  27261. };
  27262. action._byClipCacheIndex = 0;
  27263. actionsByClip[clipUuid] = actionsForClip;
  27264. } else {
  27265. const knownActions = actionsForClip.knownActions;
  27266. action._byClipCacheIndex = knownActions.length;
  27267. knownActions.push(action);
  27268. }
  27269. action._cacheIndex = actions.length;
  27270. actions.push(action);
  27271. actionsForClip.actionByRoot[rootUuid] = action;
  27272. },
  27273. _removeInactiveAction: function (action) {
  27274. const actions = this._actions,
  27275. lastInactiveAction = actions[actions.length - 1],
  27276. cacheIndex = action._cacheIndex;
  27277. lastInactiveAction._cacheIndex = cacheIndex;
  27278. actions[cacheIndex] = lastInactiveAction;
  27279. actions.pop();
  27280. action._cacheIndex = null;
  27281. const clipUuid = action._clip.uuid,
  27282. actionsByClip = this._actionsByClip,
  27283. actionsForClip = actionsByClip[clipUuid],
  27284. knownActionsForClip = actionsForClip.knownActions,
  27285. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  27286. byClipCacheIndex = action._byClipCacheIndex;
  27287. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  27288. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  27289. knownActionsForClip.pop();
  27290. action._byClipCacheIndex = null;
  27291. const actionByRoot = actionsForClip.actionByRoot,
  27292. rootUuid = (action._localRoot || this._root).uuid;
  27293. delete actionByRoot[rootUuid];
  27294. if (knownActionsForClip.length === 0) {
  27295. delete actionsByClip[clipUuid];
  27296. }
  27297. this._removeInactiveBindingsForAction(action);
  27298. },
  27299. _removeInactiveBindingsForAction: function (action) {
  27300. const bindings = action._propertyBindings;
  27301. for (let i = 0, n = bindings.length; i !== n; ++i) {
  27302. const binding = bindings[i];
  27303. if (--binding.referenceCount === 0) {
  27304. this._removeInactiveBinding(binding);
  27305. }
  27306. }
  27307. },
  27308. _lendAction: function (action) {
  27309. // [ active actions | inactive actions ]
  27310. // [ active actions >| inactive actions ]
  27311. // s a
  27312. // <-swap->
  27313. // a s
  27314. const actions = this._actions,
  27315. prevIndex = action._cacheIndex,
  27316. lastActiveIndex = this._nActiveActions++,
  27317. firstInactiveAction = actions[lastActiveIndex];
  27318. action._cacheIndex = lastActiveIndex;
  27319. actions[lastActiveIndex] = action;
  27320. firstInactiveAction._cacheIndex = prevIndex;
  27321. actions[prevIndex] = firstInactiveAction;
  27322. },
  27323. _takeBackAction: function (action) {
  27324. // [ active actions | inactive actions ]
  27325. // [ active actions |< inactive actions ]
  27326. // a s
  27327. // <-swap->
  27328. // s a
  27329. const actions = this._actions,
  27330. prevIndex = action._cacheIndex,
  27331. firstInactiveIndex = --this._nActiveActions,
  27332. lastActiveAction = actions[firstInactiveIndex];
  27333. action._cacheIndex = firstInactiveIndex;
  27334. actions[firstInactiveIndex] = action;
  27335. lastActiveAction._cacheIndex = prevIndex;
  27336. actions[prevIndex] = lastActiveAction;
  27337. },
  27338. // Memory management for PropertyMixer objects
  27339. _addInactiveBinding: function (binding, rootUuid, trackName) {
  27340. const bindingsByRoot = this._bindingsByRootAndName,
  27341. bindings = this._bindings;
  27342. let bindingByName = bindingsByRoot[rootUuid];
  27343. if (bindingByName === undefined) {
  27344. bindingByName = {};
  27345. bindingsByRoot[rootUuid] = bindingByName;
  27346. }
  27347. bindingByName[trackName] = binding;
  27348. binding._cacheIndex = bindings.length;
  27349. bindings.push(binding);
  27350. },
  27351. _removeInactiveBinding: function (binding) {
  27352. const bindings = this._bindings,
  27353. propBinding = binding.binding,
  27354. rootUuid = propBinding.rootNode.uuid,
  27355. trackName = propBinding.path,
  27356. bindingsByRoot = this._bindingsByRootAndName,
  27357. bindingByName = bindingsByRoot[rootUuid],
  27358. lastInactiveBinding = bindings[bindings.length - 1],
  27359. cacheIndex = binding._cacheIndex;
  27360. lastInactiveBinding._cacheIndex = cacheIndex;
  27361. bindings[cacheIndex] = lastInactiveBinding;
  27362. bindings.pop();
  27363. delete bindingByName[trackName];
  27364. if (Object.keys(bindingByName).length === 0) {
  27365. delete bindingsByRoot[rootUuid];
  27366. }
  27367. },
  27368. _lendBinding: function (binding) {
  27369. const bindings = this._bindings,
  27370. prevIndex = binding._cacheIndex,
  27371. lastActiveIndex = this._nActiveBindings++,
  27372. firstInactiveBinding = bindings[lastActiveIndex];
  27373. binding._cacheIndex = lastActiveIndex;
  27374. bindings[lastActiveIndex] = binding;
  27375. firstInactiveBinding._cacheIndex = prevIndex;
  27376. bindings[prevIndex] = firstInactiveBinding;
  27377. },
  27378. _takeBackBinding: function (binding) {
  27379. const bindings = this._bindings,
  27380. prevIndex = binding._cacheIndex,
  27381. firstInactiveIndex = --this._nActiveBindings,
  27382. lastActiveBinding = bindings[firstInactiveIndex];
  27383. binding._cacheIndex = firstInactiveIndex;
  27384. bindings[firstInactiveIndex] = binding;
  27385. lastActiveBinding._cacheIndex = prevIndex;
  27386. bindings[prevIndex] = lastActiveBinding;
  27387. },
  27388. // Memory management of Interpolants for weight and time scale
  27389. _lendControlInterpolant: function () {
  27390. const interpolants = this._controlInterpolants,
  27391. lastActiveIndex = this._nActiveControlInterpolants++;
  27392. let interpolant = interpolants[lastActiveIndex];
  27393. if (interpolant === undefined) {
  27394. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
  27395. interpolant.__cacheIndex = lastActiveIndex;
  27396. interpolants[lastActiveIndex] = interpolant;
  27397. }
  27398. return interpolant;
  27399. },
  27400. _takeBackControlInterpolant: function (interpolant) {
  27401. const interpolants = this._controlInterpolants,
  27402. prevIndex = interpolant.__cacheIndex,
  27403. firstInactiveIndex = --this._nActiveControlInterpolants,
  27404. lastActiveInterpolant = interpolants[firstInactiveIndex];
  27405. interpolant.__cacheIndex = firstInactiveIndex;
  27406. interpolants[firstInactiveIndex] = interpolant;
  27407. lastActiveInterpolant.__cacheIndex = prevIndex;
  27408. interpolants[prevIndex] = lastActiveInterpolant;
  27409. },
  27410. _controlInterpolantsResultBuffer: new Float32Array(1),
  27411. // return an action for a clip optionally using a custom root target
  27412. // object (this method allocates a lot of dynamic memory in case a
  27413. // previously unknown clip/root combination is specified)
  27414. clipAction: function (clip, optionalRoot, blendMode) {
  27415. const root = optionalRoot || this._root,
  27416. rootUuid = root.uuid;
  27417. let clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip;
  27418. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  27419. const actionsForClip = this._actionsByClip[clipUuid];
  27420. let prototypeAction = null;
  27421. if (blendMode === undefined) {
  27422. if (clipObject !== null) {
  27423. blendMode = clipObject.blendMode;
  27424. } else {
  27425. blendMode = NormalAnimationBlendMode;
  27426. }
  27427. }
  27428. if (actionsForClip !== undefined) {
  27429. const existingAction = actionsForClip.actionByRoot[rootUuid];
  27430. if (existingAction !== undefined && existingAction.blendMode === blendMode) {
  27431. return existingAction;
  27432. } // we know the clip, so we don't have to parse all
  27433. // the bindings again but can just copy
  27434. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  27435. if (clipObject === null) clipObject = prototypeAction._clip;
  27436. } // clip must be known when specified via string
  27437. if (clipObject === null) return null; // allocate all resources required to run it
  27438. const newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode);
  27439. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  27440. this._addInactiveAction(newAction, clipUuid, rootUuid);
  27441. return newAction;
  27442. },
  27443. // get an existing action
  27444. existingAction: function (clip, optionalRoot) {
  27445. const root = optionalRoot || this._root,
  27446. rootUuid = root.uuid,
  27447. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  27448. clipUuid = clipObject ? clipObject.uuid : clip,
  27449. actionsForClip = this._actionsByClip[clipUuid];
  27450. if (actionsForClip !== undefined) {
  27451. return actionsForClip.actionByRoot[rootUuid] || null;
  27452. }
  27453. return null;
  27454. },
  27455. // deactivates all previously scheduled actions
  27456. stopAllAction: function () {
  27457. const actions = this._actions,
  27458. nActions = this._nActiveActions;
  27459. for (let i = nActions - 1; i >= 0; --i) {
  27460. actions[i].stop();
  27461. }
  27462. return this;
  27463. },
  27464. // advance the time and update apply the animation
  27465. update: function (deltaTime) {
  27466. deltaTime *= this.timeScale;
  27467. const actions = this._actions,
  27468. nActions = this._nActiveActions,
  27469. time = this.time += deltaTime,
  27470. timeDirection = Math.sign(deltaTime),
  27471. accuIndex = this._accuIndex ^= 1; // run active actions
  27472. for (let i = 0; i !== nActions; ++i) {
  27473. const action = actions[i];
  27474. action._update(time, deltaTime, timeDirection, accuIndex);
  27475. } // update scene graph
  27476. const bindings = this._bindings,
  27477. nBindings = this._nActiveBindings;
  27478. for (let i = 0; i !== nBindings; ++i) {
  27479. bindings[i].apply(accuIndex);
  27480. }
  27481. return this;
  27482. },
  27483. // Allows you to seek to a specific time in an animation.
  27484. setTime: function (timeInSeconds) {
  27485. this.time = 0; // Zero out time attribute for AnimationMixer object;
  27486. for (let i = 0; i < this._actions.length; i++) {
  27487. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  27488. }
  27489. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  27490. },
  27491. // return this mixer's root target object
  27492. getRoot: function () {
  27493. return this._root;
  27494. },
  27495. // free all resources specific to a particular clip
  27496. uncacheClip: function (clip) {
  27497. const actions = this._actions,
  27498. clipUuid = clip.uuid,
  27499. actionsByClip = this._actionsByClip,
  27500. actionsForClip = actionsByClip[clipUuid];
  27501. if (actionsForClip !== undefined) {
  27502. // note: just calling _removeInactiveAction would mess up the
  27503. // iteration state and also require updating the state we can
  27504. // just throw away
  27505. const actionsToRemove = actionsForClip.knownActions;
  27506. for (let i = 0, n = actionsToRemove.length; i !== n; ++i) {
  27507. const action = actionsToRemove[i];
  27508. this._deactivateAction(action);
  27509. const cacheIndex = action._cacheIndex,
  27510. lastInactiveAction = actions[actions.length - 1];
  27511. action._cacheIndex = null;
  27512. action._byClipCacheIndex = null;
  27513. lastInactiveAction._cacheIndex = cacheIndex;
  27514. actions[cacheIndex] = lastInactiveAction;
  27515. actions.pop();
  27516. this._removeInactiveBindingsForAction(action);
  27517. }
  27518. delete actionsByClip[clipUuid];
  27519. }
  27520. },
  27521. // free all resources specific to a particular root target object
  27522. uncacheRoot: function (root) {
  27523. const rootUuid = root.uuid,
  27524. actionsByClip = this._actionsByClip;
  27525. for (const clipUuid in actionsByClip) {
  27526. const actionByRoot = actionsByClip[clipUuid].actionByRoot,
  27527. action = actionByRoot[rootUuid];
  27528. if (action !== undefined) {
  27529. this._deactivateAction(action);
  27530. this._removeInactiveAction(action);
  27531. }
  27532. }
  27533. const bindingsByRoot = this._bindingsByRootAndName,
  27534. bindingByName = bindingsByRoot[rootUuid];
  27535. if (bindingByName !== undefined) {
  27536. for (const trackName in bindingByName) {
  27537. const binding = bindingByName[trackName];
  27538. binding.restoreOriginalState();
  27539. this._removeInactiveBinding(binding);
  27540. }
  27541. }
  27542. },
  27543. // remove a targeted clip from the cache
  27544. uncacheAction: function (clip, optionalRoot) {
  27545. const action = this.existingAction(clip, optionalRoot);
  27546. if (action !== null) {
  27547. this._deactivateAction(action);
  27548. this._removeInactiveAction(action);
  27549. }
  27550. }
  27551. });
  27552. class Uniform {
  27553. constructor(value) {
  27554. if (typeof value === 'string') {
  27555. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  27556. value = arguments[1];
  27557. }
  27558. this.value = value;
  27559. }
  27560. clone() {
  27561. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  27562. }
  27563. }
  27564. exports.Uniform = Uniform;
  27565. function InstancedInterleavedBuffer(array, stride, meshPerAttribute) {
  27566. InterleavedBuffer.call(this, array, stride);
  27567. this.meshPerAttribute = meshPerAttribute || 1;
  27568. }
  27569. InstancedInterleavedBuffer.prototype = Object.assign(Object.create(InterleavedBuffer.prototype), {
  27570. constructor: InstancedInterleavedBuffer,
  27571. isInstancedInterleavedBuffer: true,
  27572. copy: function (source) {
  27573. InterleavedBuffer.prototype.copy.call(this, source);
  27574. this.meshPerAttribute = source.meshPerAttribute;
  27575. return this;
  27576. },
  27577. clone: function (data) {
  27578. const ib = InterleavedBuffer.prototype.clone.call(this, data);
  27579. ib.meshPerAttribute = this.meshPerAttribute;
  27580. return ib;
  27581. },
  27582. toJSON: function (data) {
  27583. const json = InterleavedBuffer.prototype.toJSON.call(this, data);
  27584. json.isInstancedInterleavedBuffer = true;
  27585. json.meshPerAttribute = this.meshPerAttribute;
  27586. return json;
  27587. }
  27588. });
  27589. function GLBufferAttribute(buffer, type, itemSize, elementSize, count) {
  27590. this.buffer = buffer;
  27591. this.type = type;
  27592. this.itemSize = itemSize;
  27593. this.elementSize = elementSize;
  27594. this.count = count;
  27595. this.version = 0;
  27596. }
  27597. Object.defineProperty(GLBufferAttribute.prototype, 'needsUpdate', {
  27598. set: function (value) {
  27599. if (value === true) this.version++;
  27600. }
  27601. });
  27602. Object.assign(GLBufferAttribute.prototype, {
  27603. isGLBufferAttribute: true,
  27604. setBuffer: function (buffer) {
  27605. this.buffer = buffer;
  27606. return this;
  27607. },
  27608. setType: function (type, elementSize) {
  27609. this.type = type;
  27610. this.elementSize = elementSize;
  27611. return this;
  27612. },
  27613. setItemSize: function (itemSize) {
  27614. this.itemSize = itemSize;
  27615. return this;
  27616. },
  27617. setCount: function (count) {
  27618. this.count = count;
  27619. return this;
  27620. }
  27621. });
  27622. function Raycaster(origin, direction, near, far) {
  27623. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  27624. this.near = near || 0;
  27625. this.far = far || Infinity;
  27626. this.camera = null;
  27627. this.layers = new Layers();
  27628. this.params = {
  27629. Mesh: {},
  27630. Line: {
  27631. threshold: 1
  27632. },
  27633. LOD: {},
  27634. Points: {
  27635. threshold: 1
  27636. },
  27637. Sprite: {}
  27638. };
  27639. Object.defineProperties(this.params, {
  27640. PointCloud: {
  27641. get: function () {
  27642. console.warn('THREE.Raycaster: params.PointCloud has been renamed to params.Points.');
  27643. return this.Points;
  27644. }
  27645. }
  27646. });
  27647. }
  27648. function ascSort(a, b) {
  27649. return a.distance - b.distance;
  27650. }
  27651. function intersectObject(object, raycaster, intersects, recursive) {
  27652. if (object.layers.test(raycaster.layers)) {
  27653. object.raycast(raycaster, intersects);
  27654. }
  27655. if (recursive === true) {
  27656. const children = object.children;
  27657. for (let i = 0, l = children.length; i < l; i++) {
  27658. intersectObject(children[i], raycaster, intersects, true);
  27659. }
  27660. }
  27661. }
  27662. Object.assign(Raycaster.prototype, {
  27663. set: function (origin, direction) {
  27664. // direction is assumed to be normalized (for accurate distance calculations)
  27665. this.ray.set(origin, direction);
  27666. },
  27667. setFromCamera: function (coords, camera) {
  27668. if (camera && camera.isPerspectiveCamera) {
  27669. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  27670. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  27671. this.camera = camera;
  27672. } else if (camera && camera.isOrthographicCamera) {
  27673. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  27674. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  27675. this.camera = camera;
  27676. } else {
  27677. console.error('THREE.Raycaster: Unsupported camera type.');
  27678. }
  27679. },
  27680. intersectObject: function (object, recursive, optionalTarget) {
  27681. const intersects = optionalTarget || [];
  27682. intersectObject(object, this, intersects, recursive);
  27683. intersects.sort(ascSort);
  27684. return intersects;
  27685. },
  27686. intersectObjects: function (objects, recursive, optionalTarget) {
  27687. const intersects = optionalTarget || [];
  27688. if (Array.isArray(objects) === false) {
  27689. console.warn('THREE.Raycaster.intersectObjects: objects is not an Array.');
  27690. return intersects;
  27691. }
  27692. for (let i = 0, l = objects.length; i < l; i++) {
  27693. intersectObject(objects[i], this, intersects, recursive);
  27694. }
  27695. intersects.sort(ascSort);
  27696. return intersects;
  27697. }
  27698. });
  27699. /**
  27700. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  27701. *
  27702. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  27703. * The azimuthal angle (theta) is measured from the positive z-axis.
  27704. */
  27705. class Spherical {
  27706. constructor(radius = 1, phi = 0, theta = 0) {
  27707. this.radius = radius;
  27708. this.phi = phi; // polar angle
  27709. this.theta = theta; // azimuthal angle
  27710. return this;
  27711. }
  27712. set(radius, phi, theta) {
  27713. this.radius = radius;
  27714. this.phi = phi;
  27715. this.theta = theta;
  27716. return this;
  27717. }
  27718. clone() {
  27719. return new this.constructor().copy(this);
  27720. }
  27721. copy(other) {
  27722. this.radius = other.radius;
  27723. this.phi = other.phi;
  27724. this.theta = other.theta;
  27725. return this;
  27726. } // restrict phi to be betwee EPS and PI-EPS
  27727. makeSafe() {
  27728. const EPS = 0.000001;
  27729. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  27730. return this;
  27731. }
  27732. setFromVector3(v) {
  27733. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27734. }
  27735. setFromCartesianCoords(x, y, z) {
  27736. this.radius = Math.sqrt(x * x + y * y + z * z);
  27737. if (this.radius === 0) {
  27738. this.theta = 0;
  27739. this.phi = 0;
  27740. } else {
  27741. this.theta = Math.atan2(x, z);
  27742. this.phi = Math.acos(MathUtils.clamp(y / this.radius, -1, 1));
  27743. }
  27744. return this;
  27745. }
  27746. }
  27747. /**
  27748. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  27749. */
  27750. exports.Spherical = Spherical;
  27751. class Cylindrical {
  27752. constructor(radius, theta, y) {
  27753. this.radius = radius !== undefined ? radius : 1.0; // distance from the origin to a point in the x-z plane
  27754. this.theta = theta !== undefined ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  27755. this.y = y !== undefined ? y : 0; // height above the x-z plane
  27756. return this;
  27757. }
  27758. set(radius, theta, y) {
  27759. this.radius = radius;
  27760. this.theta = theta;
  27761. this.y = y;
  27762. return this;
  27763. }
  27764. clone() {
  27765. return new this.constructor().copy(this);
  27766. }
  27767. copy(other) {
  27768. this.radius = other.radius;
  27769. this.theta = other.theta;
  27770. this.y = other.y;
  27771. return this;
  27772. }
  27773. setFromVector3(v) {
  27774. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27775. }
  27776. setFromCartesianCoords(x, y, z) {
  27777. this.radius = Math.sqrt(x * x + z * z);
  27778. this.theta = Math.atan2(x, z);
  27779. this.y = y;
  27780. return this;
  27781. }
  27782. }
  27783. exports.Cylindrical = Cylindrical;
  27784. const _vector$7 =
  27785. /*@__PURE__*/
  27786. new Vector2();
  27787. class Box2 {
  27788. constructor(min, max) {
  27789. Object.defineProperty(this, 'isBox2', {
  27790. value: true
  27791. });
  27792. this.min = min !== undefined ? min : new Vector2(+Infinity, +Infinity);
  27793. this.max = max !== undefined ? max : new Vector2(-Infinity, -Infinity);
  27794. }
  27795. set(min, max) {
  27796. this.min.copy(min);
  27797. this.max.copy(max);
  27798. return this;
  27799. }
  27800. setFromPoints(points) {
  27801. this.makeEmpty();
  27802. for (let i = 0, il = points.length; i < il; i++) {
  27803. this.expandByPoint(points[i]);
  27804. }
  27805. return this;
  27806. }
  27807. setFromCenterAndSize(center, size) {
  27808. const halfSize = _vector$7.copy(size).multiplyScalar(0.5);
  27809. this.min.copy(center).sub(halfSize);
  27810. this.max.copy(center).add(halfSize);
  27811. return this;
  27812. }
  27813. clone() {
  27814. return new this.constructor().copy(this);
  27815. }
  27816. copy(box) {
  27817. this.min.copy(box.min);
  27818. this.max.copy(box.max);
  27819. return this;
  27820. }
  27821. makeEmpty() {
  27822. this.min.x = this.min.y = +Infinity;
  27823. this.max.x = this.max.y = -Infinity;
  27824. return this;
  27825. }
  27826. isEmpty() {
  27827. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  27828. return this.max.x < this.min.x || this.max.y < this.min.y;
  27829. }
  27830. getCenter(target) {
  27831. if (target === undefined) {
  27832. console.warn('THREE.Box2: .getCenter() target is now required');
  27833. target = new Vector2();
  27834. }
  27835. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  27836. }
  27837. getSize(target) {
  27838. if (target === undefined) {
  27839. console.warn('THREE.Box2: .getSize() target is now required');
  27840. target = new Vector2();
  27841. }
  27842. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  27843. }
  27844. expandByPoint(point) {
  27845. this.min.min(point);
  27846. this.max.max(point);
  27847. return this;
  27848. }
  27849. expandByVector(vector) {
  27850. this.min.sub(vector);
  27851. this.max.add(vector);
  27852. return this;
  27853. }
  27854. expandByScalar(scalar) {
  27855. this.min.addScalar(-scalar);
  27856. this.max.addScalar(scalar);
  27857. return this;
  27858. }
  27859. containsPoint(point) {
  27860. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  27861. }
  27862. containsBox(box) {
  27863. 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;
  27864. }
  27865. getParameter(point, target) {
  27866. // This can potentially have a divide by zero if the box
  27867. // has a size dimension of 0.
  27868. if (target === undefined) {
  27869. console.warn('THREE.Box2: .getParameter() target is now required');
  27870. target = new Vector2();
  27871. }
  27872. 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));
  27873. }
  27874. intersectsBox(box) {
  27875. // using 4 splitting planes to rule out intersections
  27876. 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;
  27877. }
  27878. clampPoint(point, target) {
  27879. if (target === undefined) {
  27880. console.warn('THREE.Box2: .clampPoint() target is now required');
  27881. target = new Vector2();
  27882. }
  27883. return target.copy(point).clamp(this.min, this.max);
  27884. }
  27885. distanceToPoint(point) {
  27886. const clampedPoint = _vector$7.copy(point).clamp(this.min, this.max);
  27887. return clampedPoint.sub(point).length();
  27888. }
  27889. intersect(box) {
  27890. this.min.max(box.min);
  27891. this.max.min(box.max);
  27892. return this;
  27893. }
  27894. union(box) {
  27895. this.min.min(box.min);
  27896. this.max.max(box.max);
  27897. return this;
  27898. }
  27899. translate(offset) {
  27900. this.min.add(offset);
  27901. this.max.add(offset);
  27902. return this;
  27903. }
  27904. equals(box) {
  27905. return box.min.equals(this.min) && box.max.equals(this.max);
  27906. }
  27907. }
  27908. exports.Box2 = Box2;
  27909. const _startP =
  27910. /*@__PURE__*/
  27911. new Vector3();
  27912. const _startEnd =
  27913. /*@__PURE__*/
  27914. new Vector3();
  27915. class Line3 {
  27916. constructor(start, end) {
  27917. this.start = start !== undefined ? start : new Vector3();
  27918. this.end = end !== undefined ? end : new Vector3();
  27919. }
  27920. set(start, end) {
  27921. this.start.copy(start);
  27922. this.end.copy(end);
  27923. return this;
  27924. }
  27925. clone() {
  27926. return new this.constructor().copy(this);
  27927. }
  27928. copy(line) {
  27929. this.start.copy(line.start);
  27930. this.end.copy(line.end);
  27931. return this;
  27932. }
  27933. getCenter(target) {
  27934. if (target === undefined) {
  27935. console.warn('THREE.Line3: .getCenter() target is now required');
  27936. target = new Vector3();
  27937. }
  27938. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  27939. }
  27940. delta(target) {
  27941. if (target === undefined) {
  27942. console.warn('THREE.Line3: .delta() target is now required');
  27943. target = new Vector3();
  27944. }
  27945. return target.subVectors(this.end, this.start);
  27946. }
  27947. distanceSq() {
  27948. return this.start.distanceToSquared(this.end);
  27949. }
  27950. distance() {
  27951. return this.start.distanceTo(this.end);
  27952. }
  27953. at(t, target) {
  27954. if (target === undefined) {
  27955. console.warn('THREE.Line3: .at() target is now required');
  27956. target = new Vector3();
  27957. }
  27958. return this.delta(target).multiplyScalar(t).add(this.start);
  27959. }
  27960. closestPointToPointParameter(point, clampToLine) {
  27961. _startP.subVectors(point, this.start);
  27962. _startEnd.subVectors(this.end, this.start);
  27963. const startEnd2 = _startEnd.dot(_startEnd);
  27964. const startEnd_startP = _startEnd.dot(_startP);
  27965. let t = startEnd_startP / startEnd2;
  27966. if (clampToLine) {
  27967. t = MathUtils.clamp(t, 0, 1);
  27968. }
  27969. return t;
  27970. }
  27971. closestPointToPoint(point, clampToLine, target) {
  27972. const t = this.closestPointToPointParameter(point, clampToLine);
  27973. if (target === undefined) {
  27974. console.warn('THREE.Line3: .closestPointToPoint() target is now required');
  27975. target = new Vector3();
  27976. }
  27977. return this.delta(target).multiplyScalar(t).add(this.start);
  27978. }
  27979. applyMatrix4(matrix) {
  27980. this.start.applyMatrix4(matrix);
  27981. this.end.applyMatrix4(matrix);
  27982. return this;
  27983. }
  27984. equals(line) {
  27985. return line.start.equals(this.start) && line.end.equals(this.end);
  27986. }
  27987. }
  27988. exports.Line3 = Line3;
  27989. function ImmediateRenderObject(material) {
  27990. Object3D.call(this);
  27991. this.material = material;
  27992. this.render = function ()
  27993. /* renderCallback */
  27994. {};
  27995. this.hasPositions = false;
  27996. this.hasNormals = false;
  27997. this.hasColors = false;
  27998. this.hasUvs = false;
  27999. this.positionArray = null;
  28000. this.normalArray = null;
  28001. this.colorArray = null;
  28002. this.uvArray = null;
  28003. this.count = 0;
  28004. }
  28005. ImmediateRenderObject.prototype = Object.create(Object3D.prototype);
  28006. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  28007. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  28008. const _vector$8 =
  28009. /*@__PURE__*/
  28010. new Vector3();
  28011. class SpotLightHelper extends Object3D {
  28012. constructor(light, color) {
  28013. super();
  28014. this.light = light;
  28015. this.light.updateMatrixWorld();
  28016. this.matrix = light.matrixWorld;
  28017. this.matrixAutoUpdate = false;
  28018. this.color = color;
  28019. const geometry = new BufferGeometry();
  28020. const 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];
  28021. for (let i = 0, j = 1, l = 32; i < l; i++, j++) {
  28022. const p1 = i / l * Math.PI * 2;
  28023. const p2 = j / l * Math.PI * 2;
  28024. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  28025. }
  28026. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  28027. const material = new LineBasicMaterial({
  28028. fog: false,
  28029. toneMapped: false
  28030. });
  28031. this.cone = new LineSegments(geometry, material);
  28032. this.add(this.cone);
  28033. this.update();
  28034. }
  28035. dispose() {
  28036. this.cone.geometry.dispose();
  28037. this.cone.material.dispose();
  28038. }
  28039. update() {
  28040. this.light.updateMatrixWorld();
  28041. const coneLength = this.light.distance ? this.light.distance : 1000;
  28042. const coneWidth = coneLength * Math.tan(this.light.angle);
  28043. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  28044. _vector$8.setFromMatrixPosition(this.light.target.matrixWorld);
  28045. this.cone.lookAt(_vector$8);
  28046. if (this.color !== undefined) {
  28047. this.cone.material.color.set(this.color);
  28048. } else {
  28049. this.cone.material.color.copy(this.light.color);
  28050. }
  28051. }
  28052. }
  28053. exports.SpotLightHelper = SpotLightHelper;
  28054. const _vector$9 =
  28055. /*@__PURE__*/
  28056. new Vector3();
  28057. const _boneMatrix =
  28058. /*@__PURE__*/
  28059. new Matrix4();
  28060. const _matrixWorldInv =
  28061. /*@__PURE__*/
  28062. new Matrix4();
  28063. class SkeletonHelper extends LineSegments {
  28064. constructor(object) {
  28065. const bones = getBoneList(object);
  28066. const geometry = new BufferGeometry();
  28067. const vertices = [];
  28068. const colors = [];
  28069. const color1 = new Color(0, 0, 1);
  28070. const color2 = new Color(0, 1, 0);
  28071. for (let i = 0; i < bones.length; i++) {
  28072. const bone = bones[i];
  28073. if (bone.parent && bone.parent.isBone) {
  28074. vertices.push(0, 0, 0);
  28075. vertices.push(0, 0, 0);
  28076. colors.push(color1.r, color1.g, color1.b);
  28077. colors.push(color2.r, color2.g, color2.b);
  28078. }
  28079. }
  28080. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  28081. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  28082. const material = new LineBasicMaterial({
  28083. vertexColors: true,
  28084. depthTest: false,
  28085. depthWrite: false,
  28086. toneMapped: false,
  28087. transparent: true
  28088. });
  28089. super(geometry, material);
  28090. this.type = 'SkeletonHelper';
  28091. this.isSkeletonHelper = true;
  28092. this.root = object;
  28093. this.bones = bones;
  28094. this.matrix = object.matrixWorld;
  28095. this.matrixAutoUpdate = false;
  28096. }
  28097. updateMatrixWorld(force) {
  28098. const bones = this.bones;
  28099. const geometry = this.geometry;
  28100. const position = geometry.getAttribute('position');
  28101. _matrixWorldInv.copy(this.root.matrixWorld).invert();
  28102. for (let i = 0, j = 0; i < bones.length; i++) {
  28103. const bone = bones[i];
  28104. if (bone.parent && bone.parent.isBone) {
  28105. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  28106. _vector$9.setFromMatrixPosition(_boneMatrix);
  28107. position.setXYZ(j, _vector$9.x, _vector$9.y, _vector$9.z);
  28108. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  28109. _vector$9.setFromMatrixPosition(_boneMatrix);
  28110. position.setXYZ(j + 1, _vector$9.x, _vector$9.y, _vector$9.z);
  28111. j += 2;
  28112. }
  28113. }
  28114. geometry.getAttribute('position').needsUpdate = true;
  28115. super.updateMatrixWorld(force);
  28116. }
  28117. }
  28118. exports.SkeletonHelper = SkeletonHelper;
  28119. function getBoneList(object) {
  28120. const boneList = [];
  28121. if (object && object.isBone) {
  28122. boneList.push(object);
  28123. }
  28124. for (let i = 0; i < object.children.length; i++) {
  28125. boneList.push.apply(boneList, getBoneList(object.children[i]));
  28126. }
  28127. return boneList;
  28128. }
  28129. class PointLightHelper extends Mesh {
  28130. constructor(light, sphereSize, color) {
  28131. const geometry = new SphereBufferGeometry(sphereSize, 4, 2);
  28132. const material = new MeshBasicMaterial({
  28133. wireframe: true,
  28134. fog: false,
  28135. toneMapped: false
  28136. });
  28137. super(geometry, material);
  28138. this.light = light;
  28139. this.light.updateMatrixWorld();
  28140. this.color = color;
  28141. this.type = 'PointLightHelper';
  28142. this.matrix = this.light.matrixWorld;
  28143. this.matrixAutoUpdate = false;
  28144. this.update();
  28145. /*
  28146. // TODO: delete this comment?
  28147. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  28148. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  28149. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  28150. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  28151. const d = light.distance;
  28152. if ( d === 0.0 ) {
  28153. this.lightDistance.visible = false;
  28154. } else {
  28155. this.lightDistance.scale.set( d, d, d );
  28156. }
  28157. this.add( this.lightDistance );
  28158. */
  28159. }
  28160. dispose() {
  28161. this.geometry.dispose();
  28162. this.material.dispose();
  28163. }
  28164. update() {
  28165. if (this.color !== undefined) {
  28166. this.material.color.set(this.color);
  28167. } else {
  28168. this.material.color.copy(this.light.color);
  28169. }
  28170. /*
  28171. const d = this.light.distance;
  28172. if ( d === 0.0 ) {
  28173. this.lightDistance.visible = false;
  28174. } else {
  28175. this.lightDistance.visible = true;
  28176. this.lightDistance.scale.set( d, d, d );
  28177. }
  28178. */
  28179. }
  28180. }
  28181. exports.PointLightHelper = PointLightHelper;
  28182. const _vector$a =
  28183. /*@__PURE__*/
  28184. new Vector3();
  28185. const _color1 =
  28186. /*@__PURE__*/
  28187. new Color();
  28188. const _color2 =
  28189. /*@__PURE__*/
  28190. new Color();
  28191. class HemisphereLightHelper extends Object3D {
  28192. constructor(light, size, color) {
  28193. super();
  28194. this.light = light;
  28195. this.light.updateMatrixWorld();
  28196. this.matrix = light.matrixWorld;
  28197. this.matrixAutoUpdate = false;
  28198. this.color = color;
  28199. const geometry = new OctahedronBufferGeometry(size);
  28200. geometry.rotateY(Math.PI * 0.5);
  28201. this.material = new MeshBasicMaterial({
  28202. wireframe: true,
  28203. fog: false,
  28204. toneMapped: false
  28205. });
  28206. if (this.color === undefined) this.material.vertexColors = true;
  28207. const position = geometry.getAttribute('position');
  28208. const colors = new Float32Array(position.count * 3);
  28209. geometry.setAttribute('color', new BufferAttribute(colors, 3));
  28210. this.add(new Mesh(geometry, this.material));
  28211. this.update();
  28212. }
  28213. dispose() {
  28214. this.children[0].geometry.dispose();
  28215. this.children[0].material.dispose();
  28216. }
  28217. update() {
  28218. const mesh = this.children[0];
  28219. if (this.color !== undefined) {
  28220. this.material.color.set(this.color);
  28221. } else {
  28222. const colors = mesh.geometry.getAttribute('color');
  28223. _color1.copy(this.light.color);
  28224. _color2.copy(this.light.groundColor);
  28225. for (let i = 0, l = colors.count; i < l; i++) {
  28226. const color = i < l / 2 ? _color1 : _color2;
  28227. colors.setXYZ(i, color.r, color.g, color.b);
  28228. }
  28229. colors.needsUpdate = true;
  28230. }
  28231. mesh.lookAt(_vector$a.setFromMatrixPosition(this.light.matrixWorld).negate());
  28232. }
  28233. }
  28234. exports.HemisphereLightHelper = HemisphereLightHelper;
  28235. class GridHelper extends LineSegments {
  28236. constructor(size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888) {
  28237. color1 = new Color(color1);
  28238. color2 = new Color(color2);
  28239. const center = divisions / 2;
  28240. const step = size / divisions;
  28241. const halfSize = size / 2;
  28242. const vertices = [],
  28243. colors = [];
  28244. for (let i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  28245. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  28246. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  28247. const color = i === center ? color1 : color2;
  28248. color.toArray(colors, j);
  28249. j += 3;
  28250. color.toArray(colors, j);
  28251. j += 3;
  28252. color.toArray(colors, j);
  28253. j += 3;
  28254. color.toArray(colors, j);
  28255. j += 3;
  28256. }
  28257. const geometry = new BufferGeometry();
  28258. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  28259. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  28260. const material = new LineBasicMaterial({
  28261. vertexColors: true,
  28262. toneMapped: false
  28263. });
  28264. super(geometry, material);
  28265. this.type = 'GridHelper';
  28266. }
  28267. }
  28268. exports.GridHelper = GridHelper;
  28269. class PolarGridHelper extends LineSegments {
  28270. constructor(radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888) {
  28271. color1 = new Color(color1);
  28272. color2 = new Color(color2);
  28273. const vertices = [];
  28274. const colors = []; // create the radials
  28275. for (let i = 0; i <= radials; i++) {
  28276. const v = i / radials * (Math.PI * 2);
  28277. const x = Math.sin(v) * radius;
  28278. const z = Math.cos(v) * radius;
  28279. vertices.push(0, 0, 0);
  28280. vertices.push(x, 0, z);
  28281. const color = i & 1 ? color1 : color2;
  28282. colors.push(color.r, color.g, color.b);
  28283. colors.push(color.r, color.g, color.b);
  28284. } // create the circles
  28285. for (let i = 0; i <= circles; i++) {
  28286. const color = i & 1 ? color1 : color2;
  28287. const r = radius - radius / circles * i;
  28288. for (let j = 0; j < divisions; j++) {
  28289. // first vertex
  28290. let v = j / divisions * (Math.PI * 2);
  28291. let x = Math.sin(v) * r;
  28292. let z = Math.cos(v) * r;
  28293. vertices.push(x, 0, z);
  28294. colors.push(color.r, color.g, color.b); // second vertex
  28295. v = (j + 1) / divisions * (Math.PI * 2);
  28296. x = Math.sin(v) * r;
  28297. z = Math.cos(v) * r;
  28298. vertices.push(x, 0, z);
  28299. colors.push(color.r, color.g, color.b);
  28300. }
  28301. }
  28302. const geometry = new BufferGeometry();
  28303. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  28304. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  28305. const material = new LineBasicMaterial({
  28306. vertexColors: true,
  28307. toneMapped: false
  28308. });
  28309. super(geometry, material);
  28310. this.type = 'PolarGridHelper';
  28311. }
  28312. }
  28313. exports.PolarGridHelper = PolarGridHelper;
  28314. const _v1$6 =
  28315. /*@__PURE__*/
  28316. new Vector3();
  28317. const _v2$3 =
  28318. /*@__PURE__*/
  28319. new Vector3();
  28320. const _v3$1 =
  28321. /*@__PURE__*/
  28322. new Vector3();
  28323. class DirectionalLightHelper extends Object3D {
  28324. constructor(light, size, color) {
  28325. super();
  28326. this.light = light;
  28327. this.light.updateMatrixWorld();
  28328. this.matrix = light.matrixWorld;
  28329. this.matrixAutoUpdate = false;
  28330. this.color = color;
  28331. if (size === undefined) size = 1;
  28332. let geometry = new BufferGeometry();
  28333. geometry.setAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  28334. const material = new LineBasicMaterial({
  28335. fog: false,
  28336. toneMapped: false
  28337. });
  28338. this.lightPlane = new Line(geometry, material);
  28339. this.add(this.lightPlane);
  28340. geometry = new BufferGeometry();
  28341. geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  28342. this.targetLine = new Line(geometry, material);
  28343. this.add(this.targetLine);
  28344. this.update();
  28345. }
  28346. dispose() {
  28347. this.lightPlane.geometry.dispose();
  28348. this.lightPlane.material.dispose();
  28349. this.targetLine.geometry.dispose();
  28350. this.targetLine.material.dispose();
  28351. }
  28352. update() {
  28353. _v1$6.setFromMatrixPosition(this.light.matrixWorld);
  28354. _v2$3.setFromMatrixPosition(this.light.target.matrixWorld);
  28355. _v3$1.subVectors(_v2$3, _v1$6);
  28356. this.lightPlane.lookAt(_v2$3);
  28357. if (this.color !== undefined) {
  28358. this.lightPlane.material.color.set(this.color);
  28359. this.targetLine.material.color.set(this.color);
  28360. } else {
  28361. this.lightPlane.material.color.copy(this.light.color);
  28362. this.targetLine.material.color.copy(this.light.color);
  28363. }
  28364. this.targetLine.lookAt(_v2$3);
  28365. this.targetLine.scale.z = _v3$1.length();
  28366. }
  28367. }
  28368. exports.DirectionalLightHelper = DirectionalLightHelper;
  28369. const _vector$b =
  28370. /*@__PURE__*/
  28371. new Vector3();
  28372. const _camera =
  28373. /*@__PURE__*/
  28374. new Camera();
  28375. /**
  28376. * - shows frustum, line of sight and up of the camera
  28377. * - suitable for fast updates
  28378. * - based on frustum visualization in lightgl.js shadowmap example
  28379. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  28380. */
  28381. class CameraHelper extends LineSegments {
  28382. constructor(camera) {
  28383. const geometry = new BufferGeometry();
  28384. const material = new LineBasicMaterial({
  28385. color: 0xffffff,
  28386. vertexColors: true,
  28387. toneMapped: false
  28388. });
  28389. const vertices = [];
  28390. const colors = [];
  28391. const pointMap = {}; // colors
  28392. const colorFrustum = new Color(0xffaa00);
  28393. const colorCone = new Color(0xff0000);
  28394. const colorUp = new Color(0x00aaff);
  28395. const colorTarget = new Color(0xffffff);
  28396. const colorCross = new Color(0x333333); // near
  28397. addLine('n1', 'n2', colorFrustum);
  28398. addLine('n2', 'n4', colorFrustum);
  28399. addLine('n4', 'n3', colorFrustum);
  28400. addLine('n3', 'n1', colorFrustum); // far
  28401. addLine('f1', 'f2', colorFrustum);
  28402. addLine('f2', 'f4', colorFrustum);
  28403. addLine('f4', 'f3', colorFrustum);
  28404. addLine('f3', 'f1', colorFrustum); // sides
  28405. addLine('n1', 'f1', colorFrustum);
  28406. addLine('n2', 'f2', colorFrustum);
  28407. addLine('n3', 'f3', colorFrustum);
  28408. addLine('n4', 'f4', colorFrustum); // cone
  28409. addLine('p', 'n1', colorCone);
  28410. addLine('p', 'n2', colorCone);
  28411. addLine('p', 'n3', colorCone);
  28412. addLine('p', 'n4', colorCone); // up
  28413. addLine('u1', 'u2', colorUp);
  28414. addLine('u2', 'u3', colorUp);
  28415. addLine('u3', 'u1', colorUp); // target
  28416. addLine('c', 't', colorTarget);
  28417. addLine('p', 'c', colorCross); // cross
  28418. addLine('cn1', 'cn2', colorCross);
  28419. addLine('cn3', 'cn4', colorCross);
  28420. addLine('cf1', 'cf2', colorCross);
  28421. addLine('cf3', 'cf4', colorCross);
  28422. function addLine(a, b, color) {
  28423. addPoint(a, color);
  28424. addPoint(b, color);
  28425. }
  28426. function addPoint(id, color) {
  28427. vertices.push(0, 0, 0);
  28428. colors.push(color.r, color.g, color.b);
  28429. if (pointMap[id] === undefined) {
  28430. pointMap[id] = [];
  28431. }
  28432. pointMap[id].push(vertices.length / 3 - 1);
  28433. }
  28434. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  28435. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  28436. super(geometry, material);
  28437. this.type = 'CameraHelper';
  28438. this.camera = camera;
  28439. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  28440. this.matrix = camera.matrixWorld;
  28441. this.matrixAutoUpdate = false;
  28442. this.pointMap = pointMap;
  28443. this.update();
  28444. }
  28445. update() {
  28446. const geometry = this.geometry;
  28447. const pointMap = this.pointMap;
  28448. const w = 1,
  28449. h = 1; // we need just camera projection matrix inverse
  28450. // world matrix must be identity
  28451. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  28452. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  28453. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  28454. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  28455. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  28456. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  28457. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  28458. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  28459. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  28460. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  28461. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  28462. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  28463. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  28464. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  28465. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  28466. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  28467. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  28468. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  28469. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  28470. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  28471. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  28472. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  28473. geometry.getAttribute('position').needsUpdate = true;
  28474. }
  28475. }
  28476. exports.CameraHelper = CameraHelper;
  28477. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  28478. _vector$b.set(x, y, z).unproject(camera);
  28479. const points = pointMap[point];
  28480. if (points !== undefined) {
  28481. const position = geometry.getAttribute('position');
  28482. for (let i = 0, l = points.length; i < l; i++) {
  28483. position.setXYZ(points[i], _vector$b.x, _vector$b.y, _vector$b.z);
  28484. }
  28485. }
  28486. }
  28487. const _box$3 =
  28488. /*@__PURE__*/
  28489. new Box3();
  28490. class BoxHelper extends LineSegments {
  28491. constructor(object, color = 0xffff00) {
  28492. const 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]);
  28493. const positions = new Float32Array(8 * 3);
  28494. const geometry = new BufferGeometry();
  28495. geometry.setIndex(new BufferAttribute(indices, 1));
  28496. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  28497. super(geometry, new LineBasicMaterial({
  28498. color: color,
  28499. toneMapped: false
  28500. }));
  28501. this.object = object;
  28502. this.type = 'BoxHelper';
  28503. this.matrixAutoUpdate = false;
  28504. this.update();
  28505. }
  28506. update(object) {
  28507. if (object !== undefined) {
  28508. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  28509. }
  28510. if (this.object !== undefined) {
  28511. _box$3.setFromObject(this.object);
  28512. }
  28513. if (_box$3.isEmpty()) return;
  28514. const min = _box$3.min;
  28515. const max = _box$3.max;
  28516. /*
  28517. 5____4
  28518. 1/___0/|
  28519. | 6__|_7
  28520. 2/___3/
  28521. 0: max.x, max.y, max.z
  28522. 1: min.x, max.y, max.z
  28523. 2: min.x, min.y, max.z
  28524. 3: max.x, min.y, max.z
  28525. 4: max.x, max.y, min.z
  28526. 5: min.x, max.y, min.z
  28527. 6: min.x, min.y, min.z
  28528. 7: max.x, min.y, min.z
  28529. */
  28530. const position = this.geometry.attributes.position;
  28531. const array = position.array;
  28532. array[0] = max.x;
  28533. array[1] = max.y;
  28534. array[2] = max.z;
  28535. array[3] = min.x;
  28536. array[4] = max.y;
  28537. array[5] = max.z;
  28538. array[6] = min.x;
  28539. array[7] = min.y;
  28540. array[8] = max.z;
  28541. array[9] = max.x;
  28542. array[10] = min.y;
  28543. array[11] = max.z;
  28544. array[12] = max.x;
  28545. array[13] = max.y;
  28546. array[14] = min.z;
  28547. array[15] = min.x;
  28548. array[16] = max.y;
  28549. array[17] = min.z;
  28550. array[18] = min.x;
  28551. array[19] = min.y;
  28552. array[20] = min.z;
  28553. array[21] = max.x;
  28554. array[22] = min.y;
  28555. array[23] = min.z;
  28556. position.needsUpdate = true;
  28557. this.geometry.computeBoundingSphere();
  28558. }
  28559. setFromObject(object) {
  28560. this.object = object;
  28561. this.update();
  28562. return this;
  28563. }
  28564. copy(source) {
  28565. LineSegments.prototype.copy.call(this, source);
  28566. this.object = source.object;
  28567. return this;
  28568. }
  28569. }
  28570. exports.BoxHelper = BoxHelper;
  28571. class Box3Helper extends LineSegments {
  28572. constructor(box, color = 0xffff00) {
  28573. const 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]);
  28574. const 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];
  28575. const geometry = new BufferGeometry();
  28576. geometry.setIndex(new BufferAttribute(indices, 1));
  28577. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  28578. super(geometry, new LineBasicMaterial({
  28579. color: color,
  28580. toneMapped: false
  28581. }));
  28582. this.box = box;
  28583. this.type = 'Box3Helper';
  28584. this.geometry.computeBoundingSphere();
  28585. }
  28586. updateMatrixWorld(force) {
  28587. const box = this.box;
  28588. if (box.isEmpty()) return;
  28589. box.getCenter(this.position);
  28590. box.getSize(this.scale);
  28591. this.scale.multiplyScalar(0.5);
  28592. super.updateMatrixWorld(force);
  28593. }
  28594. }
  28595. exports.Box3Helper = Box3Helper;
  28596. class PlaneHelper extends Line {
  28597. constructor(plane, size = 1, hex = 0xffff00) {
  28598. const color = hex;
  28599. const 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];
  28600. const geometry = new BufferGeometry();
  28601. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  28602. geometry.computeBoundingSphere();
  28603. super(geometry, new LineBasicMaterial({
  28604. color: color,
  28605. toneMapped: false
  28606. }));
  28607. this.type = 'PlaneHelper';
  28608. this.plane = plane;
  28609. this.size = size;
  28610. const positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
  28611. const geometry2 = new BufferGeometry();
  28612. geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
  28613. geometry2.computeBoundingSphere();
  28614. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  28615. color: color,
  28616. opacity: 0.2,
  28617. transparent: true,
  28618. depthWrite: false,
  28619. toneMapped: false
  28620. })));
  28621. }
  28622. updateMatrixWorld(force) {
  28623. let scale = -this.plane.constant;
  28624. if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
  28625. this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
  28626. this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  28627. this.lookAt(this.plane.normal);
  28628. super.updateMatrixWorld(force);
  28629. }
  28630. }
  28631. exports.PlaneHelper = PlaneHelper;
  28632. const _axis =
  28633. /*@__PURE__*/
  28634. new Vector3();
  28635. let _lineGeometry, _coneGeometry;
  28636. class ArrowHelper extends Object3D {
  28637. constructor(dir, origin, length, color, headLength, headWidth) {
  28638. super(); // dir is assumed to be normalized
  28639. this.type = 'ArrowHelper';
  28640. if (dir === undefined) dir = new Vector3(0, 0, 1);
  28641. if (origin === undefined) origin = new Vector3(0, 0, 0);
  28642. if (length === undefined) length = 1;
  28643. if (color === undefined) color = 0xffff00;
  28644. if (headLength === undefined) headLength = 0.2 * length;
  28645. if (headWidth === undefined) headWidth = 0.2 * headLength;
  28646. if (_lineGeometry === undefined) {
  28647. _lineGeometry = new BufferGeometry();
  28648. _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  28649. _coneGeometry = new CylinderBufferGeometry(0, 0.5, 1, 5, 1);
  28650. _coneGeometry.translate(0, -0.5, 0);
  28651. }
  28652. this.position.copy(origin);
  28653. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  28654. color: color,
  28655. toneMapped: false
  28656. }));
  28657. this.line.matrixAutoUpdate = false;
  28658. this.add(this.line);
  28659. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  28660. color: color,
  28661. toneMapped: false
  28662. }));
  28663. this.cone.matrixAutoUpdate = false;
  28664. this.add(this.cone);
  28665. this.setDirection(dir);
  28666. this.setLength(length, headLength, headWidth);
  28667. }
  28668. setDirection(dir) {
  28669. // dir is assumed to be normalized
  28670. if (dir.y > 0.99999) {
  28671. this.quaternion.set(0, 0, 0, 1);
  28672. } else if (dir.y < -0.99999) {
  28673. this.quaternion.set(1, 0, 0, 0);
  28674. } else {
  28675. _axis.set(dir.z, 0, -dir.x).normalize();
  28676. const radians = Math.acos(dir.y);
  28677. this.quaternion.setFromAxisAngle(_axis, radians);
  28678. }
  28679. }
  28680. setLength(length, headLength, headWidth) {
  28681. if (headLength === undefined) headLength = 0.2 * length;
  28682. if (headWidth === undefined) headWidth = 0.2 * headLength;
  28683. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  28684. this.line.updateMatrix();
  28685. this.cone.scale.set(headWidth, headLength, headWidth);
  28686. this.cone.position.y = length;
  28687. this.cone.updateMatrix();
  28688. }
  28689. setColor(color) {
  28690. this.line.material.color.set(color);
  28691. this.cone.material.color.set(color);
  28692. }
  28693. copy(source) {
  28694. super.copy(source, false);
  28695. this.line.copy(source.line);
  28696. this.cone.copy(source.cone);
  28697. return this;
  28698. }
  28699. }
  28700. exports.ArrowHelper = ArrowHelper;
  28701. class AxesHelper extends LineSegments {
  28702. constructor(size = 1) {
  28703. const vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  28704. const colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  28705. const geometry = new BufferGeometry();
  28706. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  28707. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  28708. const material = new LineBasicMaterial({
  28709. vertexColors: true,
  28710. toneMapped: false
  28711. });
  28712. super(geometry, material);
  28713. this.type = 'AxesHelper';
  28714. }
  28715. }
  28716. exports.AxesHelper = AxesHelper;
  28717. const _floatView = new Float32Array(1);
  28718. const _int32View = new Int32Array(_floatView.buffer);
  28719. const DataUtils = {
  28720. // Converts float32 to float16 (stored as uint16 value).
  28721. toHalfFloat: function (val) {
  28722. // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  28723. /* This method is faster than the OpenEXR implementation (very often
  28724. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  28725. * by James Tursa?s half-precision code. */
  28726. _floatView[0] = val;
  28727. const x = _int32View[0];
  28728. let bits = x >> 16 & 0x8000;
  28729. /* Get the sign */
  28730. let m = x >> 12 & 0x07ff;
  28731. /* Keep one extra bit for rounding */
  28732. const e = x >> 23 & 0xff;
  28733. /* Using int is faster here */
  28734. /* If zero, or denormal, or exponent underflows too much for a denormal
  28735. * half, return signed zero. */
  28736. if (e < 103) return bits;
  28737. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  28738. if (e > 142) {
  28739. bits |= 0x7c00;
  28740. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  28741. * not Inf, so make sure we set one mantissa bit too. */
  28742. bits |= (e == 255 ? 0 : 1) && x & 0x007fffff;
  28743. return bits;
  28744. }
  28745. /* If exponent underflows but not too much, return a denormal */
  28746. if (e < 113) {
  28747. m |= 0x0800;
  28748. /* Extra rounding may overflow and set mantissa to 0 and exponent
  28749. * to 1, which is OK. */
  28750. bits |= (m >> 114 - e) + (m >> 113 - e & 1);
  28751. return bits;
  28752. }
  28753. bits |= e - 112 << 10 | m >> 1;
  28754. /* Extra rounding. An overflow will set mantissa to 0 and increment
  28755. * the exponent, which is OK. */
  28756. bits += m & 1;
  28757. return bits;
  28758. }
  28759. };
  28760. exports.DataUtils = DataUtils;
  28761. const LOD_MIN = 4;
  28762. const LOD_MAX = 8;
  28763. const SIZE_MAX = Math.pow(2, LOD_MAX); // The standard deviations (radians) associated with the extra mips. These are
  28764. // chosen to approximate a Trowbridge-Reitz distribution function times the
  28765. // geometric shadowing function. These sigma values squared must match the
  28766. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  28767. const EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582];
  28768. const TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; // The maximum length of the blur for loop. Smaller sigmas will use fewer
  28769. // samples and exit early, but not recompile the shader.
  28770. const MAX_SAMPLES = 20;
  28771. const ENCODINGS = {
  28772. [LinearEncoding]: 0,
  28773. [sRGBEncoding]: 1,
  28774. [RGBEEncoding]: 2,
  28775. [RGBM7Encoding]: 3,
  28776. [RGBM16Encoding]: 4,
  28777. [RGBDEncoding]: 5,
  28778. [GammaEncoding]: 6
  28779. };
  28780. const _flatCamera =
  28781. /*@__PURE__*/
  28782. new OrthographicCamera();
  28783. const {
  28784. _lodPlanes,
  28785. _sizeLods,
  28786. _sigmas
  28787. } =
  28788. /*@__PURE__*/
  28789. _createPlanes();
  28790. let _oldTarget = null; // Golden Ratio
  28791. const PHI = (1 + Math.sqrt(5)) / 2;
  28792. const INV_PHI = 1 / PHI; // Vertices of a dodecahedron (except the opposites, which represent the
  28793. // same axis), used as axis directions evenly spread on a sphere.
  28794. const _axisDirections = [
  28795. /*@__PURE__*/
  28796. new Vector3(1, 1, 1),
  28797. /*@__PURE__*/
  28798. new Vector3(-1, 1, 1),
  28799. /*@__PURE__*/
  28800. new Vector3(1, 1, -1),
  28801. /*@__PURE__*/
  28802. new Vector3(-1, 1, -1),
  28803. /*@__PURE__*/
  28804. new Vector3(0, PHI, INV_PHI),
  28805. /*@__PURE__*/
  28806. new Vector3(0, PHI, -INV_PHI),
  28807. /*@__PURE__*/
  28808. new Vector3(INV_PHI, 0, PHI),
  28809. /*@__PURE__*/
  28810. new Vector3(-INV_PHI, 0, PHI),
  28811. /*@__PURE__*/
  28812. new Vector3(PHI, INV_PHI, 0),
  28813. /*@__PURE__*/
  28814. new Vector3(-PHI, INV_PHI, 0)];
  28815. /**
  28816. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  28817. * (PMREM) from a cubeMap environment texture. This allows different levels of
  28818. * blur to be quickly accessed based on material roughness. It is packed into a
  28819. * special CubeUV format that allows us to perform custom interpolation so that
  28820. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  28821. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  28822. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  28823. * higher roughness levels. In this way we maintain resolution to smoothly
  28824. * interpolate diffuse lighting while limiting sampling computation.
  28825. */
  28826. class PMREMGenerator {
  28827. constructor(renderer) {
  28828. this._renderer = renderer;
  28829. this._pingPongRenderTarget = null;
  28830. this._blurMaterial = _getBlurShader(MAX_SAMPLES);
  28831. this._equirectShader = null;
  28832. this._cubemapShader = null;
  28833. this._compileMaterial(this._blurMaterial);
  28834. }
  28835. /**
  28836. * Generates a PMREM from a supplied Scene, which can be faster than using an
  28837. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  28838. * in radians to be applied to the scene before PMREM generation. Optional near
  28839. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  28840. * is placed at the origin).
  28841. */
  28842. fromScene(scene, sigma = 0, near = 0.1, far = 100) {
  28843. _oldTarget = this._renderer.getRenderTarget();
  28844. const cubeUVRenderTarget = this._allocateTargets();
  28845. this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
  28846. if (sigma > 0) {
  28847. this._blur(cubeUVRenderTarget, 0, 0, sigma);
  28848. }
  28849. this._applyPMREM(cubeUVRenderTarget);
  28850. this._cleanup(cubeUVRenderTarget);
  28851. return cubeUVRenderTarget;
  28852. }
  28853. /**
  28854. * Generates a PMREM from an equirectangular texture, which can be either LDR
  28855. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  28856. * as this matches best with the 256 x 256 cubemap output.
  28857. */
  28858. fromEquirectangular(equirectangular) {
  28859. return this._fromTexture(equirectangular);
  28860. }
  28861. /**
  28862. * Generates a PMREM from an cubemap texture, which can be either LDR
  28863. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  28864. * as this matches best with the 256 x 256 cubemap output.
  28865. */
  28866. fromCubemap(cubemap) {
  28867. return this._fromTexture(cubemap);
  28868. }
  28869. /**
  28870. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  28871. * your texture's network fetch for increased concurrency.
  28872. */
  28873. compileCubemapShader() {
  28874. if (this._cubemapShader === null) {
  28875. this._cubemapShader = _getCubemapShader();
  28876. this._compileMaterial(this._cubemapShader);
  28877. }
  28878. }
  28879. /**
  28880. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  28881. * your texture's network fetch for increased concurrency.
  28882. */
  28883. compileEquirectangularShader() {
  28884. if (this._equirectShader === null) {
  28885. this._equirectShader = _getEquirectShader();
  28886. this._compileMaterial(this._equirectShader);
  28887. }
  28888. }
  28889. /**
  28890. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  28891. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  28892. * one of them will cause any others to also become unusable.
  28893. */
  28894. dispose() {
  28895. this._blurMaterial.dispose();
  28896. if (this._cubemapShader !== null) this._cubemapShader.dispose();
  28897. if (this._equirectShader !== null) this._equirectShader.dispose();
  28898. for (let i = 0; i < _lodPlanes.length; i++) {
  28899. _lodPlanes[i].dispose();
  28900. }
  28901. } // private interface
  28902. _cleanup(outputTarget) {
  28903. this._pingPongRenderTarget.dispose();
  28904. this._renderer.setRenderTarget(_oldTarget);
  28905. outputTarget.scissorTest = false;
  28906. _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height);
  28907. }
  28908. _fromTexture(texture) {
  28909. _oldTarget = this._renderer.getRenderTarget();
  28910. const cubeUVRenderTarget = this._allocateTargets(texture);
  28911. this._textureToCubeUV(texture, cubeUVRenderTarget);
  28912. this._applyPMREM(cubeUVRenderTarget);
  28913. this._cleanup(cubeUVRenderTarget);
  28914. return cubeUVRenderTarget;
  28915. }
  28916. _allocateTargets(texture) {
  28917. // warning: null texture is valid
  28918. const params = {
  28919. magFilter: NearestFilter,
  28920. minFilter: NearestFilter,
  28921. generateMipmaps: false,
  28922. type: UnsignedByteType,
  28923. format: RGBEFormat,
  28924. encoding: _isLDR(texture) ? texture.encoding : RGBEEncoding,
  28925. depthBuffer: false
  28926. };
  28927. const cubeUVRenderTarget = _createRenderTarget(params);
  28928. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  28929. this._pingPongRenderTarget = _createRenderTarget(params);
  28930. return cubeUVRenderTarget;
  28931. }
  28932. _compileMaterial(material) {
  28933. const tmpMesh = new Mesh(_lodPlanes[0], material);
  28934. this._renderer.compile(tmpMesh, _flatCamera);
  28935. }
  28936. _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
  28937. const fov = 90;
  28938. const aspect = 1;
  28939. const cubeCamera = new PerspectiveCamera(fov, aspect, near, far);
  28940. const upSign = [1, -1, 1, 1, 1, 1];
  28941. const forwardSign = [1, 1, 1, -1, -1, -1];
  28942. const renderer = this._renderer;
  28943. const outputEncoding = renderer.outputEncoding;
  28944. const toneMapping = renderer.toneMapping;
  28945. const clearColor = renderer.getClearColor();
  28946. const clearAlpha = renderer.getClearAlpha();
  28947. renderer.toneMapping = NoToneMapping;
  28948. renderer.outputEncoding = LinearEncoding;
  28949. let background = scene.background;
  28950. if (background && background.isColor) {
  28951. background.convertSRGBToLinear(); // Convert linear to RGBE
  28952. const maxComponent = Math.max(background.r, background.g, background.b);
  28953. const fExp = Math.min(Math.max(Math.ceil(Math.log2(maxComponent)), -128.0), 127.0);
  28954. background = background.multiplyScalar(Math.pow(2.0, -fExp));
  28955. const alpha = (fExp + 128.0) / 255.0;
  28956. renderer.setClearColor(background, alpha);
  28957. scene.background = null;
  28958. }
  28959. for (let i = 0; i < 6; i++) {
  28960. const col = i % 3;
  28961. if (col == 0) {
  28962. cubeCamera.up.set(0, upSign[i], 0);
  28963. cubeCamera.lookAt(forwardSign[i], 0, 0);
  28964. } else if (col == 1) {
  28965. cubeCamera.up.set(0, 0, upSign[i]);
  28966. cubeCamera.lookAt(0, forwardSign[i], 0);
  28967. } else {
  28968. cubeCamera.up.set(0, upSign[i], 0);
  28969. cubeCamera.lookAt(0, 0, forwardSign[i]);
  28970. }
  28971. _setViewport(cubeUVRenderTarget, col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX);
  28972. renderer.setRenderTarget(cubeUVRenderTarget);
  28973. renderer.render(scene, cubeCamera);
  28974. }
  28975. renderer.toneMapping = toneMapping;
  28976. renderer.outputEncoding = outputEncoding;
  28977. renderer.setClearColor(clearColor, clearAlpha);
  28978. }
  28979. _textureToCubeUV(texture, cubeUVRenderTarget) {
  28980. const renderer = this._renderer;
  28981. if (texture.isCubeTexture) {
  28982. if (this._cubemapShader == null) {
  28983. this._cubemapShader = _getCubemapShader();
  28984. }
  28985. } else {
  28986. if (this._equirectShader == null) {
  28987. this._equirectShader = _getEquirectShader();
  28988. }
  28989. }
  28990. const material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader;
  28991. const mesh = new Mesh(_lodPlanes[0], material);
  28992. const uniforms = material.uniforms;
  28993. uniforms['envMap'].value = texture;
  28994. if (!texture.isCubeTexture) {
  28995. uniforms['texelSize'].value.set(1.0 / texture.image.width, 1.0 / texture.image.height);
  28996. }
  28997. uniforms['inputEncoding'].value = ENCODINGS[texture.encoding];
  28998. uniforms['outputEncoding'].value = ENCODINGS[cubeUVRenderTarget.texture.encoding];
  28999. _setViewport(cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX);
  29000. renderer.setRenderTarget(cubeUVRenderTarget);
  29001. renderer.render(mesh, _flatCamera);
  29002. }
  29003. _applyPMREM(cubeUVRenderTarget) {
  29004. const renderer = this._renderer;
  29005. const autoClear = renderer.autoClear;
  29006. renderer.autoClear = false;
  29007. for (let i = 1; i < TOTAL_LODS; i++) {
  29008. const sigma = Math.sqrt(_sigmas[i] * _sigmas[i] - _sigmas[i - 1] * _sigmas[i - 1]);
  29009. const poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
  29010. this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
  29011. }
  29012. renderer.autoClear = autoClear;
  29013. }
  29014. /**
  29015. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  29016. * vertically and horizontally, but this breaks down on a cube. Here we apply
  29017. * the blur latitudinally (around the poles), and then longitudinally (towards
  29018. * the poles) to approximate the orthogonally-separable blur. It is least
  29019. * accurate at the poles, but still does a decent job.
  29020. */
  29021. _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
  29022. const pingPongRenderTarget = this._pingPongRenderTarget;
  29023. this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis);
  29024. this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis);
  29025. }
  29026. _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
  29027. const renderer = this._renderer;
  29028. const blurMaterial = this._blurMaterial;
  29029. if (direction !== 'latitudinal' && direction !== 'longitudinal') {
  29030. console.error('blur direction must be either latitudinal or longitudinal!');
  29031. } // Number of standard deviations at which to cut off the discrete approximation.
  29032. const STANDARD_DEVIATIONS = 3;
  29033. const blurMesh = new Mesh(_lodPlanes[lodOut], blurMaterial);
  29034. const blurUniforms = blurMaterial.uniforms;
  29035. const pixels = _sizeLods[lodIn] - 1;
  29036. const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
  29037. const sigmaPixels = sigmaRadians / radiansPerPixel;
  29038. const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
  29039. if (samples > MAX_SAMPLES) {
  29040. console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`);
  29041. }
  29042. const weights = [];
  29043. let sum = 0;
  29044. for (let i = 0; i < MAX_SAMPLES; ++i) {
  29045. const x = i / sigmaPixels;
  29046. const weight = Math.exp(-x * x / 2);
  29047. weights.push(weight);
  29048. if (i == 0) {
  29049. sum += weight;
  29050. } else if (i < samples) {
  29051. sum += 2 * weight;
  29052. }
  29053. }
  29054. for (let i = 0; i < weights.length; i++) {
  29055. weights[i] = weights[i] / sum;
  29056. }
  29057. blurUniforms['envMap'].value = targetIn.texture;
  29058. blurUniforms['samples'].value = samples;
  29059. blurUniforms['weights'].value = weights;
  29060. blurUniforms['latitudinal'].value = direction === 'latitudinal';
  29061. if (poleAxis) {
  29062. blurUniforms['poleAxis'].value = poleAxis;
  29063. }
  29064. blurUniforms['dTheta'].value = radiansPerPixel;
  29065. blurUniforms['mipInt'].value = LOD_MAX - lodIn;
  29066. blurUniforms['inputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  29067. blurUniforms['outputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  29068. const outputSize = _sizeLods[lodOut];
  29069. const x = 3 * Math.max(0, SIZE_MAX - 2 * outputSize);
  29070. const y = (lodOut === 0 ? 0 : 2 * SIZE_MAX) + 2 * outputSize * (lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0);
  29071. _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
  29072. renderer.setRenderTarget(targetOut);
  29073. renderer.render(blurMesh, _flatCamera);
  29074. }
  29075. }
  29076. exports.PMREMGenerator = PMREMGenerator;
  29077. function _isLDR(texture) {
  29078. if (texture === undefined || texture.type !== UnsignedByteType) return false;
  29079. return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
  29080. }
  29081. function _createPlanes() {
  29082. const _lodPlanes = [];
  29083. const _sizeLods = [];
  29084. const _sigmas = [];
  29085. let lod = LOD_MAX;
  29086. for (let i = 0; i < TOTAL_LODS; i++) {
  29087. const sizeLod = Math.pow(2, lod);
  29088. _sizeLods.push(sizeLod);
  29089. let sigma = 1.0 / sizeLod;
  29090. if (i > LOD_MAX - LOD_MIN) {
  29091. sigma = EXTRA_LOD_SIGMA[i - LOD_MAX + LOD_MIN - 1];
  29092. } else if (i == 0) {
  29093. sigma = 0;
  29094. }
  29095. _sigmas.push(sigma);
  29096. const texelSize = 1.0 / (sizeLod - 1);
  29097. const min = -texelSize / 2;
  29098. const max = 1 + texelSize / 2;
  29099. const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
  29100. const cubeFaces = 6;
  29101. const vertices = 6;
  29102. const positionSize = 3;
  29103. const uvSize = 2;
  29104. const faceIndexSize = 1;
  29105. const position = new Float32Array(positionSize * vertices * cubeFaces);
  29106. const uv = new Float32Array(uvSize * vertices * cubeFaces);
  29107. const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
  29108. for (let face = 0; face < cubeFaces; face++) {
  29109. const x = face % 3 * 2 / 3 - 1;
  29110. const y = face > 2 ? 0 : -1;
  29111. const coordinates = [x, y, 0, x + 2 / 3, y, 0, x + 2 / 3, y + 1, 0, x, y, 0, x + 2 / 3, y + 1, 0, x, y + 1, 0];
  29112. position.set(coordinates, positionSize * vertices * face);
  29113. uv.set(uv1, uvSize * vertices * face);
  29114. const fill = [face, face, face, face, face, face];
  29115. faceIndex.set(fill, faceIndexSize * vertices * face);
  29116. }
  29117. const planes = new BufferGeometry();
  29118. planes.setAttribute('position', new BufferAttribute(position, positionSize));
  29119. planes.setAttribute('uv', new BufferAttribute(uv, uvSize));
  29120. planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize));
  29121. _lodPlanes.push(planes);
  29122. if (lod > LOD_MIN) {
  29123. lod--;
  29124. }
  29125. }
  29126. return {
  29127. _lodPlanes,
  29128. _sizeLods,
  29129. _sigmas
  29130. };
  29131. }
  29132. function _createRenderTarget(params) {
  29133. const cubeUVRenderTarget = new WebGLRenderTarget(3 * SIZE_MAX, 3 * SIZE_MAX, params);
  29134. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  29135. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  29136. cubeUVRenderTarget.scissorTest = true;
  29137. return cubeUVRenderTarget;
  29138. }
  29139. function _setViewport(target, x, y, width, height) {
  29140. target.viewport.set(x, y, width, height);
  29141. target.scissor.set(x, y, width, height);
  29142. }
  29143. function _getBlurShader(maxSamples) {
  29144. const weights = new Float32Array(maxSamples);
  29145. const poleAxis = new Vector3(0, 1, 0);
  29146. const shaderMaterial = new RawShaderMaterial({
  29147. name: 'SphericalGaussianBlur',
  29148. defines: {
  29149. 'n': maxSamples
  29150. },
  29151. uniforms: {
  29152. 'envMap': {
  29153. value: null
  29154. },
  29155. 'samples': {
  29156. value: 1
  29157. },
  29158. 'weights': {
  29159. value: weights
  29160. },
  29161. 'latitudinal': {
  29162. value: false
  29163. },
  29164. 'dTheta': {
  29165. value: 0
  29166. },
  29167. 'mipInt': {
  29168. value: 0
  29169. },
  29170. 'poleAxis': {
  29171. value: poleAxis
  29172. },
  29173. 'inputEncoding': {
  29174. value: ENCODINGS[LinearEncoding]
  29175. },
  29176. 'outputEncoding': {
  29177. value: ENCODINGS[LinearEncoding]
  29178. }
  29179. },
  29180. vertexShader: _getCommonVertexShader(),
  29181. fragmentShader:
  29182. /* glsl */
  29183. `
  29184. precision mediump float;
  29185. precision mediump int;
  29186. varying vec3 vOutputDirection;
  29187. uniform sampler2D envMap;
  29188. uniform int samples;
  29189. uniform float weights[ n ];
  29190. uniform bool latitudinal;
  29191. uniform float dTheta;
  29192. uniform float mipInt;
  29193. uniform vec3 poleAxis;
  29194. ${_getEncodings()}
  29195. #define ENVMAP_TYPE_CUBE_UV
  29196. #include <cube_uv_reflection_fragment>
  29197. vec3 getSample( float theta, vec3 axis ) {
  29198. float cosTheta = cos( theta );
  29199. // Rodrigues' axis-angle rotation
  29200. vec3 sampleDirection = vOutputDirection * cosTheta
  29201. + cross( axis, vOutputDirection ) * sin( theta )
  29202. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  29203. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  29204. }
  29205. void main() {
  29206. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  29207. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  29208. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  29209. }
  29210. axis = normalize( axis );
  29211. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  29212. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  29213. for ( int i = 1; i < n; i++ ) {
  29214. if ( i >= samples ) {
  29215. break;
  29216. }
  29217. float theta = dTheta * float( i );
  29218. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  29219. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  29220. }
  29221. gl_FragColor = linearToOutputTexel( gl_FragColor );
  29222. }
  29223. `,
  29224. blending: NoBlending,
  29225. depthTest: false,
  29226. depthWrite: false
  29227. });
  29228. return shaderMaterial;
  29229. }
  29230. function _getEquirectShader() {
  29231. const texelSize = new Vector2(1, 1);
  29232. const shaderMaterial = new RawShaderMaterial({
  29233. name: 'EquirectangularToCubeUV',
  29234. uniforms: {
  29235. 'envMap': {
  29236. value: null
  29237. },
  29238. 'texelSize': {
  29239. value: texelSize
  29240. },
  29241. 'inputEncoding': {
  29242. value: ENCODINGS[LinearEncoding]
  29243. },
  29244. 'outputEncoding': {
  29245. value: ENCODINGS[LinearEncoding]
  29246. }
  29247. },
  29248. vertexShader: _getCommonVertexShader(),
  29249. fragmentShader:
  29250. /* glsl */
  29251. `
  29252. precision mediump float;
  29253. precision mediump int;
  29254. varying vec3 vOutputDirection;
  29255. uniform sampler2D envMap;
  29256. uniform vec2 texelSize;
  29257. ${_getEncodings()}
  29258. #include <common>
  29259. void main() {
  29260. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  29261. vec3 outputDirection = normalize( vOutputDirection );
  29262. vec2 uv = equirectUv( outputDirection );
  29263. vec2 f = fract( uv / texelSize - 0.5 );
  29264. uv -= f * texelSize;
  29265. vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  29266. uv.x += texelSize.x;
  29267. vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  29268. uv.y += texelSize.y;
  29269. vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  29270. uv.x -= texelSize.x;
  29271. vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  29272. vec3 tm = mix( tl, tr, f.x );
  29273. vec3 bm = mix( bl, br, f.x );
  29274. gl_FragColor.rgb = mix( tm, bm, f.y );
  29275. gl_FragColor = linearToOutputTexel( gl_FragColor );
  29276. }
  29277. `,
  29278. blending: NoBlending,
  29279. depthTest: false,
  29280. depthWrite: false
  29281. });
  29282. return shaderMaterial;
  29283. }
  29284. function _getCubemapShader() {
  29285. const shaderMaterial = new RawShaderMaterial({
  29286. name: 'CubemapToCubeUV',
  29287. uniforms: {
  29288. 'envMap': {
  29289. value: null
  29290. },
  29291. 'inputEncoding': {
  29292. value: ENCODINGS[LinearEncoding]
  29293. },
  29294. 'outputEncoding': {
  29295. value: ENCODINGS[LinearEncoding]
  29296. }
  29297. },
  29298. vertexShader: _getCommonVertexShader(),
  29299. fragmentShader:
  29300. /* glsl */
  29301. `
  29302. precision mediump float;
  29303. precision mediump int;
  29304. varying vec3 vOutputDirection;
  29305. uniform samplerCube envMap;
  29306. ${_getEncodings()}
  29307. void main() {
  29308. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  29309. gl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;
  29310. gl_FragColor = linearToOutputTexel( gl_FragColor );
  29311. }
  29312. `,
  29313. blending: NoBlending,
  29314. depthTest: false,
  29315. depthWrite: false
  29316. });
  29317. return shaderMaterial;
  29318. }
  29319. function _getCommonVertexShader() {
  29320. return (
  29321. /* glsl */
  29322. `
  29323. precision mediump float;
  29324. precision mediump int;
  29325. attribute vec3 position;
  29326. attribute vec2 uv;
  29327. attribute float faceIndex;
  29328. varying vec3 vOutputDirection;
  29329. // RH coordinate system; PMREM face-indexing convention
  29330. vec3 getDirection( vec2 uv, float face ) {
  29331. uv = 2.0 * uv - 1.0;
  29332. vec3 direction = vec3( uv, 1.0 );
  29333. if ( face == 0.0 ) {
  29334. direction = direction.zyx; // ( 1, v, u ) pos x
  29335. } else if ( face == 1.0 ) {
  29336. direction = direction.xzy;
  29337. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  29338. } else if ( face == 2.0 ) {
  29339. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  29340. } else if ( face == 3.0 ) {
  29341. direction = direction.zyx;
  29342. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  29343. } else if ( face == 4.0 ) {
  29344. direction = direction.xzy;
  29345. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  29346. } else if ( face == 5.0 ) {
  29347. direction.z *= -1.0; // ( u, v, -1 ) neg z
  29348. }
  29349. return direction;
  29350. }
  29351. void main() {
  29352. vOutputDirection = getDirection( uv, faceIndex );
  29353. gl_Position = vec4( position, 1.0 );
  29354. }
  29355. `
  29356. );
  29357. }
  29358. function _getEncodings() {
  29359. return (
  29360. /* glsl */
  29361. `
  29362. uniform int inputEncoding;
  29363. uniform int outputEncoding;
  29364. #include <encodings_pars_fragment>
  29365. vec4 inputTexelToLinear( vec4 value ) {
  29366. if ( inputEncoding == 0 ) {
  29367. return value;
  29368. } else if ( inputEncoding == 1 ) {
  29369. return sRGBToLinear( value );
  29370. } else if ( inputEncoding == 2 ) {
  29371. return RGBEToLinear( value );
  29372. } else if ( inputEncoding == 3 ) {
  29373. return RGBMToLinear( value, 7.0 );
  29374. } else if ( inputEncoding == 4 ) {
  29375. return RGBMToLinear( value, 16.0 );
  29376. } else if ( inputEncoding == 5 ) {
  29377. return RGBDToLinear( value, 256.0 );
  29378. } else {
  29379. return GammaToLinear( value, 2.2 );
  29380. }
  29381. }
  29382. vec4 linearToOutputTexel( vec4 value ) {
  29383. if ( outputEncoding == 0 ) {
  29384. return value;
  29385. } else if ( outputEncoding == 1 ) {
  29386. return LinearTosRGB( value );
  29387. } else if ( outputEncoding == 2 ) {
  29388. return LinearToRGBE( value );
  29389. } else if ( outputEncoding == 3 ) {
  29390. return LinearToRGBM( value, 7.0 );
  29391. } else if ( outputEncoding == 4 ) {
  29392. return LinearToRGBM( value, 16.0 );
  29393. } else if ( outputEncoding == 5 ) {
  29394. return LinearToRGBD( value, 256.0 );
  29395. } else {
  29396. return LinearToGamma( value, 2.2 );
  29397. }
  29398. }
  29399. vec4 envMapTexelToLinear( vec4 color ) {
  29400. return inputTexelToLinear( color );
  29401. }
  29402. `
  29403. );
  29404. }
  29405. function Face4(a, b, c, d, normal, color, materialIndex) {
  29406. console.warn('THREE.Face4 has been removed. A THREE.Face3 will be created instead.');
  29407. return new Face3(a, b, c, normal, color, materialIndex);
  29408. }
  29409. const LineStrip = 0;
  29410. exports.LineStrip = LineStrip;
  29411. const LinePieces = 1;
  29412. exports.LinePieces = LinePieces;
  29413. const NoColors = 0;
  29414. exports.NoColors = NoColors;
  29415. const FaceColors = 1;
  29416. exports.FaceColors = FaceColors;
  29417. const VertexColors = 2;
  29418. exports.VertexColors = VertexColors;
  29419. function MeshFaceMaterial(materials) {
  29420. console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
  29421. return materials;
  29422. }
  29423. function MultiMaterial(materials = []) {
  29424. console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
  29425. materials.isMultiMaterial = true;
  29426. materials.materials = materials;
  29427. materials.clone = function () {
  29428. return materials.slice();
  29429. };
  29430. return materials;
  29431. }
  29432. function PointCloud(geometry, material) {
  29433. console.warn('THREE.PointCloud has been renamed to THREE.Points.');
  29434. return new Points(geometry, material);
  29435. }
  29436. function Particle(material) {
  29437. console.warn('THREE.Particle has been renamed to THREE.Sprite.');
  29438. return new Sprite(material);
  29439. }
  29440. function ParticleSystem(geometry, material) {
  29441. console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
  29442. return new Points(geometry, material);
  29443. }
  29444. function PointCloudMaterial(parameters) {
  29445. console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
  29446. return new PointsMaterial(parameters);
  29447. }
  29448. function ParticleBasicMaterial(parameters) {
  29449. console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
  29450. return new PointsMaterial(parameters);
  29451. }
  29452. function ParticleSystemMaterial(parameters) {
  29453. console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
  29454. return new PointsMaterial(parameters);
  29455. }
  29456. function Vertex(x, y, z) {
  29457. console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
  29458. return new Vector3(x, y, z);
  29459. } //
  29460. function DynamicBufferAttribute(array, itemSize) {
  29461. console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.');
  29462. return new BufferAttribute(array, itemSize).setUsage(DynamicDrawUsage);
  29463. }
  29464. function Int8Attribute(array, itemSize) {
  29465. console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
  29466. return new Int8BufferAttribute(array, itemSize);
  29467. }
  29468. function Uint8Attribute(array, itemSize) {
  29469. console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
  29470. return new Uint8BufferAttribute(array, itemSize);
  29471. }
  29472. function Uint8ClampedAttribute(array, itemSize) {
  29473. console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
  29474. return new Uint8ClampedBufferAttribute(array, itemSize);
  29475. }
  29476. function Int16Attribute(array, itemSize) {
  29477. console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
  29478. return new Int16BufferAttribute(array, itemSize);
  29479. }
  29480. function Uint16Attribute(array, itemSize) {
  29481. console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
  29482. return new Uint16BufferAttribute(array, itemSize);
  29483. }
  29484. function Int32Attribute(array, itemSize) {
  29485. console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
  29486. return new Int32BufferAttribute(array, itemSize);
  29487. }
  29488. function Uint32Attribute(array, itemSize) {
  29489. console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
  29490. return new Uint32BufferAttribute(array, itemSize);
  29491. }
  29492. function Float32Attribute(array, itemSize) {
  29493. console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
  29494. return new Float32BufferAttribute(array, itemSize);
  29495. }
  29496. function Float64Attribute(array, itemSize) {
  29497. console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
  29498. return new Float64BufferAttribute(array, itemSize);
  29499. } //
  29500. Curve.create = function (construct, getPoint) {
  29501. console.log('THREE.Curve.create() has been deprecated');
  29502. construct.prototype = Object.create(Curve.prototype);
  29503. construct.prototype.constructor = construct;
  29504. construct.prototype.getPoint = getPoint;
  29505. return construct;
  29506. }; //
  29507. Object.assign(CurvePath.prototype, {
  29508. createPointsGeometry: function (divisions) {
  29509. 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)
  29510. const pts = this.getPoints(divisions);
  29511. return this.createGeometry(pts);
  29512. },
  29513. createSpacedPointsGeometry: function (divisions) {
  29514. console.warn('THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.'); // generate geometry from equidistant sampling along the path
  29515. const pts = this.getSpacedPoints(divisions);
  29516. return this.createGeometry(pts);
  29517. },
  29518. createGeometry: function (points) {
  29519. console.warn('THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.');
  29520. const geometry = new Geometry();
  29521. for (let i = 0, l = points.length; i < l; i++) {
  29522. const point = points[i];
  29523. geometry.vertices.push(new Vector3(point.x, point.y, point.z || 0));
  29524. }
  29525. return geometry;
  29526. }
  29527. }); //
  29528. Object.assign(Path.prototype, {
  29529. fromPoints: function (points) {
  29530. console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
  29531. return this.setFromPoints(points);
  29532. }
  29533. }); //
  29534. function ClosedSplineCurve3(points) {
  29535. console.warn('THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
  29536. CatmullRomCurve3.call(this, points);
  29537. this.type = 'catmullrom';
  29538. this.closed = true;
  29539. }
  29540. ClosedSplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
  29541. function SplineCurve3(points) {
  29542. console.warn('THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
  29543. CatmullRomCurve3.call(this, points);
  29544. this.type = 'catmullrom';
  29545. }
  29546. SplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
  29547. function Spline(points) {
  29548. console.warn('THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.');
  29549. CatmullRomCurve3.call(this, points);
  29550. this.type = 'catmullrom';
  29551. }
  29552. Spline.prototype = Object.create(CatmullRomCurve3.prototype);
  29553. Object.assign(Spline.prototype, {
  29554. initFromArray: function ()
  29555. /* a */
  29556. {
  29557. console.error('THREE.Spline: .initFromArray() has been removed.');
  29558. },
  29559. getControlPointsArray: function ()
  29560. /* optionalTarget */
  29561. {
  29562. console.error('THREE.Spline: .getControlPointsArray() has been removed.');
  29563. },
  29564. reparametrizeByArcLength: function ()
  29565. /* samplingCoef */
  29566. {
  29567. console.error('THREE.Spline: .reparametrizeByArcLength() has been removed.');
  29568. }
  29569. }); //
  29570. function AxisHelper(size) {
  29571. console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
  29572. return new AxesHelper(size);
  29573. }
  29574. function BoundingBoxHelper(object, color) {
  29575. console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
  29576. return new BoxHelper(object, color);
  29577. }
  29578. function EdgesHelper(object, hex) {
  29579. console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
  29580. return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
  29581. color: hex !== undefined ? hex : 0xffffff
  29582. }));
  29583. }
  29584. GridHelper.prototype.setColors = function () {
  29585. console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
  29586. };
  29587. SkeletonHelper.prototype.update = function () {
  29588. console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
  29589. };
  29590. function WireframeHelper(object, hex) {
  29591. console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
  29592. return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
  29593. color: hex !== undefined ? hex : 0xffffff
  29594. }));
  29595. } //
  29596. Object.assign(Loader.prototype, {
  29597. extractUrlBase: function (url) {
  29598. console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
  29599. return LoaderUtils.extractUrlBase(url);
  29600. }
  29601. });
  29602. Loader.Handlers = {
  29603. add: function ()
  29604. /* regex, loader */
  29605. {
  29606. console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
  29607. },
  29608. get: function ()
  29609. /* file */
  29610. {
  29611. console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
  29612. }
  29613. };
  29614. function XHRLoader(manager) {
  29615. console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
  29616. return new FileLoader(manager);
  29617. }
  29618. function BinaryTextureLoader(manager) {
  29619. console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
  29620. return new DataTextureLoader(manager);
  29621. } //
  29622. Object.assign(Box2.prototype, {
  29623. center: function (optionalTarget) {
  29624. console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
  29625. return this.getCenter(optionalTarget);
  29626. },
  29627. empty: function () {
  29628. console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
  29629. return this.isEmpty();
  29630. },
  29631. isIntersectionBox: function (box) {
  29632. console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
  29633. return this.intersectsBox(box);
  29634. },
  29635. size: function (optionalTarget) {
  29636. console.warn('THREE.Box2: .size() has been renamed to .getSize().');
  29637. return this.getSize(optionalTarget);
  29638. }
  29639. });
  29640. Object.assign(Box3.prototype, {
  29641. center: function (optionalTarget) {
  29642. console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
  29643. return this.getCenter(optionalTarget);
  29644. },
  29645. empty: function () {
  29646. console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
  29647. return this.isEmpty();
  29648. },
  29649. isIntersectionBox: function (box) {
  29650. console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
  29651. return this.intersectsBox(box);
  29652. },
  29653. isIntersectionSphere: function (sphere) {
  29654. console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  29655. return this.intersectsSphere(sphere);
  29656. },
  29657. size: function (optionalTarget) {
  29658. console.warn('THREE.Box3: .size() has been renamed to .getSize().');
  29659. return this.getSize(optionalTarget);
  29660. }
  29661. });
  29662. Object.assign(Sphere.prototype, {
  29663. empty: function () {
  29664. console.warn('THREE.Sphere: .empty() has been renamed to .isEmpty().');
  29665. return this.isEmpty();
  29666. }
  29667. });
  29668. Frustum.prototype.setFromMatrix = function (m) {
  29669. console.warn('THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().');
  29670. return this.setFromProjectionMatrix(m);
  29671. };
  29672. Line3.prototype.center = function (optionalTarget) {
  29673. console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
  29674. return this.getCenter(optionalTarget);
  29675. };
  29676. Object.assign(MathUtils, {
  29677. random16: function () {
  29678. console.warn('THREE.Math: .random16() has been deprecated. Use Math.random() instead.');
  29679. return Math.random();
  29680. },
  29681. nearestPowerOfTwo: function (value) {
  29682. console.warn('THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().');
  29683. return MathUtils.floorPowerOfTwo(value);
  29684. },
  29685. nextPowerOfTwo: function (value) {
  29686. console.warn('THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().');
  29687. return MathUtils.ceilPowerOfTwo(value);
  29688. }
  29689. });
  29690. Object.assign(Matrix3.prototype, {
  29691. flattenToArrayOffset: function (array, offset) {
  29692. console.warn("THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");
  29693. return this.toArray(array, offset);
  29694. },
  29695. multiplyVector3: function (vector) {
  29696. console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
  29697. return vector.applyMatrix3(this);
  29698. },
  29699. multiplyVector3Array: function ()
  29700. /* a */
  29701. {
  29702. console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
  29703. },
  29704. applyToBufferAttribute: function (attribute) {
  29705. console.warn('THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.');
  29706. return attribute.applyMatrix3(this);
  29707. },
  29708. applyToVector3Array: function ()
  29709. /* array, offset, length */
  29710. {
  29711. console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
  29712. },
  29713. getInverse: function (matrix) {
  29714. console.warn('THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  29715. return this.copy(matrix).invert();
  29716. }
  29717. });
  29718. Object.assign(Matrix4.prototype, {
  29719. extractPosition: function (m) {
  29720. console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
  29721. return this.copyPosition(m);
  29722. },
  29723. flattenToArrayOffset: function (array, offset) {
  29724. console.warn("THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");
  29725. return this.toArray(array, offset);
  29726. },
  29727. getPosition: function () {
  29728. console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
  29729. return new Vector3().setFromMatrixColumn(this, 3);
  29730. },
  29731. setRotationFromQuaternion: function (q) {
  29732. console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
  29733. return this.makeRotationFromQuaternion(q);
  29734. },
  29735. multiplyToArray: function () {
  29736. console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
  29737. },
  29738. multiplyVector3: function (vector) {
  29739. console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29740. return vector.applyMatrix4(this);
  29741. },
  29742. multiplyVector4: function (vector) {
  29743. console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29744. return vector.applyMatrix4(this);
  29745. },
  29746. multiplyVector3Array: function ()
  29747. /* a */
  29748. {
  29749. console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
  29750. },
  29751. rotateAxis: function (v) {
  29752. console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
  29753. v.transformDirection(this);
  29754. },
  29755. crossVector: function (vector) {
  29756. console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29757. return vector.applyMatrix4(this);
  29758. },
  29759. translate: function () {
  29760. console.error('THREE.Matrix4: .translate() has been removed.');
  29761. },
  29762. rotateX: function () {
  29763. console.error('THREE.Matrix4: .rotateX() has been removed.');
  29764. },
  29765. rotateY: function () {
  29766. console.error('THREE.Matrix4: .rotateY() has been removed.');
  29767. },
  29768. rotateZ: function () {
  29769. console.error('THREE.Matrix4: .rotateZ() has been removed.');
  29770. },
  29771. rotateByAxis: function () {
  29772. console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
  29773. },
  29774. applyToBufferAttribute: function (attribute) {
  29775. console.warn('THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.');
  29776. return attribute.applyMatrix4(this);
  29777. },
  29778. applyToVector3Array: function ()
  29779. /* array, offset, length */
  29780. {
  29781. console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
  29782. },
  29783. makeFrustum: function (left, right, bottom, top, near, far) {
  29784. console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
  29785. return this.makePerspective(left, right, top, bottom, near, far);
  29786. },
  29787. getInverse: function (matrix) {
  29788. console.warn('THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  29789. return this.copy(matrix).invert();
  29790. }
  29791. });
  29792. Plane.prototype.isIntersectionLine = function (line) {
  29793. console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
  29794. return this.intersectsLine(line);
  29795. };
  29796. Object.assign(Quaternion.prototype, {
  29797. multiplyVector3: function (vector) {
  29798. console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
  29799. return vector.applyQuaternion(this);
  29800. },
  29801. inverse: function () {
  29802. console.warn('THREE.Quaternion: .inverse() has been renamed to invert().');
  29803. return this.invert();
  29804. }
  29805. });
  29806. Object.assign(Ray.prototype, {
  29807. isIntersectionBox: function (box) {
  29808. console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
  29809. return this.intersectsBox(box);
  29810. },
  29811. isIntersectionPlane: function (plane) {
  29812. console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
  29813. return this.intersectsPlane(plane);
  29814. },
  29815. isIntersectionSphere: function (sphere) {
  29816. console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  29817. return this.intersectsSphere(sphere);
  29818. }
  29819. });
  29820. Object.assign(Triangle.prototype, {
  29821. area: function () {
  29822. console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
  29823. return this.getArea();
  29824. },
  29825. barycoordFromPoint: function (point, target) {
  29826. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  29827. return this.getBarycoord(point, target);
  29828. },
  29829. midpoint: function (target) {
  29830. console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
  29831. return this.getMidpoint(target);
  29832. },
  29833. normal: function (target) {
  29834. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  29835. return this.getNormal(target);
  29836. },
  29837. plane: function (target) {
  29838. console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
  29839. return this.getPlane(target);
  29840. }
  29841. });
  29842. Object.assign(Triangle, {
  29843. barycoordFromPoint: function (point, a, b, c, target) {
  29844. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  29845. return Triangle.getBarycoord(point, a, b, c, target);
  29846. },
  29847. normal: function (a, b, c, target) {
  29848. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  29849. return Triangle.getNormal(a, b, c, target);
  29850. }
  29851. });
  29852. Object.assign(Shape.prototype, {
  29853. extractAllPoints: function (divisions) {
  29854. console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
  29855. return this.extractPoints(divisions);
  29856. },
  29857. extrude: function (options) {
  29858. console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
  29859. return new ExtrudeGeometry(this, options);
  29860. },
  29861. makeGeometry: function (options) {
  29862. console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
  29863. return new ShapeGeometry(this, options);
  29864. }
  29865. });
  29866. Object.assign(Vector2.prototype, {
  29867. fromAttribute: function (attribute, index, offset) {
  29868. console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29869. return this.fromBufferAttribute(attribute, index, offset);
  29870. },
  29871. distanceToManhattan: function (v) {
  29872. console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  29873. return this.manhattanDistanceTo(v);
  29874. },
  29875. lengthManhattan: function () {
  29876. console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
  29877. return this.manhattanLength();
  29878. }
  29879. });
  29880. Object.assign(Vector3.prototype, {
  29881. setEulerFromRotationMatrix: function () {
  29882. console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
  29883. },
  29884. setEulerFromQuaternion: function () {
  29885. console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
  29886. },
  29887. getPositionFromMatrix: function (m) {
  29888. console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
  29889. return this.setFromMatrixPosition(m);
  29890. },
  29891. getScaleFromMatrix: function (m) {
  29892. console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
  29893. return this.setFromMatrixScale(m);
  29894. },
  29895. getColumnFromMatrix: function (index, matrix) {
  29896. console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
  29897. return this.setFromMatrixColumn(matrix, index);
  29898. },
  29899. applyProjection: function (m) {
  29900. console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
  29901. return this.applyMatrix4(m);
  29902. },
  29903. fromAttribute: function (attribute, index, offset) {
  29904. console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29905. return this.fromBufferAttribute(attribute, index, offset);
  29906. },
  29907. distanceToManhattan: function (v) {
  29908. console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  29909. return this.manhattanDistanceTo(v);
  29910. },
  29911. lengthManhattan: function () {
  29912. console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
  29913. return this.manhattanLength();
  29914. }
  29915. });
  29916. Object.assign(Vector4.prototype, {
  29917. fromAttribute: function (attribute, index, offset) {
  29918. console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29919. return this.fromBufferAttribute(attribute, index, offset);
  29920. },
  29921. lengthManhattan: function () {
  29922. console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
  29923. return this.manhattanLength();
  29924. }
  29925. }); //
  29926. Object.assign(Geometry.prototype, {
  29927. computeTangents: function () {
  29928. console.error('THREE.Geometry: .computeTangents() has been removed.');
  29929. },
  29930. computeLineDistances: function () {
  29931. console.error('THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.');
  29932. },
  29933. applyMatrix: function (matrix) {
  29934. console.warn('THREE.Geometry: .applyMatrix() has been renamed to .applyMatrix4().');
  29935. return this.applyMatrix4(matrix);
  29936. }
  29937. });
  29938. Object.assign(Object3D.prototype, {
  29939. getChildByName: function (name) {
  29940. console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
  29941. return this.getObjectByName(name);
  29942. },
  29943. renderDepth: function () {
  29944. console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
  29945. },
  29946. translate: function (distance, axis) {
  29947. console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
  29948. return this.translateOnAxis(axis, distance);
  29949. },
  29950. getWorldRotation: function () {
  29951. console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
  29952. },
  29953. applyMatrix: function (matrix) {
  29954. console.warn('THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().');
  29955. return this.applyMatrix4(matrix);
  29956. }
  29957. });
  29958. Object.defineProperties(Object3D.prototype, {
  29959. eulerOrder: {
  29960. get: function () {
  29961. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  29962. return this.rotation.order;
  29963. },
  29964. set: function (value) {
  29965. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  29966. this.rotation.order = value;
  29967. }
  29968. },
  29969. useQuaternion: {
  29970. get: function () {
  29971. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  29972. },
  29973. set: function () {
  29974. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  29975. }
  29976. }
  29977. });
  29978. Object.assign(Mesh.prototype, {
  29979. setDrawMode: function () {
  29980. console.error('THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  29981. }
  29982. });
  29983. Object.defineProperties(Mesh.prototype, {
  29984. drawMode: {
  29985. get: function () {
  29986. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.');
  29987. return TrianglesDrawMode;
  29988. },
  29989. set: function () {
  29990. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  29991. }
  29992. }
  29993. });
  29994. Object.defineProperties(LOD.prototype, {
  29995. objects: {
  29996. get: function () {
  29997. console.warn('THREE.LOD: .objects has been renamed to .levels.');
  29998. return this.levels;
  29999. }
  30000. }
  30001. });
  30002. Object.defineProperty(Skeleton.prototype, 'useVertexTexture', {
  30003. get: function () {
  30004. console.warn('THREE.Skeleton: useVertexTexture has been removed.');
  30005. },
  30006. set: function () {
  30007. console.warn('THREE.Skeleton: useVertexTexture has been removed.');
  30008. }
  30009. });
  30010. SkinnedMesh.prototype.initBones = function () {
  30011. console.error('THREE.SkinnedMesh: initBones() has been removed.');
  30012. };
  30013. Object.defineProperty(Curve.prototype, '__arcLengthDivisions', {
  30014. get: function () {
  30015. console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
  30016. return this.arcLengthDivisions;
  30017. },
  30018. set: function (value) {
  30019. console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
  30020. this.arcLengthDivisions = value;
  30021. }
  30022. }); //
  30023. PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
  30024. console.warn("THREE.PerspectiveCamera.setLens is deprecated. " + "Use .setFocalLength and .filmGauge for a photographic setup.");
  30025. if (filmGauge !== undefined) this.filmGauge = filmGauge;
  30026. this.setFocalLength(focalLength);
  30027. }; //
  30028. Object.defineProperties(Light.prototype, {
  30029. onlyShadow: {
  30030. set: function () {
  30031. console.warn('THREE.Light: .onlyShadow has been removed.');
  30032. }
  30033. },
  30034. shadowCameraFov: {
  30035. set: function (value) {
  30036. console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
  30037. this.shadow.camera.fov = value;
  30038. }
  30039. },
  30040. shadowCameraLeft: {
  30041. set: function (value) {
  30042. console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
  30043. this.shadow.camera.left = value;
  30044. }
  30045. },
  30046. shadowCameraRight: {
  30047. set: function (value) {
  30048. console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
  30049. this.shadow.camera.right = value;
  30050. }
  30051. },
  30052. shadowCameraTop: {
  30053. set: function (value) {
  30054. console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
  30055. this.shadow.camera.top = value;
  30056. }
  30057. },
  30058. shadowCameraBottom: {
  30059. set: function (value) {
  30060. console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
  30061. this.shadow.camera.bottom = value;
  30062. }
  30063. },
  30064. shadowCameraNear: {
  30065. set: function (value) {
  30066. console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
  30067. this.shadow.camera.near = value;
  30068. }
  30069. },
  30070. shadowCameraFar: {
  30071. set: function (value) {
  30072. console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
  30073. this.shadow.camera.far = value;
  30074. }
  30075. },
  30076. shadowCameraVisible: {
  30077. set: function () {
  30078. console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
  30079. }
  30080. },
  30081. shadowBias: {
  30082. set: function (value) {
  30083. console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
  30084. this.shadow.bias = value;
  30085. }
  30086. },
  30087. shadowDarkness: {
  30088. set: function () {
  30089. console.warn('THREE.Light: .shadowDarkness has been removed.');
  30090. }
  30091. },
  30092. shadowMapWidth: {
  30093. set: function (value) {
  30094. console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
  30095. this.shadow.mapSize.width = value;
  30096. }
  30097. },
  30098. shadowMapHeight: {
  30099. set: function (value) {
  30100. console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
  30101. this.shadow.mapSize.height = value;
  30102. }
  30103. }
  30104. }); //
  30105. Object.defineProperties(BufferAttribute.prototype, {
  30106. length: {
  30107. get: function () {
  30108. console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
  30109. return this.array.length;
  30110. }
  30111. },
  30112. dynamic: {
  30113. get: function () {
  30114. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  30115. return this.usage === DynamicDrawUsage;
  30116. },
  30117. set: function ()
  30118. /* value */
  30119. {
  30120. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  30121. this.setUsage(DynamicDrawUsage);
  30122. }
  30123. }
  30124. });
  30125. Object.assign(BufferAttribute.prototype, {
  30126. setDynamic: function (value) {
  30127. console.warn('THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.');
  30128. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  30129. return this;
  30130. },
  30131. copyIndicesArray: function ()
  30132. /* indices */
  30133. {
  30134. console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
  30135. },
  30136. setArray: function ()
  30137. /* array */
  30138. {
  30139. console.error('THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  30140. }
  30141. });
  30142. Object.assign(BufferGeometry.prototype, {
  30143. addIndex: function (index) {
  30144. console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
  30145. this.setIndex(index);
  30146. },
  30147. addAttribute: function (name, attribute) {
  30148. console.warn('THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().');
  30149. if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
  30150. console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
  30151. return this.setAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
  30152. }
  30153. if (name === 'index') {
  30154. console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
  30155. this.setIndex(attribute);
  30156. return this;
  30157. }
  30158. return this.setAttribute(name, attribute);
  30159. },
  30160. addDrawCall: function (start, count, indexOffset) {
  30161. if (indexOffset !== undefined) {
  30162. console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
  30163. }
  30164. console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
  30165. this.addGroup(start, count);
  30166. },
  30167. clearDrawCalls: function () {
  30168. console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
  30169. this.clearGroups();
  30170. },
  30171. computeTangents: function () {
  30172. console.warn('THREE.BufferGeometry: .computeTangents() has been removed.');
  30173. },
  30174. computeOffsets: function () {
  30175. console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
  30176. },
  30177. removeAttribute: function (name) {
  30178. console.warn('THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().');
  30179. return this.deleteAttribute(name);
  30180. },
  30181. applyMatrix: function (matrix) {
  30182. console.warn('THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().');
  30183. return this.applyMatrix4(matrix);
  30184. }
  30185. });
  30186. Object.defineProperties(BufferGeometry.prototype, {
  30187. drawcalls: {
  30188. get: function () {
  30189. console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
  30190. return this.groups;
  30191. }
  30192. },
  30193. offsets: {
  30194. get: function () {
  30195. console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
  30196. return this.groups;
  30197. }
  30198. }
  30199. });
  30200. Object.defineProperties(InstancedBufferGeometry.prototype, {
  30201. maxInstancedCount: {
  30202. get: function () {
  30203. console.warn('THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.');
  30204. return this.instanceCount;
  30205. },
  30206. set: function (value) {
  30207. console.warn('THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.');
  30208. this.instanceCount = value;
  30209. }
  30210. }
  30211. });
  30212. Object.defineProperties(Raycaster.prototype, {
  30213. linePrecision: {
  30214. get: function () {
  30215. console.warn('THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.');
  30216. return this.params.Line.threshold;
  30217. },
  30218. set: function (value) {
  30219. console.warn('THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.');
  30220. this.params.Line.threshold = value;
  30221. }
  30222. }
  30223. });
  30224. Object.defineProperties(InterleavedBuffer.prototype, {
  30225. dynamic: {
  30226. get: function () {
  30227. console.warn('THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.');
  30228. return this.usage === DynamicDrawUsage;
  30229. },
  30230. set: function (value) {
  30231. console.warn('THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.');
  30232. this.setUsage(value);
  30233. }
  30234. }
  30235. });
  30236. Object.assign(InterleavedBuffer.prototype, {
  30237. setDynamic: function (value) {
  30238. console.warn('THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.');
  30239. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  30240. return this;
  30241. },
  30242. setArray: function ()
  30243. /* array */
  30244. {
  30245. console.error('THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  30246. }
  30247. }); //
  30248. Object.assign(ExtrudeBufferGeometry.prototype, {
  30249. getArrays: function () {
  30250. console.error('THREE.ExtrudeBufferGeometry: .getArrays() has been removed.');
  30251. },
  30252. addShapeList: function () {
  30253. console.error('THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.');
  30254. },
  30255. addShape: function () {
  30256. console.error('THREE.ExtrudeBufferGeometry: .addShape() has been removed.');
  30257. }
  30258. }); //
  30259. Object.assign(Scene.prototype, {
  30260. dispose: function () {
  30261. console.error('THREE.Scene: .dispose() has been removed.');
  30262. }
  30263. }); //
  30264. Object.defineProperties(Uniform.prototype, {
  30265. dynamic: {
  30266. set: function () {
  30267. console.warn('THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.');
  30268. }
  30269. },
  30270. onUpdate: {
  30271. value: function () {
  30272. console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
  30273. return this;
  30274. }
  30275. }
  30276. }); //
  30277. Object.defineProperties(Material.prototype, {
  30278. wrapAround: {
  30279. get: function () {
  30280. console.warn('THREE.Material: .wrapAround has been removed.');
  30281. },
  30282. set: function () {
  30283. console.warn('THREE.Material: .wrapAround has been removed.');
  30284. }
  30285. },
  30286. overdraw: {
  30287. get: function () {
  30288. console.warn('THREE.Material: .overdraw has been removed.');
  30289. },
  30290. set: function () {
  30291. console.warn('THREE.Material: .overdraw has been removed.');
  30292. }
  30293. },
  30294. wrapRGB: {
  30295. get: function () {
  30296. console.warn('THREE.Material: .wrapRGB has been removed.');
  30297. return new Color();
  30298. }
  30299. },
  30300. shading: {
  30301. get: function () {
  30302. console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  30303. },
  30304. set: function (value) {
  30305. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  30306. this.flatShading = value === FlatShading;
  30307. }
  30308. },
  30309. stencilMask: {
  30310. get: function () {
  30311. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  30312. return this.stencilFuncMask;
  30313. },
  30314. set: function (value) {
  30315. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  30316. this.stencilFuncMask = value;
  30317. }
  30318. }
  30319. });
  30320. Object.defineProperties(MeshPhongMaterial.prototype, {
  30321. metal: {
  30322. get: function () {
  30323. console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.');
  30324. return false;
  30325. },
  30326. set: function () {
  30327. console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead');
  30328. }
  30329. }
  30330. });
  30331. Object.defineProperties(MeshPhysicalMaterial.prototype, {
  30332. transparency: {
  30333. get: function () {
  30334. console.warn('THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.');
  30335. return this.transmission;
  30336. },
  30337. set: function (value) {
  30338. console.warn('THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.');
  30339. this.transmission = value;
  30340. }
  30341. }
  30342. });
  30343. Object.defineProperties(ShaderMaterial.prototype, {
  30344. derivatives: {
  30345. get: function () {
  30346. console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  30347. return this.extensions.derivatives;
  30348. },
  30349. set: function (value) {
  30350. console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  30351. this.extensions.derivatives = value;
  30352. }
  30353. }
  30354. }); //
  30355. Object.assign(WebGLRenderer.prototype, {
  30356. clearTarget: function (renderTarget, color, depth, stencil) {
  30357. console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
  30358. this.setRenderTarget(renderTarget);
  30359. this.clear(color, depth, stencil);
  30360. },
  30361. animate: function (callback) {
  30362. console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
  30363. this.setAnimationLoop(callback);
  30364. },
  30365. getCurrentRenderTarget: function () {
  30366. console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
  30367. return this.getRenderTarget();
  30368. },
  30369. getMaxAnisotropy: function () {
  30370. console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
  30371. return this.capabilities.getMaxAnisotropy();
  30372. },
  30373. getPrecision: function () {
  30374. console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
  30375. return this.capabilities.precision;
  30376. },
  30377. resetGLState: function () {
  30378. console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
  30379. return this.state.reset();
  30380. },
  30381. supportsFloatTextures: function () {
  30382. console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
  30383. return this.extensions.get('OES_texture_float');
  30384. },
  30385. supportsHalfFloatTextures: function () {
  30386. console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
  30387. return this.extensions.get('OES_texture_half_float');
  30388. },
  30389. supportsStandardDerivatives: function () {
  30390. console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
  30391. return this.extensions.get('OES_standard_derivatives');
  30392. },
  30393. supportsCompressedTextureS3TC: function () {
  30394. console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
  30395. return this.extensions.get('WEBGL_compressed_texture_s3tc');
  30396. },
  30397. supportsCompressedTexturePVRTC: function () {
  30398. console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
  30399. return this.extensions.get('WEBGL_compressed_texture_pvrtc');
  30400. },
  30401. supportsBlendMinMax: function () {
  30402. console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
  30403. return this.extensions.get('EXT_blend_minmax');
  30404. },
  30405. supportsVertexTextures: function () {
  30406. console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
  30407. return this.capabilities.vertexTextures;
  30408. },
  30409. supportsInstancedArrays: function () {
  30410. console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
  30411. return this.extensions.get('ANGLE_instanced_arrays');
  30412. },
  30413. enableScissorTest: function (boolean) {
  30414. console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
  30415. this.setScissorTest(boolean);
  30416. },
  30417. initMaterial: function () {
  30418. console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
  30419. },
  30420. addPrePlugin: function () {
  30421. console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
  30422. },
  30423. addPostPlugin: function () {
  30424. console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
  30425. },
  30426. updateShadowMap: function () {
  30427. console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
  30428. },
  30429. setFaceCulling: function () {
  30430. console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
  30431. },
  30432. allocTextureUnit: function () {
  30433. console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
  30434. },
  30435. setTexture: function () {
  30436. console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
  30437. },
  30438. setTexture2D: function () {
  30439. console.warn('THREE.WebGLRenderer: .setTexture2D() has been removed.');
  30440. },
  30441. setTextureCube: function () {
  30442. console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
  30443. },
  30444. getActiveMipMapLevel: function () {
  30445. console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
  30446. return this.getActiveMipmapLevel();
  30447. }
  30448. });
  30449. Object.defineProperties(WebGLRenderer.prototype, {
  30450. shadowMapEnabled: {
  30451. get: function () {
  30452. return this.shadowMap.enabled;
  30453. },
  30454. set: function (value) {
  30455. console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
  30456. this.shadowMap.enabled = value;
  30457. }
  30458. },
  30459. shadowMapType: {
  30460. get: function () {
  30461. return this.shadowMap.type;
  30462. },
  30463. set: function (value) {
  30464. console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
  30465. this.shadowMap.type = value;
  30466. }
  30467. },
  30468. shadowMapCullFace: {
  30469. get: function () {
  30470. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  30471. return undefined;
  30472. },
  30473. set: function ()
  30474. /* value */
  30475. {
  30476. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  30477. }
  30478. },
  30479. context: {
  30480. get: function () {
  30481. console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
  30482. return this.getContext();
  30483. }
  30484. },
  30485. vr: {
  30486. get: function () {
  30487. console.warn('THREE.WebGLRenderer: .vr has been renamed to .xr');
  30488. return this.xr;
  30489. }
  30490. },
  30491. gammaInput: {
  30492. get: function () {
  30493. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  30494. return false;
  30495. },
  30496. set: function () {
  30497. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  30498. }
  30499. },
  30500. gammaOutput: {
  30501. get: function () {
  30502. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  30503. return false;
  30504. },
  30505. set: function (value) {
  30506. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  30507. this.outputEncoding = value === true ? sRGBEncoding : LinearEncoding;
  30508. }
  30509. },
  30510. toneMappingWhitePoint: {
  30511. get: function () {
  30512. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  30513. return 1.0;
  30514. },
  30515. set: function () {
  30516. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  30517. }
  30518. }
  30519. });
  30520. Object.defineProperties(WebGLShadowMap.prototype, {
  30521. cullFace: {
  30522. get: function () {
  30523. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  30524. return undefined;
  30525. },
  30526. set: function ()
  30527. /* cullFace */
  30528. {
  30529. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  30530. }
  30531. },
  30532. renderReverseSided: {
  30533. get: function () {
  30534. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  30535. return undefined;
  30536. },
  30537. set: function () {
  30538. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  30539. }
  30540. },
  30541. renderSingleSided: {
  30542. get: function () {
  30543. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  30544. return undefined;
  30545. },
  30546. set: function () {
  30547. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  30548. }
  30549. }
  30550. });
  30551. function WebGLRenderTargetCube(width, height, options) {
  30552. console.warn('THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).');
  30553. return new WebGLCubeRenderTarget(width, options);
  30554. } //
  30555. Object.defineProperties(WebGLRenderTarget.prototype, {
  30556. wrapS: {
  30557. get: function () {
  30558. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  30559. return this.texture.wrapS;
  30560. },
  30561. set: function (value) {
  30562. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  30563. this.texture.wrapS = value;
  30564. }
  30565. },
  30566. wrapT: {
  30567. get: function () {
  30568. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  30569. return this.texture.wrapT;
  30570. },
  30571. set: function (value) {
  30572. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  30573. this.texture.wrapT = value;
  30574. }
  30575. },
  30576. magFilter: {
  30577. get: function () {
  30578. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  30579. return this.texture.magFilter;
  30580. },
  30581. set: function (value) {
  30582. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  30583. this.texture.magFilter = value;
  30584. }
  30585. },
  30586. minFilter: {
  30587. get: function () {
  30588. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  30589. return this.texture.minFilter;
  30590. },
  30591. set: function (value) {
  30592. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  30593. this.texture.minFilter = value;
  30594. }
  30595. },
  30596. anisotropy: {
  30597. get: function () {
  30598. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  30599. return this.texture.anisotropy;
  30600. },
  30601. set: function (value) {
  30602. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  30603. this.texture.anisotropy = value;
  30604. }
  30605. },
  30606. offset: {
  30607. get: function () {
  30608. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  30609. return this.texture.offset;
  30610. },
  30611. set: function (value) {
  30612. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  30613. this.texture.offset = value;
  30614. }
  30615. },
  30616. repeat: {
  30617. get: function () {
  30618. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  30619. return this.texture.repeat;
  30620. },
  30621. set: function (value) {
  30622. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  30623. this.texture.repeat = value;
  30624. }
  30625. },
  30626. format: {
  30627. get: function () {
  30628. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  30629. return this.texture.format;
  30630. },
  30631. set: function (value) {
  30632. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  30633. this.texture.format = value;
  30634. }
  30635. },
  30636. type: {
  30637. get: function () {
  30638. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  30639. return this.texture.type;
  30640. },
  30641. set: function (value) {
  30642. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  30643. this.texture.type = value;
  30644. }
  30645. },
  30646. generateMipmaps: {
  30647. get: function () {
  30648. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  30649. return this.texture.generateMipmaps;
  30650. },
  30651. set: function (value) {
  30652. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  30653. this.texture.generateMipmaps = value;
  30654. }
  30655. }
  30656. }); //
  30657. Object.defineProperties(Audio.prototype, {
  30658. load: {
  30659. value: function (file) {
  30660. console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
  30661. const scope = this;
  30662. const audioLoader = new AudioLoader();
  30663. audioLoader.load(file, function (buffer) {
  30664. scope.setBuffer(buffer);
  30665. });
  30666. return this;
  30667. }
  30668. },
  30669. startTime: {
  30670. set: function () {
  30671. console.warn('THREE.Audio: .startTime is now .play( delay ).');
  30672. }
  30673. }
  30674. });
  30675. AudioAnalyser.prototype.getData = function () {
  30676. console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
  30677. return this.getFrequencyData();
  30678. }; //
  30679. CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
  30680. console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
  30681. return this.update(renderer, scene);
  30682. };
  30683. CubeCamera.prototype.clear = function (renderer, color, depth, stencil) {
  30684. console.warn('THREE.CubeCamera: .clear() is now .renderTarget.clear().');
  30685. return this.renderTarget.clear(renderer, color, depth, stencil);
  30686. }; //
  30687. const GeometryUtils = {
  30688. merge: function (geometry1, geometry2, materialIndexOffset) {
  30689. console.warn('THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.');
  30690. let matrix;
  30691. if (geometry2.isMesh) {
  30692. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  30693. matrix = geometry2.matrix;
  30694. geometry2 = geometry2.geometry;
  30695. }
  30696. geometry1.merge(geometry2, matrix, materialIndexOffset);
  30697. },
  30698. center: function (geometry) {
  30699. console.warn('THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.');
  30700. return geometry.center();
  30701. }
  30702. };
  30703. exports.GeometryUtils = GeometryUtils;
  30704. ImageUtils.crossOrigin = undefined;
  30705. ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
  30706. console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
  30707. const loader = new TextureLoader();
  30708. loader.setCrossOrigin(this.crossOrigin);
  30709. const texture = loader.load(url, onLoad, undefined, onError);
  30710. if (mapping) texture.mapping = mapping;
  30711. return texture;
  30712. };
  30713. ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
  30714. console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
  30715. const loader = new CubeTextureLoader();
  30716. loader.setCrossOrigin(this.crossOrigin);
  30717. const texture = loader.load(urls, onLoad, undefined, onError);
  30718. if (mapping) texture.mapping = mapping;
  30719. return texture;
  30720. };
  30721. ImageUtils.loadCompressedTexture = function () {
  30722. console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
  30723. };
  30724. ImageUtils.loadCompressedTextureCube = function () {
  30725. console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
  30726. }; //
  30727. function CanvasRenderer() {
  30728. console.error('THREE.CanvasRenderer has been removed');
  30729. } //
  30730. function JSONLoader() {
  30731. console.error('THREE.JSONLoader has been removed.');
  30732. } //
  30733. const SceneUtils = {
  30734. createMultiMaterialObject: function ()
  30735. /* geometry, materials */
  30736. {
  30737. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  30738. },
  30739. detach: function ()
  30740. /* child, parent, scene */
  30741. {
  30742. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  30743. },
  30744. attach: function ()
  30745. /* child, scene, parent */
  30746. {
  30747. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  30748. }
  30749. }; //
  30750. exports.SceneUtils = SceneUtils;
  30751. function LensFlare() {
  30752. console.error('THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js');
  30753. }
  30754. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  30755. /* eslint-disable no-undef */
  30756. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  30757. detail: {
  30758. revision: REVISION
  30759. }
  30760. }));
  30761. /* eslint-enable no-undef */
  30762. }
  30763. },{}],"../node_modules/process/browser.js":[function(require,module,exports) {
  30764. // shim for using process in browser
  30765. var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it
  30766. // don't break things. But we need to wrap it in a try catch in case it is
  30767. // wrapped in strict mode code which doesn't define any globals. It's inside a
  30768. // function because try/catches deoptimize in certain engines.
  30769. var cachedSetTimeout;
  30770. var cachedClearTimeout;
  30771. function defaultSetTimout() {
  30772. throw new Error('setTimeout has not been defined');
  30773. }
  30774. function defaultClearTimeout() {
  30775. throw new Error('clearTimeout has not been defined');
  30776. }
  30777. (function () {
  30778. try {
  30779. if (typeof setTimeout === 'function') {
  30780. cachedSetTimeout = setTimeout;
  30781. } else {
  30782. cachedSetTimeout = defaultSetTimout;
  30783. }
  30784. } catch (e) {
  30785. cachedSetTimeout = defaultSetTimout;
  30786. }
  30787. try {
  30788. if (typeof clearTimeout === 'function') {
  30789. cachedClearTimeout = clearTimeout;
  30790. } else {
  30791. cachedClearTimeout = defaultClearTimeout;
  30792. }
  30793. } catch (e) {
  30794. cachedClearTimeout = defaultClearTimeout;
  30795. }
  30796. })();
  30797. function runTimeout(fun) {
  30798. if (cachedSetTimeout === setTimeout) {
  30799. //normal enviroments in sane situations
  30800. return setTimeout(fun, 0);
  30801. } // if setTimeout wasn't available but was latter defined
  30802. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  30803. cachedSetTimeout = setTimeout;
  30804. return setTimeout(fun, 0);
  30805. }
  30806. try {
  30807. // when when somebody has screwed with setTimeout but no I.E. maddness
  30808. return cachedSetTimeout(fun, 0);
  30809. } catch (e) {
  30810. try {
  30811. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  30812. return cachedSetTimeout.call(null, fun, 0);
  30813. } catch (e) {
  30814. // 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
  30815. return cachedSetTimeout.call(this, fun, 0);
  30816. }
  30817. }
  30818. }
  30819. function runClearTimeout(marker) {
  30820. if (cachedClearTimeout === clearTimeout) {
  30821. //normal enviroments in sane situations
  30822. return clearTimeout(marker);
  30823. } // if clearTimeout wasn't available but was latter defined
  30824. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  30825. cachedClearTimeout = clearTimeout;
  30826. return clearTimeout(marker);
  30827. }
  30828. try {
  30829. // when when somebody has screwed with setTimeout but no I.E. maddness
  30830. return cachedClearTimeout(marker);
  30831. } catch (e) {
  30832. try {
  30833. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  30834. return cachedClearTimeout.call(null, marker);
  30835. } catch (e) {
  30836. // 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.
  30837. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  30838. return cachedClearTimeout.call(this, marker);
  30839. }
  30840. }
  30841. }
  30842. var queue = [];
  30843. var draining = false;
  30844. var currentQueue;
  30845. var queueIndex = -1;
  30846. function cleanUpNextTick() {
  30847. if (!draining || !currentQueue) {
  30848. return;
  30849. }
  30850. draining = false;
  30851. if (currentQueue.length) {
  30852. queue = currentQueue.concat(queue);
  30853. } else {
  30854. queueIndex = -1;
  30855. }
  30856. if (queue.length) {
  30857. drainQueue();
  30858. }
  30859. }
  30860. function drainQueue() {
  30861. if (draining) {
  30862. return;
  30863. }
  30864. var timeout = runTimeout(cleanUpNextTick);
  30865. draining = true;
  30866. var len = queue.length;
  30867. while (len) {
  30868. currentQueue = queue;
  30869. queue = [];
  30870. while (++queueIndex < len) {
  30871. if (currentQueue) {
  30872. currentQueue[queueIndex].run();
  30873. }
  30874. }
  30875. queueIndex = -1;
  30876. len = queue.length;
  30877. }
  30878. currentQueue = null;
  30879. draining = false;
  30880. runClearTimeout(timeout);
  30881. }
  30882. process.nextTick = function (fun) {
  30883. var args = new Array(arguments.length - 1);
  30884. if (arguments.length > 1) {
  30885. for (var i = 1; i < arguments.length; i++) {
  30886. args[i - 1] = arguments[i];
  30887. }
  30888. }
  30889. queue.push(new Item(fun, args));
  30890. if (queue.length === 1 && !draining) {
  30891. runTimeout(drainQueue);
  30892. }
  30893. }; // v8 likes predictible objects
  30894. function Item(fun, array) {
  30895. this.fun = fun;
  30896. this.array = array;
  30897. }
  30898. Item.prototype.run = function () {
  30899. this.fun.apply(null, this.array);
  30900. };
  30901. process.title = 'browser';
  30902. process.env = {};
  30903. process.argv = [];
  30904. process.version = ''; // empty string to avoid regexp issues
  30905. process.versions = {};
  30906. function noop() {}
  30907. process.on = noop;
  30908. process.addListener = noop;
  30909. process.once = noop;
  30910. process.off = noop;
  30911. process.removeListener = noop;
  30912. process.removeAllListeners = noop;
  30913. process.emit = noop;
  30914. process.prependListener = noop;
  30915. process.prependOnceListener = noop;
  30916. process.listeners = function (name) {
  30917. return [];
  30918. };
  30919. process.binding = function (name) {
  30920. throw new Error('process.binding is not supported');
  30921. };
  30922. process.cwd = function () {
  30923. return '/';
  30924. };
  30925. process.chdir = function (dir) {
  30926. throw new Error('process.chdir is not supported');
  30927. };
  30928. process.umask = function () {
  30929. return 0;
  30930. };
  30931. },{}],"../node_modules/path-browserify/index.js":[function(require,module,exports) {
  30932. var process = require("process");
  30933. // .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1,
  30934. // backported and transplited with Babel, with backwards-compat fixes
  30935. // Copyright Joyent, Inc. and other Node contributors.
  30936. //
  30937. // Permission is hereby granted, free of charge, to any person obtaining a
  30938. // copy of this software and associated documentation files (the
  30939. // "Software"), to deal in the Software without restriction, including
  30940. // without limitation the rights to use, copy, modify, merge, publish,
  30941. // distribute, sublicense, and/or sell copies of the Software, and to permit
  30942. // persons to whom the Software is furnished to do so, subject to the
  30943. // following conditions:
  30944. //
  30945. // The above copyright notice and this permission notice shall be included
  30946. // in all copies or substantial portions of the Software.
  30947. //
  30948. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  30949. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  30950. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  30951. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  30952. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  30953. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  30954. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  30955. // resolves . and .. elements in a path array with directory names there
  30956. // must be no slashes, empty elements, or device names (c:\) in the array
  30957. // (so also no leading and trailing slashes - it does not distinguish
  30958. // relative and absolute paths)
  30959. function normalizeArray(parts, allowAboveRoot) {
  30960. // if the path tries to go above the root, `up` ends up > 0
  30961. var up = 0;
  30962. for (var i = parts.length - 1; i >= 0; i--) {
  30963. var last = parts[i];
  30964. if (last === '.') {
  30965. parts.splice(i, 1);
  30966. } else if (last === '..') {
  30967. parts.splice(i, 1);
  30968. up++;
  30969. } else if (up) {
  30970. parts.splice(i, 1);
  30971. up--;
  30972. }
  30973. }
  30974. // if the path is allowed to go above the root, restore leading ..s
  30975. if (allowAboveRoot) {
  30976. for (; up--; up) {
  30977. parts.unshift('..');
  30978. }
  30979. }
  30980. return parts;
  30981. }
  30982. // path.resolve([from ...], to)
  30983. // posix version
  30984. exports.resolve = function() {
  30985. var resolvedPath = '',
  30986. resolvedAbsolute = false;
  30987. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  30988. var path = (i >= 0) ? arguments[i] : process.cwd();
  30989. // Skip empty and invalid entries
  30990. if (typeof path !== 'string') {
  30991. throw new TypeError('Arguments to path.resolve must be strings');
  30992. } else if (!path) {
  30993. continue;
  30994. }
  30995. resolvedPath = path + '/' + resolvedPath;
  30996. resolvedAbsolute = path.charAt(0) === '/';
  30997. }
  30998. // At this point the path should be resolved to a full absolute path, but
  30999. // handle relative paths to be safe (might happen when process.cwd() fails)
  31000. // Normalize the path
  31001. resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
  31002. return !!p;
  31003. }), !resolvedAbsolute).join('/');
  31004. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  31005. };
  31006. // path.normalize(path)
  31007. // posix version
  31008. exports.normalize = function(path) {
  31009. var isAbsolute = exports.isAbsolute(path),
  31010. trailingSlash = substr(path, -1) === '/';
  31011. // Normalize the path
  31012. path = normalizeArray(filter(path.split('/'), function(p) {
  31013. return !!p;
  31014. }), !isAbsolute).join('/');
  31015. if (!path && !isAbsolute) {
  31016. path = '.';
  31017. }
  31018. if (path && trailingSlash) {
  31019. path += '/';
  31020. }
  31021. return (isAbsolute ? '/' : '') + path;
  31022. };
  31023. // posix version
  31024. exports.isAbsolute = function(path) {
  31025. return path.charAt(0) === '/';
  31026. };
  31027. // posix version
  31028. exports.join = function() {
  31029. var paths = Array.prototype.slice.call(arguments, 0);
  31030. return exports.normalize(filter(paths, function(p, index) {
  31031. if (typeof p !== 'string') {
  31032. throw new TypeError('Arguments to path.join must be strings');
  31033. }
  31034. return p;
  31035. }).join('/'));
  31036. };
  31037. // path.relative(from, to)
  31038. // posix version
  31039. exports.relative = function(from, to) {
  31040. from = exports.resolve(from).substr(1);
  31041. to = exports.resolve(to).substr(1);
  31042. function trim(arr) {
  31043. var start = 0;
  31044. for (; start < arr.length; start++) {
  31045. if (arr[start] !== '') break;
  31046. }
  31047. var end = arr.length - 1;
  31048. for (; end >= 0; end--) {
  31049. if (arr[end] !== '') break;
  31050. }
  31051. if (start > end) return [];
  31052. return arr.slice(start, end - start + 1);
  31053. }
  31054. var fromParts = trim(from.split('/'));
  31055. var toParts = trim(to.split('/'));
  31056. var length = Math.min(fromParts.length, toParts.length);
  31057. var samePartsLength = length;
  31058. for (var i = 0; i < length; i++) {
  31059. if (fromParts[i] !== toParts[i]) {
  31060. samePartsLength = i;
  31061. break;
  31062. }
  31063. }
  31064. var outputParts = [];
  31065. for (var i = samePartsLength; i < fromParts.length; i++) {
  31066. outputParts.push('..');
  31067. }
  31068. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  31069. return outputParts.join('/');
  31070. };
  31071. exports.sep = '/';
  31072. exports.delimiter = ':';
  31073. exports.dirname = function (path) {
  31074. if (typeof path !== 'string') path = path + '';
  31075. if (path.length === 0) return '.';
  31076. var code = path.charCodeAt(0);
  31077. var hasRoot = code === 47 /*/*/;
  31078. var end = -1;
  31079. var matchedSlash = true;
  31080. for (var i = path.length - 1; i >= 1; --i) {
  31081. code = path.charCodeAt(i);
  31082. if (code === 47 /*/*/) {
  31083. if (!matchedSlash) {
  31084. end = i;
  31085. break;
  31086. }
  31087. } else {
  31088. // We saw the first non-path separator
  31089. matchedSlash = false;
  31090. }
  31091. }
  31092. if (end === -1) return hasRoot ? '/' : '.';
  31093. if (hasRoot && end === 1) {
  31094. // return '//';
  31095. // Backwards-compat fix:
  31096. return '/';
  31097. }
  31098. return path.slice(0, end);
  31099. };
  31100. function basename(path) {
  31101. if (typeof path !== 'string') path = path + '';
  31102. var start = 0;
  31103. var end = -1;
  31104. var matchedSlash = true;
  31105. var i;
  31106. for (i = path.length - 1; i >= 0; --i) {
  31107. if (path.charCodeAt(i) === 47 /*/*/) {
  31108. // If we reached a path separator that was not part of a set of path
  31109. // separators at the end of the string, stop now
  31110. if (!matchedSlash) {
  31111. start = i + 1;
  31112. break;
  31113. }
  31114. } else if (end === -1) {
  31115. // We saw the first non-path separator, mark this as the end of our
  31116. // path component
  31117. matchedSlash = false;
  31118. end = i + 1;
  31119. }
  31120. }
  31121. if (end === -1) return '';
  31122. return path.slice(start, end);
  31123. }
  31124. // Uses a mixed approach for backwards-compatibility, as ext behavior changed
  31125. // in new Node.js versions, so only basename() above is backported here
  31126. exports.basename = function (path, ext) {
  31127. var f = basename(path);
  31128. if (ext && f.substr(-1 * ext.length) === ext) {
  31129. f = f.substr(0, f.length - ext.length);
  31130. }
  31131. return f;
  31132. };
  31133. exports.extname = function (path) {
  31134. if (typeof path !== 'string') path = path + '';
  31135. var startDot = -1;
  31136. var startPart = 0;
  31137. var end = -1;
  31138. var matchedSlash = true;
  31139. // Track the state of characters (if any) we see before our first dot and
  31140. // after any path separator we find
  31141. var preDotState = 0;
  31142. for (var i = path.length - 1; i >= 0; --i) {
  31143. var code = path.charCodeAt(i);
  31144. if (code === 47 /*/*/) {
  31145. // If we reached a path separator that was not part of a set of path
  31146. // separators at the end of the string, stop now
  31147. if (!matchedSlash) {
  31148. startPart = i + 1;
  31149. break;
  31150. }
  31151. continue;
  31152. }
  31153. if (end === -1) {
  31154. // We saw the first non-path separator, mark this as the end of our
  31155. // extension
  31156. matchedSlash = false;
  31157. end = i + 1;
  31158. }
  31159. if (code === 46 /*.*/) {
  31160. // If this is our first dot, mark it as the start of our extension
  31161. if (startDot === -1)
  31162. startDot = i;
  31163. else if (preDotState !== 1)
  31164. preDotState = 1;
  31165. } else if (startDot !== -1) {
  31166. // We saw a non-dot and non-path separator before our dot, so we should
  31167. // have a good chance at having a non-empty extension
  31168. preDotState = -1;
  31169. }
  31170. }
  31171. if (startDot === -1 || end === -1 ||
  31172. // We saw a non-dot character immediately before the dot
  31173. preDotState === 0 ||
  31174. // The (right-most) trimmed path component is exactly '..'
  31175. preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
  31176. return '';
  31177. }
  31178. return path.slice(startDot, end);
  31179. };
  31180. function filter (xs, f) {
  31181. if (xs.filter) return xs.filter(f);
  31182. var res = [];
  31183. for (var i = 0; i < xs.length; i++) {
  31184. if (f(xs[i], i, xs)) res.push(xs[i]);
  31185. }
  31186. return res;
  31187. }
  31188. // String.prototype.substr - negative index don't work in IE8
  31189. var substr = 'ab'.substr(-1) === 'b'
  31190. ? function (str, start, len) { return str.substr(start, len) }
  31191. : function (str, start, len) {
  31192. if (start < 0) start = str.length + start;
  31193. return str.substr(start, len);
  31194. }
  31195. ;
  31196. },{"process":"../node_modules/process/browser.js"}],"../src/utilities/urlJoin.js":[function(require,module,exports) {
  31197. "use strict";
  31198. Object.defineProperty(exports, "__esModule", {
  31199. value: true
  31200. });
  31201. exports.urlJoin = urlJoin;
  31202. var _path = _interopRequireDefault(require("path"));
  31203. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  31204. function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }
  31205. function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }
  31206. function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }
  31207. function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }
  31208. // Function that properly handles path resolution for parts that have
  31209. // a protocol component like "http://".
  31210. function urlJoin() {
  31211. var protocolRegex = /^[a-zA-Z]+:\/\//;
  31212. var lastRoot = -1;
  31213. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  31214. args[_key] = arguments[_key];
  31215. }
  31216. for (var i = 0, l = args.length; i < l; i++) {
  31217. if (protocolRegex.test(args[i])) {
  31218. lastRoot = i;
  31219. }
  31220. }
  31221. if (lastRoot === -1) {
  31222. return _path.default.join.apply(_path.default, args).replace(/\\/g, '/');
  31223. } else {
  31224. var parts = lastRoot <= 0 ? args : args.slice(lastRoot);
  31225. var protocol = parts[0].match(protocolRegex)[0];
  31226. parts[0] = parts[0].substring(protocol.length);
  31227. return (protocol + _path.default.join.apply(_path.default, _toConsumableArray(parts))).replace(/\\/g, '/');
  31228. }
  31229. }
  31230. },{"path":"../node_modules/path-browserify/index.js"}],"../src/utilities/LRUCache.js":[function(require,module,exports) {
  31231. "use strict";
  31232. Object.defineProperty(exports, "__esModule", {
  31233. value: true
  31234. });
  31235. exports.LRUCache = void 0;
  31236. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  31237. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  31238. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  31239. // Fires at the end of the frame and before the next one
  31240. function enqueueMicrotask(callback) {
  31241. Promise.resolve().then(callback);
  31242. }
  31243. var LRUCache =
  31244. /*#__PURE__*/
  31245. function () {
  31246. function LRUCache() {
  31247. _classCallCheck(this, LRUCache);
  31248. // options
  31249. this.maxSize = 800;
  31250. this.minSize = 600;
  31251. this.unloadPercent = 0.05; // "itemSet" doubles as both the list of the full set of items currently
  31252. // stored in the cache (keys) as well as a map to the time the item was last
  31253. // used so it can be sorted appropriately.
  31254. this.itemSet = new Map();
  31255. this.itemList = [];
  31256. this.usedSet = new Set();
  31257. this.callbacks = new Map();
  31258. this.unloadPriorityCallback = null;
  31259. var itemSet = this.itemSet;
  31260. this.defaultPriorityCallback = function (item) {
  31261. return itemSet.get(item);
  31262. };
  31263. } // Returns whether or not the cache has reached the maximum size
  31264. _createClass(LRUCache, [{
  31265. key: "isFull",
  31266. value: function isFull() {
  31267. return this.itemSet.size >= this.maxSize;
  31268. }
  31269. }, {
  31270. key: "add",
  31271. value: function add(item, removeCb) {
  31272. var itemSet = this.itemSet;
  31273. if (itemSet.has(item)) {
  31274. return false;
  31275. }
  31276. if (this.isFull()) {
  31277. return false;
  31278. }
  31279. var usedSet = this.usedSet;
  31280. var itemList = this.itemList;
  31281. var callbacks = this.callbacks;
  31282. itemList.push(item);
  31283. usedSet.add(item);
  31284. itemSet.set(item, Date.now());
  31285. callbacks.set(item, removeCb);
  31286. return true;
  31287. }
  31288. }, {
  31289. key: "remove",
  31290. value: function remove(item) {
  31291. var usedSet = this.usedSet;
  31292. var itemSet = this.itemSet;
  31293. var itemList = this.itemList;
  31294. var callbacks = this.callbacks;
  31295. if (itemSet.has(item)) {
  31296. callbacks.get(item)(item);
  31297. var index = itemList.indexOf(item);
  31298. itemList.splice(index, 1);
  31299. usedSet.delete(item);
  31300. itemSet.delete(item);
  31301. callbacks.delete(item);
  31302. return true;
  31303. }
  31304. return false;
  31305. }
  31306. }, {
  31307. key: "markUsed",
  31308. value: function markUsed(item) {
  31309. var itemSet = this.itemSet;
  31310. var usedSet = this.usedSet;
  31311. if (itemSet.has(item) && !usedSet.has(item)) {
  31312. itemSet.set(item, Date.now());
  31313. usedSet.add(item);
  31314. }
  31315. }
  31316. }, {
  31317. key: "markAllUnused",
  31318. value: function markAllUnused() {
  31319. this.usedSet.clear();
  31320. } // TODO: this should be renamed because it's not necessarily unloading all unused content
  31321. // Maybe call it "cleanup" or "unloadToMinSize"
  31322. }, {
  31323. key: "unloadUnusedContent",
  31324. value: function unloadUnusedContent() {
  31325. var unloadPercent = this.unloadPercent;
  31326. var targetSize = this.minSize;
  31327. var itemList = this.itemList;
  31328. var itemSet = this.itemSet;
  31329. var usedSet = this.usedSet;
  31330. var callbacks = this.callbacks;
  31331. var unused = itemList.length - usedSet.size;
  31332. var excess = itemList.length - targetSize;
  31333. var unloadPriorityCallback = this.unloadPriorityCallback || this.defaultPriorityCallback;
  31334. if (excess > 0 && unused > 0) {
  31335. // used items should be at the end of the array
  31336. itemList.sort(function (a, b) {
  31337. var usedA = usedSet.has(a);
  31338. var usedB = usedSet.has(b);
  31339. if (usedA && usedB) {
  31340. // If they're both used then don't bother moving them
  31341. return 0;
  31342. } else if (!usedA && !usedB) {
  31343. // Use the sort function otherwise
  31344. // higher priority should be further to the left
  31345. return unloadPriorityCallback(b) - unloadPriorityCallback(a);
  31346. } else {
  31347. // If one is used and the other is not move the used one towards the end of the array
  31348. return usedA ? 1 : -1;
  31349. }
  31350. }); // address corner cases where the minSize might be zero or smaller than maxSize - minSize,
  31351. // which would result in a very small or no items being unloaded.
  31352. var unusedExcess = Math.min(excess, unused);
  31353. var maxUnload = Math.max(targetSize * unloadPercent, unusedExcess * unloadPercent);
  31354. var nodesToUnload = Math.min(maxUnload, unused);
  31355. nodesToUnload = Math.ceil(nodesToUnload);
  31356. var removedItems = itemList.splice(0, nodesToUnload);
  31357. for (var i = 0, l = removedItems.length; i < l; i++) {
  31358. var item = removedItems[i];
  31359. callbacks.get(item)(item);
  31360. itemSet.delete(item);
  31361. callbacks.delete(item);
  31362. }
  31363. }
  31364. }
  31365. }, {
  31366. key: "scheduleUnload",
  31367. value: function scheduleUnload() {
  31368. var _this = this;
  31369. var markAllUnused = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  31370. if (!this.scheduled) {
  31371. this.scheduled = true;
  31372. enqueueMicrotask(function () {
  31373. _this.scheduled = false;
  31374. _this.unloadUnusedContent();
  31375. if (markAllUnused) {
  31376. _this.markAllUnused();
  31377. }
  31378. });
  31379. }
  31380. }
  31381. }]);
  31382. return LRUCache;
  31383. }();
  31384. exports.LRUCache = LRUCache;
  31385. },{}],"../src/utilities/PriorityQueue.js":[function(require,module,exports) {
  31386. "use strict";
  31387. Object.defineProperty(exports, "__esModule", {
  31388. value: true
  31389. });
  31390. exports.PriorityQueue = void 0;
  31391. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  31392. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  31393. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  31394. var PriorityQueue =
  31395. /*#__PURE__*/
  31396. function () {
  31397. function PriorityQueue() {
  31398. _classCallCheck(this, PriorityQueue);
  31399. // options
  31400. this.maxJobs = 6;
  31401. this.items = [];
  31402. this.callbacks = new Map();
  31403. this.currJobs = 0;
  31404. this.scheduled = false;
  31405. this.autoUpdate = true;
  31406. this.priorityCallback = function () {
  31407. throw new Error('PriorityQueue: PriorityCallback function not defined.');
  31408. };
  31409. }
  31410. _createClass(PriorityQueue, [{
  31411. key: "sort",
  31412. value: function sort() {
  31413. var priorityCallback = this.priorityCallback;
  31414. var items = this.items;
  31415. items.sort(function (a, b) {
  31416. return priorityCallback(a) - priorityCallback(b);
  31417. });
  31418. }
  31419. }, {
  31420. key: "add",
  31421. value: function add(item, callback) {
  31422. var _this = this;
  31423. return new Promise(function (resolve, reject) {
  31424. var prCallback = function prCallback() {
  31425. return callback.apply(void 0, arguments).then(resolve).catch(reject);
  31426. };
  31427. var items = _this.items;
  31428. var callbacks = _this.callbacks;
  31429. items.push(item);
  31430. callbacks.set(item, prCallback);
  31431. if (_this.autoUpdate) {
  31432. _this.scheduleJobRun();
  31433. }
  31434. });
  31435. }
  31436. }, {
  31437. key: "remove",
  31438. value: function remove(item) {
  31439. var items = this.items;
  31440. var callbacks = this.callbacks;
  31441. var index = items.indexOf(item);
  31442. if (index !== -1) {
  31443. items.splice(index, 1);
  31444. callbacks.delete(item);
  31445. }
  31446. }
  31447. }, {
  31448. key: "tryRunJobs",
  31449. value: function tryRunJobs() {
  31450. var _this2 = this;
  31451. this.sort();
  31452. var items = this.items;
  31453. var callbacks = this.callbacks;
  31454. var maxJobs = this.maxJobs;
  31455. var currJobs = this.currJobs;
  31456. while (maxJobs > currJobs && items.length > 0) {
  31457. currJobs++;
  31458. var item = items.pop();
  31459. var callback = callbacks.get(item);
  31460. callbacks.delete(item);
  31461. callback(item).then(function () {
  31462. _this2.currJobs--;
  31463. if (_this2.autoUpdate) {
  31464. _this2.scheduleJobRun();
  31465. }
  31466. }).catch(function () {
  31467. _this2.currJobs--;
  31468. if (_this2.autoUpdate) {
  31469. _this2.scheduleJobRun();
  31470. }
  31471. });
  31472. }
  31473. this.currJobs = currJobs;
  31474. }
  31475. }, {
  31476. key: "scheduleJobRun",
  31477. value: function scheduleJobRun() {
  31478. var _this3 = this;
  31479. if (!this.scheduled) {
  31480. requestAnimationFrame(function () {
  31481. _this3.tryRunJobs();
  31482. _this3.scheduled = false;
  31483. });
  31484. this.scheduled = true;
  31485. }
  31486. }
  31487. }]);
  31488. return PriorityQueue;
  31489. }();
  31490. exports.PriorityQueue = PriorityQueue;
  31491. },{}],"../src/base/constants.js":[function(require,module,exports) {
  31492. "use strict";
  31493. Object.defineProperty(exports, "__esModule", {
  31494. value: true
  31495. });
  31496. exports.FAILED = exports.LOADED = exports.PARSING = exports.LOADING = exports.UNLOADED = void 0;
  31497. var UNLOADED = 0;
  31498. exports.UNLOADED = UNLOADED;
  31499. var LOADING = 1;
  31500. exports.LOADING = LOADING;
  31501. var PARSING = 2;
  31502. exports.PARSING = PARSING;
  31503. var LOADED = 3;
  31504. exports.LOADED = LOADED;
  31505. var FAILED = 4;
  31506. exports.FAILED = FAILED;
  31507. },{}],"../src/base/traverseFunctions.js":[function(require,module,exports) {
  31508. "use strict";
  31509. Object.defineProperty(exports, "__esModule", {
  31510. value: true
  31511. });
  31512. exports.traverseSet = traverseSet;
  31513. exports.determineFrustumSet = determineFrustumSet;
  31514. exports.markUsedSetLeaves = markUsedSetLeaves;
  31515. exports.skipTraversal = skipTraversal;
  31516. exports.toggleTiles = toggleTiles;
  31517. var _constants = require("./constants.js");
  31518. function isDownloadFinished(value) {
  31519. return value === _constants.LOADED || value === _constants.FAILED;
  31520. } // Checks whether this tile was last used on the given frame.
  31521. function isUsedThisFrame(tile, frameCount) {
  31522. return tile.__lastFrameVisited === frameCount && tile.__used;
  31523. } // Resets the frame frame information for the given tile
  31524. function resetFrameState(tile, frameCount) {
  31525. if (tile.__lastFrameVisited !== frameCount) {
  31526. tile.__lastFrameVisited = frameCount;
  31527. tile.__used = false;
  31528. tile.__inFrustum = false;
  31529. tile.__isLeaf = false;
  31530. tile.__visible = false;
  31531. tile.__active = false;
  31532. tile.__error = 0;
  31533. tile.__childrenWereVisible = false;
  31534. tile.__allChildrenLoaded = false;
  31535. }
  31536. } // Recursively mark tiles used down to the next tile with content
  31537. function recursivelyMarkUsed(tile, frameCount, lruCache) {
  31538. resetFrameState(tile, frameCount);
  31539. tile.__used = true;
  31540. lruCache.markUsed(tile);
  31541. if (tile.__contentEmpty) {
  31542. var children = tile.children;
  31543. for (var i = 0, l = children.length; i < l; i++) {
  31544. recursivelyMarkUsed(children[i], frameCount, lruCache);
  31545. }
  31546. }
  31547. }
  31548. function recursivelyLoadTiles(tile, depthFromRenderedParent, renderer) {
  31549. // Try to load any external tile set children if the external tile set has loaded.
  31550. var doTraverse = tile.__contentEmpty && (!tile.__externalTileSet || isDownloadFinished(tile.__loadingState));
  31551. if (doTraverse) {
  31552. var children = tile.children;
  31553. for (var i = 0, l = children.length; i < l; i++) {
  31554. // don't increment depth to rendered parent here because we should treat
  31555. // the next layer of rendered children as just a single depth away for the
  31556. // sake of sorting.
  31557. var child = children[i];
  31558. child.__depthFromRenderedParent = depthFromRenderedParent;
  31559. recursivelyLoadTiles(child, depthFromRenderedParent, renderer);
  31560. }
  31561. } else {
  31562. renderer.requestTileContents(tile);
  31563. }
  31564. } // Helper function for recursively traversing a tile set. If `beforeCb` returns `true` then the
  31565. // traversal will end early.
  31566. function traverseSet(tile) {
  31567. var beforeCb = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
  31568. var afterCb = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  31569. var parent = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
  31570. var depth = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;
  31571. if (beforeCb && beforeCb(tile, parent, depth)) {
  31572. if (afterCb) {
  31573. afterCb(tile, parent, depth);
  31574. }
  31575. return;
  31576. }
  31577. var children = tile.children;
  31578. for (var i = 0, l = children.length; i < l; i++) {
  31579. traverseSet(children[i], beforeCb, afterCb, tile, depth + 1);
  31580. }
  31581. if (afterCb) {
  31582. afterCb(tile, parent, depth);
  31583. }
  31584. } // Determine which tiles are within the camera frustum.
  31585. // TODO: this is marking items as used in the lrucache, which means some data is
  31586. // being kept around that isn't being used -- is that okay?
  31587. function determineFrustumSet(tile, renderer) {
  31588. var stats = renderer.stats;
  31589. var frameCount = renderer.frameCount;
  31590. var errorTarget = renderer.errorTarget;
  31591. var maxDepth = renderer.maxDepth;
  31592. var loadSiblings = renderer.loadSiblings;
  31593. var lruCache = renderer.lruCache;
  31594. var stopAtEmptyTiles = renderer.stopAtEmptyTiles;
  31595. resetFrameState(tile, frameCount); // Early out if this tile is not within view.
  31596. var inFrustum = renderer.tileInView(tile);
  31597. if (inFrustum === false) {
  31598. return false;
  31599. }
  31600. tile.__used = true;
  31601. lruCache.markUsed(tile);
  31602. tile.__inFrustum = true;
  31603. stats.inFrustum++; // Early out if this tile has less error than we're targeting but don't stop
  31604. // at an external tile set.
  31605. if ((stopAtEmptyTiles || !tile.__contentEmpty) && !tile.__externalTileSet) {
  31606. var error = renderer.calculateError(tile);
  31607. tile.__error = error;
  31608. if (error <= errorTarget) {
  31609. return true;
  31610. } // Early out if we've reached the maximum allowed depth.
  31611. if (renderer.maxDepth > 0 && tile.__depth + 1 >= maxDepth) {
  31612. return true;
  31613. }
  31614. } // Traverse children and see if any children are in view.
  31615. var anyChildrenUsed = false;
  31616. var children = tile.children;
  31617. for (var i = 0, l = children.length; i < l; i++) {
  31618. var c = children[i];
  31619. var r = determineFrustumSet(c, renderer);
  31620. anyChildrenUsed = anyChildrenUsed || r;
  31621. } // If there are children within view and we are loading siblings then mark
  31622. // all sibling tiles as used, as well.
  31623. if (anyChildrenUsed && loadSiblings) {
  31624. for (var _i = 0, _l = children.length; _i < _l; _i++) {
  31625. var _c = children[_i];
  31626. recursivelyMarkUsed(_c, frameCount, lruCache);
  31627. }
  31628. }
  31629. return true;
  31630. } // Traverse and mark the tiles that are at the leaf nodes of the "used" tree.
  31631. function markUsedSetLeaves(tile, renderer) {
  31632. var stats = renderer.stats;
  31633. var frameCount = renderer.frameCount;
  31634. if (!isUsedThisFrame(tile, frameCount)) {
  31635. return;
  31636. }
  31637. stats.used++; // This tile is a leaf if none of the children had been used.
  31638. var children = tile.children;
  31639. var anyChildrenUsed = false;
  31640. for (var i = 0, l = children.length; i < l; i++) {
  31641. var c = children[i];
  31642. anyChildrenUsed = anyChildrenUsed || isUsedThisFrame(c, frameCount);
  31643. }
  31644. if (!anyChildrenUsed) {
  31645. // TODO: This isn't necessarily right because it's possible that a parent tile is considered in the
  31646. // frustum while the child tiles are not, making them unused. If all children have loaded and were properly
  31647. // considered to be in the used set then we shouldn't set ourselves to a leaf here.
  31648. tile.__isLeaf = true;
  31649. } else {
  31650. var childrenWereVisible = false;
  31651. var allChildrenLoaded = true;
  31652. for (var _i2 = 0, _l2 = children.length; _i2 < _l2; _i2++) {
  31653. var _c2 = children[_i2];
  31654. markUsedSetLeaves(_c2, renderer);
  31655. childrenWereVisible = childrenWereVisible || _c2.__wasSetVisible || _c2.__childrenWereVisible;
  31656. if (isUsedThisFrame(_c2, frameCount)) {
  31657. var childLoaded = _c2.__allChildrenLoaded || !_c2.__contentEmpty && isDownloadFinished(_c2.__loadingState) || _c2.__externalTileSet && _c2.__loadingState === _constants.FAILED;
  31658. allChildrenLoaded = allChildrenLoaded && childLoaded;
  31659. }
  31660. }
  31661. tile.__childrenWereVisible = childrenWereVisible;
  31662. tile.__allChildrenLoaded = allChildrenLoaded;
  31663. }
  31664. } // Skip past tiles we consider unrenderable because they are outside the error threshold.
  31665. function skipTraversal(tile, renderer) {
  31666. var stats = renderer.stats;
  31667. var frameCount = renderer.frameCount;
  31668. if (!isUsedThisFrame(tile, frameCount)) {
  31669. return;
  31670. }
  31671. var parent = tile.parent;
  31672. var parentDepthToParent = parent ? parent.__depthFromRenderedParent : -1;
  31673. tile.__depthFromRenderedParent = parentDepthToParent; // Request the tile contents or mark it as visible if we've found a leaf.
  31674. var lruCache = renderer.lruCache;
  31675. if (tile.__isLeaf) {
  31676. tile.__depthFromRenderedParent++;
  31677. if (tile.__loadingState === _constants.LOADED) {
  31678. if (tile.__inFrustum) {
  31679. tile.__visible = true;
  31680. stats.visible++;
  31681. }
  31682. tile.__active = true;
  31683. stats.active++;
  31684. } else if (!lruCache.isFull() && (!tile.__contentEmpty || tile.__externalTileSet)) {
  31685. renderer.requestTileContents(tile);
  31686. }
  31687. return;
  31688. }
  31689. var errorRequirement = (renderer.errorTarget + 1) * renderer.errorThreshold;
  31690. var meetsSSE = tile.__error <= errorRequirement;
  31691. var includeTile = meetsSSE || tile.refine === 'ADD';
  31692. var hasModel = !tile.__contentEmpty;
  31693. var hasContent = hasModel || tile.__externalTileSet;
  31694. var loadedContent = isDownloadFinished(tile.__loadingState) && hasContent;
  31695. var childrenWereVisible = tile.__childrenWereVisible;
  31696. var children = tile.children;
  31697. var allChildrenHaveContent = tile.__allChildrenLoaded; // Increment the relative depth of the node to the nearest rendered parent if it has content
  31698. // and is being rendered.
  31699. if (includeTile && hasModel) {
  31700. tile.__depthFromRenderedParent++;
  31701. } // If we've met the SSE requirements and we can load content then fire a fetch.
  31702. if (includeTile && !loadedContent && !lruCache.isFull() && hasContent) {
  31703. renderer.requestTileContents(tile);
  31704. } // Only mark this tile as visible if it meets the screen space error requirements, has loaded content, not
  31705. // all children have loaded yet, and if no children were visible last frame. We want to keep children visible
  31706. // that _were_ visible to avoid a pop in level of detail as the camera moves around and parent / sibling tiles
  31707. // load in.
  31708. // Skip the tile entirely if there's no content to load
  31709. if (meetsSSE && !allChildrenHaveContent && !childrenWereVisible && loadedContent || tile.refine === 'ADD' && loadedContent) {
  31710. if (tile.__inFrustum) {
  31711. tile.__visible = true;
  31712. stats.visible++;
  31713. }
  31714. tile.__active = true;
  31715. stats.active++;
  31716. } // If we're additive then don't stop the traversal here because it doesn't matter whether the children load in
  31717. // at the same rate.
  31718. if (tile.refine !== 'ADD' && meetsSSE && !allChildrenHaveContent && loadedContent) {
  31719. // load the child content if we've found that we've been loaded so we can move down to the next tile
  31720. // layer when the data has loaded.
  31721. for (var i = 0, l = children.length; i < l; i++) {
  31722. var c = children[i];
  31723. if (isUsedThisFrame(c, frameCount) && !lruCache.isFull()) {
  31724. c.__depthFromRenderedParent = tile.__depthFromRenderedParent + 1;
  31725. recursivelyLoadTiles(c, c.__depthFromRenderedParent, renderer);
  31726. }
  31727. }
  31728. } else {
  31729. for (var _i3 = 0, _l3 = children.length; _i3 < _l3; _i3++) {
  31730. var _c3 = children[_i3];
  31731. if (isUsedThisFrame(_c3, frameCount)) {
  31732. skipTraversal(_c3, renderer);
  31733. }
  31734. }
  31735. }
  31736. } // Final traverse to toggle tile visibility.
  31737. function toggleTiles(tile, renderer) {
  31738. var frameCount = renderer.frameCount;
  31739. var isUsed = isUsedThisFrame(tile, frameCount);
  31740. if (isUsed || tile.__usedLastFrame) {
  31741. var setActive = false;
  31742. var setVisible = false;
  31743. if (isUsed) {
  31744. // enable visibility if active due to shadows
  31745. setActive = tile.__active;
  31746. if (renderer.displayActiveTiles) {
  31747. setVisible = tile.__active || tile.__visible;
  31748. } else {
  31749. setVisible = tile.__visible;
  31750. }
  31751. } // If the active or visible state changed then call the functions.
  31752. if (!tile.__contentEmpty && tile.__loadingState === _constants.LOADED) {
  31753. if (tile.__wasSetActive !== setActive) {
  31754. renderer.setTileActive(tile, setActive);
  31755. }
  31756. if (tile.__wasSetVisible !== setVisible) {
  31757. renderer.setTileVisible(tile, setVisible);
  31758. }
  31759. }
  31760. tile.__wasSetActive = setActive;
  31761. tile.__wasSetVisible = setVisible;
  31762. tile.__usedLastFrame = isUsed;
  31763. var children = tile.children;
  31764. for (var i = 0, l = children.length; i < l; i++) {
  31765. var c = children[i];
  31766. toggleTiles(c, renderer);
  31767. }
  31768. }
  31769. }
  31770. },{"./constants.js":"../src/base/constants.js"}],"../src/base/TilesRendererBase.js":[function(require,module,exports) {
  31771. "use strict";
  31772. Object.defineProperty(exports, "__esModule", {
  31773. value: true
  31774. });
  31775. exports.TilesRendererBase = void 0;
  31776. var _path = _interopRequireDefault(require("path"));
  31777. var _urlJoin = require("../utilities/urlJoin.js");
  31778. var _LRUCache = require("../utilities/LRUCache.js");
  31779. var _PriorityQueue = require("../utilities/PriorityQueue.js");
  31780. var _traverseFunctions = require("./traverseFunctions.js");
  31781. var _constants = require("./constants.js");
  31782. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  31783. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  31784. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  31785. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  31786. // Function for sorting the evicted LRU items. We should evict the shallowest depth first.
  31787. var priorityCallback = function priorityCallback(tile) {
  31788. return 1 / (tile.__depthFromRenderedParent + 1);
  31789. };
  31790. var defaultIonToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJlNzMyOGZjZC1jMWUzLTQxNDctOGQxYi03YTYyZDQ1OTIxMjkiLCJpZCI6MjU5LCJpYXQiOjE2MDE1Njk1NDN9.X1a0DCM6F539g9MDSs_ldZ0gwgruxLAZiBl60JwG1ck';
  31791. var TilesRendererBase =
  31792. /*#__PURE__*/
  31793. function () {
  31794. _createClass(TilesRendererBase, [{
  31795. key: "rootTileSet",
  31796. get: function get() {
  31797. var tileSet = this.tileSets[this.rootURL];
  31798. if (!tileSet || tileSet instanceof Promise) {
  31799. return null;
  31800. } else {
  31801. return tileSet;
  31802. }
  31803. }
  31804. }, {
  31805. key: "root",
  31806. get: function get() {
  31807. var tileSet = this.rootTileSet;
  31808. return tileSet ? tileSet.root : null;
  31809. } //The url can be:
  31810. //A plain url to the tileset json file
  31811. //A Cesium Ion asset number with access token
  31812. //A url to the Cesium Ion json file with bearer token as the ionAccessToken. This needs to be fetched from the Ion endpoint separately
  31813. }]);
  31814. function TilesRendererBase(url) {
  31815. var ionAccessToken = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultIonToken;
  31816. _classCallCheck(this, TilesRendererBase);
  31817. // state
  31818. this.tileSets = {};
  31819. this.fetchOptions = {};
  31820. this.setupUrlTokens(url, ionAccessToken);
  31821. var lruCache = new _LRUCache.LRUCache();
  31822. lruCache.unloadPriorityCallback = priorityCallback;
  31823. var downloadQueue = new _PriorityQueue.PriorityQueue();
  31824. downloadQueue.maxJobs = 4;
  31825. downloadQueue.priorityCallback = priorityCallback;
  31826. var parseQueue = new _PriorityQueue.PriorityQueue();
  31827. parseQueue.maxJobs = 1;
  31828. parseQueue.priorityCallback = priorityCallback;
  31829. this.lruCache = lruCache;
  31830. this.downloadQueue = downloadQueue;
  31831. this.parseQueue = parseQueue;
  31832. this.stats = {
  31833. parsing: 0,
  31834. downloading: 0,
  31835. failed: 0,
  31836. inFrustum: 0,
  31837. used: 0,
  31838. active: 0,
  31839. visible: 0
  31840. };
  31841. this.frameCount = 0; // options
  31842. this.errorTarget = 6.0;
  31843. this.errorThreshold = Infinity;
  31844. this.loadSiblings = true;
  31845. this.displayActiveTiles = false;
  31846. this.maxDepth = Infinity;
  31847. this.stopAtEmptyTiles = true;
  31848. }
  31849. _createClass(TilesRendererBase, [{
  31850. key: "setupUrlTokens",
  31851. value: function setupUrlTokens(url, ionToken) {
  31852. this.ionAssetId = this.isInt(url) ? url : null;
  31853. this.ionAccessToken = ionToken;
  31854. this.fetchOptions.headers = {};
  31855. if (!this.ionAssetId) {
  31856. this.rootURL = url;
  31857. if (this.isIonJsonUrl(url)) {
  31858. this.ionAssetId = url.split("/")[3];
  31859. this.ionJsonUrl = new URL(url);
  31860. this.ionVersion = this.ionJsonUrl.searchParams.get('v');
  31861. this.fetchOptions.headers.Authorization = "Bearer ".concat(ionToken);
  31862. this.rootURL = this.ionJsonUrl;
  31863. }
  31864. return;
  31865. } else {
  31866. this.ionEndpointUrl = new URL("https://api.cesium.com/v1/assets/".concat(this.ionAssetId, "/endpoint"));
  31867. this.ionEndpointUrl.searchParams.append('access_token', ionToken);
  31868. }
  31869. }
  31870. }, {
  31871. key: "isInt",
  31872. value: function isInt(input) {
  31873. return typeof input === 'string' ? !isNaN(input) && !isNaN(parseFloat(input, 10)) && Number.isInteger(parseFloat(input, 10)) : Number.isInteger(input);
  31874. }
  31875. }, {
  31876. key: "isIonJsonUrl",
  31877. value: function isIonJsonUrl(input) {
  31878. return input.includes('://assets.cesium.com/') && input.includes('/tileset.json');
  31879. }
  31880. }, {
  31881. key: "getIonAssetJson",
  31882. value: function getIonAssetJson(url) {
  31883. var _this = this;
  31884. return fetch(url, this.fetchOptions).then(function (res) {
  31885. if (res.ok) {
  31886. return res.json();
  31887. } else {
  31888. return Promise.reject("".concat(res.status, " : ").concat(res.statusText));
  31889. }
  31890. }).then(function (json) {
  31891. _this.ionJsonUrl = new URL(json.url);
  31892. _this.ionVersion = _this.ionJsonUrl.searchParams.get('v');
  31893. _this.fetchOptions.headers.Authorization = "Bearer ".concat(json.accessToken);
  31894. _this.rootURL = _this.ionJsonUrl;
  31895. });
  31896. }
  31897. }, {
  31898. key: "traverse",
  31899. value: function traverse(beforecb, aftercb) {
  31900. var tileSets = this.tileSets;
  31901. var rootTileSet = tileSets[this.rootURL];
  31902. if (!rootTileSet || !rootTileSet.root) return;
  31903. (0, _traverseFunctions.traverseSet)(rootTileSet.root, beforecb, aftercb);
  31904. } // Public API
  31905. }, {
  31906. key: "update",
  31907. value: function update() {
  31908. var _this2 = this;
  31909. var stats = this.stats;
  31910. var lruCache = this.lruCache;
  31911. var tileSets = this.tileSets;
  31912. var rootTileSet = tileSets[this.rootURL];
  31913. if (!(this.rootURL in tileSets)) {
  31914. if (this.ionAssetId && !this.ionJsonUrl) {
  31915. if (this.ionJsonUrl == undefined) {
  31916. this.ionJsonUrl = false; // Can't use promise to block update loop, hence this hack
  31917. this.getIonAssetJson(this.ionEndpointUrl).catch(function (err) {
  31918. return console.error("TilesRenderer: Failed to load ION endpoint \"".concat(_this2.ionEndpointUrl, "\" with error: ").concat(err));
  31919. });
  31920. }
  31921. return;
  31922. }
  31923. this.loadRootTileSet(this.rootURL);
  31924. return;
  31925. } else if (!rootTileSet || !rootTileSet.root) {
  31926. return;
  31927. }
  31928. var root = rootTileSet.root;
  31929. stats.inFrustum = 0, stats.used = 0, stats.active = 0, stats.visible = 0, this.frameCount++;
  31930. (0, _traverseFunctions.determineFrustumSet)(root, this);
  31931. (0, _traverseFunctions.markUsedSetLeaves)(root, this);
  31932. (0, _traverseFunctions.skipTraversal)(root, this);
  31933. (0, _traverseFunctions.toggleTiles)(root, this);
  31934. lruCache.scheduleUnload();
  31935. } // Overrideable
  31936. }, {
  31937. key: "parseTile",
  31938. value: function parseTile(buffer, tile, extension) {
  31939. return null;
  31940. }
  31941. }, {
  31942. key: "disposeTile",
  31943. value: function disposeTile(tile) {}
  31944. }, {
  31945. key: "preprocessNode",
  31946. value: function preprocessNode(tile, parentTile, tileSetDir) {
  31947. if (tile.content) {
  31948. // Fix old file formats
  31949. if (!('uri' in tile.content) && 'url' in tile.content) {
  31950. tile.content.uri = tile.content.url;
  31951. delete tile.content.url;
  31952. }
  31953. if (tile.content.uri) {
  31954. tile.content.uri = (0, _urlJoin.urlJoin)(tileSetDir, tile.content.uri);
  31955. } // NOTE: fix for some cases where tilesets provide the bounding volume
  31956. // but volumes are not present.
  31957. if (tile.content.boundingVolume && !('box' in tile.content.boundingVolume || 'sphere' in tile.content.boundingVolume || 'region' in tile.content.boundingVolume)) {
  31958. delete tile.content.boundingVolume;
  31959. }
  31960. }
  31961. tile.parent = parentTile;
  31962. tile.children = tile.children || [];
  31963. var uri = tile.content && tile.content.uri;
  31964. if (uri) {
  31965. // "content" should only indicate loadable meshes, not external tile sets
  31966. var isExternalTileSet = /\.json$/i.test(tile.content.uri);
  31967. tile.__externalTileSet = isExternalTileSet;
  31968. tile.__contentEmpty = isExternalTileSet;
  31969. } else {
  31970. tile.__externalTileSet = false;
  31971. tile.__contentEmpty = true;
  31972. }
  31973. tile.__error = 0.0;
  31974. tile.__inFrustum = false;
  31975. tile.__isLeaf = false;
  31976. tile.__usedLastFrame = false;
  31977. tile.__used = false;
  31978. tile.__wasSetVisible = false;
  31979. tile.__visible = false;
  31980. tile.__childrenWereVisible = false;
  31981. tile.__allChildrenLoaded = false;
  31982. tile.__wasSetActive = false;
  31983. tile.__active = false;
  31984. tile.__loadingState = _constants.UNLOADED;
  31985. tile.__loadIndex = 0;
  31986. tile.__loadAbort = null;
  31987. tile.__depthFromRenderedParent = -1;
  31988. if (parentTile === null) {
  31989. tile.__depth = 0;
  31990. tile.refine = tile.refine || 'REPLACE';
  31991. } else {
  31992. tile.__depth = parentTile.__depth + 1;
  31993. tile.refine = tile.refine || parentTile.refine;
  31994. }
  31995. }
  31996. }, {
  31997. key: "setTileActive",
  31998. value: function setTileActive(tile, state) {}
  31999. }, {
  32000. key: "setTileVisible",
  32001. value: function setTileVisible(tile, state) {}
  32002. }, {
  32003. key: "calculateError",
  32004. value: function calculateError(tile) {
  32005. return 0;
  32006. }
  32007. }, {
  32008. key: "tileInView",
  32009. value: function tileInView(tile) {
  32010. return true;
  32011. } // Private Functions
  32012. }, {
  32013. key: "fetchTileSet",
  32014. value: function fetchTileSet(url, fetchOptions) {
  32015. var _this3 = this;
  32016. var parent = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  32017. return fetch(url, fetchOptions).then(function (res) {
  32018. if (res.ok) {
  32019. return res.json();
  32020. } else {
  32021. throw new Error("TilesRenderer: Failed to load tileset \"".concat(url, "\" with status ").concat(res.status, " : ").concat(res.statusText));
  32022. }
  32023. }).then(function (json) {
  32024. var version = json.asset.version;
  32025. console.assert(version === '1.0' || version === '0.0', 'asset.version is expected to be a string of "1.0" or "0.0"');
  32026. var basePath = _path.default.dirname(url);
  32027. (0, _traverseFunctions.traverseSet)(json.root, function (node, parent) {
  32028. return _this3.preprocessNode(node, parent, basePath);
  32029. }, null, parent, parent ? parent.__depth : 0);
  32030. return json;
  32031. });
  32032. }
  32033. }, {
  32034. key: "loadRootTileSet",
  32035. value: function loadRootTileSet(url) {
  32036. var tileSets = this.tileSets;
  32037. if (!(url in tileSets)) {
  32038. var pr = this.fetchTileSet(url, this.fetchOptions).then(function (json) {
  32039. tileSets[url] = json;
  32040. });
  32041. pr.catch(function (err) {
  32042. console.error(err);
  32043. tileSets[url] = err;
  32044. });
  32045. tileSets[url] = pr;
  32046. return pr;
  32047. } else if (tileSets[url] instanceof Error) {
  32048. return Promise.reject(tileSets[url]);
  32049. } else {
  32050. return Promise.resolve(tileSets[url]);
  32051. }
  32052. }
  32053. }, {
  32054. key: "requestTileContents",
  32055. value: function requestTileContents(tile) {
  32056. var _this4 = this;
  32057. // If the tile is already being loaded then don't
  32058. // start it again.
  32059. if (tile.__loadingState !== _constants.UNLOADED) {
  32060. return;
  32061. }
  32062. var stats = this.stats;
  32063. var lruCache = this.lruCache;
  32064. var downloadQueue = this.downloadQueue;
  32065. var parseQueue = this.parseQueue;
  32066. var isExternalTileSet = tile.__externalTileSet;
  32067. lruCache.add(tile, function (t) {
  32068. // Stop the load if it's started
  32069. if (t.__loadingState === _constants.LOADING) {
  32070. t.__loadAbort.abort();
  32071. t.__loadAbort = null;
  32072. } else if (isExternalTileSet) {
  32073. t.children.length = 0;
  32074. } else {
  32075. _this4.disposeTile(t);
  32076. } // Decrement stats
  32077. if (t.__loadingState === _constants.LOADING) {
  32078. stats.downloading--;
  32079. } else if (t.__loadingState === _constants.PARSING) {
  32080. stats.parsing--;
  32081. }
  32082. t.__loadingState = _constants.UNLOADED;
  32083. t.__loadIndex++;
  32084. parseQueue.remove(t);
  32085. downloadQueue.remove(t);
  32086. }); // Track a new load index so we avoid the condition where this load is stopped and
  32087. // another begins soon after so we don't parse twice.
  32088. tile.__loadIndex++;
  32089. var loadIndex = tile.__loadIndex;
  32090. var controller = new AbortController();
  32091. var signal = controller.signal;
  32092. stats.downloading++;
  32093. tile.__loadAbort = controller;
  32094. tile.__loadingState = _constants.LOADING;
  32095. var errorCallback = function errorCallback(e) {
  32096. // if it has been unloaded then the tile has been disposed
  32097. if (tile.__loadIndex !== loadIndex) {
  32098. return;
  32099. }
  32100. if (e.name !== 'AbortError') {
  32101. parseQueue.remove(tile);
  32102. downloadQueue.remove(tile);
  32103. if (tile.__loadingState === _constants.PARSING) {
  32104. stats.parsing--;
  32105. } else if (tile.__loadingState === _constants.LOADING) {
  32106. stats.downloading--;
  32107. }
  32108. stats.failed++;
  32109. console.error("TilesRenderer : Failed to load tile at url \"".concat(tile.content.uri, "\"."));
  32110. console.error(e);
  32111. tile.__loadingState = _constants.FAILED;
  32112. } else {
  32113. lruCache.remove(tile);
  32114. }
  32115. };
  32116. if (isExternalTileSet) {
  32117. downloadQueue.add(tile, function (tile) {
  32118. // if it has been unloaded then the tile has been disposed
  32119. if (tile.__loadIndex !== loadIndex) {
  32120. return Promise.resolve();
  32121. }
  32122. var uri = tile.content.uri;
  32123. if (_this4.ionAssetId) {
  32124. uri = new URL(tile.content.uri);
  32125. uri.searchParams.append('v', _this4.ionVersion);
  32126. }
  32127. return _this4.fetchTileSet(uri, Object.assign({
  32128. signal: signal
  32129. }, _this4.fetchOptions), tile);
  32130. }).then(function (json) {
  32131. // if it has been unloaded then the tile has been disposed
  32132. if (tile.__loadIndex !== loadIndex) {
  32133. return;
  32134. }
  32135. stats.downloading--;
  32136. tile.__loadAbort = null;
  32137. tile.__loadingState = _constants.LOADED;
  32138. tile.children.push(json.root);
  32139. }).catch(errorCallback);
  32140. } else {
  32141. downloadQueue.add(tile, function (tile) {
  32142. if (tile.__loadIndex !== loadIndex) {
  32143. return Promise.resolve();
  32144. }
  32145. var uri = tile.content.uri;
  32146. if (_this4.ionAssetId) {
  32147. uri = new URL(tile.content.uri);
  32148. uri.searchParams.append('v', _this4.ionVersion);
  32149. }
  32150. return fetch(uri, Object.assign({
  32151. signal: signal
  32152. }, _this4.fetchOptions));
  32153. }).then(function (res) {
  32154. if (tile.__loadIndex !== loadIndex) {
  32155. return;
  32156. }
  32157. if (res.ok) {
  32158. return res.arrayBuffer();
  32159. } else {
  32160. throw new Error("Failed to load model with error code ".concat(res.status));
  32161. }
  32162. }).then(function (buffer) {
  32163. // if it has been unloaded then the tile has been disposed
  32164. if (tile.__loadIndex !== loadIndex) {
  32165. return;
  32166. }
  32167. stats.downloading--;
  32168. stats.parsing++;
  32169. tile.__loadAbort = null;
  32170. tile.__loadingState = _constants.PARSING;
  32171. return parseQueue.add(tile, function (tile) {
  32172. // if it has been unloaded then the tile has been disposed
  32173. if (tile.__loadIndex !== loadIndex) {
  32174. return Promise.resolve();
  32175. }
  32176. var uri = tile.content.uri;
  32177. var extension = uri.split(/\./g).pop();
  32178. return _this4.parseTile(buffer, tile, extension);
  32179. });
  32180. }).then(function () {
  32181. // if it has been unloaded then the tile has been disposed
  32182. if (tile.__loadIndex !== loadIndex) {
  32183. return;
  32184. }
  32185. stats.parsing--;
  32186. tile.__loadingState = _constants.LOADED;
  32187. if (tile.__wasSetVisible) {
  32188. _this4.setTileVisible(tile, true);
  32189. }
  32190. if (tile.__wasSetActive) {
  32191. _this4.setTileActive(tile, true);
  32192. }
  32193. }).catch(errorCallback);
  32194. }
  32195. }
  32196. }, {
  32197. key: "dispose",
  32198. value: function dispose() {
  32199. var lruCache = this.lruCache;
  32200. this.traverse(function (tile) {
  32201. lruCache.remove(tile);
  32202. });
  32203. }
  32204. }]);
  32205. return TilesRendererBase;
  32206. }();
  32207. exports.TilesRendererBase = TilesRendererBase;
  32208. },{"path":"../node_modules/path-browserify/index.js","../utilities/urlJoin.js":"../src/utilities/urlJoin.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/utilities/arrayToString.js":[function(require,module,exports) {
  32209. "use strict";
  32210. Object.defineProperty(exports, "__esModule", {
  32211. value: true
  32212. });
  32213. exports.arrayToString = arrayToString;
  32214. function arrayToString(array) {
  32215. var str = '';
  32216. for (var i = 0, l = array.length; i < l; i++) {
  32217. str += String.fromCharCode(array[i]);
  32218. }
  32219. return str;
  32220. }
  32221. },{}],"../src/utilities/FeatureTable.js":[function(require,module,exports) {
  32222. "use strict";
  32223. Object.defineProperty(exports, "__esModule", {
  32224. value: true
  32225. });
  32226. exports.BatchTable = exports.FeatureTable = void 0;
  32227. var _arrayToString = require("./arrayToString.js");
  32228. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  32229. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  32230. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  32231. function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
  32232. function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
  32233. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  32234. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  32235. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  32236. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  32237. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  32238. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  32239. var FeatureTable =
  32240. /*#__PURE__*/
  32241. function () {
  32242. function FeatureTable(buffer, start, headerLength, binLength) {
  32243. _classCallCheck(this, FeatureTable);
  32244. this.buffer = buffer;
  32245. this.binOffset = start + headerLength;
  32246. this.binLength = binLength;
  32247. var header = null;
  32248. if (headerLength !== 0) {
  32249. var headerData = new Uint8Array(buffer, start, headerLength);
  32250. header = JSON.parse((0, _arrayToString.arrayToString)(headerData));
  32251. } else {
  32252. header = {};
  32253. }
  32254. this.header = header;
  32255. }
  32256. _createClass(FeatureTable, [{
  32257. key: "getKeys",
  32258. value: function getKeys() {
  32259. return Object.keys(this.header);
  32260. }
  32261. }, {
  32262. key: "getData",
  32263. value: function getData(key, count) {
  32264. var defaultComponentType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  32265. var defaultType = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
  32266. var header = this.header;
  32267. if (!(key in header)) {
  32268. return null;
  32269. }
  32270. var feature = header[key];
  32271. if (!(feature instanceof Object)) {
  32272. return feature;
  32273. } else if (Array.isArray(feature)) {
  32274. return feature;
  32275. } else {
  32276. var buffer = this.buffer,
  32277. binOffset = this.binOffset,
  32278. binLength = this.binLength;
  32279. var byteOffset = feature.byteOffset || 0;
  32280. var featureType = feature.type || defaultType;
  32281. var featureComponentType = feature.componentType || defaultComponentType;
  32282. if ('type' in feature && defaultType && feature.type !== defaultType) {
  32283. throw new Error('FeatureTable: Specified type does not match expected type.');
  32284. }
  32285. var stride;
  32286. switch (featureType) {
  32287. case 'SCALAR':
  32288. stride = 1;
  32289. break;
  32290. case 'VEC2':
  32291. stride = 2;
  32292. break;
  32293. case 'VEC3':
  32294. stride = 3;
  32295. break;
  32296. case 'VEC4':
  32297. stride = 4;
  32298. break;
  32299. default:
  32300. throw new Error("FeatureTable : Feature type not provided for \"".concat(key, "\"."));
  32301. }
  32302. var data;
  32303. var arrayStart = binOffset + byteOffset;
  32304. var arrayLength = count * stride;
  32305. switch (featureComponentType) {
  32306. case 'BYTE':
  32307. data = new Int8Array(buffer, arrayStart, arrayLength);
  32308. break;
  32309. case 'UNSIGNED_BYTE':
  32310. data = new Uint8Array(buffer, arrayStart, arrayLength);
  32311. break;
  32312. case 'SHORT':
  32313. data = new Int16Array(buffer, arrayStart, arrayLength);
  32314. break;
  32315. case 'UNSIGNED_SHORT':
  32316. data = new Uint16Array(buffer, arrayStart, arrayLength);
  32317. break;
  32318. case 'INT':
  32319. data = new Int32Array(buffer, arrayStart, arrayLength);
  32320. break;
  32321. case 'UNSIGNED_INT':
  32322. data = new Uint32Array(buffer, arrayStart, arrayLength);
  32323. break;
  32324. case 'FLOAT':
  32325. data = new Float32Array(buffer, arrayStart, arrayLength);
  32326. break;
  32327. case 'DOUBLE':
  32328. data = new Float64Array(buffer, arrayStart, arrayLength);
  32329. break;
  32330. default:
  32331. throw new Error("FeatureTable : Feature component type not provided for \"".concat(key, "\"."));
  32332. }
  32333. var dataEnd = arrayStart + arrayLength * data.BYTES_PER_ELEMENT;
  32334. if (dataEnd > binOffset + binLength) {
  32335. throw new Error('FeatureTable: Feature data read outside binary body length.');
  32336. }
  32337. return data;
  32338. }
  32339. }
  32340. }]);
  32341. return FeatureTable;
  32342. }();
  32343. exports.FeatureTable = FeatureTable;
  32344. var BatchTable =
  32345. /*#__PURE__*/
  32346. function (_FeatureTable) {
  32347. _inherits(BatchTable, _FeatureTable);
  32348. function BatchTable(buffer, batchSize, start, headerLength, binLength) {
  32349. var _this;
  32350. _classCallCheck(this, BatchTable);
  32351. _this = _possibleConstructorReturn(this, _getPrototypeOf(BatchTable).call(this, buffer, start, headerLength, binLength));
  32352. _this.batchSize = batchSize;
  32353. return _this;
  32354. }
  32355. _createClass(BatchTable, [{
  32356. key: "getData",
  32357. value: function getData(key) {
  32358. var componentType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
  32359. var type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  32360. return _get(_getPrototypeOf(BatchTable.prototype), "getData", this).call(this, key, this.batchSize, type, componentType);
  32361. }
  32362. }]);
  32363. return BatchTable;
  32364. }(FeatureTable);
  32365. exports.BatchTable = BatchTable;
  32366. },{"./arrayToString.js":"../src/utilities/arrayToString.js"}],"../src/base/B3DMLoaderBase.js":[function(require,module,exports) {
  32367. "use strict";
  32368. Object.defineProperty(exports, "__esModule", {
  32369. value: true
  32370. });
  32371. exports.B3DMLoaderBase = void 0;
  32372. var _FeatureTable = require("../utilities/FeatureTable.js");
  32373. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  32374. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  32375. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  32376. var B3DMLoaderBase =
  32377. /*#__PURE__*/
  32378. function () {
  32379. function B3DMLoaderBase() {
  32380. _classCallCheck(this, B3DMLoaderBase);
  32381. this.fetchOptions = {};
  32382. }
  32383. _createClass(B3DMLoaderBase, [{
  32384. key: "load",
  32385. value: function load(url) {
  32386. var _this = this;
  32387. return fetch(url, this.fetchOptions).then(function (res) {
  32388. if (!res.ok) {
  32389. throw new Error("Failed to load file \"".concat(url, "\" with status ").concat(res.status, " : ").concat(res.statusText));
  32390. }
  32391. return res.arrayBuffer();
  32392. }).then(function (buffer) {
  32393. return _this.parse(buffer);
  32394. });
  32395. }
  32396. }, {
  32397. key: "parse",
  32398. value: function parse(buffer) {
  32399. // TODO: this should be able to take a uint8array with an offset and length
  32400. var dataView = new DataView(buffer); // 28-byte header
  32401. // 4 bytes
  32402. var magic = String.fromCharCode(dataView.getUint8(0)) + String.fromCharCode(dataView.getUint8(1)) + String.fromCharCode(dataView.getUint8(2)) + String.fromCharCode(dataView.getUint8(3));
  32403. console.assert(magic === 'b3dm'); // 4 bytes
  32404. var version = dataView.getUint32(4, true);
  32405. console.assert(version === 1); // 4 bytes
  32406. var byteLength = dataView.getUint32(8, true);
  32407. console.assert(byteLength === buffer.byteLength); // 4 bytes
  32408. var featureTableJSONByteLength = dataView.getUint32(12, true); // 4 bytes
  32409. var featureTableBinaryByteLength = dataView.getUint32(16, true); // 4 bytes
  32410. var batchTableJSONByteLength = dataView.getUint32(20, true); // 4 bytes
  32411. var batchTableBinaryByteLength = dataView.getUint32(24, true); // Feature Table
  32412. var featureTableStart = 28;
  32413. var featureTable = new _FeatureTable.FeatureTable(buffer, featureTableStart, featureTableJSONByteLength, featureTableBinaryByteLength); // Batch Table
  32414. var batchTableStart = featureTableStart + featureTableJSONByteLength + featureTableBinaryByteLength;
  32415. var batchTable = new _FeatureTable.BatchTable(buffer, featureTable.getData('BATCH_LENGTH'), batchTableStart, batchTableJSONByteLength, batchTableBinaryByteLength);
  32416. var glbStart = batchTableStart + batchTableJSONByteLength + batchTableBinaryByteLength;
  32417. var glbBytes = new Uint8Array(buffer, glbStart, byteLength - glbStart);
  32418. return {
  32419. version: version,
  32420. featureTable: featureTable,
  32421. batchTable: batchTable,
  32422. glbBytes: glbBytes
  32423. };
  32424. }
  32425. }]);
  32426. return B3DMLoaderBase;
  32427. }();
  32428. exports.B3DMLoaderBase = B3DMLoaderBase;
  32429. },{"../utilities/FeatureTable.js":"../src/utilities/FeatureTable.js"}],"../node_modules/three/examples/jsm/loaders/GLTFLoader.js":[function(require,module,exports) {
  32430. "use strict";
  32431. Object.defineProperty(exports, "__esModule", {
  32432. value: true
  32433. });
  32434. exports.GLTFLoader = void 0;
  32435. var _threeModule = require("../../../build/three.module.js");
  32436. var GLTFLoader = function () {
  32437. function GLTFLoader(manager) {
  32438. _threeModule.Loader.call(this, manager);
  32439. this.dracoLoader = null;
  32440. this.ddsLoader = null;
  32441. this.ktx2Loader = null;
  32442. this.meshoptDecoder = null;
  32443. this.pluginCallbacks = [];
  32444. this.register(function (parser) {
  32445. return new GLTFMaterialsClearcoatExtension(parser);
  32446. });
  32447. this.register(function (parser) {
  32448. return new GLTFTextureBasisUExtension(parser);
  32449. });
  32450. this.register(function (parser) {
  32451. return new GLTFTextureWebPExtension(parser);
  32452. });
  32453. this.register(function (parser) {
  32454. return new GLTFMaterialsTransmissionExtension(parser);
  32455. });
  32456. this.register(function (parser) {
  32457. return new GLTFLightsExtension(parser);
  32458. });
  32459. this.register(function (parser) {
  32460. return new GLTFMeshoptCompression(parser);
  32461. });
  32462. }
  32463. GLTFLoader.prototype = Object.assign(Object.create(_threeModule.Loader.prototype), {
  32464. constructor: GLTFLoader,
  32465. load: function (url, onLoad, onProgress, onError) {
  32466. var scope = this;
  32467. var resourcePath;
  32468. if (this.resourcePath !== '') {
  32469. resourcePath = this.resourcePath;
  32470. } else if (this.path !== '') {
  32471. resourcePath = this.path;
  32472. } else {
  32473. resourcePath = _threeModule.LoaderUtils.extractUrlBase(url);
  32474. } // Tells the LoadingManager to track an extra item, which resolves after
  32475. // the model is fully loaded. This means the count of items loaded will
  32476. // be incorrect, but ensures manager.onLoad() does not fire early.
  32477. this.manager.itemStart(url);
  32478. var _onError = function (e) {
  32479. if (onError) {
  32480. onError(e);
  32481. } else {
  32482. console.error(e);
  32483. }
  32484. scope.manager.itemError(url);
  32485. scope.manager.itemEnd(url);
  32486. };
  32487. var loader = new _threeModule.FileLoader(this.manager);
  32488. loader.setPath(this.path);
  32489. loader.setResponseType('arraybuffer');
  32490. loader.setRequestHeader(this.requestHeader);
  32491. loader.setWithCredentials(this.withCredentials);
  32492. loader.load(url, function (data) {
  32493. try {
  32494. scope.parse(data, resourcePath, function (gltf) {
  32495. onLoad(gltf);
  32496. scope.manager.itemEnd(url);
  32497. }, _onError);
  32498. } catch (e) {
  32499. _onError(e);
  32500. }
  32501. }, onProgress, _onError);
  32502. },
  32503. setDRACOLoader: function (dracoLoader) {
  32504. this.dracoLoader = dracoLoader;
  32505. return this;
  32506. },
  32507. setDDSLoader: function (ddsLoader) {
  32508. this.ddsLoader = ddsLoader;
  32509. return this;
  32510. },
  32511. setKTX2Loader: function (ktx2Loader) {
  32512. this.ktx2Loader = ktx2Loader;
  32513. return this;
  32514. },
  32515. setMeshoptDecoder: function (meshoptDecoder) {
  32516. this.meshoptDecoder = meshoptDecoder;
  32517. return this;
  32518. },
  32519. register: function (callback) {
  32520. if (this.pluginCallbacks.indexOf(callback) === -1) {
  32521. this.pluginCallbacks.push(callback);
  32522. }
  32523. return this;
  32524. },
  32525. unregister: function (callback) {
  32526. if (this.pluginCallbacks.indexOf(callback) !== -1) {
  32527. this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(callback), 1);
  32528. }
  32529. return this;
  32530. },
  32531. parse: function (data, path, onLoad, onError) {
  32532. var content;
  32533. var extensions = {};
  32534. var plugins = {};
  32535. if (typeof data === 'string') {
  32536. content = data;
  32537. } else {
  32538. var magic = _threeModule.LoaderUtils.decodeText(new Uint8Array(data, 0, 4));
  32539. if (magic === BINARY_EXTENSION_HEADER_MAGIC) {
  32540. try {
  32541. extensions[EXTENSIONS.KHR_BINARY_GLTF] = new GLTFBinaryExtension(data);
  32542. } catch (error) {
  32543. if (onError) onError(error);
  32544. return;
  32545. }
  32546. content = extensions[EXTENSIONS.KHR_BINARY_GLTF].content;
  32547. } else {
  32548. content = _threeModule.LoaderUtils.decodeText(new Uint8Array(data));
  32549. }
  32550. }
  32551. var json = JSON.parse(content);
  32552. if (json.asset === undefined || json.asset.version[0] < 2) {
  32553. if (onError) onError(new Error('THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.'));
  32554. return;
  32555. }
  32556. var parser = new GLTFParser(json, {
  32557. path: path || this.resourcePath || '',
  32558. crossOrigin: this.crossOrigin,
  32559. manager: this.manager,
  32560. ktx2Loader: this.ktx2Loader,
  32561. meshoptDecoder: this.meshoptDecoder
  32562. });
  32563. parser.fileLoader.setRequestHeader(this.requestHeader);
  32564. for (var i = 0; i < this.pluginCallbacks.length; i++) {
  32565. var plugin = this.pluginCallbacks[i](parser);
  32566. plugins[plugin.name] = plugin; // Workaround to avoid determining as unknown extension
  32567. // in addUnknownExtensionsToUserData().
  32568. // Remove this workaround if we move all the existing
  32569. // extension handlers to plugin system
  32570. extensions[plugin.name] = true;
  32571. }
  32572. if (json.extensionsUsed) {
  32573. for (var i = 0; i < json.extensionsUsed.length; ++i) {
  32574. var extensionName = json.extensionsUsed[i];
  32575. var extensionsRequired = json.extensionsRequired || [];
  32576. switch (extensionName) {
  32577. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  32578. extensions[extensionName] = new GLTFMaterialsUnlitExtension();
  32579. break;
  32580. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  32581. extensions[extensionName] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  32582. break;
  32583. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  32584. extensions[extensionName] = new GLTFDracoMeshCompressionExtension(json, this.dracoLoader);
  32585. break;
  32586. case EXTENSIONS.MSFT_TEXTURE_DDS:
  32587. extensions[extensionName] = new GLTFTextureDDSExtension(this.ddsLoader);
  32588. break;
  32589. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  32590. extensions[extensionName] = new GLTFTextureTransformExtension();
  32591. break;
  32592. case EXTENSIONS.KHR_MESH_QUANTIZATION:
  32593. extensions[extensionName] = new GLTFMeshQuantizationExtension();
  32594. break;
  32595. default:
  32596. if (extensionsRequired.indexOf(extensionName) >= 0 && plugins[extensionName] === undefined) {
  32597. console.warn('THREE.GLTFLoader: Unknown extension "' + extensionName + '".');
  32598. }
  32599. }
  32600. }
  32601. }
  32602. parser.setExtensions(extensions);
  32603. parser.setPlugins(plugins);
  32604. parser.parse(onLoad, onError);
  32605. }
  32606. });
  32607. /* GLTFREGISTRY */
  32608. function GLTFRegistry() {
  32609. var objects = {};
  32610. return {
  32611. get: function (key) {
  32612. return objects[key];
  32613. },
  32614. add: function (key, object) {
  32615. objects[key] = object;
  32616. },
  32617. remove: function (key) {
  32618. delete objects[key];
  32619. },
  32620. removeAll: function () {
  32621. objects = {};
  32622. }
  32623. };
  32624. }
  32625. /*********************************/
  32626. /********** EXTENSIONS ***********/
  32627. /*********************************/
  32628. var EXTENSIONS = {
  32629. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  32630. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  32631. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  32632. KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat',
  32633. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  32634. KHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission',
  32635. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  32636. KHR_TEXTURE_BASISU: 'KHR_texture_basisu',
  32637. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  32638. KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization',
  32639. EXT_TEXTURE_WEBP: 'EXT_texture_webp',
  32640. EXT_MESHOPT_COMPRESSION: 'EXT_meshopt_compression',
  32641. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  32642. };
  32643. /**
  32644. * DDS Texture Extension
  32645. *
  32646. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  32647. *
  32648. */
  32649. function GLTFTextureDDSExtension(ddsLoader) {
  32650. if (!ddsLoader) {
  32651. throw new Error('THREE.GLTFLoader: Attempting to load .dds texture without importing DDSLoader');
  32652. }
  32653. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  32654. this.ddsLoader = ddsLoader;
  32655. }
  32656. /**
  32657. * Punctual Lights Extension
  32658. *
  32659. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  32660. */
  32661. function GLTFLightsExtension(parser) {
  32662. this.parser = parser;
  32663. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL; // Object3D instance caches
  32664. this.cache = {
  32665. refs: {},
  32666. uses: {}
  32667. };
  32668. }
  32669. GLTFLightsExtension.prototype._markDefs = function () {
  32670. var parser = this.parser;
  32671. var nodeDefs = this.parser.json.nodes || [];
  32672. for (var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) {
  32673. var nodeDef = nodeDefs[nodeIndex];
  32674. if (nodeDef.extensions && nodeDef.extensions[this.name] && nodeDef.extensions[this.name].light !== undefined) {
  32675. parser._addNodeRef(this.cache, nodeDef.extensions[this.name].light);
  32676. }
  32677. }
  32678. };
  32679. GLTFLightsExtension.prototype._loadLight = function (lightIndex) {
  32680. var parser = this.parser;
  32681. var cacheKey = 'light:' + lightIndex;
  32682. var dependency = parser.cache.get(cacheKey);
  32683. if (dependency) return dependency;
  32684. var json = parser.json;
  32685. var extensions = json.extensions && json.extensions[this.name] || {};
  32686. var lightDefs = extensions.lights || [];
  32687. var lightDef = lightDefs[lightIndex];
  32688. var lightNode;
  32689. var color = new _threeModule.Color(0xffffff);
  32690. if (lightDef.color !== undefined) color.fromArray(lightDef.color);
  32691. var range = lightDef.range !== undefined ? lightDef.range : 0;
  32692. switch (lightDef.type) {
  32693. case 'directional':
  32694. lightNode = new _threeModule.DirectionalLight(color);
  32695. lightNode.target.position.set(0, 0, -1);
  32696. lightNode.add(lightNode.target);
  32697. break;
  32698. case 'point':
  32699. lightNode = new _threeModule.PointLight(color);
  32700. lightNode.distance = range;
  32701. break;
  32702. case 'spot':
  32703. lightNode = new _threeModule.SpotLight(color);
  32704. lightNode.distance = range; // Handle spotlight properties.
  32705. lightDef.spot = lightDef.spot || {};
  32706. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  32707. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  32708. lightNode.angle = lightDef.spot.outerConeAngle;
  32709. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  32710. lightNode.target.position.set(0, 0, -1);
  32711. lightNode.add(lightNode.target);
  32712. break;
  32713. default:
  32714. throw new Error('THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".');
  32715. } // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  32716. // here, because node-level parsing will only override position if explicitly specified.
  32717. lightNode.position.set(0, 0, 0);
  32718. lightNode.decay = 2;
  32719. if (lightDef.intensity !== undefined) lightNode.intensity = lightDef.intensity;
  32720. lightNode.name = parser.createUniqueName(lightDef.name || 'light_' + lightIndex);
  32721. dependency = Promise.resolve(lightNode);
  32722. parser.cache.add(cacheKey, dependency);
  32723. return dependency;
  32724. };
  32725. GLTFLightsExtension.prototype.createNodeAttachment = function (nodeIndex) {
  32726. var self = this;
  32727. var parser = this.parser;
  32728. var json = parser.json;
  32729. var nodeDef = json.nodes[nodeIndex];
  32730. var lightDef = nodeDef.extensions && nodeDef.extensions[this.name] || {};
  32731. var lightIndex = lightDef.light;
  32732. if (lightIndex === undefined) return null;
  32733. return this._loadLight(lightIndex).then(function (light) {
  32734. return parser._getNodeRef(self.cache, lightIndex, light);
  32735. });
  32736. };
  32737. /**
  32738. * Unlit Materials Extension
  32739. *
  32740. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  32741. */
  32742. function GLTFMaterialsUnlitExtension() {
  32743. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  32744. }
  32745. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () {
  32746. return _threeModule.MeshBasicMaterial;
  32747. };
  32748. GLTFMaterialsUnlitExtension.prototype.extendParams = function (materialParams, materialDef, parser) {
  32749. var pending = [];
  32750. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  32751. materialParams.opacity = 1.0;
  32752. var metallicRoughness = materialDef.pbrMetallicRoughness;
  32753. if (metallicRoughness) {
  32754. if (Array.isArray(metallicRoughness.baseColorFactor)) {
  32755. var array = metallicRoughness.baseColorFactor;
  32756. materialParams.color.fromArray(array);
  32757. materialParams.opacity = array[3];
  32758. }
  32759. if (metallicRoughness.baseColorTexture !== undefined) {
  32760. pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture));
  32761. }
  32762. }
  32763. return Promise.all(pending);
  32764. };
  32765. /**
  32766. * Clearcoat Materials Extension
  32767. *
  32768. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat
  32769. */
  32770. function GLTFMaterialsClearcoatExtension(parser) {
  32771. this.parser = parser;
  32772. this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT;
  32773. }
  32774. GLTFMaterialsClearcoatExtension.prototype.getMaterialType = function (materialIndex) {
  32775. var parser = this.parser;
  32776. var materialDef = parser.json.materials[materialIndex];
  32777. if (!materialDef.extensions || !materialDef.extensions[this.name]) return null;
  32778. return _threeModule.MeshPhysicalMaterial;
  32779. };
  32780. GLTFMaterialsClearcoatExtension.prototype.extendMaterialParams = function (materialIndex, materialParams) {
  32781. var parser = this.parser;
  32782. var materialDef = parser.json.materials[materialIndex];
  32783. if (!materialDef.extensions || !materialDef.extensions[this.name]) {
  32784. return Promise.resolve();
  32785. }
  32786. var pending = [];
  32787. var extension = materialDef.extensions[this.name];
  32788. if (extension.clearcoatFactor !== undefined) {
  32789. materialParams.clearcoat = extension.clearcoatFactor;
  32790. }
  32791. if (extension.clearcoatTexture !== undefined) {
  32792. pending.push(parser.assignTexture(materialParams, 'clearcoatMap', extension.clearcoatTexture));
  32793. }
  32794. if (extension.clearcoatRoughnessFactor !== undefined) {
  32795. materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor;
  32796. }
  32797. if (extension.clearcoatRoughnessTexture !== undefined) {
  32798. pending.push(parser.assignTexture(materialParams, 'clearcoatRoughnessMap', extension.clearcoatRoughnessTexture));
  32799. }
  32800. if (extension.clearcoatNormalTexture !== undefined) {
  32801. pending.push(parser.assignTexture(materialParams, 'clearcoatNormalMap', extension.clearcoatNormalTexture));
  32802. if (extension.clearcoatNormalTexture.scale !== undefined) {
  32803. var scale = extension.clearcoatNormalTexture.scale;
  32804. materialParams.clearcoatNormalScale = new _threeModule.Vector2(scale, scale);
  32805. }
  32806. }
  32807. return Promise.all(pending);
  32808. };
  32809. /**
  32810. * Transmission Materials Extension
  32811. *
  32812. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission
  32813. * Draft: https://github.com/KhronosGroup/glTF/pull/1698
  32814. */
  32815. function GLTFMaterialsTransmissionExtension(parser) {
  32816. this.parser = parser;
  32817. this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION;
  32818. }
  32819. GLTFMaterialsTransmissionExtension.prototype.getMaterialType = function (materialIndex) {
  32820. var parser = this.parser;
  32821. var materialDef = parser.json.materials[materialIndex];
  32822. if (!materialDef.extensions || !materialDef.extensions[this.name]) return null;
  32823. return _threeModule.MeshPhysicalMaterial;
  32824. };
  32825. GLTFMaterialsTransmissionExtension.prototype.extendMaterialParams = function (materialIndex, materialParams) {
  32826. var parser = this.parser;
  32827. var materialDef = parser.json.materials[materialIndex];
  32828. if (!materialDef.extensions || !materialDef.extensions[this.name]) {
  32829. return Promise.resolve();
  32830. }
  32831. var pending = [];
  32832. var extension = materialDef.extensions[this.name];
  32833. if (extension.transmissionFactor !== undefined) {
  32834. materialParams.transmission = extension.transmissionFactor;
  32835. }
  32836. if (extension.transmissionTexture !== undefined) {
  32837. pending.push(parser.assignTexture(materialParams, 'transmissionMap', extension.transmissionTexture));
  32838. }
  32839. return Promise.all(pending);
  32840. };
  32841. /**
  32842. * BasisU Texture Extension
  32843. *
  32844. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu
  32845. */
  32846. function GLTFTextureBasisUExtension(parser) {
  32847. this.parser = parser;
  32848. this.name = EXTENSIONS.KHR_TEXTURE_BASISU;
  32849. }
  32850. GLTFTextureBasisUExtension.prototype.loadTexture = function (textureIndex) {
  32851. var parser = this.parser;
  32852. var json = parser.json;
  32853. var textureDef = json.textures[textureIndex];
  32854. if (!textureDef.extensions || !textureDef.extensions[this.name]) {
  32855. return null;
  32856. }
  32857. var extension = textureDef.extensions[this.name];
  32858. var source = json.images[extension.source];
  32859. var loader = parser.options.ktx2Loader;
  32860. if (!loader) {
  32861. if (json.extensionsRequired && json.extensionsRequired.indexOf(this.name) >= 0) {
  32862. throw new Error('THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures');
  32863. } else {
  32864. // Assumes that the extension is optional and that a fallback texture is present
  32865. return null;
  32866. }
  32867. }
  32868. return parser.loadTextureImage(textureIndex, source, loader);
  32869. };
  32870. /**
  32871. * WebP Texture Extension
  32872. *
  32873. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_webp
  32874. */
  32875. function GLTFTextureWebPExtension(parser) {
  32876. this.parser = parser;
  32877. this.name = EXTENSIONS.EXT_TEXTURE_WEBP;
  32878. this.isSupported = null;
  32879. }
  32880. GLTFTextureWebPExtension.prototype.loadTexture = function (textureIndex) {
  32881. var name = this.name;
  32882. var parser = this.parser;
  32883. var json = parser.json;
  32884. var textureDef = json.textures[textureIndex];
  32885. if (!textureDef.extensions || !textureDef.extensions[name]) {
  32886. return null;
  32887. }
  32888. var extension = textureDef.extensions[name];
  32889. var source = json.images[extension.source];
  32890. var loader = source.uri ? parser.options.manager.getHandler(source.uri) : parser.textureLoader;
  32891. return this.detectSupport().then(function (isSupported) {
  32892. if (isSupported) return parser.loadTextureImage(textureIndex, source, loader);
  32893. if (json.extensionsRequired && json.extensionsRequired.indexOf(name) >= 0) {
  32894. throw new Error('THREE.GLTFLoader: WebP required by asset but unsupported.');
  32895. } // Fall back to PNG or JPEG.
  32896. return parser.loadTexture(textureIndex);
  32897. });
  32898. };
  32899. GLTFTextureWebPExtension.prototype.detectSupport = function () {
  32900. if (!this.isSupported) {
  32901. this.isSupported = new Promise(function (resolve) {
  32902. var image = new Image(); // Lossy test image. Support for lossy images doesn't guarantee support for all
  32903. // WebP images, unfortunately.
  32904. image.src = 'data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA';
  32905. image.onload = image.onerror = function () {
  32906. resolve(image.height === 1);
  32907. };
  32908. });
  32909. }
  32910. return this.isSupported;
  32911. };
  32912. /**
  32913. * meshopt BufferView Compression Extension
  32914. *
  32915. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_meshopt_compression
  32916. */
  32917. function GLTFMeshoptCompression(parser) {
  32918. this.name = EXTENSIONS.EXT_MESHOPT_COMPRESSION;
  32919. this.parser = parser;
  32920. }
  32921. GLTFMeshoptCompression.prototype.loadBufferView = function (index) {
  32922. var json = this.parser.json;
  32923. var bufferView = json.bufferViews[index];
  32924. if (bufferView.extensions && bufferView.extensions[this.name]) {
  32925. var extensionDef = bufferView.extensions[this.name];
  32926. var buffer = this.parser.getDependency('buffer', extensionDef.buffer);
  32927. var decoder = this.parser.options.meshoptDecoder;
  32928. if (!decoder || !decoder.supported) {
  32929. if (json.extensionsRequired && json.extensionsRequired.indexOf(this.name) >= 0) {
  32930. throw new Error('THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files');
  32931. } else {
  32932. // Assumes that the extension is optional and that fallback buffer data is present
  32933. return null;
  32934. }
  32935. }
  32936. return Promise.all([buffer, decoder.ready]).then(function (res) {
  32937. var byteOffset = extensionDef.byteOffset || 0;
  32938. var byteLength = extensionDef.byteLength || 0;
  32939. var count = extensionDef.count;
  32940. var stride = extensionDef.byteStride;
  32941. var result = new ArrayBuffer(count * stride);
  32942. var source = new Uint8Array(res[0], byteOffset, byteLength);
  32943. decoder.decodeGltfBuffer(new Uint8Array(result), count, stride, source, extensionDef.mode, extensionDef.filter);
  32944. return result;
  32945. });
  32946. } else {
  32947. return null;
  32948. }
  32949. };
  32950. /* BINARY EXTENSION */
  32951. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  32952. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  32953. var BINARY_EXTENSION_CHUNK_TYPES = {
  32954. JSON: 0x4E4F534A,
  32955. BIN: 0x004E4942
  32956. };
  32957. function GLTFBinaryExtension(data) {
  32958. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  32959. this.content = null;
  32960. this.body = null;
  32961. var headerView = new DataView(data, 0, BINARY_EXTENSION_HEADER_LENGTH);
  32962. this.header = {
  32963. magic: _threeModule.LoaderUtils.decodeText(new Uint8Array(data.slice(0, 4))),
  32964. version: headerView.getUint32(4, true),
  32965. length: headerView.getUint32(8, true)
  32966. };
  32967. if (this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC) {
  32968. throw new Error('THREE.GLTFLoader: Unsupported glTF-Binary header.');
  32969. } else if (this.header.version < 2.0) {
  32970. throw new Error('THREE.GLTFLoader: Legacy binary file detected.');
  32971. }
  32972. var chunkView = new DataView(data, BINARY_EXTENSION_HEADER_LENGTH);
  32973. var chunkIndex = 0;
  32974. while (chunkIndex < chunkView.byteLength) {
  32975. var chunkLength = chunkView.getUint32(chunkIndex, true);
  32976. chunkIndex += 4;
  32977. var chunkType = chunkView.getUint32(chunkIndex, true);
  32978. chunkIndex += 4;
  32979. if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON) {
  32980. var contentArray = new Uint8Array(data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength);
  32981. this.content = _threeModule.LoaderUtils.decodeText(contentArray);
  32982. } else if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN) {
  32983. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  32984. this.body = data.slice(byteOffset, byteOffset + chunkLength);
  32985. } // Clients must ignore chunks with unknown types.
  32986. chunkIndex += chunkLength;
  32987. }
  32988. if (this.content === null) {
  32989. throw new Error('THREE.GLTFLoader: JSON content not found.');
  32990. }
  32991. }
  32992. /**
  32993. * DRACO Mesh Compression Extension
  32994. *
  32995. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  32996. */
  32997. function GLTFDracoMeshCompressionExtension(json, dracoLoader) {
  32998. if (!dracoLoader) {
  32999. throw new Error('THREE.GLTFLoader: No DRACOLoader instance provided.');
  33000. }
  33001. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  33002. this.json = json;
  33003. this.dracoLoader = dracoLoader;
  33004. this.dracoLoader.preload();
  33005. }
  33006. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function (primitive, parser) {
  33007. var json = this.json;
  33008. var dracoLoader = this.dracoLoader;
  33009. var bufferViewIndex = primitive.extensions[this.name].bufferView;
  33010. var gltfAttributeMap = primitive.extensions[this.name].attributes;
  33011. var threeAttributeMap = {};
  33012. var attributeNormalizedMap = {};
  33013. var attributeTypeMap = {};
  33014. for (var attributeName in gltfAttributeMap) {
  33015. var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
  33016. threeAttributeMap[threeAttributeName] = gltfAttributeMap[attributeName];
  33017. }
  33018. for (attributeName in primitive.attributes) {
  33019. var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
  33020. if (gltfAttributeMap[attributeName] !== undefined) {
  33021. var accessorDef = json.accessors[primitive.attributes[attributeName]];
  33022. var componentType = WEBGL_COMPONENT_TYPES[accessorDef.componentType];
  33023. attributeTypeMap[threeAttributeName] = componentType;
  33024. attributeNormalizedMap[threeAttributeName] = accessorDef.normalized === true;
  33025. }
  33026. }
  33027. return parser.getDependency('bufferView', bufferViewIndex).then(function (bufferView) {
  33028. return new Promise(function (resolve) {
  33029. dracoLoader.decodeDracoFile(bufferView, function (geometry) {
  33030. for (var attributeName in geometry.attributes) {
  33031. var attribute = geometry.attributes[attributeName];
  33032. var normalized = attributeNormalizedMap[attributeName];
  33033. if (normalized !== undefined) attribute.normalized = normalized;
  33034. }
  33035. resolve(geometry);
  33036. }, threeAttributeMap, attributeTypeMap);
  33037. });
  33038. });
  33039. };
  33040. /**
  33041. * Texture Transform Extension
  33042. *
  33043. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
  33044. */
  33045. function GLTFTextureTransformExtension() {
  33046. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  33047. }
  33048. GLTFTextureTransformExtension.prototype.extendTexture = function (texture, transform) {
  33049. texture = texture.clone();
  33050. if (transform.offset !== undefined) {
  33051. texture.offset.fromArray(transform.offset);
  33052. }
  33053. if (transform.rotation !== undefined) {
  33054. texture.rotation = transform.rotation;
  33055. }
  33056. if (transform.scale !== undefined) {
  33057. texture.repeat.fromArray(transform.scale);
  33058. }
  33059. if (transform.texCoord !== undefined) {
  33060. console.warn('THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.');
  33061. }
  33062. texture.needsUpdate = true;
  33063. return texture;
  33064. };
  33065. /**
  33066. * Specular-Glossiness Extension
  33067. *
  33068. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  33069. */
  33070. /**
  33071. * A sub class of StandardMaterial with some of the functionality
  33072. * changed via the `onBeforeCompile` callback
  33073. * @pailhead
  33074. */
  33075. function GLTFMeshStandardSGMaterial(params) {
  33076. _threeModule.MeshStandardMaterial.call(this);
  33077. this.isGLTFSpecularGlossinessMaterial = true; //various chunks that need replacing
  33078. var specularMapParsFragmentChunk = ['#ifdef USE_SPECULARMAP', ' uniform sampler2D specularMap;', '#endif'].join('\n');
  33079. var glossinessMapParsFragmentChunk = ['#ifdef USE_GLOSSINESSMAP', ' uniform sampler2D glossinessMap;', '#endif'].join('\n');
  33080. 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');
  33081. 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');
  33082. var lightPhysicalFragmentChunk = ['PhysicalMaterial material;', 'material.diffuseColor = diffuseColor.rgb * ( 1. - max( specularFactor.r, max( specularFactor.g, specularFactor.b ) ) );', 'vec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );', 'float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );', 'material.specularRoughness = max( 1.0 - glossinessFactor, 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.', 'material.specularRoughness += geometryRoughness;', 'material.specularRoughness = min( material.specularRoughness, 1.0 );', 'material.specularColor = specularFactor;'].join('\n');
  33083. var uniforms = {
  33084. specular: {
  33085. value: new _threeModule.Color().setHex(0xffffff)
  33086. },
  33087. glossiness: {
  33088. value: 1
  33089. },
  33090. specularMap: {
  33091. value: null
  33092. },
  33093. glossinessMap: {
  33094. value: null
  33095. }
  33096. };
  33097. this._extraUniforms = uniforms;
  33098. this.onBeforeCompile = function (shader) {
  33099. for (var uniformName in uniforms) {
  33100. shader.uniforms[uniformName] = uniforms[uniformName];
  33101. }
  33102. shader.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);
  33103. };
  33104. Object.defineProperties(this, {
  33105. specular: {
  33106. get: function () {
  33107. return uniforms.specular.value;
  33108. },
  33109. set: function (v) {
  33110. uniforms.specular.value = v;
  33111. }
  33112. },
  33113. specularMap: {
  33114. get: function () {
  33115. return uniforms.specularMap.value;
  33116. },
  33117. set: function (v) {
  33118. uniforms.specularMap.value = v;
  33119. if (v) {
  33120. this.defines.USE_SPECULARMAP = ''; // USE_UV is set by the renderer for specular maps
  33121. } else {
  33122. delete this.defines.USE_SPECULARMAP;
  33123. }
  33124. }
  33125. },
  33126. glossiness: {
  33127. get: function () {
  33128. return uniforms.glossiness.value;
  33129. },
  33130. set: function (v) {
  33131. uniforms.glossiness.value = v;
  33132. }
  33133. },
  33134. glossinessMap: {
  33135. get: function () {
  33136. return uniforms.glossinessMap.value;
  33137. },
  33138. set: function (v) {
  33139. uniforms.glossinessMap.value = v;
  33140. if (v) {
  33141. this.defines.USE_GLOSSINESSMAP = '';
  33142. this.defines.USE_UV = '';
  33143. } else {
  33144. delete this.defines.USE_GLOSSINESSMAP;
  33145. delete this.defines.USE_UV;
  33146. }
  33147. }
  33148. }
  33149. });
  33150. delete this.metalness;
  33151. delete this.roughness;
  33152. delete this.metalnessMap;
  33153. delete this.roughnessMap;
  33154. this.setValues(params);
  33155. }
  33156. GLTFMeshStandardSGMaterial.prototype = Object.create(_threeModule.MeshStandardMaterial.prototype);
  33157. GLTFMeshStandardSGMaterial.prototype.constructor = GLTFMeshStandardSGMaterial;
  33158. GLTFMeshStandardSGMaterial.prototype.copy = function (source) {
  33159. _threeModule.MeshStandardMaterial.prototype.copy.call(this, source);
  33160. this.specularMap = source.specularMap;
  33161. this.specular.copy(source.specular);
  33162. this.glossinessMap = source.glossinessMap;
  33163. this.glossiness = source.glossiness;
  33164. delete this.metalness;
  33165. delete this.roughness;
  33166. delete this.metalnessMap;
  33167. delete this.roughnessMap;
  33168. return this;
  33169. };
  33170. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  33171. return {
  33172. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  33173. specularGlossinessParams: ['color', 'map', 'lightMap', 'lightMapIntensity', 'aoMap', 'aoMapIntensity', 'emissive', 'emissiveIntensity', 'emissiveMap', 'bumpMap', 'bumpScale', 'normalMap', 'normalMapType', 'displacementMap', 'displacementScale', 'displacementBias', 'specularMap', 'specular', 'glossinessMap', 'glossiness', 'alphaMap', 'envMap', 'envMapIntensity', 'refractionRatio'],
  33174. getMaterialType: function () {
  33175. return GLTFMeshStandardSGMaterial;
  33176. },
  33177. extendParams: function (materialParams, materialDef, parser) {
  33178. var pbrSpecularGlossiness = materialDef.extensions[this.name];
  33179. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  33180. materialParams.opacity = 1.0;
  33181. var pending = [];
  33182. if (Array.isArray(pbrSpecularGlossiness.diffuseFactor)) {
  33183. var array = pbrSpecularGlossiness.diffuseFactor;
  33184. materialParams.color.fromArray(array);
  33185. materialParams.opacity = array[3];
  33186. }
  33187. if (pbrSpecularGlossiness.diffuseTexture !== undefined) {
  33188. pending.push(parser.assignTexture(materialParams, 'map', pbrSpecularGlossiness.diffuseTexture));
  33189. }
  33190. materialParams.emissive = new _threeModule.Color(0.0, 0.0, 0.0);
  33191. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  33192. materialParams.specular = new _threeModule.Color(1.0, 1.0, 1.0);
  33193. if (Array.isArray(pbrSpecularGlossiness.specularFactor)) {
  33194. materialParams.specular.fromArray(pbrSpecularGlossiness.specularFactor);
  33195. }
  33196. if (pbrSpecularGlossiness.specularGlossinessTexture !== undefined) {
  33197. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  33198. pending.push(parser.assignTexture(materialParams, 'glossinessMap', specGlossMapDef));
  33199. pending.push(parser.assignTexture(materialParams, 'specularMap', specGlossMapDef));
  33200. }
  33201. return Promise.all(pending);
  33202. },
  33203. createMaterial: function (materialParams) {
  33204. var material = new GLTFMeshStandardSGMaterial(materialParams);
  33205. material.fog = true;
  33206. material.color = materialParams.color;
  33207. material.map = materialParams.map === undefined ? null : materialParams.map;
  33208. material.lightMap = null;
  33209. material.lightMapIntensity = 1.0;
  33210. material.aoMap = materialParams.aoMap === undefined ? null : materialParams.aoMap;
  33211. material.aoMapIntensity = 1.0;
  33212. material.emissive = materialParams.emissive;
  33213. material.emissiveIntensity = 1.0;
  33214. material.emissiveMap = materialParams.emissiveMap === undefined ? null : materialParams.emissiveMap;
  33215. material.bumpMap = materialParams.bumpMap === undefined ? null : materialParams.bumpMap;
  33216. material.bumpScale = 1;
  33217. material.normalMap = materialParams.normalMap === undefined ? null : materialParams.normalMap;
  33218. material.normalMapType = _threeModule.TangentSpaceNormalMap;
  33219. if (materialParams.normalScale) material.normalScale = materialParams.normalScale;
  33220. material.displacementMap = null;
  33221. material.displacementScale = 1;
  33222. material.displacementBias = 0;
  33223. material.specularMap = materialParams.specularMap === undefined ? null : materialParams.specularMap;
  33224. material.specular = materialParams.specular;
  33225. material.glossinessMap = materialParams.glossinessMap === undefined ? null : materialParams.glossinessMap;
  33226. material.glossiness = materialParams.glossiness;
  33227. material.alphaMap = null;
  33228. material.envMap = materialParams.envMap === undefined ? null : materialParams.envMap;
  33229. material.envMapIntensity = 1.0;
  33230. material.refractionRatio = 0.98;
  33231. return material;
  33232. }
  33233. };
  33234. }
  33235. /**
  33236. * Mesh Quantization Extension
  33237. *
  33238. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization
  33239. */
  33240. function GLTFMeshQuantizationExtension() {
  33241. this.name = EXTENSIONS.KHR_MESH_QUANTIZATION;
  33242. }
  33243. /*********************************/
  33244. /********** INTERPOLATION ********/
  33245. /*********************************/
  33246. // Spline Interpolation
  33247. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  33248. function GLTFCubicSplineInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  33249. _threeModule.Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  33250. }
  33251. GLTFCubicSplineInterpolant.prototype = Object.create(_threeModule.Interpolant.prototype);
  33252. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  33253. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function (index) {
  33254. // Copies a sample value to the result buffer. See description of glTF
  33255. // CUBICSPLINE values layout in interpolate_() function below.
  33256. var result = this.resultBuffer,
  33257. values = this.sampleValues,
  33258. valueSize = this.valueSize,
  33259. offset = index * valueSize * 3 + valueSize;
  33260. for (var i = 0; i !== valueSize; i++) {
  33261. result[i] = values[offset + i];
  33262. }
  33263. return result;
  33264. };
  33265. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  33266. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  33267. GLTFCubicSplineInterpolant.prototype.interpolate_ = function (i1, t0, t, t1) {
  33268. var result = this.resultBuffer;
  33269. var values = this.sampleValues;
  33270. var stride = this.valueSize;
  33271. var stride2 = stride * 2;
  33272. var stride3 = stride * 3;
  33273. var td = t1 - t0;
  33274. var p = (t - t0) / td;
  33275. var pp = p * p;
  33276. var ppp = pp * p;
  33277. var offset1 = i1 * stride3;
  33278. var offset0 = offset1 - stride3;
  33279. var s2 = -2 * ppp + 3 * pp;
  33280. var s3 = ppp - pp;
  33281. var s0 = 1 - s2;
  33282. var s1 = s3 - pp + p; // Layout of keyframe output values for CUBICSPLINE animations:
  33283. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  33284. for (var i = 0; i !== stride; i++) {
  33285. var p0 = values[offset0 + i + stride]; // splineVertex_k
  33286. var m0 = values[offset0 + i + stride2] * td; // outTangent_k * (t_k+1 - t_k)
  33287. var p1 = values[offset1 + i + stride]; // splineVertex_k+1
  33288. var m1 = values[offset1 + i] * td; // inTangent_k+1 * (t_k+1 - t_k)
  33289. result[i] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  33290. }
  33291. return result;
  33292. };
  33293. /*********************************/
  33294. /********** INTERNALS ************/
  33295. /*********************************/
  33296. /* CONSTANTS */
  33297. var WEBGL_CONSTANTS = {
  33298. FLOAT: 5126,
  33299. //FLOAT_MAT2: 35674,
  33300. FLOAT_MAT3: 35675,
  33301. FLOAT_MAT4: 35676,
  33302. FLOAT_VEC2: 35664,
  33303. FLOAT_VEC3: 35665,
  33304. FLOAT_VEC4: 35666,
  33305. LINEAR: 9729,
  33306. REPEAT: 10497,
  33307. SAMPLER_2D: 35678,
  33308. POINTS: 0,
  33309. LINES: 1,
  33310. LINE_LOOP: 2,
  33311. LINE_STRIP: 3,
  33312. TRIANGLES: 4,
  33313. TRIANGLE_STRIP: 5,
  33314. TRIANGLE_FAN: 6,
  33315. UNSIGNED_BYTE: 5121,
  33316. UNSIGNED_SHORT: 5123
  33317. };
  33318. var WEBGL_COMPONENT_TYPES = {
  33319. 5120: Int8Array,
  33320. 5121: Uint8Array,
  33321. 5122: Int16Array,
  33322. 5123: Uint16Array,
  33323. 5125: Uint32Array,
  33324. 5126: Float32Array
  33325. };
  33326. var WEBGL_FILTERS = {
  33327. 9728: _threeModule.NearestFilter,
  33328. 9729: _threeModule.LinearFilter,
  33329. 9984: _threeModule.NearestMipmapNearestFilter,
  33330. 9985: _threeModule.LinearMipmapNearestFilter,
  33331. 9986: _threeModule.NearestMipmapLinearFilter,
  33332. 9987: _threeModule.LinearMipmapLinearFilter
  33333. };
  33334. var WEBGL_WRAPPINGS = {
  33335. 33071: _threeModule.ClampToEdgeWrapping,
  33336. 33648: _threeModule.MirroredRepeatWrapping,
  33337. 10497: _threeModule.RepeatWrapping
  33338. };
  33339. var WEBGL_TYPE_SIZES = {
  33340. 'SCALAR': 1,
  33341. 'VEC2': 2,
  33342. 'VEC3': 3,
  33343. 'VEC4': 4,
  33344. 'MAT2': 4,
  33345. 'MAT3': 9,
  33346. 'MAT4': 16
  33347. };
  33348. var ATTRIBUTES = {
  33349. POSITION: 'position',
  33350. NORMAL: 'normal',
  33351. TANGENT: 'tangent',
  33352. TEXCOORD_0: 'uv',
  33353. TEXCOORD_1: 'uv2',
  33354. COLOR_0: 'color',
  33355. WEIGHTS_0: 'skinWeight',
  33356. JOINTS_0: 'skinIndex'
  33357. };
  33358. var PATH_PROPERTIES = {
  33359. scale: 'scale',
  33360. translation: 'position',
  33361. rotation: 'quaternion',
  33362. weights: 'morphTargetInfluences'
  33363. };
  33364. var INTERPOLATION = {
  33365. CUBICSPLINE: undefined,
  33366. // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  33367. // keyframe track will be initialized with a default interpolation type, then modified.
  33368. LINEAR: _threeModule.InterpolateLinear,
  33369. STEP: _threeModule.InterpolateDiscrete
  33370. };
  33371. var ALPHA_MODES = {
  33372. OPAQUE: 'OPAQUE',
  33373. MASK: 'MASK',
  33374. BLEND: 'BLEND'
  33375. };
  33376. /* UTILITY FUNCTIONS */
  33377. function resolveURL(url, path) {
  33378. // Invalid URL
  33379. if (typeof url !== 'string' || url === '') return ''; // Host Relative URL
  33380. if (/^https?:\/\//i.test(path) && /^\//.test(url)) {
  33381. path = path.replace(/(^https?:\/\/[^\/]+).*/i, '$1');
  33382. } // Absolute URL http://,https://,//
  33383. if (/^(https?:)?\/\//i.test(url)) return url; // Data URI
  33384. if (/^data:.*,.*$/i.test(url)) return url; // Blob URL
  33385. if (/^blob:.*$/i.test(url)) return url; // Relative URL
  33386. return path + url;
  33387. }
  33388. /**
  33389. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  33390. */
  33391. function createDefaultMaterial(cache) {
  33392. if (cache['DefaultMaterial'] === undefined) {
  33393. cache['DefaultMaterial'] = new _threeModule.MeshStandardMaterial({
  33394. color: 0xFFFFFF,
  33395. emissive: 0x000000,
  33396. metalness: 1,
  33397. roughness: 1,
  33398. transparent: false,
  33399. depthTest: true,
  33400. side: _threeModule.FrontSide
  33401. });
  33402. }
  33403. return cache['DefaultMaterial'];
  33404. }
  33405. function addUnknownExtensionsToUserData(knownExtensions, object, objectDef) {
  33406. // Add unknown glTF extensions to an object's userData.
  33407. for (var name in objectDef.extensions) {
  33408. if (knownExtensions[name] === undefined) {
  33409. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  33410. object.userData.gltfExtensions[name] = objectDef.extensions[name];
  33411. }
  33412. }
  33413. }
  33414. /**
  33415. * @param {Object3D|Material|BufferGeometry} object
  33416. * @param {GLTF.definition} gltfDef
  33417. */
  33418. function assignExtrasToUserData(object, gltfDef) {
  33419. if (gltfDef.extras !== undefined) {
  33420. if (typeof gltfDef.extras === 'object') {
  33421. Object.assign(object.userData, gltfDef.extras);
  33422. } else {
  33423. console.warn('THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras);
  33424. }
  33425. }
  33426. }
  33427. /**
  33428. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  33429. *
  33430. * @param {BufferGeometry} geometry
  33431. * @param {Array<GLTF.Target>} targets
  33432. * @param {GLTFParser} parser
  33433. * @return {Promise<BufferGeometry>}
  33434. */
  33435. function addMorphTargets(geometry, targets, parser) {
  33436. var hasMorphPosition = false;
  33437. var hasMorphNormal = false;
  33438. for (var i = 0, il = targets.length; i < il; i++) {
  33439. var target = targets[i];
  33440. if (target.POSITION !== undefined) hasMorphPosition = true;
  33441. if (target.NORMAL !== undefined) hasMorphNormal = true;
  33442. if (hasMorphPosition && hasMorphNormal) break;
  33443. }
  33444. if (!hasMorphPosition && !hasMorphNormal) return Promise.resolve(geometry);
  33445. var pendingPositionAccessors = [];
  33446. var pendingNormalAccessors = [];
  33447. for (var i = 0, il = targets.length; i < il; i++) {
  33448. var target = targets[i];
  33449. if (hasMorphPosition) {
  33450. var pendingAccessor = target.POSITION !== undefined ? parser.getDependency('accessor', target.POSITION) : geometry.attributes.position;
  33451. pendingPositionAccessors.push(pendingAccessor);
  33452. }
  33453. if (hasMorphNormal) {
  33454. var pendingAccessor = target.NORMAL !== undefined ? parser.getDependency('accessor', target.NORMAL) : geometry.attributes.normal;
  33455. pendingNormalAccessors.push(pendingAccessor);
  33456. }
  33457. }
  33458. return Promise.all([Promise.all(pendingPositionAccessors), Promise.all(pendingNormalAccessors)]).then(function (accessors) {
  33459. var morphPositions = accessors[0];
  33460. var morphNormals = accessors[1];
  33461. if (hasMorphPosition) geometry.morphAttributes.position = morphPositions;
  33462. if (hasMorphNormal) geometry.morphAttributes.normal = morphNormals;
  33463. geometry.morphTargetsRelative = true;
  33464. return geometry;
  33465. });
  33466. }
  33467. /**
  33468. * @param {Mesh} mesh
  33469. * @param {GLTF.Mesh} meshDef
  33470. */
  33471. function updateMorphTargets(mesh, meshDef) {
  33472. mesh.updateMorphTargets();
  33473. if (meshDef.weights !== undefined) {
  33474. for (var i = 0, il = meshDef.weights.length; i < il; i++) {
  33475. mesh.morphTargetInfluences[i] = meshDef.weights[i];
  33476. }
  33477. } // .extras has user-defined data, so check that .extras.targetNames is an array.
  33478. if (meshDef.extras && Array.isArray(meshDef.extras.targetNames)) {
  33479. var targetNames = meshDef.extras.targetNames;
  33480. if (mesh.morphTargetInfluences.length === targetNames.length) {
  33481. mesh.morphTargetDictionary = {};
  33482. for (var i = 0, il = targetNames.length; i < il; i++) {
  33483. mesh.morphTargetDictionary[targetNames[i]] = i;
  33484. }
  33485. } else {
  33486. console.warn('THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.');
  33487. }
  33488. }
  33489. }
  33490. function createPrimitiveKey(primitiveDef) {
  33491. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION];
  33492. var geometryKey;
  33493. if (dracoExtension) {
  33494. geometryKey = 'draco:' + dracoExtension.bufferView + ':' + dracoExtension.indices + ':' + createAttributesKey(dracoExtension.attributes);
  33495. } else {
  33496. geometryKey = primitiveDef.indices + ':' + createAttributesKey(primitiveDef.attributes) + ':' + primitiveDef.mode;
  33497. }
  33498. return geometryKey;
  33499. }
  33500. function createAttributesKey(attributes) {
  33501. var attributesKey = '';
  33502. var keys = Object.keys(attributes).sort();
  33503. for (var i = 0, il = keys.length; i < il; i++) {
  33504. attributesKey += keys[i] + ':' + attributes[keys[i]] + ';';
  33505. }
  33506. return attributesKey;
  33507. }
  33508. /* GLTF PARSER */
  33509. function GLTFParser(json, options) {
  33510. this.json = json || {};
  33511. this.extensions = {};
  33512. this.plugins = {};
  33513. this.options = options || {}; // loader object cache
  33514. this.cache = new GLTFRegistry(); // associations between Three.js objects and glTF elements
  33515. this.associations = new Map(); // BufferGeometry caching
  33516. this.primitiveCache = {}; // Object3D instance caches
  33517. this.meshCache = {
  33518. refs: {},
  33519. uses: {}
  33520. };
  33521. this.cameraCache = {
  33522. refs: {},
  33523. uses: {}
  33524. };
  33525. this.lightCache = {
  33526. refs: {},
  33527. uses: {}
  33528. }; // Track node names, to ensure no duplicates
  33529. this.nodeNamesUsed = {}; // Use an ImageBitmapLoader if imageBitmaps are supported. Moves much of the
  33530. // expensive work of uploading a texture to the GPU off the main thread.
  33531. if (typeof createImageBitmap !== 'undefined' && /Firefox/.test(navigator.userAgent) === false) {
  33532. this.textureLoader = new _threeModule.ImageBitmapLoader(this.options.manager);
  33533. } else {
  33534. this.textureLoader = new _threeModule.TextureLoader(this.options.manager);
  33535. }
  33536. this.textureLoader.setCrossOrigin(this.options.crossOrigin);
  33537. this.fileLoader = new _threeModule.FileLoader(this.options.manager);
  33538. this.fileLoader.setResponseType('arraybuffer');
  33539. if (this.options.crossOrigin === 'use-credentials') {
  33540. this.fileLoader.setWithCredentials(true);
  33541. }
  33542. }
  33543. GLTFParser.prototype.setExtensions = function (extensions) {
  33544. this.extensions = extensions;
  33545. };
  33546. GLTFParser.prototype.setPlugins = function (plugins) {
  33547. this.plugins = plugins;
  33548. };
  33549. GLTFParser.prototype.parse = function (onLoad, onError) {
  33550. var parser = this;
  33551. var json = this.json;
  33552. var extensions = this.extensions; // Clear the loader cache
  33553. this.cache.removeAll(); // Mark the special nodes/meshes in json for efficient parse
  33554. this._invokeAll(function (ext) {
  33555. return ext._markDefs && ext._markDefs();
  33556. });
  33557. Promise.all([this.getDependencies('scene'), this.getDependencies('animation'), this.getDependencies('camera')]).then(function (dependencies) {
  33558. var result = {
  33559. scene: dependencies[0][json.scene || 0],
  33560. scenes: dependencies[0],
  33561. animations: dependencies[1],
  33562. cameras: dependencies[2],
  33563. asset: json.asset,
  33564. parser: parser,
  33565. userData: {}
  33566. };
  33567. addUnknownExtensionsToUserData(extensions, result, json);
  33568. assignExtrasToUserData(result, json);
  33569. onLoad(result);
  33570. }).catch(onError);
  33571. };
  33572. /**
  33573. * Marks the special nodes/meshes in json for efficient parse.
  33574. */
  33575. GLTFParser.prototype._markDefs = function () {
  33576. var nodeDefs = this.json.nodes || [];
  33577. var skinDefs = this.json.skins || [];
  33578. var meshDefs = this.json.meshes || []; // Nothing in the node definition indicates whether it is a Bone or an
  33579. // Object3D. Use the skins' joint references to mark bones.
  33580. for (var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex++) {
  33581. var joints = skinDefs[skinIndex].joints;
  33582. for (var i = 0, il = joints.length; i < il; i++) {
  33583. nodeDefs[joints[i]].isBone = true;
  33584. }
  33585. } // Iterate over all nodes, marking references to shared resources,
  33586. // as well as skeleton joints.
  33587. for (var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) {
  33588. var nodeDef = nodeDefs[nodeIndex];
  33589. if (nodeDef.mesh !== undefined) {
  33590. this._addNodeRef(this.meshCache, nodeDef.mesh); // Nothing in the mesh definition indicates whether it is
  33591. // a SkinnedMesh or Mesh. Use the node's mesh reference
  33592. // to mark SkinnedMesh if node has skin.
  33593. if (nodeDef.skin !== undefined) {
  33594. meshDefs[nodeDef.mesh].isSkinnedMesh = true;
  33595. }
  33596. }
  33597. if (nodeDef.camera !== undefined) {
  33598. this._addNodeRef(this.cameraCache, nodeDef.camera);
  33599. }
  33600. }
  33601. };
  33602. /**
  33603. * Counts references to shared node / Object3D resources. These resources
  33604. * can be reused, or "instantiated", at multiple nodes in the scene
  33605. * hierarchy. Mesh, Camera, and Light instances are instantiated and must
  33606. * be marked. Non-scenegraph resources (like Materials, Geometries, and
  33607. * Textures) can be reused directly and are not marked here.
  33608. *
  33609. * Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  33610. */
  33611. GLTFParser.prototype._addNodeRef = function (cache, index) {
  33612. if (index === undefined) return;
  33613. if (cache.refs[index] === undefined) {
  33614. cache.refs[index] = cache.uses[index] = 0;
  33615. }
  33616. cache.refs[index]++;
  33617. };
  33618. /** Returns a reference to a shared resource, cloning it if necessary. */
  33619. GLTFParser.prototype._getNodeRef = function (cache, index, object) {
  33620. if (cache.refs[index] <= 1) return object;
  33621. var ref = object.clone();
  33622. ref.name += '_instance_' + cache.uses[index]++;
  33623. return ref;
  33624. };
  33625. GLTFParser.prototype._invokeOne = function (func) {
  33626. var extensions = Object.values(this.plugins);
  33627. extensions.push(this);
  33628. for (var i = 0; i < extensions.length; i++) {
  33629. var result = func(extensions[i]);
  33630. if (result) return result;
  33631. }
  33632. };
  33633. GLTFParser.prototype._invokeAll = function (func) {
  33634. var extensions = Object.values(this.plugins);
  33635. extensions.unshift(this);
  33636. var pending = [];
  33637. for (var i = 0; i < extensions.length; i++) {
  33638. var result = func(extensions[i]);
  33639. if (result) pending.push(result);
  33640. }
  33641. return pending;
  33642. };
  33643. /**
  33644. * Requests the specified dependency asynchronously, with caching.
  33645. * @param {string} type
  33646. * @param {number} index
  33647. * @return {Promise<Object3D|Material|THREE.Texture|AnimationClip|ArrayBuffer|Object>}
  33648. */
  33649. GLTFParser.prototype.getDependency = function (type, index) {
  33650. var cacheKey = type + ':' + index;
  33651. var dependency = this.cache.get(cacheKey);
  33652. if (!dependency) {
  33653. switch (type) {
  33654. case 'scene':
  33655. dependency = this.loadScene(index);
  33656. break;
  33657. case 'node':
  33658. dependency = this.loadNode(index);
  33659. break;
  33660. case 'mesh':
  33661. dependency = this._invokeOne(function (ext) {
  33662. return ext.loadMesh && ext.loadMesh(index);
  33663. });
  33664. break;
  33665. case 'accessor':
  33666. dependency = this.loadAccessor(index);
  33667. break;
  33668. case 'bufferView':
  33669. dependency = this._invokeOne(function (ext) {
  33670. return ext.loadBufferView && ext.loadBufferView(index);
  33671. });
  33672. break;
  33673. case 'buffer':
  33674. dependency = this.loadBuffer(index);
  33675. break;
  33676. case 'material':
  33677. dependency = this._invokeOne(function (ext) {
  33678. return ext.loadMaterial && ext.loadMaterial(index);
  33679. });
  33680. break;
  33681. case 'texture':
  33682. dependency = this._invokeOne(function (ext) {
  33683. return ext.loadTexture && ext.loadTexture(index);
  33684. });
  33685. break;
  33686. case 'skin':
  33687. dependency = this.loadSkin(index);
  33688. break;
  33689. case 'animation':
  33690. dependency = this.loadAnimation(index);
  33691. break;
  33692. case 'camera':
  33693. dependency = this.loadCamera(index);
  33694. break;
  33695. default:
  33696. throw new Error('Unknown type: ' + type);
  33697. }
  33698. this.cache.add(cacheKey, dependency);
  33699. }
  33700. return dependency;
  33701. };
  33702. /**
  33703. * Requests all dependencies of the specified type asynchronously, with caching.
  33704. * @param {string} type
  33705. * @return {Promise<Array<Object>>}
  33706. */
  33707. GLTFParser.prototype.getDependencies = function (type) {
  33708. var dependencies = this.cache.get(type);
  33709. if (!dependencies) {
  33710. var parser = this;
  33711. var defs = this.json[type + (type === 'mesh' ? 'es' : 's')] || [];
  33712. dependencies = Promise.all(defs.map(function (def, index) {
  33713. return parser.getDependency(type, index);
  33714. }));
  33715. this.cache.add(type, dependencies);
  33716. }
  33717. return dependencies;
  33718. };
  33719. /**
  33720. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  33721. * @param {number} bufferIndex
  33722. * @return {Promise<ArrayBuffer>}
  33723. */
  33724. GLTFParser.prototype.loadBuffer = function (bufferIndex) {
  33725. var bufferDef = this.json.buffers[bufferIndex];
  33726. var loader = this.fileLoader;
  33727. if (bufferDef.type && bufferDef.type !== 'arraybuffer') {
  33728. throw new Error('THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.');
  33729. } // If present, GLB container is required to be the first buffer.
  33730. if (bufferDef.uri === undefined && bufferIndex === 0) {
  33731. return Promise.resolve(this.extensions[EXTENSIONS.KHR_BINARY_GLTF].body);
  33732. }
  33733. var options = this.options;
  33734. return new Promise(function (resolve, reject) {
  33735. loader.load(resolveURL(bufferDef.uri, options.path), resolve, undefined, function () {
  33736. reject(new Error('THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".'));
  33737. });
  33738. });
  33739. };
  33740. /**
  33741. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  33742. * @param {number} bufferViewIndex
  33743. * @return {Promise<ArrayBuffer>}
  33744. */
  33745. GLTFParser.prototype.loadBufferView = function (bufferViewIndex) {
  33746. var bufferViewDef = this.json.bufferViews[bufferViewIndex];
  33747. return this.getDependency('buffer', bufferViewDef.buffer).then(function (buffer) {
  33748. var byteLength = bufferViewDef.byteLength || 0;
  33749. var byteOffset = bufferViewDef.byteOffset || 0;
  33750. return buffer.slice(byteOffset, byteOffset + byteLength);
  33751. });
  33752. };
  33753. /**
  33754. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  33755. * @param {number} accessorIndex
  33756. * @return {Promise<BufferAttribute|InterleavedBufferAttribute>}
  33757. */
  33758. GLTFParser.prototype.loadAccessor = function (accessorIndex) {
  33759. var parser = this;
  33760. var json = this.json;
  33761. var accessorDef = this.json.accessors[accessorIndex];
  33762. if (accessorDef.bufferView === undefined && accessorDef.sparse === undefined) {
  33763. // Ignore empty accessors, which may be used to declare runtime
  33764. // information about attributes coming from another source (e.g. Draco
  33765. // compression extension).
  33766. return Promise.resolve(null);
  33767. }
  33768. var pendingBufferViews = [];
  33769. if (accessorDef.bufferView !== undefined) {
  33770. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.bufferView));
  33771. } else {
  33772. pendingBufferViews.push(null);
  33773. }
  33774. if (accessorDef.sparse !== undefined) {
  33775. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.indices.bufferView));
  33776. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.values.bufferView));
  33777. }
  33778. return Promise.all(pendingBufferViews).then(function (bufferViews) {
  33779. var bufferView = bufferViews[0];
  33780. var itemSize = WEBGL_TYPE_SIZES[accessorDef.type];
  33781. var TypedArray = WEBGL_COMPONENT_TYPES[accessorDef.componentType]; // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  33782. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  33783. var itemBytes = elementBytes * itemSize;
  33784. var byteOffset = accessorDef.byteOffset || 0;
  33785. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[accessorDef.bufferView].byteStride : undefined;
  33786. var normalized = accessorDef.normalized === true;
  33787. var array, bufferAttribute; // The buffer is not interleaved if the stride is the item size in bytes.
  33788. if (byteStride && byteStride !== itemBytes) {
  33789. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
  33790. // This makes sure that IBA.count reflects accessor.count properly
  33791. var ibSlice = Math.floor(byteOffset / byteStride);
  33792. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
  33793. var ib = parser.cache.get(ibCacheKey);
  33794. if (!ib) {
  33795. array = new TypedArray(bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes); // Integer parameters to IB/IBA are in array elements, not bytes.
  33796. ib = new _threeModule.InterleavedBuffer(array, byteStride / elementBytes);
  33797. parser.cache.add(ibCacheKey, ib);
  33798. }
  33799. bufferAttribute = new _threeModule.InterleavedBufferAttribute(ib, itemSize, byteOffset % byteStride / elementBytes, normalized);
  33800. } else {
  33801. if (bufferView === null) {
  33802. array = new TypedArray(accessorDef.count * itemSize);
  33803. } else {
  33804. array = new TypedArray(bufferView, byteOffset, accessorDef.count * itemSize);
  33805. }
  33806. bufferAttribute = new _threeModule.BufferAttribute(array, itemSize, normalized);
  33807. } // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  33808. if (accessorDef.sparse !== undefined) {
  33809. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  33810. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[accessorDef.sparse.indices.componentType];
  33811. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  33812. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  33813. var sparseIndices = new TypedArrayIndices(bufferViews[1], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices);
  33814. var sparseValues = new TypedArray(bufferViews[2], byteOffsetValues, accessorDef.sparse.count * itemSize);
  33815. if (bufferView !== null) {
  33816. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  33817. bufferAttribute = new _threeModule.BufferAttribute(bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized);
  33818. }
  33819. for (var i = 0, il = sparseIndices.length; i < il; i++) {
  33820. var index = sparseIndices[i];
  33821. bufferAttribute.setX(index, sparseValues[i * itemSize]);
  33822. if (itemSize >= 2) bufferAttribute.setY(index, sparseValues[i * itemSize + 1]);
  33823. if (itemSize >= 3) bufferAttribute.setZ(index, sparseValues[i * itemSize + 2]);
  33824. if (itemSize >= 4) bufferAttribute.setW(index, sparseValues[i * itemSize + 3]);
  33825. if (itemSize >= 5) throw new Error('THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.');
  33826. }
  33827. }
  33828. return bufferAttribute;
  33829. });
  33830. };
  33831. /**
  33832. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  33833. * @param {number} textureIndex
  33834. * @return {Promise<THREE.Texture>}
  33835. */
  33836. GLTFParser.prototype.loadTexture = function (textureIndex) {
  33837. var parser = this;
  33838. var json = this.json;
  33839. var options = this.options;
  33840. var textureDef = json.textures[textureIndex];
  33841. var textureExtensions = textureDef.extensions || {};
  33842. var source;
  33843. if (textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS]) {
  33844. source = json.images[textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS].source];
  33845. } else {
  33846. source = json.images[textureDef.source];
  33847. }
  33848. var loader;
  33849. if (source.uri) {
  33850. loader = options.manager.getHandler(source.uri);
  33851. }
  33852. if (!loader) {
  33853. loader = textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS] ? parser.extensions[EXTENSIONS.MSFT_TEXTURE_DDS].ddsLoader : this.textureLoader;
  33854. }
  33855. return this.loadTextureImage(textureIndex, source, loader);
  33856. };
  33857. GLTFParser.prototype.loadTextureImage = function (textureIndex, source, loader) {
  33858. var parser = this;
  33859. var json = this.json;
  33860. var options = this.options;
  33861. var textureDef = json.textures[textureIndex];
  33862. var URL = self.URL || self.webkitURL;
  33863. var sourceURI = source.uri;
  33864. var isObjectURL = false;
  33865. var hasAlpha = true;
  33866. if (source.mimeType === 'image/jpeg') hasAlpha = false;
  33867. if (source.bufferView !== undefined) {
  33868. // Load binary image data from bufferView, if provided.
  33869. sourceURI = parser.getDependency('bufferView', source.bufferView).then(function (bufferView) {
  33870. if (source.mimeType === 'image/png') {
  33871. // Inspect the PNG 'IHDR' chunk to determine whether the image could have an
  33872. // alpha channel. This check is conservative — the image could have an alpha
  33873. // channel with all values == 1, and the indexed type (colorType == 3) only
  33874. // sometimes contains alpha.
  33875. //
  33876. // https://en.wikipedia.org/wiki/Portable_Network_Graphics#File_header
  33877. var colorType = new DataView(bufferView, 25, 1).getUint8(0, false);
  33878. hasAlpha = colorType === 6 || colorType === 4 || colorType === 3;
  33879. }
  33880. isObjectURL = true;
  33881. var blob = new Blob([bufferView], {
  33882. type: source.mimeType
  33883. });
  33884. sourceURI = URL.createObjectURL(blob);
  33885. return sourceURI;
  33886. });
  33887. }
  33888. return Promise.resolve(sourceURI).then(function (sourceURI) {
  33889. return new Promise(function (resolve, reject) {
  33890. var onLoad = resolve;
  33891. if (loader.isImageBitmapLoader === true) {
  33892. onLoad = function (imageBitmap) {
  33893. resolve(new _threeModule.CanvasTexture(imageBitmap));
  33894. };
  33895. }
  33896. loader.load(resolveURL(sourceURI, options.path), onLoad, undefined, reject);
  33897. });
  33898. }).then(function (texture) {
  33899. // Clean up resources and configure Texture.
  33900. if (isObjectURL === true) {
  33901. URL.revokeObjectURL(sourceURI);
  33902. }
  33903. texture.flipY = false;
  33904. if (textureDef.name) texture.name = textureDef.name; // When there is definitely no alpha channel in the texture, set RGBFormat to save space.
  33905. if (!hasAlpha) texture.format = _threeModule.RGBFormat;
  33906. var samplers = json.samplers || {};
  33907. var sampler = samplers[textureDef.sampler] || {};
  33908. texture.magFilter = WEBGL_FILTERS[sampler.magFilter] || _threeModule.LinearFilter;
  33909. texture.minFilter = WEBGL_FILTERS[sampler.minFilter] || _threeModule.LinearMipmapLinearFilter;
  33910. texture.wrapS = WEBGL_WRAPPINGS[sampler.wrapS] || _threeModule.RepeatWrapping;
  33911. texture.wrapT = WEBGL_WRAPPINGS[sampler.wrapT] || _threeModule.RepeatWrapping;
  33912. parser.associations.set(texture, {
  33913. type: 'textures',
  33914. index: textureIndex
  33915. });
  33916. return texture;
  33917. });
  33918. };
  33919. /**
  33920. * Asynchronously assigns a texture to the given material parameters.
  33921. * @param {Object} materialParams
  33922. * @param {string} mapName
  33923. * @param {Object} mapDef
  33924. * @return {Promise}
  33925. */
  33926. GLTFParser.prototype.assignTexture = function (materialParams, mapName, mapDef) {
  33927. var parser = this;
  33928. return this.getDependency('texture', mapDef.index).then(function (texture) {
  33929. // Materials sample aoMap from UV set 1 and other maps from UV set 0 - this can't be configured
  33930. // However, we will copy UV set 0 to UV set 1 on demand for aoMap
  33931. if (mapDef.texCoord !== undefined && mapDef.texCoord != 0 && !(mapName === 'aoMap' && mapDef.texCoord == 1)) {
  33932. console.warn('THREE.GLTFLoader: Custom UV set ' + mapDef.texCoord + ' for texture ' + mapName + ' not yet supported.');
  33933. }
  33934. if (parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM]) {
  33935. var transform = mapDef.extensions !== undefined ? mapDef.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] : undefined;
  33936. if (transform) {
  33937. var gltfReference = parser.associations.get(texture);
  33938. texture = parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM].extendTexture(texture, transform);
  33939. parser.associations.set(texture, gltfReference);
  33940. }
  33941. }
  33942. materialParams[mapName] = texture;
  33943. });
  33944. };
  33945. /**
  33946. * Assigns final material to a Mesh, Line, or Points instance. The instance
  33947. * already has a material (generated from the glTF material options alone)
  33948. * but reuse of the same glTF material may require multiple threejs materials
  33949. * to accomodate different primitive types, defines, etc. New materials will
  33950. * be created if necessary, and reused from a cache.
  33951. * @param {Object3D} mesh Mesh, Line, or Points instance.
  33952. */
  33953. GLTFParser.prototype.assignFinalMaterial = function (mesh) {
  33954. var geometry = mesh.geometry;
  33955. var material = mesh.material;
  33956. var useVertexTangents = geometry.attributes.tangent !== undefined;
  33957. var useVertexColors = geometry.attributes.color !== undefined;
  33958. var useFlatShading = geometry.attributes.normal === undefined;
  33959. var useSkinning = mesh.isSkinnedMesh === true;
  33960. var useMorphTargets = Object.keys(geometry.morphAttributes).length > 0;
  33961. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  33962. if (mesh.isPoints) {
  33963. var cacheKey = 'PointsMaterial:' + material.uuid;
  33964. var pointsMaterial = this.cache.get(cacheKey);
  33965. if (!pointsMaterial) {
  33966. pointsMaterial = new _threeModule.PointsMaterial();
  33967. _threeModule.Material.prototype.copy.call(pointsMaterial, material);
  33968. pointsMaterial.color.copy(material.color);
  33969. pointsMaterial.map = material.map;
  33970. pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
  33971. this.cache.add(cacheKey, pointsMaterial);
  33972. }
  33973. material = pointsMaterial;
  33974. } else if (mesh.isLine) {
  33975. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  33976. var lineMaterial = this.cache.get(cacheKey);
  33977. if (!lineMaterial) {
  33978. lineMaterial = new _threeModule.LineBasicMaterial();
  33979. _threeModule.Material.prototype.copy.call(lineMaterial, material);
  33980. lineMaterial.color.copy(material.color);
  33981. this.cache.add(cacheKey, lineMaterial);
  33982. }
  33983. material = lineMaterial;
  33984. } // Clone the material if it will be modified
  33985. if (useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets) {
  33986. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  33987. if (material.isGLTFSpecularGlossinessMaterial) cacheKey += 'specular-glossiness:';
  33988. if (useSkinning) cacheKey += 'skinning:';
  33989. if (useVertexTangents) cacheKey += 'vertex-tangents:';
  33990. if (useVertexColors) cacheKey += 'vertex-colors:';
  33991. if (useFlatShading) cacheKey += 'flat-shading:';
  33992. if (useMorphTargets) cacheKey += 'morph-targets:';
  33993. if (useMorphNormals) cacheKey += 'morph-normals:';
  33994. var cachedMaterial = this.cache.get(cacheKey);
  33995. if (!cachedMaterial) {
  33996. cachedMaterial = material.clone();
  33997. if (useSkinning) cachedMaterial.skinning = true;
  33998. if (useVertexTangents) cachedMaterial.vertexTangents = true;
  33999. if (useVertexColors) cachedMaterial.vertexColors = true;
  34000. if (useFlatShading) cachedMaterial.flatShading = true;
  34001. if (useMorphTargets) cachedMaterial.morphTargets = true;
  34002. if (useMorphNormals) cachedMaterial.morphNormals = true;
  34003. this.cache.add(cacheKey, cachedMaterial);
  34004. this.associations.set(cachedMaterial, this.associations.get(material));
  34005. }
  34006. material = cachedMaterial;
  34007. } // workarounds for mesh and geometry
  34008. if (material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined) {
  34009. geometry.setAttribute('uv2', geometry.attributes.uv);
  34010. } // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  34011. if (material.normalScale && !useVertexTangents) {
  34012. material.normalScale.y = -material.normalScale.y;
  34013. }
  34014. if (material.clearcoatNormalScale && !useVertexTangents) {
  34015. material.clearcoatNormalScale.y = -material.clearcoatNormalScale.y;
  34016. }
  34017. mesh.material = material;
  34018. };
  34019. GLTFParser.prototype.getMaterialType = function ()
  34020. /* materialIndex */
  34021. {
  34022. return _threeModule.MeshStandardMaterial;
  34023. };
  34024. /**
  34025. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  34026. * @param {number} materialIndex
  34027. * @return {Promise<Material>}
  34028. */
  34029. GLTFParser.prototype.loadMaterial = function (materialIndex) {
  34030. var parser = this;
  34031. var json = this.json;
  34032. var extensions = this.extensions;
  34033. var materialDef = json.materials[materialIndex];
  34034. var materialType;
  34035. var materialParams = {};
  34036. var materialExtensions = materialDef.extensions || {};
  34037. var pending = [];
  34038. if (materialExtensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS]) {
  34039. var sgExtension = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS];
  34040. materialType = sgExtension.getMaterialType();
  34041. pending.push(sgExtension.extendParams(materialParams, materialDef, parser));
  34042. } else if (materialExtensions[EXTENSIONS.KHR_MATERIALS_UNLIT]) {
  34043. var kmuExtension = extensions[EXTENSIONS.KHR_MATERIALS_UNLIT];
  34044. materialType = kmuExtension.getMaterialType();
  34045. pending.push(kmuExtension.extendParams(materialParams, materialDef, parser));
  34046. } else {
  34047. // Specification:
  34048. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  34049. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  34050. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  34051. materialParams.opacity = 1.0;
  34052. if (Array.isArray(metallicRoughness.baseColorFactor)) {
  34053. var array = metallicRoughness.baseColorFactor;
  34054. materialParams.color.fromArray(array);
  34055. materialParams.opacity = array[3];
  34056. }
  34057. if (metallicRoughness.baseColorTexture !== undefined) {
  34058. pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture));
  34059. }
  34060. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  34061. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  34062. if (metallicRoughness.metallicRoughnessTexture !== undefined) {
  34063. pending.push(parser.assignTexture(materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture));
  34064. pending.push(parser.assignTexture(materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture));
  34065. }
  34066. materialType = this._invokeOne(function (ext) {
  34067. return ext.getMaterialType && ext.getMaterialType(materialIndex);
  34068. });
  34069. pending.push(Promise.all(this._invokeAll(function (ext) {
  34070. return ext.extendMaterialParams && ext.extendMaterialParams(materialIndex, materialParams);
  34071. })));
  34072. }
  34073. if (materialDef.doubleSided === true) {
  34074. materialParams.side = _threeModule.DoubleSide;
  34075. }
  34076. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  34077. if (alphaMode === ALPHA_MODES.BLEND) {
  34078. materialParams.transparent = true; // See: https://github.com/mrdoob/three.js/issues/17706
  34079. materialParams.depthWrite = false;
  34080. } else {
  34081. materialParams.transparent = false;
  34082. if (alphaMode === ALPHA_MODES.MASK) {
  34083. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  34084. }
  34085. }
  34086. if (materialDef.normalTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  34087. pending.push(parser.assignTexture(materialParams, 'normalMap', materialDef.normalTexture));
  34088. materialParams.normalScale = new _threeModule.Vector2(1, 1);
  34089. if (materialDef.normalTexture.scale !== undefined) {
  34090. materialParams.normalScale.set(materialDef.normalTexture.scale, materialDef.normalTexture.scale);
  34091. }
  34092. }
  34093. if (materialDef.occlusionTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  34094. pending.push(parser.assignTexture(materialParams, 'aoMap', materialDef.occlusionTexture));
  34095. if (materialDef.occlusionTexture.strength !== undefined) {
  34096. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  34097. }
  34098. }
  34099. if (materialDef.emissiveFactor !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  34100. materialParams.emissive = new _threeModule.Color().fromArray(materialDef.emissiveFactor);
  34101. }
  34102. if (materialDef.emissiveTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  34103. pending.push(parser.assignTexture(materialParams, 'emissiveMap', materialDef.emissiveTexture));
  34104. }
  34105. return Promise.all(pending).then(function () {
  34106. var material;
  34107. if (materialType === GLTFMeshStandardSGMaterial) {
  34108. material = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].createMaterial(materialParams);
  34109. } else {
  34110. material = new materialType(materialParams);
  34111. }
  34112. if (materialDef.name) material.name = materialDef.name; // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  34113. if (material.map) material.map.encoding = _threeModule.sRGBEncoding;
  34114. if (material.emissiveMap) material.emissiveMap.encoding = _threeModule.sRGBEncoding;
  34115. assignExtrasToUserData(material, materialDef);
  34116. parser.associations.set(material, {
  34117. type: 'materials',
  34118. index: materialIndex
  34119. });
  34120. if (materialDef.extensions) addUnknownExtensionsToUserData(extensions, material, materialDef);
  34121. return material;
  34122. });
  34123. };
  34124. /** When Object3D instances are targeted by animation, they need unique names. */
  34125. GLTFParser.prototype.createUniqueName = function (originalName) {
  34126. var name = _threeModule.PropertyBinding.sanitizeNodeName(originalName || '');
  34127. for (var i = 1; this.nodeNamesUsed[name]; ++i) {
  34128. name = originalName + '_' + i;
  34129. }
  34130. this.nodeNamesUsed[name] = true;
  34131. return name;
  34132. };
  34133. /**
  34134. * @param {BufferGeometry} geometry
  34135. * @param {GLTF.Primitive} primitiveDef
  34136. * @param {GLTFParser} parser
  34137. */
  34138. function computeBounds(geometry, primitiveDef, parser) {
  34139. var attributes = primitiveDef.attributes;
  34140. var box = new _threeModule.Box3();
  34141. if (attributes.POSITION !== undefined) {
  34142. var accessor = parser.json.accessors[attributes.POSITION];
  34143. var min = accessor.min;
  34144. var max = accessor.max; // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  34145. if (min !== undefined && max !== undefined) {
  34146. box.set(new _threeModule.Vector3(min[0], min[1], min[2]), new _threeModule.Vector3(max[0], max[1], max[2]));
  34147. } else {
  34148. console.warn('THREE.GLTFLoader: Missing min/max properties for accessor POSITION.');
  34149. return;
  34150. }
  34151. } else {
  34152. return;
  34153. }
  34154. var targets = primitiveDef.targets;
  34155. if (targets !== undefined) {
  34156. var maxDisplacement = new _threeModule.Vector3();
  34157. var vector = new _threeModule.Vector3();
  34158. for (var i = 0, il = targets.length; i < il; i++) {
  34159. var target = targets[i];
  34160. if (target.POSITION !== undefined) {
  34161. var accessor = parser.json.accessors[target.POSITION];
  34162. var min = accessor.min;
  34163. var max = accessor.max; // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  34164. if (min !== undefined && max !== undefined) {
  34165. // we need to get max of absolute components because target weight is [-1,1]
  34166. vector.setX(Math.max(Math.abs(min[0]), Math.abs(max[0])));
  34167. vector.setY(Math.max(Math.abs(min[1]), Math.abs(max[1])));
  34168. vector.setZ(Math.max(Math.abs(min[2]), Math.abs(max[2]))); // Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative
  34169. // to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets
  34170. // are used to implement key-frame animations and as such only two are active at a time - this results in very large
  34171. // boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size.
  34172. maxDisplacement.max(vector);
  34173. } else {
  34174. console.warn('THREE.GLTFLoader: Missing min/max properties for accessor POSITION.');
  34175. }
  34176. }
  34177. } // As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets.
  34178. box.expandByVector(maxDisplacement);
  34179. }
  34180. geometry.boundingBox = box;
  34181. var sphere = new _threeModule.Sphere();
  34182. box.getCenter(sphere.center);
  34183. sphere.radius = box.min.distanceTo(box.max) / 2;
  34184. geometry.boundingSphere = sphere;
  34185. }
  34186. /**
  34187. * @param {BufferGeometry} geometry
  34188. * @param {GLTF.Primitive} primitiveDef
  34189. * @param {GLTFParser} parser
  34190. * @return {Promise<BufferGeometry>}
  34191. */
  34192. function addPrimitiveAttributes(geometry, primitiveDef, parser) {
  34193. var attributes = primitiveDef.attributes;
  34194. var pending = [];
  34195. function assignAttributeAccessor(accessorIndex, attributeName) {
  34196. return parser.getDependency('accessor', accessorIndex).then(function (accessor) {
  34197. geometry.setAttribute(attributeName, accessor);
  34198. });
  34199. }
  34200. for (var gltfAttributeName in attributes) {
  34201. var threeAttributeName = ATTRIBUTES[gltfAttributeName] || gltfAttributeName.toLowerCase(); // Skip attributes already provided by e.g. Draco extension.
  34202. if (threeAttributeName in geometry.attributes) continue;
  34203. pending.push(assignAttributeAccessor(attributes[gltfAttributeName], threeAttributeName));
  34204. }
  34205. if (primitiveDef.indices !== undefined && !geometry.index) {
  34206. var accessor = parser.getDependency('accessor', primitiveDef.indices).then(function (accessor) {
  34207. geometry.setIndex(accessor);
  34208. });
  34209. pending.push(accessor);
  34210. }
  34211. assignExtrasToUserData(geometry, primitiveDef);
  34212. computeBounds(geometry, primitiveDef, parser);
  34213. return Promise.all(pending).then(function () {
  34214. return primitiveDef.targets !== undefined ? addMorphTargets(geometry, primitiveDef.targets, parser) : geometry;
  34215. });
  34216. }
  34217. /**
  34218. * @param {BufferGeometry} geometry
  34219. * @param {Number} drawMode
  34220. * @return {BufferGeometry}
  34221. */
  34222. function toTrianglesDrawMode(geometry, drawMode) {
  34223. var index = geometry.getIndex(); // generate index if not present
  34224. if (index === null) {
  34225. var indices = [];
  34226. var position = geometry.getAttribute('position');
  34227. if (position !== undefined) {
  34228. for (var i = 0; i < position.count; i++) {
  34229. indices.push(i);
  34230. }
  34231. geometry.setIndex(indices);
  34232. index = geometry.getIndex();
  34233. } else {
  34234. console.error('THREE.GLTFLoader.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.');
  34235. return geometry;
  34236. }
  34237. } //
  34238. var numberOfTriangles = index.count - 2;
  34239. var newIndices = [];
  34240. if (drawMode === _threeModule.TriangleFanDrawMode) {
  34241. // gl.TRIANGLE_FAN
  34242. for (var i = 1; i <= numberOfTriangles; i++) {
  34243. newIndices.push(index.getX(0));
  34244. newIndices.push(index.getX(i));
  34245. newIndices.push(index.getX(i + 1));
  34246. }
  34247. } else {
  34248. // gl.TRIANGLE_STRIP
  34249. for (var i = 0; i < numberOfTriangles; i++) {
  34250. if (i % 2 === 0) {
  34251. newIndices.push(index.getX(i));
  34252. newIndices.push(index.getX(i + 1));
  34253. newIndices.push(index.getX(i + 2));
  34254. } else {
  34255. newIndices.push(index.getX(i + 2));
  34256. newIndices.push(index.getX(i + 1));
  34257. newIndices.push(index.getX(i));
  34258. }
  34259. }
  34260. }
  34261. if (newIndices.length / 3 !== numberOfTriangles) {
  34262. console.error('THREE.GLTFLoader.toTrianglesDrawMode(): Unable to generate correct amount of triangles.');
  34263. } // build final geometry
  34264. var newGeometry = geometry.clone();
  34265. newGeometry.setIndex(newIndices);
  34266. return newGeometry;
  34267. }
  34268. /**
  34269. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  34270. *
  34271. * Creates BufferGeometries from primitives.
  34272. *
  34273. * @param {Array<GLTF.Primitive>} primitives
  34274. * @return {Promise<Array<BufferGeometry>>}
  34275. */
  34276. GLTFParser.prototype.loadGeometries = function (primitives) {
  34277. var parser = this;
  34278. var extensions = this.extensions;
  34279. var cache = this.primitiveCache;
  34280. function createDracoPrimitive(primitive) {
  34281. return extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(primitive, parser).then(function (geometry) {
  34282. return addPrimitiveAttributes(geometry, primitive, parser);
  34283. });
  34284. }
  34285. var pending = [];
  34286. for (var i = 0, il = primitives.length; i < il; i++) {
  34287. var primitive = primitives[i];
  34288. var cacheKey = createPrimitiveKey(primitive); // See if we've already created this geometry
  34289. var cached = cache[cacheKey];
  34290. if (cached) {
  34291. // Use the cached geometry if it exists
  34292. pending.push(cached.promise);
  34293. } else {
  34294. var geometryPromise;
  34295. if (primitive.extensions && primitive.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]) {
  34296. // Use DRACO geometry if available
  34297. geometryPromise = createDracoPrimitive(primitive);
  34298. } else {
  34299. // Otherwise create a new geometry
  34300. geometryPromise = addPrimitiveAttributes(new _threeModule.BufferGeometry(), primitive, parser);
  34301. } // Cache this geometry
  34302. cache[cacheKey] = {
  34303. primitive: primitive,
  34304. promise: geometryPromise
  34305. };
  34306. pending.push(geometryPromise);
  34307. }
  34308. }
  34309. return Promise.all(pending);
  34310. };
  34311. /**
  34312. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  34313. * @param {number} meshIndex
  34314. * @return {Promise<Group|Mesh|SkinnedMesh>}
  34315. */
  34316. GLTFParser.prototype.loadMesh = function (meshIndex) {
  34317. var parser = this;
  34318. var json = this.json;
  34319. var extensions = this.extensions;
  34320. var meshDef = json.meshes[meshIndex];
  34321. var primitives = meshDef.primitives;
  34322. var pending = [];
  34323. for (var i = 0, il = primitives.length; i < il; i++) {
  34324. var material = primitives[i].material === undefined ? createDefaultMaterial(this.cache) : this.getDependency('material', primitives[i].material);
  34325. pending.push(material);
  34326. }
  34327. pending.push(parser.loadGeometries(primitives));
  34328. return Promise.all(pending).then(function (results) {
  34329. var materials = results.slice(0, results.length - 1);
  34330. var geometries = results[results.length - 1];
  34331. var meshes = [];
  34332. for (var i = 0, il = geometries.length; i < il; i++) {
  34333. var geometry = geometries[i];
  34334. var primitive = primitives[i]; // 1. create Mesh
  34335. var mesh;
  34336. var material = materials[i];
  34337. if (primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN || primitive.mode === undefined) {
  34338. // .isSkinnedMesh isn't in glTF spec. See ._markDefs()
  34339. mesh = meshDef.isSkinnedMesh === true ? new _threeModule.SkinnedMesh(geometry, material) : new _threeModule.Mesh(geometry, material);
  34340. if (mesh.isSkinnedMesh === true && !mesh.geometry.attributes.skinWeight.normalized) {
  34341. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  34342. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  34343. mesh.normalizeSkinWeights();
  34344. }
  34345. if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP) {
  34346. mesh.geometry = toTrianglesDrawMode(mesh.geometry, _threeModule.TriangleStripDrawMode);
  34347. } else if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN) {
  34348. mesh.geometry = toTrianglesDrawMode(mesh.geometry, _threeModule.TriangleFanDrawMode);
  34349. }
  34350. } else if (primitive.mode === WEBGL_CONSTANTS.LINES) {
  34351. mesh = new _threeModule.LineSegments(geometry, material);
  34352. } else if (primitive.mode === WEBGL_CONSTANTS.LINE_STRIP) {
  34353. mesh = new _threeModule.Line(geometry, material);
  34354. } else if (primitive.mode === WEBGL_CONSTANTS.LINE_LOOP) {
  34355. mesh = new _threeModule.LineLoop(geometry, material);
  34356. } else if (primitive.mode === WEBGL_CONSTANTS.POINTS) {
  34357. mesh = new _threeModule.Points(geometry, material);
  34358. } else {
  34359. throw new Error('THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode);
  34360. }
  34361. if (Object.keys(mesh.geometry.morphAttributes).length > 0) {
  34362. updateMorphTargets(mesh, meshDef);
  34363. }
  34364. mesh.name = parser.createUniqueName(meshDef.name || 'mesh_' + meshIndex);
  34365. assignExtrasToUserData(mesh, meshDef);
  34366. if (primitive.extensions) addUnknownExtensionsToUserData(extensions, mesh, primitive);
  34367. parser.assignFinalMaterial(mesh);
  34368. meshes.push(mesh);
  34369. }
  34370. if (meshes.length === 1) {
  34371. return meshes[0];
  34372. }
  34373. var group = new _threeModule.Group();
  34374. for (var i = 0, il = meshes.length; i < il; i++) {
  34375. group.add(meshes[i]);
  34376. }
  34377. return group;
  34378. });
  34379. };
  34380. /**
  34381. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  34382. * @param {number} cameraIndex
  34383. * @return {Promise<THREE.Camera>}
  34384. */
  34385. GLTFParser.prototype.loadCamera = function (cameraIndex) {
  34386. var camera;
  34387. var cameraDef = this.json.cameras[cameraIndex];
  34388. var params = cameraDef[cameraDef.type];
  34389. if (!params) {
  34390. console.warn('THREE.GLTFLoader: Missing camera parameters.');
  34391. return;
  34392. }
  34393. if (cameraDef.type === 'perspective') {
  34394. camera = new _threeModule.PerspectiveCamera(_threeModule.MathUtils.radToDeg(params.yfov), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6);
  34395. } else if (cameraDef.type === 'orthographic') {
  34396. camera = new _threeModule.OrthographicCamera(-params.xmag, params.xmag, params.ymag, -params.ymag, params.znear, params.zfar);
  34397. }
  34398. if (cameraDef.name) camera.name = this.createUniqueName(cameraDef.name);
  34399. assignExtrasToUserData(camera, cameraDef);
  34400. return Promise.resolve(camera);
  34401. };
  34402. /**
  34403. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  34404. * @param {number} skinIndex
  34405. * @return {Promise<Object>}
  34406. */
  34407. GLTFParser.prototype.loadSkin = function (skinIndex) {
  34408. var skinDef = this.json.skins[skinIndex];
  34409. var skinEntry = {
  34410. joints: skinDef.joints
  34411. };
  34412. if (skinDef.inverseBindMatrices === undefined) {
  34413. return Promise.resolve(skinEntry);
  34414. }
  34415. return this.getDependency('accessor', skinDef.inverseBindMatrices).then(function (accessor) {
  34416. skinEntry.inverseBindMatrices = accessor;
  34417. return skinEntry;
  34418. });
  34419. };
  34420. /**
  34421. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  34422. * @param {number} animationIndex
  34423. * @return {Promise<AnimationClip>}
  34424. */
  34425. GLTFParser.prototype.loadAnimation = function (animationIndex) {
  34426. var json = this.json;
  34427. var animationDef = json.animations[animationIndex];
  34428. var pendingNodes = [];
  34429. var pendingInputAccessors = [];
  34430. var pendingOutputAccessors = [];
  34431. var pendingSamplers = [];
  34432. var pendingTargets = [];
  34433. for (var i = 0, il = animationDef.channels.length; i < il; i++) {
  34434. var channel = animationDef.channels[i];
  34435. var sampler = animationDef.samplers[channel.sampler];
  34436. var target = channel.target;
  34437. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  34438. var input = animationDef.parameters !== undefined ? animationDef.parameters[sampler.input] : sampler.input;
  34439. var output = animationDef.parameters !== undefined ? animationDef.parameters[sampler.output] : sampler.output;
  34440. pendingNodes.push(this.getDependency('node', name));
  34441. pendingInputAccessors.push(this.getDependency('accessor', input));
  34442. pendingOutputAccessors.push(this.getDependency('accessor', output));
  34443. pendingSamplers.push(sampler);
  34444. pendingTargets.push(target);
  34445. }
  34446. return Promise.all([Promise.all(pendingNodes), Promise.all(pendingInputAccessors), Promise.all(pendingOutputAccessors), Promise.all(pendingSamplers), Promise.all(pendingTargets)]).then(function (dependencies) {
  34447. var nodes = dependencies[0];
  34448. var inputAccessors = dependencies[1];
  34449. var outputAccessors = dependencies[2];
  34450. var samplers = dependencies[3];
  34451. var targets = dependencies[4];
  34452. var tracks = [];
  34453. for (var i = 0, il = nodes.length; i < il; i++) {
  34454. var node = nodes[i];
  34455. var inputAccessor = inputAccessors[i];
  34456. var outputAccessor = outputAccessors[i];
  34457. var sampler = samplers[i];
  34458. var target = targets[i];
  34459. if (node === undefined) continue;
  34460. node.updateMatrix();
  34461. node.matrixAutoUpdate = true;
  34462. var TypedKeyframeTrack;
  34463. switch (PATH_PROPERTIES[target.path]) {
  34464. case PATH_PROPERTIES.weights:
  34465. TypedKeyframeTrack = _threeModule.NumberKeyframeTrack;
  34466. break;
  34467. case PATH_PROPERTIES.rotation:
  34468. TypedKeyframeTrack = _threeModule.QuaternionKeyframeTrack;
  34469. break;
  34470. case PATH_PROPERTIES.position:
  34471. case PATH_PROPERTIES.scale:
  34472. default:
  34473. TypedKeyframeTrack = _threeModule.VectorKeyframeTrack;
  34474. break;
  34475. }
  34476. var targetName = node.name ? node.name : node.uuid;
  34477. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[sampler.interpolation] : _threeModule.InterpolateLinear;
  34478. var targetNames = [];
  34479. if (PATH_PROPERTIES[target.path] === PATH_PROPERTIES.weights) {
  34480. // Node may be a Group (glTF mesh with several primitives) or a Mesh.
  34481. node.traverse(function (object) {
  34482. if (object.isMesh === true && object.morphTargetInfluences) {
  34483. targetNames.push(object.name ? object.name : object.uuid);
  34484. }
  34485. });
  34486. } else {
  34487. targetNames.push(targetName);
  34488. }
  34489. var outputArray = outputAccessor.array;
  34490. if (outputAccessor.normalized) {
  34491. var scale;
  34492. if (outputArray.constructor === Int8Array) {
  34493. scale = 1 / 127;
  34494. } else if (outputArray.constructor === Uint8Array) {
  34495. scale = 1 / 255;
  34496. } else if (outputArray.constructor == Int16Array) {
  34497. scale = 1 / 32767;
  34498. } else if (outputArray.constructor === Uint16Array) {
  34499. scale = 1 / 65535;
  34500. } else {
  34501. throw new Error('THREE.GLTFLoader: Unsupported output accessor component type.');
  34502. }
  34503. var scaled = new Float32Array(outputArray.length);
  34504. for (var j = 0, jl = outputArray.length; j < jl; j++) {
  34505. scaled[j] = outputArray[j] * scale;
  34506. }
  34507. outputArray = scaled;
  34508. }
  34509. for (var j = 0, jl = targetNames.length; j < jl; j++) {
  34510. var track = new TypedKeyframeTrack(targetNames[j] + '.' + PATH_PROPERTIES[target.path], inputAccessor.array, outputArray, interpolation); // Override interpolation with custom factory method.
  34511. if (sampler.interpolation === 'CUBICSPLINE') {
  34512. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline(result) {
  34513. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  34514. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  34515. // must be divided by three to get the interpolant's sampleSize argument.
  34516. return new GLTFCubicSplineInterpolant(this.times, this.values, this.getValueSize() / 3, result);
  34517. }; // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  34518. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  34519. }
  34520. tracks.push(track);
  34521. }
  34522. }
  34523. var name = animationDef.name ? animationDef.name : 'animation_' + animationIndex;
  34524. return new _threeModule.AnimationClip(name, undefined, tracks);
  34525. });
  34526. };
  34527. /**
  34528. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  34529. * @param {number} nodeIndex
  34530. * @return {Promise<Object3D>}
  34531. */
  34532. GLTFParser.prototype.loadNode = function (nodeIndex) {
  34533. var json = this.json;
  34534. var extensions = this.extensions;
  34535. var parser = this;
  34536. var nodeDef = json.nodes[nodeIndex]; // reserve node's name before its dependencies, so the root has the intended name.
  34537. var nodeName = nodeDef.name ? parser.createUniqueName(nodeDef.name) : '';
  34538. return function () {
  34539. var pending = [];
  34540. if (nodeDef.mesh !== undefined) {
  34541. pending.push(parser.getDependency('mesh', nodeDef.mesh).then(function (mesh) {
  34542. var node = parser._getNodeRef(parser.meshCache, nodeDef.mesh, mesh); // if weights are provided on the node, override weights on the mesh.
  34543. if (nodeDef.weights !== undefined) {
  34544. node.traverse(function (o) {
  34545. if (!o.isMesh) return;
  34546. for (var i = 0, il = nodeDef.weights.length; i < il; i++) {
  34547. o.morphTargetInfluences[i] = nodeDef.weights[i];
  34548. }
  34549. });
  34550. }
  34551. return node;
  34552. }));
  34553. }
  34554. if (nodeDef.camera !== undefined) {
  34555. pending.push(parser.getDependency('camera', nodeDef.camera).then(function (camera) {
  34556. return parser._getNodeRef(parser.cameraCache, nodeDef.camera, camera);
  34557. }));
  34558. }
  34559. parser._invokeAll(function (ext) {
  34560. return ext.createNodeAttachment && ext.createNodeAttachment(nodeIndex);
  34561. }).forEach(function (promise) {
  34562. pending.push(promise);
  34563. });
  34564. return Promise.all(pending);
  34565. }().then(function (objects) {
  34566. var node; // .isBone isn't in glTF spec. See ._markDefs
  34567. if (nodeDef.isBone === true) {
  34568. node = new _threeModule.Bone();
  34569. } else if (objects.length > 1) {
  34570. node = new _threeModule.Group();
  34571. } else if (objects.length === 1) {
  34572. node = objects[0];
  34573. } else {
  34574. node = new _threeModule.Object3D();
  34575. }
  34576. if (node !== objects[0]) {
  34577. for (var i = 0, il = objects.length; i < il; i++) {
  34578. node.add(objects[i]);
  34579. }
  34580. }
  34581. if (nodeDef.name) {
  34582. node.userData.name = nodeDef.name;
  34583. node.name = nodeName;
  34584. }
  34585. assignExtrasToUserData(node, nodeDef);
  34586. if (nodeDef.extensions) addUnknownExtensionsToUserData(extensions, node, nodeDef);
  34587. if (nodeDef.matrix !== undefined) {
  34588. var matrix = new _threeModule.Matrix4();
  34589. matrix.fromArray(nodeDef.matrix);
  34590. node.applyMatrix4(matrix);
  34591. } else {
  34592. if (nodeDef.translation !== undefined) {
  34593. node.position.fromArray(nodeDef.translation);
  34594. }
  34595. if (nodeDef.rotation !== undefined) {
  34596. node.quaternion.fromArray(nodeDef.rotation);
  34597. }
  34598. if (nodeDef.scale !== undefined) {
  34599. node.scale.fromArray(nodeDef.scale);
  34600. }
  34601. }
  34602. parser.associations.set(node, {
  34603. type: 'nodes',
  34604. index: nodeIndex
  34605. });
  34606. return node;
  34607. });
  34608. };
  34609. /**
  34610. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  34611. * @param {number} sceneIndex
  34612. * @return {Promise<Group>}
  34613. */
  34614. GLTFParser.prototype.loadScene = function () {
  34615. // scene node hierachy builder
  34616. function buildNodeHierachy(nodeId, parentObject, json, parser) {
  34617. var nodeDef = json.nodes[nodeId];
  34618. return parser.getDependency('node', nodeId).then(function (node) {
  34619. if (nodeDef.skin === undefined) return node; // build skeleton here as well
  34620. var skinEntry;
  34621. return parser.getDependency('skin', nodeDef.skin).then(function (skin) {
  34622. skinEntry = skin;
  34623. var pendingJoints = [];
  34624. for (var i = 0, il = skinEntry.joints.length; i < il; i++) {
  34625. pendingJoints.push(parser.getDependency('node', skinEntry.joints[i]));
  34626. }
  34627. return Promise.all(pendingJoints);
  34628. }).then(function (jointNodes) {
  34629. node.traverse(function (mesh) {
  34630. if (!mesh.isMesh) return;
  34631. var bones = [];
  34632. var boneInverses = [];
  34633. for (var j = 0, jl = jointNodes.length; j < jl; j++) {
  34634. var jointNode = jointNodes[j];
  34635. if (jointNode) {
  34636. bones.push(jointNode);
  34637. var mat = new _threeModule.Matrix4();
  34638. if (skinEntry.inverseBindMatrices !== undefined) {
  34639. mat.fromArray(skinEntry.inverseBindMatrices.array, j * 16);
  34640. }
  34641. boneInverses.push(mat);
  34642. } else {
  34643. console.warn('THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[j]);
  34644. }
  34645. }
  34646. mesh.bind(new _threeModule.Skeleton(bones, boneInverses), mesh.matrixWorld);
  34647. });
  34648. return node;
  34649. });
  34650. }).then(function (node) {
  34651. // build node hierachy
  34652. parentObject.add(node);
  34653. var pending = [];
  34654. if (nodeDef.children) {
  34655. var children = nodeDef.children;
  34656. for (var i = 0, il = children.length; i < il; i++) {
  34657. var child = children[i];
  34658. pending.push(buildNodeHierachy(child, node, json, parser));
  34659. }
  34660. }
  34661. return Promise.all(pending);
  34662. });
  34663. }
  34664. return function loadScene(sceneIndex) {
  34665. var json = this.json;
  34666. var extensions = this.extensions;
  34667. var sceneDef = this.json.scenes[sceneIndex];
  34668. var parser = this; // Loader returns Group, not Scene.
  34669. // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172
  34670. var scene = new _threeModule.Group();
  34671. if (sceneDef.name) scene.name = parser.createUniqueName(sceneDef.name);
  34672. assignExtrasToUserData(scene, sceneDef);
  34673. if (sceneDef.extensions) addUnknownExtensionsToUserData(extensions, scene, sceneDef);
  34674. var nodeIds = sceneDef.nodes || [];
  34675. var pending = [];
  34676. for (var i = 0, il = nodeIds.length; i < il; i++) {
  34677. pending.push(buildNodeHierachy(nodeIds[i], scene, json, parser));
  34678. }
  34679. return Promise.all(pending).then(function () {
  34680. return scene;
  34681. });
  34682. };
  34683. }();
  34684. return GLTFLoader;
  34685. }();
  34686. exports.GLTFLoader = GLTFLoader;
  34687. },{"../../../build/three.module.js":"../node_modules/three/build/three.module.js"}],"../src/three/B3DMLoader.js":[function(require,module,exports) {
  34688. "use strict";
  34689. Object.defineProperty(exports, "__esModule", {
  34690. value: true
  34691. });
  34692. exports.B3DMLoader = void 0;
  34693. var _B3DMLoaderBase2 = require("../base/B3DMLoaderBase.js");
  34694. var _three = require("three");
  34695. var _GLTFLoader = require("three/examples/jsm/loaders/GLTFLoader.js");
  34696. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  34697. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  34698. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  34699. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  34700. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  34701. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  34702. function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
  34703. function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
  34704. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  34705. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  34706. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  34707. var B3DMLoader =
  34708. /*#__PURE__*/
  34709. function (_B3DMLoaderBase) {
  34710. _inherits(B3DMLoader, _B3DMLoaderBase);
  34711. function B3DMLoader() {
  34712. var _this;
  34713. var manager = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _three.DefaultLoadingManager;
  34714. _classCallCheck(this, B3DMLoader);
  34715. _this = _possibleConstructorReturn(this, _getPrototypeOf(B3DMLoader).call(this));
  34716. _this.manager = manager;
  34717. return _this;
  34718. }
  34719. _createClass(B3DMLoader, [{
  34720. key: "parse",
  34721. value: function parse(buffer) {
  34722. var _this2 = this;
  34723. var b3dm = _get(_getPrototypeOf(B3DMLoader.prototype), "parse", this).call(this, buffer);
  34724. var gltfBuffer = b3dm.glbBytes.slice().buffer;
  34725. return new Promise(function (resolve, reject) {
  34726. var manager = _this2.manager;
  34727. var loader = manager.getHandler('path.gltf') || new _GLTFLoader.GLTFLoader(manager);
  34728. loader.parse(gltfBuffer, null, function (model) {
  34729. var batchTable = b3dm.batchTable,
  34730. featureTable = b3dm.featureTable;
  34731. var scene = model.scene;
  34732. var rtcCenter = featureTable.getData('RTC_CENTER');
  34733. if (rtcCenter) {
  34734. scene.position.x += rtcCenter[0];
  34735. scene.position.y += rtcCenter[1];
  34736. scene.position.z += rtcCenter[2];
  34737. }
  34738. model.batchTable = batchTable;
  34739. model.featureTable = featureTable;
  34740. scene.batchTable = batchTable;
  34741. scene.featureTable = featureTable;
  34742. resolve(model);
  34743. }, reject);
  34744. });
  34745. }
  34746. }]);
  34747. return B3DMLoader;
  34748. }(_B3DMLoaderBase2.B3DMLoaderBase);
  34749. exports.B3DMLoader = B3DMLoader;
  34750. },{"../base/B3DMLoaderBase.js":"../src/base/B3DMLoaderBase.js","three":"../node_modules/three/build/three.module.js","three/examples/jsm/loaders/GLTFLoader.js":"../node_modules/three/examples/jsm/loaders/GLTFLoader.js"}],"../src/base/PNTSLoaderBase.js":[function(require,module,exports) {
  34751. "use strict";
  34752. Object.defineProperty(exports, "__esModule", {
  34753. value: true
  34754. });
  34755. exports.PNTSLoaderBase = void 0;
  34756. var _FeatureTable = require("../utilities/FeatureTable.js");
  34757. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  34758. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  34759. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  34760. var PNTSLoaderBase =
  34761. /*#__PURE__*/
  34762. function () {
  34763. function PNTSLoaderBase() {
  34764. _classCallCheck(this, PNTSLoaderBase);
  34765. this.fetchOptions = {};
  34766. }
  34767. _createClass(PNTSLoaderBase, [{
  34768. key: "load",
  34769. value: function load(url) {
  34770. var _this = this;
  34771. return fetch(url, this.fetchOptions).then(function (res) {
  34772. if (!res.ok) {
  34773. throw new Error("Failed to load file \"".concat(url, "\" with status ").concat(res.status, " : ").concat(res.statusText));
  34774. }
  34775. return res.arrayBuffer();
  34776. }).then(function (buffer) {
  34777. return _this.parse(buffer);
  34778. });
  34779. }
  34780. }, {
  34781. key: "parse",
  34782. value: function parse(buffer) {
  34783. var dataView = new DataView(buffer); // 28-byte header
  34784. // 4 bytes
  34785. var magic = String.fromCharCode(dataView.getUint8(0)) + String.fromCharCode(dataView.getUint8(1)) + String.fromCharCode(dataView.getUint8(2)) + String.fromCharCode(dataView.getUint8(3));
  34786. console.assert(magic === 'pnts'); // 4 bytes
  34787. var version = dataView.getUint32(4, true);
  34788. console.assert(version === 1); // 4 bytes
  34789. var byteLength = dataView.getUint32(8, true);
  34790. console.assert(byteLength === buffer.byteLength); // 4 bytes
  34791. var featureTableJSONByteLength = dataView.getUint32(12, true); // 4 bytes
  34792. var featureTableBinaryByteLength = dataView.getUint32(16, true); // 4 bytes
  34793. var batchTableJSONByteLength = dataView.getUint32(20, true); // 4 bytes
  34794. var batchTableBinaryByteLength = dataView.getUint32(24, true); // Feature Table
  34795. var featureTableStart = 28;
  34796. var featureTable = new _FeatureTable.FeatureTable(buffer, featureTableStart, featureTableJSONByteLength, featureTableBinaryByteLength); // Batch Table
  34797. var batchLength = featureTable.getData('BATCH_LENGTH') || featureTable.getData('POINTS_LENGTH');
  34798. var batchTableStart = featureTableStart + featureTableJSONByteLength + featureTableBinaryByteLength;
  34799. var batchTable = new _FeatureTable.BatchTable(buffer, batchLength, batchTableStart, batchTableJSONByteLength, batchTableBinaryByteLength);
  34800. return {
  34801. version: version,
  34802. featureTable: featureTable,
  34803. batchTable: batchTable
  34804. };
  34805. }
  34806. }]);
  34807. return PNTSLoaderBase;
  34808. }();
  34809. exports.PNTSLoaderBase = PNTSLoaderBase;
  34810. },{"../utilities/FeatureTable.js":"../src/utilities/FeatureTable.js"}],"../src/three/PNTSLoader.js":[function(require,module,exports) {
  34811. "use strict";
  34812. Object.defineProperty(exports, "__esModule", {
  34813. value: true
  34814. });
  34815. exports.PNTSLoader = void 0;
  34816. var _PNTSLoaderBase2 = require("../base/PNTSLoaderBase.js");
  34817. var _three = require("three");
  34818. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  34819. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  34820. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  34821. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  34822. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  34823. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  34824. function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
  34825. function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
  34826. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  34827. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  34828. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  34829. var PNTSLoader =
  34830. /*#__PURE__*/
  34831. function (_PNTSLoaderBase) {
  34832. _inherits(PNTSLoader, _PNTSLoaderBase);
  34833. function PNTSLoader() {
  34834. var _this;
  34835. var manager = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _three.DefaultLoadingManager;
  34836. _classCallCheck(this, PNTSLoader);
  34837. _this = _possibleConstructorReturn(this, _getPrototypeOf(PNTSLoader).call(this));
  34838. _this.manager = manager;
  34839. return _this;
  34840. }
  34841. _createClass(PNTSLoader, [{
  34842. key: "parse",
  34843. value: function parse(buffer) {
  34844. var result = _get(_getPrototypeOf(PNTSLoader.prototype), "parse", this).call(this, buffer);
  34845. var featureTable = result.featureTable; // global semantics
  34846. var POINTS_LENGTH = featureTable.getData('POINTS_LENGTH'); // RTC_CENTER
  34847. // QUANTIZED_VOLUME_OFFSET
  34848. // QUANTIZED_VOLUME_SCALE
  34849. // CONSTANT_RGBA
  34850. // BATCH_LENGTH
  34851. var POSITION = featureTable.getData('POSITION', POINTS_LENGTH, 'FLOAT', 'VEC3');
  34852. var RGB = featureTable.getData('RGB', POINTS_LENGTH, 'UNSIGNED_BYTE', 'VEC3'); // POSITION_QUANTIZED
  34853. // RGBA
  34854. // RGB565
  34855. // NORMAL
  34856. // NORMAL_OCT16P
  34857. // BATCH_ID
  34858. if (POSITION === null) {
  34859. throw new Error('PNTSLoader : POSITION_QUANTIZED feature type is not supported.');
  34860. }
  34861. var geometry = new _three.BufferGeometry();
  34862. geometry.setAttribute('position', new _three.BufferAttribute(POSITION, 3, false));
  34863. var material = new _three.PointsMaterial();
  34864. material.size = 2;
  34865. material.sizeAttenuation = false;
  34866. if (RGB !== null) {
  34867. geometry.setAttribute('color', new _three.BufferAttribute(RGB, 3, true));
  34868. material.vertexColors = true;
  34869. }
  34870. var object = new _three.Points(geometry, material);
  34871. result.scene = object;
  34872. result.scene.featureTable = featureTable;
  34873. return result;
  34874. }
  34875. }]);
  34876. return PNTSLoader;
  34877. }(_PNTSLoaderBase2.PNTSLoaderBase);
  34878. exports.PNTSLoader = PNTSLoader;
  34879. },{"../base/PNTSLoaderBase.js":"../src/base/PNTSLoaderBase.js","three":"../node_modules/three/build/three.module.js"}],"../src/base/I3DMLoaderBase.js":[function(require,module,exports) {
  34880. "use strict";
  34881. Object.defineProperty(exports, "__esModule", {
  34882. value: true
  34883. });
  34884. exports.I3DMLoaderBase = void 0;
  34885. var _FeatureTable = require("../utilities/FeatureTable.js");
  34886. var _arrayToString = require("../utilities/arrayToString.js");
  34887. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  34888. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  34889. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  34890. var I3DMLoaderBase =
  34891. /*#__PURE__*/
  34892. function () {
  34893. function I3DMLoaderBase() {
  34894. _classCallCheck(this, I3DMLoaderBase);
  34895. this.fetchOptions = {};
  34896. }
  34897. _createClass(I3DMLoaderBase, [{
  34898. key: "load",
  34899. value: function load(url) {
  34900. var _this = this;
  34901. return fetch(url, this.fetchOptions).then(function (res) {
  34902. if (!res.ok) {
  34903. throw new Error("Failed to load file \"".concat(url, "\" with status ").concat(res.status, " : ").concat(res.statusText));
  34904. }
  34905. return res.arrayBuffer();
  34906. }).then(function (buffer) {
  34907. return _this.parse(buffer);
  34908. });
  34909. }
  34910. }, {
  34911. key: "parse",
  34912. value: function parse(buffer) {
  34913. var dataView = new DataView(buffer); // 32-byte header
  34914. // 4 bytes
  34915. var magic = String.fromCharCode(dataView.getUint8(0)) + String.fromCharCode(dataView.getUint8(1)) + String.fromCharCode(dataView.getUint8(2)) + String.fromCharCode(dataView.getUint8(3));
  34916. console.assert(magic === 'i3dm'); // 4 bytes
  34917. var version = dataView.getUint32(4, true);
  34918. console.assert(version === 1); // 4 bytes
  34919. var byteLength = dataView.getUint32(8, true);
  34920. console.assert(byteLength === buffer.byteLength); // 4 bytes
  34921. var featureTableJSONByteLength = dataView.getUint32(12, true); // 4 bytes
  34922. var featureTableBinaryByteLength = dataView.getUint32(16, true); // 4 bytes
  34923. var batchTableJSONByteLength = dataView.getUint32(20, true); // 4 bytes
  34924. var batchTableBinaryByteLength = dataView.getUint32(24, true); // 4 bytes
  34925. var gltfFormat = dataView.getUint32(28, true); // Feature Table
  34926. var featureTableStart = 32;
  34927. var featureTable = new _FeatureTable.FeatureTable(buffer, featureTableStart, featureTableJSONByteLength, featureTableBinaryByteLength); // Batch Table
  34928. var batchLength = featureTable.getData('INSTANCES_LENGTH');
  34929. var batchTableStart = featureTableStart + featureTableJSONByteLength + featureTableBinaryByteLength;
  34930. var batchTable = new _FeatureTable.BatchTable(buffer, batchLength, batchTableStart, batchTableJSONByteLength, batchTableBinaryByteLength);
  34931. var glbStart = batchTableStart + batchTableJSONByteLength + batchTableBinaryByteLength;
  34932. var bodyBytes = new Uint8Array(buffer, glbStart, byteLength - glbStart);
  34933. var glbBytes = null;
  34934. var promise = null;
  34935. if (gltfFormat) {
  34936. glbBytes = bodyBytes;
  34937. promise = Promise.resolve();
  34938. } else {
  34939. var externalUri = (0, _arrayToString.arrayToString)(bodyBytes);
  34940. promise = fetch(externalUri, this.fetchOptions).then(function (res) {
  34941. return res.buffer;
  34942. }).then(function (buffer) {
  34943. glbBytes = new Uint8Array(buffer);
  34944. });
  34945. }
  34946. return promise.then(function () {
  34947. return {
  34948. version: version,
  34949. featureTable: featureTable,
  34950. batchTable: batchTable,
  34951. glbBytes: glbBytes
  34952. };
  34953. });
  34954. }
  34955. }]);
  34956. return I3DMLoaderBase;
  34957. }();
  34958. exports.I3DMLoaderBase = I3DMLoaderBase;
  34959. },{"../utilities/FeatureTable.js":"../src/utilities/FeatureTable.js","../utilities/arrayToString.js":"../src/utilities/arrayToString.js"}],"../src/three/I3DMLoader.js":[function(require,module,exports) {
  34960. "use strict";
  34961. Object.defineProperty(exports, "__esModule", {
  34962. value: true
  34963. });
  34964. exports.I3DMLoader = void 0;
  34965. var _I3DMLoaderBase2 = require("../base/I3DMLoaderBase.js");
  34966. var _three = require("three");
  34967. var _GLTFLoader = require("three/examples/jsm/loaders/GLTFLoader.js");
  34968. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  34969. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  34970. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  34971. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  34972. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  34973. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  34974. function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
  34975. function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
  34976. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  34977. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  34978. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  34979. var tempPos = new _three.Vector3();
  34980. var tempQuat = new _three.Quaternion();
  34981. var tempSca = new _three.Vector3();
  34982. var tempMat = new _three.Matrix4();
  34983. var I3DMLoader =
  34984. /*#__PURE__*/
  34985. function (_I3DMLoaderBase) {
  34986. _inherits(I3DMLoader, _I3DMLoaderBase);
  34987. function I3DMLoader() {
  34988. var _this;
  34989. var manager = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _three.DefaultLoadingManager;
  34990. _classCallCheck(this, I3DMLoader);
  34991. _this = _possibleConstructorReturn(this, _getPrototypeOf(I3DMLoader).call(this));
  34992. _this.manager = manager;
  34993. return _this;
  34994. }
  34995. _createClass(I3DMLoader, [{
  34996. key: "parse",
  34997. value: function parse(buffer) {
  34998. var _this2 = this;
  34999. return _get(_getPrototypeOf(I3DMLoader.prototype), "parse", this).call(this, buffer).then(function (i3dm) {
  35000. var featureTable = i3dm.featureTable,
  35001. batchTable = i3dm.batchTable;
  35002. var gltfBuffer = i3dm.glbBytes.slice().buffer;
  35003. return new Promise(function (resolve, reject) {
  35004. var manager = _this2.manager;
  35005. var loader = manager.getHandler('path.gltf') || new _GLTFLoader.GLTFLoader(manager);
  35006. loader.parse(gltfBuffer, null, function (model) {
  35007. var INSTANCES_LENGTH = featureTable.getData('INSTANCES_LENGTH'); // RTC_CENTER
  35008. // QUANTIZED_VOLUME_OFFSET
  35009. // QUANTIZED_VOLUME_SCALE
  35010. // EAST_NORTH_UP
  35011. var POSITION = featureTable.getData('POSITION', INSTANCES_LENGTH, 'FLOAT', 'VEC3'); // POSITION_QUANTIZED
  35012. // NORMAL_UP
  35013. // NORMAL_RIGHT
  35014. // NORMAL_UP_OCT32P
  35015. // NORMAL_RIGHT_OCT32P
  35016. // SCALE
  35017. // SCALE_NON_UNIFORM
  35018. // BATCH_ID
  35019. var instanceMap = new Map();
  35020. var instances = [];
  35021. model.scene.traverse(function (child) {
  35022. if (child.isMesh) {
  35023. var geometry = child.geometry,
  35024. material = child.material;
  35025. var instancedMesh = new _three.InstancedMesh(geometry, material, INSTANCES_LENGTH);
  35026. instances.push(instancedMesh);
  35027. instanceMap.set(child, instancedMesh);
  35028. }
  35029. });
  35030. var averageVector = new _three.Vector3();
  35031. var transformedVector = new _three.Vector3();
  35032. for (var i = 0; i < INSTANCES_LENGTH; i++) {
  35033. // TODO: handle quantized position
  35034. averageVector.x += POSITION[i * 3 + 0] / INSTANCES_LENGTH;
  35035. averageVector.y += POSITION[i * 3 + 1] / INSTANCES_LENGTH;
  35036. averageVector.z += POSITION[i * 3 + 2] / INSTANCES_LENGTH;
  35037. } // replace the meshes with instanced meshes
  35038. instanceMap.forEach(function (instancedMesh, mesh) {
  35039. var parent = mesh.parent;
  35040. if (parent) {
  35041. // Mesh have no children
  35042. parent.remove(mesh);
  35043. parent.add(instancedMesh); // Center the instance around an average point to avoid jitter at large scales.
  35044. transformedVector.copy(averageVector).applyQuaternion(parent.quaternion).multiply(parent.scale);
  35045. instancedMesh.add(transformedVector);
  35046. }
  35047. });
  35048. for (var _i = 0; _i < INSTANCES_LENGTH; _i++) {
  35049. // TODO: handle quantized position
  35050. tempPos.set(POSITION[_i * 3 + 0] - averageVector.x, POSITION[_i * 3 + 1] - averageVector.y, POSITION[_i * 3 + 2] - averageVector.z); // TODO: handle normal orientation features
  35051. tempQuat.set(0, 0, 0, 1); // TODO: handle scale features
  35052. tempSca.set(1, 1, 1);
  35053. tempMat.compose(tempPos, tempQuat, tempSca);
  35054. for (var j = 0, l = instances.length; j < l; j++) {
  35055. var instance = instances[j];
  35056. instance.setMatrixAt(_i, tempMat);
  35057. }
  35058. }
  35059. model.batchTable = batchTable;
  35060. model.featureTable = featureTable;
  35061. model.scene.batchTable = batchTable;
  35062. model.scene.featureTable = featureTable;
  35063. resolve(model);
  35064. }, reject);
  35065. });
  35066. });
  35067. }
  35068. }]);
  35069. return I3DMLoader;
  35070. }(_I3DMLoaderBase2.I3DMLoaderBase);
  35071. exports.I3DMLoader = I3DMLoader;
  35072. },{"../base/I3DMLoaderBase.js":"../src/base/I3DMLoaderBase.js","three":"../node_modules/three/build/three.module.js","three/examples/jsm/loaders/GLTFLoader.js":"../node_modules/three/examples/jsm/loaders/GLTFLoader.js"}],"../src/base/CMPTLoaderBase.js":[function(require,module,exports) {
  35073. "use strict";
  35074. Object.defineProperty(exports, "__esModule", {
  35075. value: true
  35076. });
  35077. exports.CMPTLoaderBase = void 0;
  35078. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  35079. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  35080. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  35081. // CMPT File Format
  35082. // https://github.com/CesiumGS/3d-tiles/blob/master/specification/TileFormats/Composite/README.md
  35083. var CMPTLoaderBase =
  35084. /*#__PURE__*/
  35085. function () {
  35086. function CMPTLoaderBase() {
  35087. _classCallCheck(this, CMPTLoaderBase);
  35088. this.fetchOptions = {};
  35089. }
  35090. _createClass(CMPTLoaderBase, [{
  35091. key: "load",
  35092. value: function load(url) {
  35093. var _this = this;
  35094. return fetch(url, this.fetchOptions).then(function (res) {
  35095. if (!res.ok) {
  35096. throw new Error("Failed to load file \"".concat(url, "\" with status ").concat(res.status, " : ").concat(res.statusText));
  35097. }
  35098. return res.arrayBuffer();
  35099. }).then(function (buffer) {
  35100. return _this.parse(buffer);
  35101. });
  35102. }
  35103. }, {
  35104. key: "parse",
  35105. value: function parse(buffer) {
  35106. var dataView = new DataView(buffer); // 16-byte header
  35107. // 4 bytes
  35108. var magic = String.fromCharCode(dataView.getUint8(0)) + String.fromCharCode(dataView.getUint8(1)) + String.fromCharCode(dataView.getUint8(2)) + String.fromCharCode(dataView.getUint8(3));
  35109. console.assert(magic === 'cmpt'); // 4 bytes
  35110. var version = dataView.getUint32(4, true);
  35111. console.assert(version === 1); // 4 bytes
  35112. var byteLength = dataView.getUint32(8, true);
  35113. console.assert(byteLength === buffer.byteLength); // 4 bytes
  35114. var tilesLength = dataView.getUint32(12, true);
  35115. var tiles = [];
  35116. var offset = 16;
  35117. for (var i = 0; i < tilesLength; i++) {
  35118. var tileView = new DataView(buffer, offset, 12);
  35119. var tileMagic = String.fromCharCode(tileView.getUint8(0)) + String.fromCharCode(tileView.getUint8(1)) + String.fromCharCode(tileView.getUint8(2)) + String.fromCharCode(tileView.getUint8(3));
  35120. var tileVersion = tileView.getUint32(4, true);
  35121. var _byteLength = tileView.getUint32(8, true);
  35122. var tileBuffer = new Uint8Array(buffer, offset, _byteLength);
  35123. tiles.push({
  35124. type: tileMagic,
  35125. buffer: tileBuffer,
  35126. version: tileVersion
  35127. });
  35128. offset += _byteLength;
  35129. }
  35130. return {
  35131. version: version,
  35132. tiles: tiles
  35133. };
  35134. }
  35135. }]);
  35136. return CMPTLoaderBase;
  35137. }();
  35138. exports.CMPTLoaderBase = CMPTLoaderBase;
  35139. },{}],"../src/three/CMPTLoader.js":[function(require,module,exports) {
  35140. "use strict";
  35141. Object.defineProperty(exports, "__esModule", {
  35142. value: true
  35143. });
  35144. exports.CMPTLoader = void 0;
  35145. var _three = require("three");
  35146. var _CMPTLoaderBase2 = require("../base/CMPTLoaderBase.js");
  35147. var _B3DMLoader = require("./B3DMLoader.js");
  35148. var _PNTSLoader = require("./PNTSLoader.js");
  35149. var _I3DMLoader = require("./I3DMLoader.js");
  35150. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  35151. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  35152. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  35153. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  35154. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  35155. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  35156. function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
  35157. function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
  35158. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  35159. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  35160. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  35161. var CMPTLoader =
  35162. /*#__PURE__*/
  35163. function (_CMPTLoaderBase) {
  35164. _inherits(CMPTLoader, _CMPTLoaderBase);
  35165. function CMPTLoader() {
  35166. var _this;
  35167. var manager = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _three.DefaultLoadingManager;
  35168. _classCallCheck(this, CMPTLoader);
  35169. _this = _possibleConstructorReturn(this, _getPrototypeOf(CMPTLoader).call(this));
  35170. _this.manager = manager;
  35171. return _this;
  35172. }
  35173. _createClass(CMPTLoader, [{
  35174. key: "parse",
  35175. value: function parse(buffer) {
  35176. var result = _get(_getPrototypeOf(CMPTLoader.prototype), "parse", this).call(this, buffer);
  35177. var manager = this.manager;
  35178. var group = new _three.Group();
  35179. var results = [];
  35180. var promises = [];
  35181. for (var i in result.tiles) {
  35182. var _result$tiles$i = result.tiles[i],
  35183. type = _result$tiles$i.type,
  35184. _buffer = _result$tiles$i.buffer;
  35185. switch (type) {
  35186. case 'b3dm':
  35187. {
  35188. var slicedBuffer = _buffer.slice();
  35189. var promise = new _B3DMLoader.B3DMLoader(manager).parse(slicedBuffer.buffer).then(function (res) {
  35190. results.push(res);
  35191. group.add(res.scene);
  35192. });
  35193. promises.push(promise);
  35194. break;
  35195. }
  35196. case 'pnts':
  35197. {
  35198. var _slicedBuffer = _buffer.slice();
  35199. var pointsResult = new _PNTSLoader.PNTSLoader(manager).parse(_slicedBuffer.buffer);
  35200. results.push(pointsResult);
  35201. group.add(pointsResult.scene);
  35202. break;
  35203. }
  35204. case 'i3dm':
  35205. {
  35206. var _slicedBuffer2 = _buffer.slice();
  35207. var _promise = new _I3DMLoader.I3DMLoader(manager).parse(_slicedBuffer2.buffer).then(function (res) {
  35208. results.push(res);
  35209. group.add(res.scene);
  35210. });
  35211. promises.push(_promise);
  35212. break;
  35213. }
  35214. }
  35215. }
  35216. return Promise.all(promises).then(function () {
  35217. return {
  35218. tiles: results,
  35219. scene: group
  35220. };
  35221. });
  35222. }
  35223. }]);
  35224. return CMPTLoader;
  35225. }(_CMPTLoaderBase2.CMPTLoaderBase);
  35226. exports.CMPTLoader = CMPTLoader;
  35227. },{"three":"../node_modules/three/build/three.module.js","../base/CMPTLoaderBase.js":"../src/base/CMPTLoaderBase.js","./B3DMLoader.js":"../src/three/B3DMLoader.js","./PNTSLoader.js":"../src/three/PNTSLoader.js","./I3DMLoader.js":"../src/three/I3DMLoader.js"}],"../src/three/TilesGroup.js":[function(require,module,exports) {
  35228. "use strict";
  35229. Object.defineProperty(exports, "__esModule", {
  35230. value: true
  35231. });
  35232. exports.TilesGroup = void 0;
  35233. var _three = require("three");
  35234. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  35235. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  35236. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  35237. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  35238. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  35239. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  35240. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  35241. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  35242. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  35243. // Specialization of "Group" that only updates world matrices of children if
  35244. // the transform has changed since the last update and ignores the "force"
  35245. // parameter under the assumption that the children tiles will not move.
  35246. var tempMat = new _three.Matrix4();
  35247. var TilesGroup =
  35248. /*#__PURE__*/
  35249. function (_Group) {
  35250. _inherits(TilesGroup, _Group);
  35251. function TilesGroup(tilesRenderer) {
  35252. var _this;
  35253. _classCallCheck(this, TilesGroup);
  35254. _this = _possibleConstructorReturn(this, _getPrototypeOf(TilesGroup).call(this));
  35255. _this.tilesRenderer = tilesRenderer;
  35256. return _this;
  35257. }
  35258. _createClass(TilesGroup, [{
  35259. key: "raycast",
  35260. value: function raycast(raycaster, intersects) {
  35261. this.tilesRenderer.raycast(raycaster, intersects);
  35262. }
  35263. }, {
  35264. key: "updateMatrixWorld",
  35265. value: function updateMatrixWorld(force) {
  35266. if (this.matrixAutoUpdate) {
  35267. this.updateMatrix();
  35268. }
  35269. if (this.matrixWorldNeedsUpdate || force) {
  35270. if (this.parent === null) {
  35271. tempMat.copy(this.matrix);
  35272. } else {
  35273. tempMat.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  35274. }
  35275. this.matrixWorldNeedsUpdate = false; // check if the matrix changed relative to what it was.
  35276. var elA = tempMat.elements;
  35277. var elB = this.matrixWorld.elements;
  35278. var isDifferent = false;
  35279. for (var i = 0; i < 16; i++) {
  35280. var itemA = elA[i];
  35281. var itemB = elB[i];
  35282. var diff = Math.abs(itemA - itemB);
  35283. if (diff > Number.EPSILON) {
  35284. isDifferent = true;
  35285. break;
  35286. }
  35287. }
  35288. if (isDifferent) {
  35289. this.matrixWorld.copy(tempMat); // update children
  35290. // the children will not have to change unless the parent group has updated
  35291. var children = this.children;
  35292. for (var _i = 0, l = children.length; _i < l; _i++) {
  35293. children[_i].updateMatrixWorld();
  35294. }
  35295. }
  35296. }
  35297. }
  35298. }]);
  35299. return TilesGroup;
  35300. }(_three.Group);
  35301. exports.TilesGroup = TilesGroup;
  35302. },{"three":"../node_modules/three/build/three.module.js"}],"../src/three/raycastTraverse.js":[function(require,module,exports) {
  35303. "use strict";
  35304. Object.defineProperty(exports, "__esModule", {
  35305. value: true
  35306. });
  35307. exports.raycastTraverseFirstHit = raycastTraverseFirstHit;
  35308. exports.raycastTraverse = raycastTraverse;
  35309. var _three = require("three");
  35310. var _sphere = new _three.Sphere();
  35311. var _mat = new _three.Matrix4();
  35312. var _vec = new _three.Vector3();
  35313. var _vec2 = new _three.Vector3();
  35314. var _ray = new _three.Ray();
  35315. var _hitArray = [];
  35316. function distanceSort(a, b) {
  35317. return a.distance - b.distance;
  35318. }
  35319. function intersectTileScene(scene, raycaster, intersects) {
  35320. // Don't intersect the box3 helpers because those are used for debugging
  35321. scene.traverse(function (c) {
  35322. // We set the default raycast function to empty so three.js doesn't automatically cast against it
  35323. Object.getPrototypeOf(c).raycast.call(c, raycaster, intersects);
  35324. });
  35325. } // Returns the closest hit when traversing the tree
  35326. function raycastTraverseFirstHit(root, group, activeTiles, raycaster) {
  35327. // If the root is active make sure we've checked it
  35328. if (activeTiles.has(root)) {
  35329. intersectTileScene(root.cached.scene, raycaster, _hitArray);
  35330. if (_hitArray.length > 0) {
  35331. if (_hitArray.length > 1) {
  35332. _hitArray.sort(distanceSort);
  35333. }
  35334. var res = _hitArray[0];
  35335. _hitArray.length = 0;
  35336. return res;
  35337. } else {
  35338. return null;
  35339. }
  35340. } // TODO: can we avoid creating a new array here every time to save on memory?
  35341. var array = [];
  35342. var children = root.children;
  35343. for (var i = 0, l = children.length; i < l; i++) {
  35344. var tile = children[i];
  35345. var cached = tile.cached;
  35346. var groupMatrixWorld = group.matrixWorld;
  35347. _mat.copy(groupMatrixWorld); // if we don't hit the sphere then early out
  35348. var sphere = cached.sphere;
  35349. if (sphere) {
  35350. _sphere.copy(sphere);
  35351. _sphere.applyMatrix4(_mat);
  35352. if (!raycaster.ray.intersectsSphere(_sphere)) {
  35353. continue;
  35354. }
  35355. } // TODO: check region?
  35356. var boundingBox = cached.box;
  35357. var obbMat = cached.boxTransform;
  35358. if (boundingBox) {
  35359. _mat.multiply(obbMat).invert();
  35360. _ray.copy(raycaster.ray);
  35361. _ray.applyMatrix4(_mat);
  35362. if (_ray.intersectBox(boundingBox, _vec)) {
  35363. // account for tile scale
  35364. var invScale = void 0;
  35365. _vec2.setFromMatrixScale(_mat);
  35366. invScale = _vec2.x;
  35367. if (Math.abs(Math.max(_vec2.x - _vec2.y, _vec2.x - _vec2.z)) > 1e-6) {
  35368. console.warn('ThreeTilesRenderer : Non uniform scale used for tile which may cause issues when raycasting.');
  35369. } // if we intersect the box save the distance to the tile bounds
  35370. var data = {
  35371. distance: Infinity,
  35372. tile: null
  35373. };
  35374. array.push(data);
  35375. data.distance = _vec.distanceToSquared(_ray.origin) * invScale * invScale;
  35376. data.tile = tile;
  35377. } else {
  35378. continue;
  35379. }
  35380. }
  35381. } // sort them by ascending distance
  35382. array.sort(distanceSort); // traverse until we find the best hit and early out if a tile bounds
  35383. // couldn't possible include a best hit
  35384. var bestDistanceSquared = Infinity;
  35385. var bestHit = null;
  35386. for (var _i = 0, _l = array.length; _i < _l; _i++) {
  35387. var _data = array[_i];
  35388. var distanceSquared = _data.distance;
  35389. if (distanceSquared > bestDistanceSquared) {
  35390. break;
  35391. } else {
  35392. var _tile = _data.tile;
  35393. var scene = _tile.cached.scene;
  35394. var hit = null;
  35395. if (activeTiles.has(_tile)) {
  35396. // save the hit if it's closer
  35397. intersectTileScene(scene, raycaster, _hitArray);
  35398. if (_hitArray.length > 0) {
  35399. if (_hitArray.length > 1) {
  35400. _hitArray.sort(distanceSort);
  35401. }
  35402. hit = _hitArray[0];
  35403. }
  35404. } else {
  35405. hit = raycastTraverseFirstHit(_tile, group, activeTiles, raycaster);
  35406. }
  35407. if (hit) {
  35408. var hitDistanceSquared = hit.distance * hit.distance;
  35409. if (hitDistanceSquared < bestDistanceSquared) {
  35410. bestDistanceSquared = hitDistanceSquared;
  35411. bestHit = hit;
  35412. }
  35413. _hitArray.length = 0;
  35414. }
  35415. }
  35416. }
  35417. return bestHit;
  35418. }
  35419. function raycastTraverse(tile, group, activeTiles, raycaster, intersects) {
  35420. var cached = tile.cached;
  35421. var groupMatrixWorld = group.matrixWorld;
  35422. _mat.copy(groupMatrixWorld); // Early out if we don't hit this tile sphere
  35423. var sphere = cached.sphere;
  35424. if (sphere) {
  35425. _sphere.copy(sphere);
  35426. _sphere.applyMatrix4(_mat);
  35427. if (!raycaster.ray.intersectsSphere(_sphere)) {
  35428. return;
  35429. }
  35430. } // Early out if we don't this this tile box
  35431. var boundingBox = cached.box;
  35432. var obbMat = cached.boxTransform;
  35433. if (boundingBox) {
  35434. _mat.multiply(obbMat).invert();
  35435. _ray.copy(raycaster.ray).applyMatrix4(_mat);
  35436. if (!_ray.intersectsBox(boundingBox)) {
  35437. return;
  35438. }
  35439. } // TODO: check region
  35440. var scene = cached.scene;
  35441. if (activeTiles.has(tile)) {
  35442. intersectTileScene(scene, raycaster, intersects);
  35443. return;
  35444. }
  35445. var children = tile.children;
  35446. for (var i = 0, l = children.length; i < l; i++) {
  35447. raycastTraverse(children[i], group, activeTiles, raycaster, intersects);
  35448. }
  35449. }
  35450. },{"three":"../node_modules/three/build/three.module.js"}],"../src/three/TilesRenderer.js":[function(require,module,exports) {
  35451. "use strict";
  35452. Object.defineProperty(exports, "__esModule", {
  35453. value: true
  35454. });
  35455. exports.TilesRenderer = void 0;
  35456. var _TilesRendererBase2 = require("../base/TilesRendererBase.js");
  35457. var _B3DMLoader = require("./B3DMLoader.js");
  35458. var _PNTSLoader = require("./PNTSLoader.js");
  35459. var _I3DMLoader = require("./I3DMLoader.js");
  35460. var _CMPTLoader = require("./CMPTLoader.js");
  35461. var _TilesGroup = require("./TilesGroup.js");
  35462. var _three = require("three");
  35463. var _raycastTraverse = require("./raycastTraverse.js");
  35464. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  35465. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  35466. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  35467. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  35468. function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
  35469. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  35470. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  35471. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  35472. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  35473. function set(target, property, value, receiver) { if (typeof Reflect !== "undefined" && Reflect.set) { set = Reflect.set; } else { set = function set(target, property, value, receiver) { var base = _superPropBase(target, property); var desc; if (base) { desc = Object.getOwnPropertyDescriptor(base, property); if (desc.set) { desc.set.call(receiver, value); return true; } else if (!desc.writable) { return false; } } desc = Object.getOwnPropertyDescriptor(receiver, property); if (desc) { if (!desc.writable) { return false; } desc.value = value; Object.defineProperty(receiver, property, desc); } else { _defineProperty(receiver, property, value); } return true; }; } return set(target, property, value, receiver); }
  35474. function _set(target, property, value, receiver, isStrict) { var s = set(target, property, value, receiver || target); if (!s && isStrict) { throw new Error('failed to set property'); } return value; }
  35475. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  35476. function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
  35477. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  35478. var INITIAL_FRUSTUM_CULLED = Symbol('INITIAL_FRUSTUM_CULLED');
  35479. var DEG2RAD = _three.Math.DEG2RAD;
  35480. var tempMat = new _three.Matrix4();
  35481. var tempMat2 = new _three.Matrix4();
  35482. var tempVector = new _three.Vector3();
  35483. var vecX = new _three.Vector3();
  35484. var vecY = new _three.Vector3();
  35485. var vecZ = new _three.Vector3();
  35486. var X_AXIS = new _three.Vector3(1, 0, 0);
  35487. var Y_AXIS = new _three.Vector3(0, 1, 0);
  35488. function emptyRaycast() {}
  35489. function updateFrustumCulled(object, toInitialValue) {
  35490. object.traverse(function (c) {
  35491. c.frustumCulled = c[INITIAL_FRUSTUM_CULLED] && toInitialValue;
  35492. });
  35493. }
  35494. var TilesRenderer =
  35495. /*#__PURE__*/
  35496. function (_TilesRendererBase) {
  35497. _inherits(TilesRenderer, _TilesRendererBase);
  35498. _createClass(TilesRenderer, [{
  35499. key: "autoDisableRendererCulling",
  35500. get: function get() {
  35501. return this._autoDisableRendererCulling;
  35502. },
  35503. set: function set(value) {
  35504. if (this._autoDisableRendererCulling !== value) {
  35505. _set(_getPrototypeOf(TilesRenderer.prototype), "_autoDisableRendererCulling", value, this, true);
  35506. this.traverse(function (tile) {
  35507. if (tile.scene) {
  35508. updateFrustumCulled(tile.scene, value);
  35509. }
  35510. });
  35511. }
  35512. }
  35513. }]);
  35514. function TilesRenderer() {
  35515. var _getPrototypeOf2;
  35516. var _this;
  35517. _classCallCheck(this, TilesRenderer);
  35518. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  35519. args[_key] = arguments[_key];
  35520. }
  35521. _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(TilesRenderer)).call.apply(_getPrototypeOf2, [this].concat(args)));
  35522. _this.group = new _TilesGroup.TilesGroup(_assertThisInitialized(_this));
  35523. _this.cameras = [];
  35524. _this.cameraMap = new Map();
  35525. _this.cameraInfo = [];
  35526. _this.activeTiles = new Set();
  35527. _this.visibleTiles = new Set();
  35528. _this._autoDisableRendererCulling = true;
  35529. _this.onLoadTileSet = null;
  35530. _this.onLoadModel = null;
  35531. _this.onDisposeModel = null;
  35532. _this.manager = new _three.LoadingManager();
  35533. return _this;
  35534. }
  35535. /* Public API */
  35536. _createClass(TilesRenderer, [{
  35537. key: "getBounds",
  35538. value: function getBounds(box) {
  35539. if (!this.root) {
  35540. return false;
  35541. }
  35542. var cached = this.root.cached;
  35543. var boundingBox = cached.box;
  35544. var obbMat = cached.boxTransform;
  35545. if (boundingBox) {
  35546. box.copy(boundingBox);
  35547. box.applyMatrix4(obbMat);
  35548. return true;
  35549. } else {
  35550. return false;
  35551. }
  35552. }
  35553. }, {
  35554. key: "forEachLoadedModel",
  35555. value: function forEachLoadedModel(callback) {
  35556. this.traverse(function (tile) {
  35557. var scene = tile.cached.scene;
  35558. if (scene) {
  35559. callback(scene, tile);
  35560. }
  35561. });
  35562. }
  35563. }, {
  35564. key: "raycast",
  35565. value: function raycast(raycaster, intersects) {
  35566. if (!this.root) {
  35567. return;
  35568. }
  35569. if (raycaster.firstHitOnly) {
  35570. var hit = (0, _raycastTraverse.raycastTraverseFirstHit)(this.root, this.group, this.activeTiles, raycaster);
  35571. if (hit) {
  35572. intersects.push(hit);
  35573. }
  35574. } else {
  35575. (0, _raycastTraverse.raycastTraverse)(this.root, this.group, this.activeTiles, raycaster, intersects);
  35576. }
  35577. }
  35578. }, {
  35579. key: "hasCamera",
  35580. value: function hasCamera(camera) {
  35581. return this.cameraMap.has(camera);
  35582. }
  35583. }, {
  35584. key: "setCamera",
  35585. value: function setCamera(camera) {
  35586. var cameras = this.cameras;
  35587. var cameraMap = this.cameraMap;
  35588. if (!cameraMap.has(camera)) {
  35589. cameraMap.set(camera, new _three.Vector2());
  35590. cameras.push(camera);
  35591. return true;
  35592. }
  35593. return false;
  35594. }
  35595. }, {
  35596. key: "setResolution",
  35597. value: function setResolution(camera, xOrVec, y) {
  35598. var cameraMap = this.cameraMap;
  35599. if (!cameraMap.has(camera)) {
  35600. return false;
  35601. }
  35602. if (xOrVec instanceof _three.Vector2) {
  35603. cameraMap.get(camera).copy(xOrVec);
  35604. } else {
  35605. cameraMap.get(camera).set(xOrVec, y);
  35606. }
  35607. return true;
  35608. }
  35609. }, {
  35610. key: "setResolutionFromRenderer",
  35611. value: function setResolutionFromRenderer(camera, renderer) {
  35612. var cameraMap = this.cameraMap;
  35613. if (!cameraMap.has(camera)) {
  35614. return false;
  35615. }
  35616. var resolution = cameraMap.get(camera);
  35617. renderer.getSize(resolution);
  35618. resolution.multiplyScalar(renderer.getPixelRatio());
  35619. return true;
  35620. }
  35621. }, {
  35622. key: "rotationBetweenDirections",
  35623. value: function rotationBetweenDirections(dir1, dir2) {
  35624. var rotation = new _three.Quaternion();
  35625. var a = new _three.Vector3().crossVectors(dir1, dir2);
  35626. rotation.x = a.x;
  35627. rotation.y = a.y;
  35628. rotation.z = a.z;
  35629. rotation.w = 1 + dir1.clone().dot(dir2);
  35630. rotation.normalize();
  35631. return rotation;
  35632. }
  35633. }, {
  35634. key: "deleteCamera",
  35635. value: function deleteCamera(camera) {
  35636. var cameras = this.cameras;
  35637. var cameraMap = this.cameraMap;
  35638. if (cameraMap.has(camera)) {
  35639. var index = cameras.indexOf(camera);
  35640. cameras.splice(index, 1);
  35641. cameraMap.delete(camera);
  35642. return true;
  35643. }
  35644. return false;
  35645. }
  35646. /* Overriden */
  35647. }, {
  35648. key: "fetchTileSet",
  35649. value: function fetchTileSet(url) {
  35650. var _get2,
  35651. _this2 = this;
  35652. for (var _len2 = arguments.length, rest = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  35653. rest[_key2 - 1] = arguments[_key2];
  35654. }
  35655. var pr = (_get2 = _get(_getPrototypeOf(TilesRenderer.prototype), "fetchTileSet", this)).call.apply(_get2, [this, url].concat(rest));
  35656. pr.then(function (json) {
  35657. if (_this2.onLoadTileSet) {
  35658. // Push this onto the end of the event stack to ensure this runs
  35659. // after the base renderer has placed the provided json where it
  35660. // needs to be placed and is ready for an update.
  35661. Promise.resolve().then(function () {
  35662. _this2.onLoadTileSet(json, url);
  35663. });
  35664. }
  35665. Promise.resolve().then(function () {
  35666. if (_this2.ionAssetId) {
  35667. var transform = _this2.root.cached.boxTransform;
  35668. var position = new _three.Vector3().setFromMatrixPosition(transform);
  35669. var distance = position.length();
  35670. var surfaceDir = position.normalize();
  35671. var rotation = _this2.rotationBetweenDirections(surfaceDir, new _three.Vector3(0, 1, 0)); // Rotate tiles to the north pole around the Earth
  35672. _this2.group.quaternion.x = rotation.x;
  35673. _this2.group.quaternion.y = rotation.y;
  35674. _this2.group.quaternion.z = rotation.z;
  35675. _this2.group.quaternion.w = rotation.w; //Move tiles to the center of the Earth
  35676. _this2.group.position.y = -distance;
  35677. }
  35678. });
  35679. });
  35680. return pr;
  35681. }
  35682. /** set projection matrix to frustum for legacy versions of three.js */
  35683. }, {
  35684. key: "setFromProjectionMatrix",
  35685. value: function setFromProjectionMatrix(frustum, m) {
  35686. var planes = frustum.planes;
  35687. var me = m.elements;
  35688. var me0 = me[0],
  35689. me1 = me[1],
  35690. me2 = me[2],
  35691. me3 = me[3];
  35692. var me4 = me[4],
  35693. me5 = me[5],
  35694. me6 = me[6],
  35695. me7 = me[7];
  35696. var me8 = me[8],
  35697. me9 = me[9],
  35698. me10 = me[10],
  35699. me11 = me[11];
  35700. var me12 = me[12],
  35701. me13 = me[13],
  35702. me14 = me[14],
  35703. me15 = me[15];
  35704. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  35705. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  35706. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  35707. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  35708. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  35709. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  35710. }
  35711. }, {
  35712. key: "update",
  35713. value: function update() {
  35714. var group = this.group;
  35715. var cameras = this.cameras;
  35716. var cameraMap = this.cameraMap;
  35717. var cameraInfo = this.cameraInfo;
  35718. if (cameras.length === 0) {
  35719. console.warn('TilesRenderer: no cameras defined. Cannot update 3d tiles.');
  35720. return;
  35721. } // automatically scale the array of cameraInfo to match the cameras
  35722. while (cameraInfo.length > cameras.length) {
  35723. cameraInfo.pop();
  35724. }
  35725. while (cameraInfo.length < cameras.length) {
  35726. cameraInfo.push({
  35727. frustum: new _three.Frustum(),
  35728. sseDenominator: -1,
  35729. position: new _three.Vector3(),
  35730. invScale: -1,
  35731. pixelSize: 0
  35732. });
  35733. } // extract scale of group container
  35734. tempMat2.copy(group.matrixWorld).invert();
  35735. var invScale;
  35736. tempVector.setFromMatrixScale(tempMat2);
  35737. invScale = tempVector.x;
  35738. if (Math.abs(Math.max(tempVector.x - tempVector.y, tempVector.x - tempVector.z)) > 1e-6) {
  35739. console.warn('ThreeTilesRenderer : Non uniform scale used for tile which may cause issues when calculating screen space error.');
  35740. } // store the camera cameraInfo in the 3d tiles root frame
  35741. for (var i = 0, l = cameraInfo.length; i < l; i++) {
  35742. var camera = cameras[i];
  35743. var info = cameraInfo[i];
  35744. var frustum = info.frustum;
  35745. var position = info.position;
  35746. var resolution = cameraMap.get(camera);
  35747. if (resolution.width === 0 || resolution.height === 0) {
  35748. console.warn('TilesRenderer: resolution for camera error calculation is not set.');
  35749. }
  35750. if (camera.isPerspectiveCamera) {
  35751. info.sseDenominator = 2 * Math.tan(0.5 * camera.fov * DEG2RAD) / resolution.height;
  35752. }
  35753. if (camera.isOrthographicCamera) {
  35754. var w = camera.right - camera.left;
  35755. var h = camera.top - camera.bottom;
  35756. info.pixelSize = Math.max(h / resolution.height, w / resolution.width);
  35757. }
  35758. info.invScale = invScale; // get frustum in grop root frame
  35759. tempMat.copy(group.matrixWorld);
  35760. tempMat.premultiply(camera.matrixWorldInverse);
  35761. tempMat.premultiply(camera.projectionMatrix);
  35762. if (typeof frustum.setFromProjectionMatrix === 'function') {
  35763. frustum.setFromProjectionMatrix(tempMat);
  35764. } else {
  35765. this.setFromProjectionMatrix(frustum, tempMat);
  35766. } // get transform position in group root frame
  35767. position.set(0, 0, 0);
  35768. position.applyMatrix4(camera.matrixWorld);
  35769. position.applyMatrix4(tempMat2);
  35770. }
  35771. _get(_getPrototypeOf(TilesRenderer.prototype), "update", this).call(this);
  35772. }
  35773. }, {
  35774. key: "preprocessNode",
  35775. value: function preprocessNode(tile, parentTile, tileSetDir) {
  35776. _get(_getPrototypeOf(TilesRenderer.prototype), "preprocessNode", this).call(this, tile, parentTile, tileSetDir);
  35777. var transform = new _three.Matrix4();
  35778. if (tile.transform) {
  35779. var transformArr = tile.transform;
  35780. for (var i = 0; i < 16; i++) {
  35781. transform.elements[i] = transformArr[i];
  35782. }
  35783. } else {
  35784. transform.identity();
  35785. }
  35786. if (parentTile) {
  35787. transform.multiply(parentTile.cached.transform);
  35788. }
  35789. var box = null;
  35790. var boxTransform = null;
  35791. var boxTransformInverse = null;
  35792. if ('box' in tile.boundingVolume) {
  35793. var data = tile.boundingVolume.box;
  35794. box = new _three.Box3();
  35795. boxTransform = new _three.Matrix4();
  35796. boxTransformInverse = new _three.Matrix4(); // get the extents of the bounds in each axis
  35797. vecX.set(data[3], data[4], data[5]);
  35798. vecY.set(data[6], data[7], data[8]);
  35799. vecZ.set(data[9], data[10], data[11]);
  35800. var scaleX = vecX.length();
  35801. var scaleY = vecY.length();
  35802. var scaleZ = vecZ.length();
  35803. vecX.normalize();
  35804. vecY.normalize();
  35805. vecZ.normalize(); // create the oriented frame that the box exists in
  35806. 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);
  35807. boxTransform.premultiply(transform);
  35808. boxTransformInverse.copy(boxTransform).invert(); // scale the box by the extents
  35809. box.min.set(-scaleX, -scaleY, -scaleZ);
  35810. box.max.set(scaleX, scaleY, scaleZ);
  35811. }
  35812. var sphere = null;
  35813. if ('sphere' in tile.boundingVolume) {
  35814. var _data = tile.boundingVolume.sphere;
  35815. sphere = new _three.Sphere();
  35816. sphere.center.set(_data[0], _data[1], _data[2]);
  35817. sphere.radius = _data[3];
  35818. sphere.applyMatrix4(transform);
  35819. } else if ('box' in tile.boundingVolume) {
  35820. var _data2 = tile.boundingVolume.box;
  35821. sphere = new _three.Sphere();
  35822. box.getBoundingSphere(sphere);
  35823. sphere.center.set(_data2[0], _data2[1], _data2[2]);
  35824. sphere.applyMatrix4(transform);
  35825. }
  35826. var region = null;
  35827. if ('region' in tile.boundingVolume) {
  35828. console.warn('ThreeTilesRenderer: region bounding volume not supported.');
  35829. }
  35830. tile.cached = {
  35831. loadIndex: 0,
  35832. transform: transform,
  35833. active: false,
  35834. inFrustum: [],
  35835. box: box,
  35836. boxTransform: boxTransform,
  35837. boxTransformInverse: boxTransformInverse,
  35838. sphere: sphere,
  35839. region: region,
  35840. scene: null,
  35841. geometry: null,
  35842. material: null,
  35843. distance: Infinity
  35844. };
  35845. }
  35846. }, {
  35847. key: "parseTile",
  35848. value: function parseTile(buffer, tile, extension) {
  35849. var _this3 = this;
  35850. tile._loadIndex = tile._loadIndex || 0;
  35851. tile._loadIndex++;
  35852. var manager = this.manager;
  35853. var loadIndex = tile._loadIndex;
  35854. var promise = null;
  35855. switch (extension) {
  35856. case 'b3dm':
  35857. promise = new _B3DMLoader.B3DMLoader(manager).parse(buffer).then(function (res) {
  35858. return res.scene;
  35859. });
  35860. break;
  35861. case 'pnts':
  35862. promise = Promise.resolve(new _PNTSLoader.PNTSLoader(manager).parse(buffer).scene);
  35863. break;
  35864. case 'i3dm':
  35865. promise = new _I3DMLoader.I3DMLoader(manager).parse(buffer).then(function (res) {
  35866. return res.scene;
  35867. });
  35868. break;
  35869. case 'cmpt':
  35870. promise = new _CMPTLoader.CMPTLoader(manager).parse(buffer).then(function (res) {
  35871. return res.scene;
  35872. });
  35873. break;
  35874. default:
  35875. console.warn("TilesRenderer: Content type \"".concat(extension, "\" not supported."));
  35876. promise = Promise.resolve(null);
  35877. break;
  35878. }
  35879. return promise.then(function (scene) {
  35880. if (tile._loadIndex !== loadIndex) {
  35881. return;
  35882. }
  35883. var upAxis = _this3.rootTileSet.asset && _this3.rootTileSet.asset.gltfUpAxis || 'y';
  35884. var cached = tile.cached;
  35885. var cachedTransform = cached.transform;
  35886. switch (upAxis.toLowerCase()) {
  35887. case 'x':
  35888. scene.matrix.makeRotationAxis(Y_AXIS, -Math.PI / 2);
  35889. break;
  35890. case 'y':
  35891. scene.matrix.makeRotationAxis(X_AXIS, Math.PI / 2);
  35892. break;
  35893. case 'z':
  35894. break;
  35895. }
  35896. scene.matrix.premultiply(cachedTransform);
  35897. scene.matrix.decompose(scene.position, scene.quaternion, scene.scale);
  35898. scene.traverse(function (c) {
  35899. c[INITIAL_FRUSTUM_CULLED] = c.frustumCulled;
  35900. });
  35901. updateFrustumCulled(scene, _this3.autoDisableRendererCulling);
  35902. cached.scene = scene; // We handle raycasting in a custom way so remove it from here
  35903. scene.traverse(function (c) {
  35904. c.raycast = emptyRaycast;
  35905. });
  35906. var materials = [];
  35907. var geometry = [];
  35908. var textures = [];
  35909. scene.traverse(function (c) {
  35910. if (c.geometry) {
  35911. geometry.push(c.geometry);
  35912. }
  35913. if (c.material) {
  35914. var material = c.material;
  35915. materials.push(c.material);
  35916. for (var key in material) {
  35917. var value = material[key];
  35918. if (value && value.isTexture) {
  35919. textures.push(value);
  35920. }
  35921. }
  35922. }
  35923. });
  35924. cached.materials = materials;
  35925. cached.geometry = geometry;
  35926. cached.textures = textures;
  35927. if (_this3.onLoadModel) {
  35928. _this3.onLoadModel(scene, tile);
  35929. }
  35930. });
  35931. }
  35932. }, {
  35933. key: "disposeTile",
  35934. value: function disposeTile(tile) {
  35935. // This could get called before the tile has finished downloading
  35936. var cached = tile.cached;
  35937. if (cached.scene) {
  35938. var materials = cached.materials;
  35939. var geometry = cached.geometry;
  35940. var textures = cached.textures;
  35941. for (var i = 0, l = geometry.length; i < l; i++) {
  35942. geometry[i].dispose();
  35943. }
  35944. for (var _i = 0, _l = materials.length; _i < _l; _i++) {
  35945. materials[_i].dispose();
  35946. }
  35947. for (var _i2 = 0, _l2 = textures.length; _i2 < _l2; _i2++) {
  35948. var texture = textures[_i2];
  35949. texture.dispose();
  35950. }
  35951. if (this.onDisposeModel) {
  35952. this.onDisposeModel(cached.scene, tile);
  35953. }
  35954. cached.scene = null;
  35955. cached.materials = null;
  35956. cached.textures = null;
  35957. cached.geometry = null;
  35958. }
  35959. tile._loadIndex++;
  35960. }
  35961. }, {
  35962. key: "setTileVisible",
  35963. value: function setTileVisible(tile, visible) {
  35964. var scene = tile.cached.scene;
  35965. var visibleTiles = this.visibleTiles;
  35966. var group = this.group;
  35967. if (visible) {
  35968. group.add(scene);
  35969. visibleTiles.add(tile);
  35970. scene.updateMatrixWorld(true);
  35971. } else {
  35972. group.remove(scene);
  35973. visibleTiles.delete(tile);
  35974. }
  35975. }
  35976. }, {
  35977. key: "setTileActive",
  35978. value: function setTileActive(tile, active) {
  35979. var activeTiles = this.activeTiles;
  35980. if (active) {
  35981. activeTiles.add(tile);
  35982. } else {
  35983. activeTiles.delete(tile);
  35984. }
  35985. }
  35986. }, {
  35987. key: "calculateError",
  35988. value: function calculateError(tile) {
  35989. if (tile.geometricError === 0.0) {
  35990. return 0.0;
  35991. }
  35992. var cached = tile.cached;
  35993. var inFrustum = cached.inFrustum;
  35994. var cameras = this.cameras;
  35995. var cameraInfo = this.cameraInfo; // TODO: Use the content bounding volume here?
  35996. var boundingVolume = tile.boundingVolume;
  35997. if ('box' in boundingVolume) {
  35998. var boundingBox = cached.box;
  35999. var boxTransformInverse = cached.boxTransformInverse;
  36000. var maxError = -Infinity;
  36001. var minDistance = Infinity;
  36002. for (var i = 0, l = cameras.length; i < l; i++) {
  36003. if (!inFrustum[i]) {
  36004. continue;
  36005. } // transform camera position into local frame of the tile bounding box
  36006. var camera = cameras[i];
  36007. var info = cameraInfo[i];
  36008. var invScale = info.invScale;
  36009. tempVector.copy(info.position);
  36010. tempVector.applyMatrix4(boxTransformInverse);
  36011. var error = void 0;
  36012. if (camera.isOrthographicCamera) {
  36013. var pixelSize = info.pixelSize;
  36014. error = tile.geometricError / (pixelSize * invScale);
  36015. } else {
  36016. var distance = boundingBox.distanceToPoint(tempVector);
  36017. var scaledDistance = distance * invScale;
  36018. var sseDenominator = info.sseDenominator;
  36019. error = tile.geometricError / (scaledDistance * sseDenominator);
  36020. minDistance = Math.min(minDistance, scaledDistance);
  36021. }
  36022. maxError = Math.max(maxError, error);
  36023. }
  36024. tile.cached.distance = minDistance;
  36025. return maxError;
  36026. } else if ('sphere' in boundingVolume) {
  36027. // const sphere = cached.sphere;
  36028. console.warn('ThreeTilesRenderer : Sphere bounds not supported.');
  36029. } else if ('region' in boundingVolume) {
  36030. // unsupported
  36031. console.warn('ThreeTilesRenderer : Region bounds not supported.');
  36032. }
  36033. return Infinity;
  36034. }
  36035. }, {
  36036. key: "tileInView",
  36037. value: function tileInView(tile) {
  36038. // TODO: we should use the more precise bounding volumes here if possible
  36039. // cache the root-space planes
  36040. // Use separating axis theorem for frustum and obb
  36041. var cached = tile.cached;
  36042. var sphere = cached.sphere;
  36043. var inFrustum = cached.inFrustum;
  36044. if (sphere) {
  36045. var cameraInfo = this.cameraInfo;
  36046. var inView = false;
  36047. for (var i = 0, l = cameraInfo.length; i < l; i++) {
  36048. // Track which camera frustums this tile is in so we can use it
  36049. // to ignore the error calculations for cameras that can't see it
  36050. var frustum = cameraInfo[i].frustum;
  36051. if (frustum.intersectsSphere(sphere)) {
  36052. inView = true;
  36053. inFrustum[i] = true;
  36054. } else {
  36055. inFrustum[i] = false;
  36056. }
  36057. }
  36058. return inView;
  36059. }
  36060. return true;
  36061. }
  36062. }]);
  36063. return TilesRenderer;
  36064. }(_TilesRendererBase2.TilesRendererBase);
  36065. exports.TilesRenderer = TilesRenderer;
  36066. },{"../base/TilesRendererBase.js":"../src/base/TilesRendererBase.js","./B3DMLoader.js":"../src/three/B3DMLoader.js","./PNTSLoader.js":"../src/three/PNTSLoader.js","./I3DMLoader.js":"../src/three/I3DMLoader.js","./CMPTLoader.js":"../src/three/CMPTLoader.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) {
  36067. "use strict";
  36068. Object.defineProperty(exports, "__esModule", {
  36069. value: true
  36070. });
  36071. exports.SphereHelper = void 0;
  36072. var _three = require("three");
  36073. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  36074. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  36075. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  36076. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  36077. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  36078. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  36079. function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
  36080. function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
  36081. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  36082. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  36083. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  36084. var _vector = new _three.Vector3();
  36085. var axes = ['x', 'y', 'z'];
  36086. var SphereHelper =
  36087. /*#__PURE__*/
  36088. function (_LineSegments) {
  36089. _inherits(SphereHelper, _LineSegments);
  36090. function SphereHelper(sphere) {
  36091. var _this;
  36092. var color = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0xffff00;
  36093. var angleSteps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 40;
  36094. _classCallCheck(this, SphereHelper);
  36095. var geometry = new _three.BufferGeometry();
  36096. var positions = [];
  36097. for (var i = 0; i < 3; i++) {
  36098. var axis1 = axes[i];
  36099. var axis2 = axes[(i + 1) % 3];
  36100. _vector.set(0, 0, 0);
  36101. for (var a = 0; a < angleSteps; a++) {
  36102. var angle = void 0;
  36103. angle = 2 * Math.PI * a / (angleSteps - 1);
  36104. _vector[axis1] = Math.sin(angle);
  36105. _vector[axis2] = Math.cos(angle);
  36106. positions.push(_vector.x, _vector.y, _vector.z);
  36107. angle = 2 * Math.PI * (a + 1) / (angleSteps - 1);
  36108. _vector[axis1] = Math.sin(angle);
  36109. _vector[axis2] = Math.cos(angle);
  36110. positions.push(_vector.x, _vector.y, _vector.z);
  36111. }
  36112. }
  36113. geometry.setAttribute('position', new _three.BufferAttribute(new Float32Array(positions), 3));
  36114. geometry.computeBoundingSphere();
  36115. _this = _possibleConstructorReturn(this, _getPrototypeOf(SphereHelper).call(this, geometry, new _three.LineBasicMaterial({
  36116. color: color,
  36117. toneMapped: false
  36118. })));
  36119. _this.sphere = sphere;
  36120. _this.type = 'SphereHelper';
  36121. return _this;
  36122. }
  36123. _createClass(SphereHelper, [{
  36124. key: "updateMatrixWorld",
  36125. value: function updateMatrixWorld(force) {
  36126. var sphere = this.sphere;
  36127. this.position.copy(sphere.center);
  36128. this.scale.setScalar(sphere.radius);
  36129. _get(_getPrototypeOf(SphereHelper.prototype), "updateMatrixWorld", this).call(this, force);
  36130. }
  36131. }]);
  36132. return SphereHelper;
  36133. }(_three.LineSegments);
  36134. exports.SphereHelper = SphereHelper;
  36135. },{"three":"../node_modules/three/build/three.module.js"}],"../src/three/DebugTilesRenderer.js":[function(require,module,exports) {
  36136. "use strict";
  36137. Object.defineProperty(exports, "__esModule", {
  36138. value: true
  36139. });
  36140. exports.DebugTilesRenderer = exports.RANDOM_COLOR = exports.IS_LEAF = exports.RELATIVE_DEPTH = exports.DEPTH = exports.DISTANCE = exports.GEOMETRIC_ERROR = exports.SCREEN_ERROR = exports.NONE = void 0;
  36141. var _three = require("three");
  36142. var _TilesRenderer2 = require("./TilesRenderer.js");
  36143. var _SphereHelper = require("./SphereHelper.js");
  36144. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  36145. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  36146. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  36147. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  36148. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  36149. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  36150. function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
  36151. function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
  36152. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  36153. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  36154. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  36155. var ORIGINAL_MATERIAL = Symbol('ORIGINAL_MATERIAL');
  36156. var HAS_RANDOM_COLOR = Symbol('HAS_RANDOM_COLOR');
  36157. function emptyRaycast() {}
  36158. var NONE = 0;
  36159. exports.NONE = NONE;
  36160. var SCREEN_ERROR = 1;
  36161. exports.SCREEN_ERROR = SCREEN_ERROR;
  36162. var GEOMETRIC_ERROR = 2;
  36163. exports.GEOMETRIC_ERROR = GEOMETRIC_ERROR;
  36164. var DISTANCE = 3;
  36165. exports.DISTANCE = DISTANCE;
  36166. var DEPTH = 4;
  36167. exports.DEPTH = DEPTH;
  36168. var RELATIVE_DEPTH = 5;
  36169. exports.RELATIVE_DEPTH = RELATIVE_DEPTH;
  36170. var IS_LEAF = 6;
  36171. exports.IS_LEAF = IS_LEAF;
  36172. var RANDOM_COLOR = 7;
  36173. exports.RANDOM_COLOR = RANDOM_COLOR;
  36174. var DebugTilesRenderer =
  36175. /*#__PURE__*/
  36176. function (_TilesRenderer) {
  36177. _inherits(DebugTilesRenderer, _TilesRenderer);
  36178. function DebugTilesRenderer() {
  36179. var _getPrototypeOf2;
  36180. var _this;
  36181. _classCallCheck(this, DebugTilesRenderer);
  36182. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  36183. args[_key] = arguments[_key];
  36184. }
  36185. _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(DebugTilesRenderer)).call.apply(_getPrototypeOf2, [this].concat(args)));
  36186. var tilesGroup = _this.group;
  36187. var boxGroup = new _three.Group();
  36188. tilesGroup.add(boxGroup);
  36189. var sphereGroup = new _three.Group();
  36190. tilesGroup.add(sphereGroup);
  36191. _this.displayBoxBounds = false;
  36192. _this.displaySphereBounds = false;
  36193. _this.colorMode = NONE;
  36194. _this.boxGroup = boxGroup;
  36195. _this.sphereGroup = sphereGroup;
  36196. _this.maxDebugDepth = -1;
  36197. _this.maxDebugDistance = -1;
  36198. _this.maxDebugError = -1;
  36199. _this.extremeDebugDepth = -1;
  36200. _this.extremeDebugError = -1;
  36201. return _this;
  36202. }
  36203. _createClass(DebugTilesRenderer, [{
  36204. key: "initExtremes",
  36205. value: function initExtremes() {
  36206. // initialize the extreme values of the hierarchy
  36207. var maxDepth = -1;
  36208. this.traverse(function (tile) {
  36209. maxDepth = Math.max(maxDepth, tile.__depth);
  36210. });
  36211. var maxError = -1;
  36212. this.traverse(function (tile) {
  36213. maxError = Math.max(maxError, tile.geometricError);
  36214. });
  36215. this.extremeDebugDepth = maxDepth;
  36216. this.extremeDebugError = maxError;
  36217. }
  36218. }, {
  36219. key: "loadTileSet",
  36220. value: function loadTileSet() {
  36221. var _get2,
  36222. _this2 = this;
  36223. for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  36224. args[_key2] = arguments[_key2];
  36225. }
  36226. var pr = (_get2 = _get(_getPrototypeOf(DebugTilesRenderer.prototype), "loadTileSet", this)).call.apply(_get2, [this].concat(args));
  36227. pr.then(function () {
  36228. return _this2.initExtremes();
  36229. }).catch(function () {// error is logged internally
  36230. });
  36231. return pr;
  36232. }
  36233. }, {
  36234. key: "getTileInformationFromActiveObject",
  36235. value: function getTileInformationFromActiveObject(object) {
  36236. // Find which tile this scene is associated with. This is slow and
  36237. // intended for debug purposes only.
  36238. var targetTile = null;
  36239. var activeTiles = this.activeTiles;
  36240. activeTiles.forEach(function (tile) {
  36241. if (targetTile) {
  36242. return true;
  36243. }
  36244. var scene = tile.cached.scene;
  36245. if (scene) {
  36246. scene.traverse(function (c) {
  36247. if (c === object) {
  36248. targetTile = tile;
  36249. }
  36250. });
  36251. }
  36252. });
  36253. if (targetTile) {
  36254. return {
  36255. distanceToCamera: targetTile.cached.distance,
  36256. geometricError: targetTile.geometricError,
  36257. screenSpaceError: targetTile.__error,
  36258. depth: targetTile.__depth,
  36259. isLeaf: targetTile.__isLeaf
  36260. };
  36261. } else {
  36262. return null;
  36263. }
  36264. }
  36265. }, {
  36266. key: "update",
  36267. value: function update() {
  36268. _get(_getPrototypeOf(DebugTilesRenderer.prototype), "update", this).call(this);
  36269. if (!this.root) {
  36270. return;
  36271. } // set box or sphere visibility
  36272. this.boxGroup.visible = this.displayBoxBounds;
  36273. this.sphereGroup.visible = this.displaySphereBounds; // get max values to use for materials
  36274. var maxDepth = -1;
  36275. if (this.maxDebugDepth === -1) {
  36276. maxDepth = this.extremeDebugDepth;
  36277. } else {
  36278. maxDepth = this.maxDebugDepth;
  36279. }
  36280. var maxError = -1;
  36281. if (this.maxDebugError === -1) {
  36282. maxError = this.extremeDebugError;
  36283. } else {
  36284. maxError = this.maxDebugError;
  36285. }
  36286. var maxDistance = -1;
  36287. if (this.maxDebugDistance === -1) {
  36288. maxDistance = this.root.cached.sphere.radius;
  36289. } else {
  36290. maxDistance = this.maxDebugDistance;
  36291. }
  36292. var errorTarget = this.errorTarget;
  36293. var colorMode = this.colorMode;
  36294. var visibleTiles = this.visibleTiles;
  36295. visibleTiles.forEach(function (tile) {
  36296. var scene = tile.cached.scene; // create a random color per-tile
  36297. var h, s, l;
  36298. if (colorMode === RANDOM_COLOR) {
  36299. h = Math.random();
  36300. s = 0.5 + Math.random() * 0.5;
  36301. l = 0.375 + Math.random() * 0.25;
  36302. }
  36303. scene.traverse(function (c) {
  36304. var currMaterial = c.material;
  36305. if (currMaterial) {
  36306. // Reset the material if needed
  36307. var originalMaterial = c[ORIGINAL_MATERIAL];
  36308. if (colorMode === NONE && currMaterial !== originalMaterial) {
  36309. c.material.dispose();
  36310. c.material = c[ORIGINAL_MATERIAL];
  36311. } else if (colorMode !== NONE && currMaterial === originalMaterial) {
  36312. if (c.isPoints) {
  36313. var pointsMaterial = new _three.PointsMaterial();
  36314. pointsMaterial.size = originalMaterial.size;
  36315. pointsMaterial.sizeAttenuation = originalMaterial.sizeAttenuation;
  36316. c.material = pointsMaterial;
  36317. } else {
  36318. c.material = new _three.MeshBasicMaterial();
  36319. }
  36320. }
  36321. if (colorMode !== RANDOM_COLOR) {
  36322. delete c.material[HAS_RANDOM_COLOR];
  36323. } // Set the color on the basic material
  36324. switch (colorMode) {
  36325. case DEPTH:
  36326. {
  36327. var val = tile.__depth / maxDepth;
  36328. c.material.color.setRGB(val, val, val);
  36329. break;
  36330. }
  36331. case RELATIVE_DEPTH:
  36332. {
  36333. var _val = tile.__depthFromRenderedParent / maxDepth;
  36334. c.material.color.setRGB(_val, _val, _val);
  36335. break;
  36336. }
  36337. case SCREEN_ERROR:
  36338. {
  36339. var _val2 = tile.__error / errorTarget;
  36340. if (_val2 > 1.0) {
  36341. c.material.color.setRGB(1.0, 0.0, 0.0);
  36342. } else {
  36343. c.material.color.setRGB(_val2, _val2, _val2);
  36344. }
  36345. break;
  36346. }
  36347. case GEOMETRIC_ERROR:
  36348. {
  36349. var _val3 = Math.min(tile.geometricError / maxError, 1);
  36350. c.material.color.setRGB(_val3, _val3, _val3);
  36351. break;
  36352. }
  36353. case DISTANCE:
  36354. {
  36355. // We don't update the distance if the geometric error is 0.0 so
  36356. // it will always be black.
  36357. var _val4 = Math.min(tile.cached.distance / maxDistance, 1);
  36358. c.material.color.setRGB(_val4, _val4, _val4);
  36359. break;
  36360. }
  36361. case IS_LEAF:
  36362. {
  36363. if (!tile.children || tile.children.length === 0) {
  36364. c.material.color.set(0xffffff);
  36365. } else {
  36366. c.material.color.set(0);
  36367. }
  36368. break;
  36369. }
  36370. case RANDOM_COLOR:
  36371. {
  36372. if (!c.material[HAS_RANDOM_COLOR]) {
  36373. c.material.color.setHSL(h, s, l);
  36374. c.material[HAS_RANDOM_COLOR] = true;
  36375. }
  36376. break;
  36377. }
  36378. }
  36379. }
  36380. });
  36381. });
  36382. }
  36383. }, {
  36384. key: "setTileVisible",
  36385. value: function setTileVisible(tile, visible) {
  36386. _get(_getPrototypeOf(DebugTilesRenderer.prototype), "setTileVisible", this).call(this, tile, visible);
  36387. var cached = tile.cached;
  36388. var sphereGroup = this.sphereGroup;
  36389. var boxGroup = this.boxGroup;
  36390. var boxHelperGroup = cached.boxHelperGroup;
  36391. var sphereHelper = cached.sphereHelper;
  36392. if (!visible) {
  36393. boxGroup.remove(boxHelperGroup);
  36394. sphereGroup.remove(sphereHelper);
  36395. } else {
  36396. boxGroup.add(boxHelperGroup);
  36397. boxHelperGroup.updateMatrixWorld(true);
  36398. sphereGroup.add(sphereHelper);
  36399. sphereHelper.updateMatrixWorld(true);
  36400. }
  36401. }
  36402. }, {
  36403. key: "parseTile",
  36404. value: function parseTile(buffer, tile, extension) {
  36405. var _this3 = this;
  36406. return _get(_getPrototypeOf(DebugTilesRenderer.prototype), "parseTile", this).call(this, buffer, tile, extension).then(function () {
  36407. var cached = tile.cached;
  36408. var scene = cached.scene;
  36409. if (scene) {
  36410. var cachedBox = cached.box;
  36411. var cachedBoxMat = cached.boxTransform; // Create debug bounding box
  36412. var boxHelperGroup = new _three.Group();
  36413. boxHelperGroup.matrix.copy(cachedBoxMat);
  36414. boxHelperGroup.matrix.decompose(boxHelperGroup.position, boxHelperGroup.quaternion, boxHelperGroup.scale);
  36415. var boxHelper = new _three.Box3Helper(cachedBox);
  36416. boxHelper.raycast = emptyRaycast;
  36417. boxHelperGroup.add(boxHelper);
  36418. cached.boxHelperGroup = boxHelperGroup;
  36419. if (_this3.visibleTiles.has(tile) && _this3.displayBoxBounds) {
  36420. _this3.boxGroup.add(boxHelperGroup);
  36421. boxHelperGroup.updateMatrixWorld(true);
  36422. } // Create debugbounding sphere
  36423. var cachedSphere = cached.sphere;
  36424. var sphereHelper = new _SphereHelper.SphereHelper(cachedSphere);
  36425. sphereHelper.raycast = emptyRaycast;
  36426. cached.sphereHelper = sphereHelper;
  36427. if (_this3.visibleTiles.has(tile) && _this3.displaySphereBounds) {
  36428. _this3.sphereGroup.add(sphereHelper);
  36429. sphereHelper.updateMatrixWorld(true);
  36430. } // Cache the original materials
  36431. scene.traverse(function (c) {
  36432. var material = c.material;
  36433. if (material) {
  36434. c[ORIGINAL_MATERIAL] = material;
  36435. }
  36436. });
  36437. }
  36438. });
  36439. }
  36440. }, {
  36441. key: "disposeTile",
  36442. value: function disposeTile(tile) {
  36443. _get(_getPrototypeOf(DebugTilesRenderer.prototype), "disposeTile", this).call(this, tile);
  36444. var cached = tile.cached;
  36445. if (cached.boxHelperGroup) {
  36446. cached.boxHelperGroup.children[0].geometry.dispose();
  36447. cached.sphereHelper.geometry.dispose();
  36448. delete cached.boxHelperGroup;
  36449. delete cached.sphereHelper;
  36450. }
  36451. }
  36452. }]);
  36453. return DebugTilesRenderer;
  36454. }(_TilesRenderer2.TilesRenderer);
  36455. exports.DebugTilesRenderer = DebugTilesRenderer;
  36456. },{"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) {
  36457. "use strict";
  36458. Object.defineProperty(exports, "__esModule", {
  36459. value: true
  36460. });
  36461. Object.defineProperty(exports, "DebugTilesRenderer", {
  36462. enumerable: true,
  36463. get: function () {
  36464. return _DebugTilesRenderer.DebugTilesRenderer;
  36465. }
  36466. });
  36467. Object.defineProperty(exports, "NONE", {
  36468. enumerable: true,
  36469. get: function () {
  36470. return _DebugTilesRenderer.NONE;
  36471. }
  36472. });
  36473. Object.defineProperty(exports, "SCREEN_ERROR", {
  36474. enumerable: true,
  36475. get: function () {
  36476. return _DebugTilesRenderer.SCREEN_ERROR;
  36477. }
  36478. });
  36479. Object.defineProperty(exports, "GEOMETRIC_ERROR", {
  36480. enumerable: true,
  36481. get: function () {
  36482. return _DebugTilesRenderer.GEOMETRIC_ERROR;
  36483. }
  36484. });
  36485. Object.defineProperty(exports, "DISTANCE", {
  36486. enumerable: true,
  36487. get: function () {
  36488. return _DebugTilesRenderer.DISTANCE;
  36489. }
  36490. });
  36491. Object.defineProperty(exports, "DEPTH", {
  36492. enumerable: true,
  36493. get: function () {
  36494. return _DebugTilesRenderer.DEPTH;
  36495. }
  36496. });
  36497. Object.defineProperty(exports, "RELATIVE_DEPTH", {
  36498. enumerable: true,
  36499. get: function () {
  36500. return _DebugTilesRenderer.RELATIVE_DEPTH;
  36501. }
  36502. });
  36503. Object.defineProperty(exports, "IS_LEAF", {
  36504. enumerable: true,
  36505. get: function () {
  36506. return _DebugTilesRenderer.IS_LEAF;
  36507. }
  36508. });
  36509. Object.defineProperty(exports, "RANDOM_COLOR", {
  36510. enumerable: true,
  36511. get: function () {
  36512. return _DebugTilesRenderer.RANDOM_COLOR;
  36513. }
  36514. });
  36515. Object.defineProperty(exports, "TilesRenderer", {
  36516. enumerable: true,
  36517. get: function () {
  36518. return _TilesRenderer.TilesRenderer;
  36519. }
  36520. });
  36521. Object.defineProperty(exports, "B3DMLoader", {
  36522. enumerable: true,
  36523. get: function () {
  36524. return _B3DMLoader.B3DMLoader;
  36525. }
  36526. });
  36527. Object.defineProperty(exports, "PNTSLoader", {
  36528. enumerable: true,
  36529. get: function () {
  36530. return _PNTSLoader.PNTSLoader;
  36531. }
  36532. });
  36533. Object.defineProperty(exports, "I3DMLoader", {
  36534. enumerable: true,
  36535. get: function () {
  36536. return _I3DMLoader.I3DMLoader;
  36537. }
  36538. });
  36539. Object.defineProperty(exports, "CMPTLoader", {
  36540. enumerable: true,
  36541. get: function () {
  36542. return _CMPTLoader.CMPTLoader;
  36543. }
  36544. });
  36545. Object.defineProperty(exports, "TilesRendererBase", {
  36546. enumerable: true,
  36547. get: function () {
  36548. return _TilesRendererBase.TilesRendererBase;
  36549. }
  36550. });
  36551. Object.defineProperty(exports, "B3DMLoaderBase", {
  36552. enumerable: true,
  36553. get: function () {
  36554. return _B3DMLoaderBase.B3DMLoaderBase;
  36555. }
  36556. });
  36557. Object.defineProperty(exports, "I3DMLoaderBase", {
  36558. enumerable: true,
  36559. get: function () {
  36560. return _I3DMLoaderBase.I3DMLoaderBase;
  36561. }
  36562. });
  36563. Object.defineProperty(exports, "PNTSLoaderBase", {
  36564. enumerable: true,
  36565. get: function () {
  36566. return _PNTSLoaderBase.PNTSLoaderBase;
  36567. }
  36568. });
  36569. Object.defineProperty(exports, "CMPTLoaderBase", {
  36570. enumerable: true,
  36571. get: function () {
  36572. return _CMPTLoaderBase.CMPTLoaderBase;
  36573. }
  36574. });
  36575. Object.defineProperty(exports, "LRUCache", {
  36576. enumerable: true,
  36577. get: function () {
  36578. return _LRUCache.LRUCache;
  36579. }
  36580. });
  36581. Object.defineProperty(exports, "PriorityQueue", {
  36582. enumerable: true,
  36583. get: function () {
  36584. return _PriorityQueue.PriorityQueue;
  36585. }
  36586. });
  36587. var _DebugTilesRenderer = require("./three/DebugTilesRenderer.js");
  36588. var _TilesRenderer = require("./three/TilesRenderer.js");
  36589. var _B3DMLoader = require("./three/B3DMLoader.js");
  36590. var _PNTSLoader = require("./three/PNTSLoader.js");
  36591. var _I3DMLoader = require("./three/I3DMLoader.js");
  36592. var _CMPTLoader = require("./three/CMPTLoader.js");
  36593. var _TilesRendererBase = require("./base/TilesRendererBase.js");
  36594. var _B3DMLoaderBase = require("./base/B3DMLoaderBase.js");
  36595. var _I3DMLoaderBase = require("./base/I3DMLoaderBase.js");
  36596. var _PNTSLoaderBase = require("./base/PNTSLoaderBase.js");
  36597. var _CMPTLoaderBase = require("./base/CMPTLoaderBase.js");
  36598. var _LRUCache = require("./utilities/LRUCache.js");
  36599. var _PriorityQueue = require("./utilities/PriorityQueue.js");
  36600. },{"./three/DebugTilesRenderer.js":"../src/three/DebugTilesRenderer.js","./three/TilesRenderer.js":"../src/three/TilesRenderer.js","./three/B3DMLoader.js":"../src/three/B3DMLoader.js","./three/PNTSLoader.js":"../src/three/PNTSLoader.js","./three/I3DMLoader.js":"../src/three/I3DMLoader.js","./three/CMPTLoader.js":"../src/three/CMPTLoader.js","./base/TilesRendererBase.js":"../src/base/TilesRendererBase.js","./base/B3DMLoaderBase.js":"../src/base/B3DMLoaderBase.js","./base/I3DMLoaderBase.js":"../src/base/I3DMLoaderBase.js","./base/PNTSLoaderBase.js":"../src/base/PNTSLoaderBase.js","./base/CMPTLoaderBase.js":"../src/base/CMPTLoaderBase.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) {
  36601. "use strict";
  36602. Object.defineProperty(exports, "__esModule", {
  36603. value: true
  36604. });
  36605. exports.MapControls = exports.OrbitControls = void 0;
  36606. var _threeModule = require("../../../build/three.module.js");
  36607. // This set of controls performs orbiting, dollying (zooming), and panning.
  36608. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  36609. //
  36610. // Orbit - left mouse / touch: one-finger move
  36611. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  36612. // Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move
  36613. var OrbitControls = function (object, domElement) {
  36614. if (domElement === undefined) console.warn('THREE.OrbitControls: The second parameter "domElement" is now mandatory.');
  36615. if (domElement === document) console.error('THREE.OrbitControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.');
  36616. this.object = object;
  36617. this.domElement = domElement; // Set to false to disable this control
  36618. this.enabled = true; // "target" sets the location of focus, where the object orbits around
  36619. this.target = new _threeModule.Vector3(); // How far you can dolly in and out ( PerspectiveCamera only )
  36620. this.minDistance = 0;
  36621. this.maxDistance = Infinity; // How far you can zoom in and out ( OrthographicCamera only )
  36622. this.minZoom = 0;
  36623. this.maxZoom = Infinity; // How far you can orbit vertically, upper and lower limits.
  36624. // Range is 0 to Math.PI radians.
  36625. this.minPolarAngle = 0; // radians
  36626. this.maxPolarAngle = Math.PI; // radians
  36627. // How far you can orbit horizontally, upper and lower limits.
  36628. // If set, the interval [ min, max ] must be a sub-interval of [ - 2 PI, 2 PI ], with ( max - min < 2 PI )
  36629. this.minAzimuthAngle = -Infinity; // radians
  36630. this.maxAzimuthAngle = Infinity; // radians
  36631. // Set to true to enable damping (inertia)
  36632. // If damping is enabled, you must call controls.update() in your animation loop
  36633. this.enableDamping = false;
  36634. this.dampingFactor = 0.05; // This option actually enables dollying in and out; left as "zoom" for backwards compatibility.
  36635. // Set to false to disable zooming
  36636. this.enableZoom = true;
  36637. this.zoomSpeed = 1.0; // Set to false to disable rotating
  36638. this.enableRotate = true;
  36639. this.rotateSpeed = 1.0; // Set to false to disable panning
  36640. this.enablePan = true;
  36641. this.panSpeed = 1.0;
  36642. this.screenSpacePanning = true; // if false, pan orthogonal to world-space direction camera.up
  36643. this.keyPanSpeed = 7.0; // pixels moved per arrow key push
  36644. // Set to true to automatically rotate around the target
  36645. // If auto-rotate is enabled, you must call controls.update() in your animation loop
  36646. this.autoRotate = false;
  36647. this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60
  36648. // Set to false to disable use of the keys
  36649. this.enableKeys = true; // The four arrow keys
  36650. this.keys = {
  36651. LEFT: 37,
  36652. UP: 38,
  36653. RIGHT: 39,
  36654. BOTTOM: 40
  36655. }; // Mouse buttons
  36656. this.mouseButtons = {
  36657. LEFT: _threeModule.MOUSE.ROTATE,
  36658. MIDDLE: _threeModule.MOUSE.DOLLY,
  36659. RIGHT: _threeModule.MOUSE.PAN
  36660. }; // Touch fingers
  36661. this.touches = {
  36662. ONE: _threeModule.TOUCH.ROTATE,
  36663. TWO: _threeModule.TOUCH.DOLLY_PAN
  36664. }; // for reset
  36665. this.target0 = this.target.clone();
  36666. this.position0 = this.object.position.clone();
  36667. this.zoom0 = this.object.zoom; //
  36668. // public methods
  36669. //
  36670. this.getPolarAngle = function () {
  36671. return spherical.phi;
  36672. };
  36673. this.getAzimuthalAngle = function () {
  36674. return spherical.theta;
  36675. };
  36676. this.saveState = function () {
  36677. scope.target0.copy(scope.target);
  36678. scope.position0.copy(scope.object.position);
  36679. scope.zoom0 = scope.object.zoom;
  36680. };
  36681. this.reset = function () {
  36682. scope.target.copy(scope.target0);
  36683. scope.object.position.copy(scope.position0);
  36684. scope.object.zoom = scope.zoom0;
  36685. scope.object.updateProjectionMatrix();
  36686. scope.dispatchEvent(changeEvent);
  36687. scope.update();
  36688. state = STATE.NONE;
  36689. }; // this method is exposed, but perhaps it would be better if we can make it private...
  36690. this.update = function () {
  36691. var offset = new _threeModule.Vector3(); // so camera.up is the orbit axis
  36692. var quat = new _threeModule.Quaternion().setFromUnitVectors(object.up, new _threeModule.Vector3(0, 1, 0));
  36693. var quatInverse = quat.clone().invert();
  36694. var lastPosition = new _threeModule.Vector3();
  36695. var lastQuaternion = new _threeModule.Quaternion();
  36696. var twoPI = 2 * Math.PI;
  36697. return function update() {
  36698. var position = scope.object.position;
  36699. offset.copy(position).sub(scope.target); // rotate offset to "y-axis-is-up" space
  36700. offset.applyQuaternion(quat); // angle from z-axis around y-axis
  36701. spherical.setFromVector3(offset);
  36702. if (scope.autoRotate && state === STATE.NONE) {
  36703. rotateLeft(getAutoRotationAngle());
  36704. }
  36705. if (scope.enableDamping) {
  36706. spherical.theta += sphericalDelta.theta * scope.dampingFactor;
  36707. spherical.phi += sphericalDelta.phi * scope.dampingFactor;
  36708. } else {
  36709. spherical.theta += sphericalDelta.theta;
  36710. spherical.phi += sphericalDelta.phi;
  36711. } // restrict theta to be between desired limits
  36712. var min = scope.minAzimuthAngle;
  36713. var max = scope.maxAzimuthAngle;
  36714. if (isFinite(min) && isFinite(max)) {
  36715. if (min < -Math.PI) min += twoPI;else if (min > Math.PI) min -= twoPI;
  36716. if (max < -Math.PI) max += twoPI;else if (max > Math.PI) max -= twoPI;
  36717. if (min <= max) {
  36718. spherical.theta = Math.max(min, Math.min(max, spherical.theta));
  36719. } else {
  36720. spherical.theta = spherical.theta > (min + max) / 2 ? Math.max(min, spherical.theta) : Math.min(max, spherical.theta);
  36721. }
  36722. } // restrict phi to be between desired limits
  36723. spherical.phi = Math.max(scope.minPolarAngle, Math.min(scope.maxPolarAngle, spherical.phi));
  36724. spherical.makeSafe();
  36725. spherical.radius *= scale; // restrict radius to be between desired limits
  36726. spherical.radius = Math.max(scope.minDistance, Math.min(scope.maxDistance, spherical.radius)); // move target to panned location
  36727. if (scope.enableDamping === true) {
  36728. scope.target.addScaledVector(panOffset, scope.dampingFactor);
  36729. } else {
  36730. scope.target.add(panOffset);
  36731. }
  36732. offset.setFromSpherical(spherical); // rotate offset back to "camera-up-vector-is-up" space
  36733. offset.applyQuaternion(quatInverse);
  36734. position.copy(scope.target).add(offset);
  36735. scope.object.lookAt(scope.target);
  36736. if (scope.enableDamping === true) {
  36737. sphericalDelta.theta *= 1 - scope.dampingFactor;
  36738. sphericalDelta.phi *= 1 - scope.dampingFactor;
  36739. panOffset.multiplyScalar(1 - scope.dampingFactor);
  36740. } else {
  36741. sphericalDelta.set(0, 0, 0);
  36742. panOffset.set(0, 0, 0);
  36743. }
  36744. scale = 1; // update condition is:
  36745. // min(camera displacement, camera rotation in radians)^2 > EPS
  36746. // using small-angle approximation cos(x/2) = 1 - x^2 / 8
  36747. if (zoomChanged || lastPosition.distanceToSquared(scope.object.position) > EPS || 8 * (1 - lastQuaternion.dot(scope.object.quaternion)) > EPS) {
  36748. scope.dispatchEvent(changeEvent);
  36749. lastPosition.copy(scope.object.position);
  36750. lastQuaternion.copy(scope.object.quaternion);
  36751. zoomChanged = false;
  36752. return true;
  36753. }
  36754. return false;
  36755. };
  36756. }();
  36757. this.dispose = function () {
  36758. scope.domElement.removeEventListener('contextmenu', onContextMenu, false);
  36759. scope.domElement.removeEventListener('pointerdown', onPointerDown, false);
  36760. scope.domElement.removeEventListener('wheel', onMouseWheel, false);
  36761. scope.domElement.removeEventListener('touchstart', onTouchStart, false);
  36762. scope.domElement.removeEventListener('touchend', onTouchEnd, false);
  36763. scope.domElement.removeEventListener('touchmove', onTouchMove, false);
  36764. scope.domElement.ownerDocument.removeEventListener('pointermove', onPointerMove, false);
  36765. scope.domElement.ownerDocument.removeEventListener('pointerup', onPointerUp, false);
  36766. scope.domElement.removeEventListener('keydown', onKeyDown, false); //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here?
  36767. }; //
  36768. // internals
  36769. //
  36770. var scope = this;
  36771. var changeEvent = {
  36772. type: 'change'
  36773. };
  36774. var startEvent = {
  36775. type: 'start'
  36776. };
  36777. var endEvent = {
  36778. type: 'end'
  36779. };
  36780. var STATE = {
  36781. NONE: -1,
  36782. ROTATE: 0,
  36783. DOLLY: 1,
  36784. PAN: 2,
  36785. TOUCH_ROTATE: 3,
  36786. TOUCH_PAN: 4,
  36787. TOUCH_DOLLY_PAN: 5,
  36788. TOUCH_DOLLY_ROTATE: 6
  36789. };
  36790. var state = STATE.NONE;
  36791. var EPS = 0.000001; // current position in spherical coordinates
  36792. var spherical = new _threeModule.Spherical();
  36793. var sphericalDelta = new _threeModule.Spherical();
  36794. var scale = 1;
  36795. var panOffset = new _threeModule.Vector3();
  36796. var zoomChanged = false;
  36797. var rotateStart = new _threeModule.Vector2();
  36798. var rotateEnd = new _threeModule.Vector2();
  36799. var rotateDelta = new _threeModule.Vector2();
  36800. var panStart = new _threeModule.Vector2();
  36801. var panEnd = new _threeModule.Vector2();
  36802. var panDelta = new _threeModule.Vector2();
  36803. var dollyStart = new _threeModule.Vector2();
  36804. var dollyEnd = new _threeModule.Vector2();
  36805. var dollyDelta = new _threeModule.Vector2();
  36806. function getAutoRotationAngle() {
  36807. return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
  36808. }
  36809. function getZoomScale() {
  36810. return Math.pow(0.95, scope.zoomSpeed);
  36811. }
  36812. function rotateLeft(angle) {
  36813. sphericalDelta.theta -= angle;
  36814. }
  36815. function rotateUp(angle) {
  36816. sphericalDelta.phi -= angle;
  36817. }
  36818. var panLeft = function () {
  36819. var v = new _threeModule.Vector3();
  36820. return function panLeft(distance, objectMatrix) {
  36821. v.setFromMatrixColumn(objectMatrix, 0); // get X column of objectMatrix
  36822. v.multiplyScalar(-distance);
  36823. panOffset.add(v);
  36824. };
  36825. }();
  36826. var panUp = function () {
  36827. var v = new _threeModule.Vector3();
  36828. return function panUp(distance, objectMatrix) {
  36829. if (scope.screenSpacePanning === true) {
  36830. v.setFromMatrixColumn(objectMatrix, 1);
  36831. } else {
  36832. v.setFromMatrixColumn(objectMatrix, 0);
  36833. v.crossVectors(scope.object.up, v);
  36834. }
  36835. v.multiplyScalar(distance);
  36836. panOffset.add(v);
  36837. };
  36838. }(); // deltaX and deltaY are in pixels; right and down are positive
  36839. var pan = function () {
  36840. var offset = new _threeModule.Vector3();
  36841. return function pan(deltaX, deltaY) {
  36842. var element = scope.domElement;
  36843. if (scope.object.isPerspectiveCamera) {
  36844. // perspective
  36845. var position = scope.object.position;
  36846. offset.copy(position).sub(scope.target);
  36847. var targetDistance = offset.length(); // half of the fov is center to top of screen
  36848. targetDistance *= Math.tan(scope.object.fov / 2 * Math.PI / 180.0); // we use only clientHeight here so aspect ratio does not distort speed
  36849. panLeft(2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix);
  36850. panUp(2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix);
  36851. } else if (scope.object.isOrthographicCamera) {
  36852. // orthographic
  36853. panLeft(deltaX * (scope.object.right - scope.object.left) / scope.object.zoom / element.clientWidth, scope.object.matrix);
  36854. panUp(deltaY * (scope.object.top - scope.object.bottom) / scope.object.zoom / element.clientHeight, scope.object.matrix);
  36855. } else {
  36856. // camera neither orthographic nor perspective
  36857. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.');
  36858. scope.enablePan = false;
  36859. }
  36860. };
  36861. }();
  36862. function dollyOut(dollyScale) {
  36863. if (scope.object.isPerspectiveCamera) {
  36864. scale /= dollyScale;
  36865. } else if (scope.object.isOrthographicCamera) {
  36866. scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom * dollyScale));
  36867. scope.object.updateProjectionMatrix();
  36868. zoomChanged = true;
  36869. } else {
  36870. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.');
  36871. scope.enableZoom = false;
  36872. }
  36873. }
  36874. function dollyIn(dollyScale) {
  36875. if (scope.object.isPerspectiveCamera) {
  36876. scale *= dollyScale;
  36877. } else if (scope.object.isOrthographicCamera) {
  36878. scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom / dollyScale));
  36879. scope.object.updateProjectionMatrix();
  36880. zoomChanged = true;
  36881. } else {
  36882. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.');
  36883. scope.enableZoom = false;
  36884. }
  36885. } //
  36886. // event callbacks - update the object state
  36887. //
  36888. function handleMouseDownRotate(event) {
  36889. rotateStart.set(event.clientX, event.clientY);
  36890. }
  36891. function handleMouseDownDolly(event) {
  36892. dollyStart.set(event.clientX, event.clientY);
  36893. }
  36894. function handleMouseDownPan(event) {
  36895. panStart.set(event.clientX, event.clientY);
  36896. }
  36897. function handleMouseMoveRotate(event) {
  36898. rotateEnd.set(event.clientX, event.clientY);
  36899. rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);
  36900. var element = scope.domElement;
  36901. rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height
  36902. rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight);
  36903. rotateStart.copy(rotateEnd);
  36904. scope.update();
  36905. }
  36906. function handleMouseMoveDolly(event) {
  36907. dollyEnd.set(event.clientX, event.clientY);
  36908. dollyDelta.subVectors(dollyEnd, dollyStart);
  36909. if (dollyDelta.y > 0) {
  36910. dollyOut(getZoomScale());
  36911. } else if (dollyDelta.y < 0) {
  36912. dollyIn(getZoomScale());
  36913. }
  36914. dollyStart.copy(dollyEnd);
  36915. scope.update();
  36916. }
  36917. function handleMouseMovePan(event) {
  36918. panEnd.set(event.clientX, event.clientY);
  36919. panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);
  36920. pan(panDelta.x, panDelta.y);
  36921. panStart.copy(panEnd);
  36922. scope.update();
  36923. }
  36924. function handleMouseUp()
  36925. /*event*/
  36926. {// no-op
  36927. }
  36928. function handleMouseWheel(event) {
  36929. if (event.deltaY < 0) {
  36930. dollyIn(getZoomScale());
  36931. } else if (event.deltaY > 0) {
  36932. dollyOut(getZoomScale());
  36933. }
  36934. scope.update();
  36935. }
  36936. function handleKeyDown(event) {
  36937. var needsUpdate = false;
  36938. switch (event.keyCode) {
  36939. case scope.keys.UP:
  36940. pan(0, scope.keyPanSpeed);
  36941. needsUpdate = true;
  36942. break;
  36943. case scope.keys.BOTTOM:
  36944. pan(0, -scope.keyPanSpeed);
  36945. needsUpdate = true;
  36946. break;
  36947. case scope.keys.LEFT:
  36948. pan(scope.keyPanSpeed, 0);
  36949. needsUpdate = true;
  36950. break;
  36951. case scope.keys.RIGHT:
  36952. pan(-scope.keyPanSpeed, 0);
  36953. needsUpdate = true;
  36954. break;
  36955. }
  36956. if (needsUpdate) {
  36957. // prevent the browser from scrolling on cursor keys
  36958. event.preventDefault();
  36959. scope.update();
  36960. }
  36961. }
  36962. function handleTouchStartRotate(event) {
  36963. if (event.touches.length == 1) {
  36964. rotateStart.set(event.touches[0].pageX, event.touches[0].pageY);
  36965. } else {
  36966. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  36967. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  36968. rotateStart.set(x, y);
  36969. }
  36970. }
  36971. function handleTouchStartPan(event) {
  36972. if (event.touches.length == 1) {
  36973. panStart.set(event.touches[0].pageX, event.touches[0].pageY);
  36974. } else {
  36975. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  36976. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  36977. panStart.set(x, y);
  36978. }
  36979. }
  36980. function handleTouchStartDolly(event) {
  36981. var dx = event.touches[0].pageX - event.touches[1].pageX;
  36982. var dy = event.touches[0].pageY - event.touches[1].pageY;
  36983. var distance = Math.sqrt(dx * dx + dy * dy);
  36984. dollyStart.set(0, distance);
  36985. }
  36986. function handleTouchStartDollyPan(event) {
  36987. if (scope.enableZoom) handleTouchStartDolly(event);
  36988. if (scope.enablePan) handleTouchStartPan(event);
  36989. }
  36990. function handleTouchStartDollyRotate(event) {
  36991. if (scope.enableZoom) handleTouchStartDolly(event);
  36992. if (scope.enableRotate) handleTouchStartRotate(event);
  36993. }
  36994. function handleTouchMoveRotate(event) {
  36995. if (event.touches.length == 1) {
  36996. rotateEnd.set(event.touches[0].pageX, event.touches[0].pageY);
  36997. } else {
  36998. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  36999. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  37000. rotateEnd.set(x, y);
  37001. }
  37002. rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);
  37003. var element = scope.domElement;
  37004. rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height
  37005. rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight);
  37006. rotateStart.copy(rotateEnd);
  37007. }
  37008. function handleTouchMovePan(event) {
  37009. if (event.touches.length == 1) {
  37010. panEnd.set(event.touches[0].pageX, event.touches[0].pageY);
  37011. } else {
  37012. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  37013. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  37014. panEnd.set(x, y);
  37015. }
  37016. panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);
  37017. pan(panDelta.x, panDelta.y);
  37018. panStart.copy(panEnd);
  37019. }
  37020. function handleTouchMoveDolly(event) {
  37021. var dx = event.touches[0].pageX - event.touches[1].pageX;
  37022. var dy = event.touches[0].pageY - event.touches[1].pageY;
  37023. var distance = Math.sqrt(dx * dx + dy * dy);
  37024. dollyEnd.set(0, distance);
  37025. dollyDelta.set(0, Math.pow(dollyEnd.y / dollyStart.y, scope.zoomSpeed));
  37026. dollyOut(dollyDelta.y);
  37027. dollyStart.copy(dollyEnd);
  37028. }
  37029. function handleTouchMoveDollyPan(event) {
  37030. if (scope.enableZoom) handleTouchMoveDolly(event);
  37031. if (scope.enablePan) handleTouchMovePan(event);
  37032. }
  37033. function handleTouchMoveDollyRotate(event) {
  37034. if (scope.enableZoom) handleTouchMoveDolly(event);
  37035. if (scope.enableRotate) handleTouchMoveRotate(event);
  37036. }
  37037. function handleTouchEnd()
  37038. /*event*/
  37039. {} // no-op
  37040. //
  37041. // event handlers - FSM: listen for events and reset state
  37042. //
  37043. function onPointerDown(event) {
  37044. if (scope.enabled === false) return;
  37045. switch (event.pointerType) {
  37046. case 'mouse':
  37047. case 'pen':
  37048. onMouseDown(event);
  37049. break;
  37050. // TODO touch
  37051. }
  37052. }
  37053. function onPointerMove(event) {
  37054. if (scope.enabled === false) return;
  37055. switch (event.pointerType) {
  37056. case 'mouse':
  37057. case 'pen':
  37058. onMouseMove(event);
  37059. break;
  37060. // TODO touch
  37061. }
  37062. }
  37063. function onPointerUp(event) {
  37064. switch (event.pointerType) {
  37065. case 'mouse':
  37066. case 'pen':
  37067. onMouseUp(event);
  37068. break;
  37069. // TODO touch
  37070. }
  37071. }
  37072. function onMouseDown(event) {
  37073. // Prevent the browser from scrolling.
  37074. event.preventDefault(); // Manually set the focus since calling preventDefault above
  37075. // prevents the browser from setting it automatically.
  37076. scope.domElement.focus ? scope.domElement.focus() : window.focus();
  37077. var mouseAction;
  37078. switch (event.button) {
  37079. case 0:
  37080. mouseAction = scope.mouseButtons.LEFT;
  37081. break;
  37082. case 1:
  37083. mouseAction = scope.mouseButtons.MIDDLE;
  37084. break;
  37085. case 2:
  37086. mouseAction = scope.mouseButtons.RIGHT;
  37087. break;
  37088. default:
  37089. mouseAction = -1;
  37090. }
  37091. switch (mouseAction) {
  37092. case _threeModule.MOUSE.DOLLY:
  37093. if (scope.enableZoom === false) return;
  37094. handleMouseDownDolly(event);
  37095. state = STATE.DOLLY;
  37096. break;
  37097. case _threeModule.MOUSE.ROTATE:
  37098. if (event.ctrlKey || event.metaKey || event.shiftKey) {
  37099. if (scope.enablePan === false) return;
  37100. handleMouseDownPan(event);
  37101. state = STATE.PAN;
  37102. } else {
  37103. if (scope.enableRotate === false) return;
  37104. handleMouseDownRotate(event);
  37105. state = STATE.ROTATE;
  37106. }
  37107. break;
  37108. case _threeModule.MOUSE.PAN:
  37109. if (event.ctrlKey || event.metaKey || event.shiftKey) {
  37110. if (scope.enableRotate === false) return;
  37111. handleMouseDownRotate(event);
  37112. state = STATE.ROTATE;
  37113. } else {
  37114. if (scope.enablePan === false) return;
  37115. handleMouseDownPan(event);
  37116. state = STATE.PAN;
  37117. }
  37118. break;
  37119. default:
  37120. state = STATE.NONE;
  37121. }
  37122. if (state !== STATE.NONE) {
  37123. scope.domElement.ownerDocument.addEventListener('pointermove', onPointerMove, false);
  37124. scope.domElement.ownerDocument.addEventListener('pointerup', onPointerUp, false);
  37125. scope.dispatchEvent(startEvent);
  37126. }
  37127. }
  37128. function onMouseMove(event) {
  37129. if (scope.enabled === false) return;
  37130. event.preventDefault();
  37131. switch (state) {
  37132. case STATE.ROTATE:
  37133. if (scope.enableRotate === false) return;
  37134. handleMouseMoveRotate(event);
  37135. break;
  37136. case STATE.DOLLY:
  37137. if (scope.enableZoom === false) return;
  37138. handleMouseMoveDolly(event);
  37139. break;
  37140. case STATE.PAN:
  37141. if (scope.enablePan === false) return;
  37142. handleMouseMovePan(event);
  37143. break;
  37144. }
  37145. }
  37146. function onMouseUp(event) {
  37147. scope.domElement.ownerDocument.removeEventListener('pointermove', onPointerMove, false);
  37148. scope.domElement.ownerDocument.removeEventListener('pointerup', onPointerUp, false);
  37149. if (scope.enabled === false) return;
  37150. handleMouseUp(event);
  37151. scope.dispatchEvent(endEvent);
  37152. state = STATE.NONE;
  37153. }
  37154. function onMouseWheel(event) {
  37155. if (scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE && state !== STATE.ROTATE) return;
  37156. event.preventDefault();
  37157. event.stopPropagation();
  37158. scope.dispatchEvent(startEvent);
  37159. handleMouseWheel(event);
  37160. scope.dispatchEvent(endEvent);
  37161. }
  37162. function onKeyDown(event) {
  37163. if (scope.enabled === false || scope.enableKeys === false || scope.enablePan === false) return;
  37164. handleKeyDown(event);
  37165. }
  37166. function onTouchStart(event) {
  37167. if (scope.enabled === false) return;
  37168. event.preventDefault(); // prevent scrolling
  37169. switch (event.touches.length) {
  37170. case 1:
  37171. switch (scope.touches.ONE) {
  37172. case _threeModule.TOUCH.ROTATE:
  37173. if (scope.enableRotate === false) return;
  37174. handleTouchStartRotate(event);
  37175. state = STATE.TOUCH_ROTATE;
  37176. break;
  37177. case _threeModule.TOUCH.PAN:
  37178. if (scope.enablePan === false) return;
  37179. handleTouchStartPan(event);
  37180. state = STATE.TOUCH_PAN;
  37181. break;
  37182. default:
  37183. state = STATE.NONE;
  37184. }
  37185. break;
  37186. case 2:
  37187. switch (scope.touches.TWO) {
  37188. case _threeModule.TOUCH.DOLLY_PAN:
  37189. if (scope.enableZoom === false && scope.enablePan === false) return;
  37190. handleTouchStartDollyPan(event);
  37191. state = STATE.TOUCH_DOLLY_PAN;
  37192. break;
  37193. case _threeModule.TOUCH.DOLLY_ROTATE:
  37194. if (scope.enableZoom === false && scope.enableRotate === false) return;
  37195. handleTouchStartDollyRotate(event);
  37196. state = STATE.TOUCH_DOLLY_ROTATE;
  37197. break;
  37198. default:
  37199. state = STATE.NONE;
  37200. }
  37201. break;
  37202. default:
  37203. state = STATE.NONE;
  37204. }
  37205. if (state !== STATE.NONE) {
  37206. scope.dispatchEvent(startEvent);
  37207. }
  37208. }
  37209. function onTouchMove(event) {
  37210. if (scope.enabled === false) return;
  37211. event.preventDefault(); // prevent scrolling
  37212. event.stopPropagation();
  37213. switch (state) {
  37214. case STATE.TOUCH_ROTATE:
  37215. if (scope.enableRotate === false) return;
  37216. handleTouchMoveRotate(event);
  37217. scope.update();
  37218. break;
  37219. case STATE.TOUCH_PAN:
  37220. if (scope.enablePan === false) return;
  37221. handleTouchMovePan(event);
  37222. scope.update();
  37223. break;
  37224. case STATE.TOUCH_DOLLY_PAN:
  37225. if (scope.enableZoom === false && scope.enablePan === false) return;
  37226. handleTouchMoveDollyPan(event);
  37227. scope.update();
  37228. break;
  37229. case STATE.TOUCH_DOLLY_ROTATE:
  37230. if (scope.enableZoom === false && scope.enableRotate === false) return;
  37231. handleTouchMoveDollyRotate(event);
  37232. scope.update();
  37233. break;
  37234. default:
  37235. state = STATE.NONE;
  37236. }
  37237. }
  37238. function onTouchEnd(event) {
  37239. if (scope.enabled === false) return;
  37240. handleTouchEnd(event);
  37241. scope.dispatchEvent(endEvent);
  37242. state = STATE.NONE;
  37243. }
  37244. function onContextMenu(event) {
  37245. if (scope.enabled === false) return;
  37246. event.preventDefault();
  37247. } //
  37248. scope.domElement.addEventListener('contextmenu', onContextMenu, false);
  37249. scope.domElement.addEventListener('pointerdown', onPointerDown, false);
  37250. scope.domElement.addEventListener('wheel', onMouseWheel, false);
  37251. scope.domElement.addEventListener('touchstart', onTouchStart, false);
  37252. scope.domElement.addEventListener('touchend', onTouchEnd, false);
  37253. scope.domElement.addEventListener('touchmove', onTouchMove, false);
  37254. scope.domElement.addEventListener('keydown', onKeyDown, false); // force an update at start
  37255. this.update();
  37256. };
  37257. exports.OrbitControls = OrbitControls;
  37258. OrbitControls.prototype = Object.create(_threeModule.EventDispatcher.prototype);
  37259. OrbitControls.prototype.constructor = OrbitControls; // This set of controls performs orbiting, dollying (zooming), and panning.
  37260. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  37261. // This is very similar to OrbitControls, another set of touch behavior
  37262. //
  37263. // Orbit - right mouse, or left mouse + ctrl/meta/shiftKey / touch: two-finger rotate
  37264. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  37265. // Pan - left mouse, or arrow keys / touch: one-finger move
  37266. var MapControls = function (object, domElement) {
  37267. OrbitControls.call(this, object, domElement);
  37268. this.screenSpacePanning = false; // pan orthogonal to world-space direction camera.up
  37269. this.mouseButtons.LEFT = _threeModule.MOUSE.PAN;
  37270. this.mouseButtons.RIGHT = _threeModule.MOUSE.ROTATE;
  37271. this.touches.ONE = _threeModule.TOUCH.PAN;
  37272. this.touches.TWO = _threeModule.TOUCH.DOLLY_ROTATE;
  37273. };
  37274. exports.MapControls = MapControls;
  37275. MapControls.prototype = Object.create(_threeModule.EventDispatcher.prototype);
  37276. MapControls.prototype.constructor = MapControls;
  37277. },{"../../../build/three.module.js":"../node_modules/three/build/three.module.js"}],"../node_modules/three/examples/jsm/utils/BufferGeometryUtils.js":[function(require,module,exports) {
  37278. "use strict";
  37279. Object.defineProperty(exports, "__esModule", {
  37280. value: true
  37281. });
  37282. exports.BufferGeometryUtils = void 0;
  37283. var _threeModule = require("../../../build/three.module.js");
  37284. var BufferGeometryUtils = {
  37285. computeTangents: function (geometry) {
  37286. var index = geometry.index;
  37287. var attributes = geometry.attributes; // based on http://www.terathon.com/code/tangent.html
  37288. // (per vertex tangents)
  37289. if (index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) {
  37290. console.error('THREE.BufferGeometryUtils: .computeTangents() failed. Missing required attributes (index, position, normal or uv)');
  37291. return;
  37292. }
  37293. var indices = index.array;
  37294. var positions = attributes.position.array;
  37295. var normals = attributes.normal.array;
  37296. var uvs = attributes.uv.array;
  37297. var nVertices = positions.length / 3;
  37298. if (attributes.tangent === undefined) {
  37299. geometry.setAttribute('tangent', new _threeModule.BufferAttribute(new Float32Array(4 * nVertices), 4));
  37300. }
  37301. var tangents = attributes.tangent.array;
  37302. var tan1 = [],
  37303. tan2 = [];
  37304. for (var i = 0; i < nVertices; i++) {
  37305. tan1[i] = new _threeModule.Vector3();
  37306. tan2[i] = new _threeModule.Vector3();
  37307. }
  37308. var vA = new _threeModule.Vector3(),
  37309. vB = new _threeModule.Vector3(),
  37310. vC = new _threeModule.Vector3(),
  37311. uvA = new _threeModule.Vector2(),
  37312. uvB = new _threeModule.Vector2(),
  37313. uvC = new _threeModule.Vector2(),
  37314. sdir = new _threeModule.Vector3(),
  37315. tdir = new _threeModule.Vector3();
  37316. function handleTriangle(a, b, c) {
  37317. vA.fromArray(positions, a * 3);
  37318. vB.fromArray(positions, b * 3);
  37319. vC.fromArray(positions, c * 3);
  37320. uvA.fromArray(uvs, a * 2);
  37321. uvB.fromArray(uvs, b * 2);
  37322. uvC.fromArray(uvs, c * 2);
  37323. vB.sub(vA);
  37324. vC.sub(vA);
  37325. uvB.sub(uvA);
  37326. uvC.sub(uvA);
  37327. var r = 1.0 / (uvB.x * uvC.y - uvC.x * uvB.y); // silently ignore degenerate uv triangles having coincident or colinear vertices
  37328. if (!isFinite(r)) return;
  37329. sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r);
  37330. tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r);
  37331. tan1[a].add(sdir);
  37332. tan1[b].add(sdir);
  37333. tan1[c].add(sdir);
  37334. tan2[a].add(tdir);
  37335. tan2[b].add(tdir);
  37336. tan2[c].add(tdir);
  37337. }
  37338. var groups = geometry.groups;
  37339. if (groups.length === 0) {
  37340. groups = [{
  37341. start: 0,
  37342. count: indices.length
  37343. }];
  37344. }
  37345. for (var i = 0, il = groups.length; i < il; ++i) {
  37346. var group = groups[i];
  37347. var start = group.start;
  37348. var count = group.count;
  37349. for (var j = start, jl = start + count; j < jl; j += 3) {
  37350. handleTriangle(indices[j + 0], indices[j + 1], indices[j + 2]);
  37351. }
  37352. }
  37353. var tmp = new _threeModule.Vector3(),
  37354. tmp2 = new _threeModule.Vector3();
  37355. var n = new _threeModule.Vector3(),
  37356. n2 = new _threeModule.Vector3();
  37357. var w, t, test;
  37358. function handleVertex(v) {
  37359. n.fromArray(normals, v * 3);
  37360. n2.copy(n);
  37361. t = tan1[v]; // Gram-Schmidt orthogonalize
  37362. tmp.copy(t);
  37363. tmp.sub(n.multiplyScalar(n.dot(t))).normalize(); // Calculate handedness
  37364. tmp2.crossVectors(n2, t);
  37365. test = tmp2.dot(tan2[v]);
  37366. w = test < 0.0 ? -1.0 : 1.0;
  37367. tangents[v * 4] = tmp.x;
  37368. tangents[v * 4 + 1] = tmp.y;
  37369. tangents[v * 4 + 2] = tmp.z;
  37370. tangents[v * 4 + 3] = w;
  37371. }
  37372. for (var i = 0, il = groups.length; i < il; ++i) {
  37373. var group = groups[i];
  37374. var start = group.start;
  37375. var count = group.count;
  37376. for (var j = start, jl = start + count; j < jl; j += 3) {
  37377. handleVertex(indices[j + 0]);
  37378. handleVertex(indices[j + 1]);
  37379. handleVertex(indices[j + 2]);
  37380. }
  37381. }
  37382. },
  37383. /**
  37384. * @param {Array<BufferGeometry>} geometries
  37385. * @param {Boolean} useGroups
  37386. * @return {BufferGeometry}
  37387. */
  37388. mergeBufferGeometries: function (geometries, useGroups) {
  37389. var isIndexed = geometries[0].index !== null;
  37390. var attributesUsed = new Set(Object.keys(geometries[0].attributes));
  37391. var morphAttributesUsed = new Set(Object.keys(geometries[0].morphAttributes));
  37392. var attributes = {};
  37393. var morphAttributes = {};
  37394. var morphTargetsRelative = geometries[0].morphTargetsRelative;
  37395. var mergedGeometry = new _threeModule.BufferGeometry();
  37396. var offset = 0;
  37397. for (var i = 0; i < geometries.length; ++i) {
  37398. var geometry = geometries[i];
  37399. var attributesCount = 0; // ensure that all geometries are indexed, or none
  37400. if (isIndexed !== (geometry.index !== null)) {
  37401. console.error('THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them.');
  37402. return null;
  37403. } // gather attributes, exit early if they're different
  37404. for (var name in geometry.attributes) {
  37405. if (!attributesUsed.has(name)) {
  37406. console.error('THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. All geometries must have compatible attributes; make sure "' + name + '" attribute exists among all geometries, or in none of them.');
  37407. return null;
  37408. }
  37409. if (attributes[name] === undefined) attributes[name] = [];
  37410. attributes[name].push(geometry.attributes[name]);
  37411. attributesCount++;
  37412. } // ensure geometries have the same number of attributes
  37413. if (attributesCount !== attributesUsed.size) {
  37414. console.error('THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. Make sure all geometries have the same number of attributes.');
  37415. return null;
  37416. } // gather morph attributes, exit early if they're different
  37417. if (morphTargetsRelative !== geometry.morphTargetsRelative) {
  37418. console.error('THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. .morphTargetsRelative must be consistent throughout all geometries.');
  37419. return null;
  37420. }
  37421. for (var name in geometry.morphAttributes) {
  37422. if (!morphAttributesUsed.has(name)) {
  37423. console.error('THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. .morphAttributes must be consistent throughout all geometries.');
  37424. return null;
  37425. }
  37426. if (morphAttributes[name] === undefined) morphAttributes[name] = [];
  37427. morphAttributes[name].push(geometry.morphAttributes[name]);
  37428. } // gather .userData
  37429. mergedGeometry.userData.mergedUserData = mergedGeometry.userData.mergedUserData || [];
  37430. mergedGeometry.userData.mergedUserData.push(geometry.userData);
  37431. if (useGroups) {
  37432. var count;
  37433. if (isIndexed) {
  37434. count = geometry.index.count;
  37435. } else if (geometry.attributes.position !== undefined) {
  37436. count = geometry.attributes.position.count;
  37437. } else {
  37438. console.error('THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. The geometry must have either an index or a position attribute');
  37439. return null;
  37440. }
  37441. mergedGeometry.addGroup(offset, count, i);
  37442. offset += count;
  37443. }
  37444. } // merge indices
  37445. if (isIndexed) {
  37446. var indexOffset = 0;
  37447. var mergedIndex = [];
  37448. for (var i = 0; i < geometries.length; ++i) {
  37449. var index = geometries[i].index;
  37450. for (var j = 0; j < index.count; ++j) {
  37451. mergedIndex.push(index.getX(j) + indexOffset);
  37452. }
  37453. indexOffset += geometries[i].attributes.position.count;
  37454. }
  37455. mergedGeometry.setIndex(mergedIndex);
  37456. } // merge attributes
  37457. for (var name in attributes) {
  37458. var mergedAttribute = this.mergeBufferAttributes(attributes[name]);
  37459. if (!mergedAttribute) {
  37460. console.error('THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the ' + name + ' attribute.');
  37461. return null;
  37462. }
  37463. mergedGeometry.setAttribute(name, mergedAttribute);
  37464. } // merge morph attributes
  37465. for (var name in morphAttributes) {
  37466. var numMorphTargets = morphAttributes[name][0].length;
  37467. if (numMorphTargets === 0) break;
  37468. mergedGeometry.morphAttributes = mergedGeometry.morphAttributes || {};
  37469. mergedGeometry.morphAttributes[name] = [];
  37470. for (var i = 0; i < numMorphTargets; ++i) {
  37471. var morphAttributesToMerge = [];
  37472. for (var j = 0; j < morphAttributes[name].length; ++j) {
  37473. morphAttributesToMerge.push(morphAttributes[name][j][i]);
  37474. }
  37475. var mergedMorphAttribute = this.mergeBufferAttributes(morphAttributesToMerge);
  37476. if (!mergedMorphAttribute) {
  37477. console.error('THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the ' + name + ' morphAttribute.');
  37478. return null;
  37479. }
  37480. mergedGeometry.morphAttributes[name].push(mergedMorphAttribute);
  37481. }
  37482. }
  37483. return mergedGeometry;
  37484. },
  37485. /**
  37486. * @param {Array<BufferAttribute>} attributes
  37487. * @return {BufferAttribute}
  37488. */
  37489. mergeBufferAttributes: function (attributes) {
  37490. var TypedArray;
  37491. var itemSize;
  37492. var normalized;
  37493. var arrayLength = 0;
  37494. for (var i = 0; i < attributes.length; ++i) {
  37495. var attribute = attributes[i];
  37496. if (attribute.isInterleavedBufferAttribute) {
  37497. console.error('THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. InterleavedBufferAttributes are not supported.');
  37498. return null;
  37499. }
  37500. if (TypedArray === undefined) TypedArray = attribute.array.constructor;
  37501. if (TypedArray !== attribute.array.constructor) {
  37502. console.error('THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes.');
  37503. return null;
  37504. }
  37505. if (itemSize === undefined) itemSize = attribute.itemSize;
  37506. if (itemSize !== attribute.itemSize) {
  37507. console.error('THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes.');
  37508. return null;
  37509. }
  37510. if (normalized === undefined) normalized = attribute.normalized;
  37511. if (normalized !== attribute.normalized) {
  37512. console.error('THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes.');
  37513. return null;
  37514. }
  37515. arrayLength += attribute.array.length;
  37516. }
  37517. var array = new TypedArray(arrayLength);
  37518. var offset = 0;
  37519. for (var i = 0; i < attributes.length; ++i) {
  37520. array.set(attributes[i].array, offset);
  37521. offset += attributes[i].array.length;
  37522. }
  37523. return new _threeModule.BufferAttribute(array, itemSize, normalized);
  37524. },
  37525. /**
  37526. * @param {Array<BufferAttribute>} attributes
  37527. * @return {Array<InterleavedBufferAttribute>}
  37528. */
  37529. interleaveAttributes: function (attributes) {
  37530. // Interleaves the provided attributes into an InterleavedBuffer and returns
  37531. // a set of InterleavedBufferAttributes for each attribute
  37532. var TypedArray;
  37533. var arrayLength = 0;
  37534. var stride = 0; // calculate the the length and type of the interleavedBuffer
  37535. for (var i = 0, l = attributes.length; i < l; ++i) {
  37536. var attribute = attributes[i];
  37537. if (TypedArray === undefined) TypedArray = attribute.array.constructor;
  37538. if (TypedArray !== attribute.array.constructor) {
  37539. console.error('AttributeBuffers of different types cannot be interleaved');
  37540. return null;
  37541. }
  37542. arrayLength += attribute.array.length;
  37543. stride += attribute.itemSize;
  37544. } // Create the set of buffer attributes
  37545. var interleavedBuffer = new _threeModule.InterleavedBuffer(new TypedArray(arrayLength), stride);
  37546. var offset = 0;
  37547. var res = [];
  37548. var getters = ['getX', 'getY', 'getZ', 'getW'];
  37549. var setters = ['setX', 'setY', 'setZ', 'setW'];
  37550. for (var j = 0, l = attributes.length; j < l; j++) {
  37551. var attribute = attributes[j];
  37552. var itemSize = attribute.itemSize;
  37553. var count = attribute.count;
  37554. var iba = new _threeModule.InterleavedBufferAttribute(interleavedBuffer, itemSize, offset, attribute.normalized);
  37555. res.push(iba);
  37556. offset += itemSize; // Move the data for each attribute into the new interleavedBuffer
  37557. // at the appropriate offset
  37558. for (var c = 0; c < count; c++) {
  37559. for (var k = 0; k < itemSize; k++) {
  37560. iba[setters[k]](c, attribute[getters[k]](c));
  37561. }
  37562. }
  37563. }
  37564. return res;
  37565. },
  37566. /**
  37567. * @param {Array<BufferGeometry>} geometry
  37568. * @return {number}
  37569. */
  37570. estimateBytesUsed: function (geometry) {
  37571. // Return the estimated memory used by this geometry in bytes
  37572. // Calculate using itemSize, count, and BYTES_PER_ELEMENT to account
  37573. // for InterleavedBufferAttributes.
  37574. var mem = 0;
  37575. for (var name in geometry.attributes) {
  37576. var attr = geometry.getAttribute(name);
  37577. mem += attr.count * attr.itemSize * attr.array.BYTES_PER_ELEMENT;
  37578. }
  37579. var indices = geometry.getIndex();
  37580. mem += indices ? indices.count * indices.itemSize * indices.array.BYTES_PER_ELEMENT : 0;
  37581. return mem;
  37582. },
  37583. /**
  37584. * @param {BufferGeometry} geometry
  37585. * @param {number} tolerance
  37586. * @return {BufferGeometry>}
  37587. */
  37588. mergeVertices: function (geometry, tolerance = 1e-4) {
  37589. tolerance = Math.max(tolerance, Number.EPSILON); // Generate an index buffer if the geometry doesn't have one, or optimize it
  37590. // if it's already available.
  37591. var hashToIndex = {};
  37592. var indices = geometry.getIndex();
  37593. var positions = geometry.getAttribute('position');
  37594. var vertexCount = indices ? indices.count : positions.count; // next value for triangle indices
  37595. var nextIndex = 0; // attributes and new attribute arrays
  37596. var attributeNames = Object.keys(geometry.attributes);
  37597. var attrArrays = {};
  37598. var morphAttrsArrays = {};
  37599. var newIndices = [];
  37600. var getters = ['getX', 'getY', 'getZ', 'getW']; // initialize the arrays
  37601. for (var i = 0, l = attributeNames.length; i < l; i++) {
  37602. var name = attributeNames[i];
  37603. attrArrays[name] = [];
  37604. var morphAttr = geometry.morphAttributes[name];
  37605. if (morphAttr) {
  37606. morphAttrsArrays[name] = new Array(morphAttr.length).fill().map(() => []);
  37607. }
  37608. } // convert the error tolerance to an amount of decimal places to truncate to
  37609. var decimalShift = Math.log10(1 / tolerance);
  37610. var shiftMultiplier = Math.pow(10, decimalShift);
  37611. for (var i = 0; i < vertexCount; i++) {
  37612. var index = indices ? indices.getX(i) : i; // Generate a hash for the vertex attributes at the current index 'i'
  37613. var hash = '';
  37614. for (var j = 0, l = attributeNames.length; j < l; j++) {
  37615. var name = attributeNames[j];
  37616. var attribute = geometry.getAttribute(name);
  37617. var itemSize = attribute.itemSize;
  37618. for (var k = 0; k < itemSize; k++) {
  37619. // double tilde truncates the decimal value
  37620. hash += `${~~(attribute[getters[k]](index) * shiftMultiplier)},`;
  37621. }
  37622. } // Add another reference to the vertex if it's already
  37623. // used by another index
  37624. if (hash in hashToIndex) {
  37625. newIndices.push(hashToIndex[hash]);
  37626. } else {
  37627. // copy data to the new index in the attribute arrays
  37628. for (var j = 0, l = attributeNames.length; j < l; j++) {
  37629. var name = attributeNames[j];
  37630. var attribute = geometry.getAttribute(name);
  37631. var morphAttr = geometry.morphAttributes[name];
  37632. var itemSize = attribute.itemSize;
  37633. var newarray = attrArrays[name];
  37634. var newMorphArrays = morphAttrsArrays[name];
  37635. for (var k = 0; k < itemSize; k++) {
  37636. var getterFunc = getters[k];
  37637. newarray.push(attribute[getterFunc](index));
  37638. if (morphAttr) {
  37639. for (var m = 0, ml = morphAttr.length; m < ml; m++) {
  37640. newMorphArrays[m].push(morphAttr[m][getterFunc](index));
  37641. }
  37642. }
  37643. }
  37644. }
  37645. hashToIndex[hash] = nextIndex;
  37646. newIndices.push(nextIndex);
  37647. nextIndex++;
  37648. }
  37649. } // Generate typed arrays from new attribute arrays and update
  37650. // the attributeBuffers
  37651. const result = geometry.clone();
  37652. for (var i = 0, l = attributeNames.length; i < l; i++) {
  37653. var name = attributeNames[i];
  37654. var oldAttribute = geometry.getAttribute(name);
  37655. var buffer = new oldAttribute.array.constructor(attrArrays[name]);
  37656. var attribute = new _threeModule.BufferAttribute(buffer, oldAttribute.itemSize, oldAttribute.normalized);
  37657. result.setAttribute(name, attribute); // Update the attribute arrays
  37658. if (name in morphAttrsArrays) {
  37659. for (var j = 0; j < morphAttrsArrays[name].length; j++) {
  37660. var oldMorphAttribute = geometry.morphAttributes[name][j];
  37661. var buffer = new oldMorphAttribute.array.constructor(morphAttrsArrays[name][j]);
  37662. var morphAttribute = new _threeModule.BufferAttribute(buffer, oldMorphAttribute.itemSize, oldMorphAttribute.normalized);
  37663. result.morphAttributes[name][j] = morphAttribute;
  37664. }
  37665. }
  37666. } // indices
  37667. result.setIndex(newIndices);
  37668. return result;
  37669. },
  37670. /**
  37671. * @param {BufferGeometry} geometry
  37672. * @param {number} drawMode
  37673. * @return {BufferGeometry>}
  37674. */
  37675. toTrianglesDrawMode: function (geometry, drawMode) {
  37676. if (drawMode === _threeModule.TrianglesDrawMode) {
  37677. console.warn('THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.');
  37678. return geometry;
  37679. }
  37680. if (drawMode === _threeModule.TriangleFanDrawMode || drawMode === _threeModule.TriangleStripDrawMode) {
  37681. var index = geometry.getIndex(); // generate index if not present
  37682. if (index === null) {
  37683. var indices = [];
  37684. var position = geometry.getAttribute('position');
  37685. if (position !== undefined) {
  37686. for (var i = 0; i < position.count; i++) {
  37687. indices.push(i);
  37688. }
  37689. geometry.setIndex(indices);
  37690. index = geometry.getIndex();
  37691. } else {
  37692. console.error('THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.');
  37693. return geometry;
  37694. }
  37695. } //
  37696. var numberOfTriangles = index.count - 2;
  37697. var newIndices = [];
  37698. if (drawMode === _threeModule.TriangleFanDrawMode) {
  37699. // gl.TRIANGLE_FAN
  37700. for (var i = 1; i <= numberOfTriangles; i++) {
  37701. newIndices.push(index.getX(0));
  37702. newIndices.push(index.getX(i));
  37703. newIndices.push(index.getX(i + 1));
  37704. }
  37705. } else {
  37706. // gl.TRIANGLE_STRIP
  37707. for (var i = 0; i < numberOfTriangles; i++) {
  37708. if (i % 2 === 0) {
  37709. newIndices.push(index.getX(i));
  37710. newIndices.push(index.getX(i + 1));
  37711. newIndices.push(index.getX(i + 2));
  37712. } else {
  37713. newIndices.push(index.getX(i + 2));
  37714. newIndices.push(index.getX(i + 1));
  37715. newIndices.push(index.getX(i));
  37716. }
  37717. }
  37718. }
  37719. if (newIndices.length / 3 !== numberOfTriangles) {
  37720. console.error('THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.');
  37721. } // build final geometry
  37722. var newGeometry = geometry.clone();
  37723. newGeometry.setIndex(newIndices);
  37724. newGeometry.clearGroups();
  37725. return newGeometry;
  37726. } else {
  37727. console.error('THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:', drawMode);
  37728. return geometry;
  37729. }
  37730. }
  37731. };
  37732. exports.BufferGeometryUtils = BufferGeometryUtils;
  37733. },{"../../../build/three.module.js":"../node_modules/three/build/three.module.js"}],"../node_modules/three/examples/jsm/loaders/DRACOLoader.js":[function(require,module,exports) {
  37734. "use strict";
  37735. Object.defineProperty(exports, "__esModule", {
  37736. value: true
  37737. });
  37738. exports.DRACOLoader = void 0;
  37739. var _threeModule = require("../../../build/three.module.js");
  37740. var DRACOLoader = function (manager) {
  37741. _threeModule.Loader.call(this, manager);
  37742. this.decoderPath = '';
  37743. this.decoderConfig = {};
  37744. this.decoderBinary = null;
  37745. this.decoderPending = null;
  37746. this.workerLimit = 4;
  37747. this.workerPool = [];
  37748. this.workerNextTaskID = 1;
  37749. this.workerSourceURL = '';
  37750. this.defaultAttributeIDs = {
  37751. position: 'POSITION',
  37752. normal: 'NORMAL',
  37753. color: 'COLOR',
  37754. uv: 'TEX_COORD'
  37755. };
  37756. this.defaultAttributeTypes = {
  37757. position: 'Float32Array',
  37758. normal: 'Float32Array',
  37759. color: 'Float32Array',
  37760. uv: 'Float32Array'
  37761. };
  37762. };
  37763. exports.DRACOLoader = DRACOLoader;
  37764. DRACOLoader.prototype = Object.assign(Object.create(_threeModule.Loader.prototype), {
  37765. constructor: DRACOLoader,
  37766. setDecoderPath: function (path) {
  37767. this.decoderPath = path;
  37768. return this;
  37769. },
  37770. setDecoderConfig: function (config) {
  37771. this.decoderConfig = config;
  37772. return this;
  37773. },
  37774. setWorkerLimit: function (workerLimit) {
  37775. this.workerLimit = workerLimit;
  37776. return this;
  37777. },
  37778. /** @deprecated */
  37779. setVerbosity: function () {
  37780. console.warn('THREE.DRACOLoader: The .setVerbosity() method has been removed.');
  37781. },
  37782. /** @deprecated */
  37783. setDrawMode: function () {
  37784. console.warn('THREE.DRACOLoader: The .setDrawMode() method has been removed.');
  37785. },
  37786. /** @deprecated */
  37787. setSkipDequantization: function () {
  37788. console.warn('THREE.DRACOLoader: The .setSkipDequantization() method has been removed.');
  37789. },
  37790. load: function (url, onLoad, onProgress, onError) {
  37791. var loader = new _threeModule.FileLoader(this.manager);
  37792. loader.setPath(this.path);
  37793. loader.setResponseType('arraybuffer');
  37794. loader.setRequestHeader(this.requestHeader);
  37795. loader.setWithCredentials(this.withCredentials);
  37796. loader.load(url, buffer => {
  37797. var taskConfig = {
  37798. attributeIDs: this.defaultAttributeIDs,
  37799. attributeTypes: this.defaultAttributeTypes,
  37800. useUniqueIDs: false
  37801. };
  37802. this.decodeGeometry(buffer, taskConfig).then(onLoad).catch(onError);
  37803. }, onProgress, onError);
  37804. },
  37805. /** @deprecated Kept for backward-compatibility with previous DRACOLoader versions. */
  37806. decodeDracoFile: function (buffer, callback, attributeIDs, attributeTypes) {
  37807. var taskConfig = {
  37808. attributeIDs: attributeIDs || this.defaultAttributeIDs,
  37809. attributeTypes: attributeTypes || this.defaultAttributeTypes,
  37810. useUniqueIDs: !!attributeIDs
  37811. };
  37812. this.decodeGeometry(buffer, taskConfig).then(callback);
  37813. },
  37814. decodeGeometry: function (buffer, taskConfig) {
  37815. // TODO: For backward-compatibility, support 'attributeTypes' objects containing
  37816. // references (rather than names) to typed array constructors. These must be
  37817. // serialized before sending them to the worker.
  37818. for (var attribute in taskConfig.attributeTypes) {
  37819. var type = taskConfig.attributeTypes[attribute];
  37820. if (type.BYTES_PER_ELEMENT !== undefined) {
  37821. taskConfig.attributeTypes[attribute] = type.name;
  37822. }
  37823. } //
  37824. var taskKey = JSON.stringify(taskConfig); // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  37825. // again from this thread.
  37826. if (DRACOLoader.taskCache.has(buffer)) {
  37827. var cachedTask = DRACOLoader.taskCache.get(buffer);
  37828. if (cachedTask.key === taskKey) {
  37829. return cachedTask.promise;
  37830. } else if (buffer.byteLength === 0) {
  37831. // Technically, it would be possible to wait for the previous task to complete,
  37832. // transfer the buffer back, and decode again with the second configuration. That
  37833. // is complex, and I don't know of any reason to decode a Draco buffer twice in
  37834. // different ways, so this is left unimplemented.
  37835. throw new Error('THREE.DRACOLoader: Unable to re-decode a buffer with different ' + 'settings. Buffer has already been transferred.');
  37836. }
  37837. } //
  37838. var worker;
  37839. var taskID = this.workerNextTaskID++;
  37840. var taskCost = buffer.byteLength; // Obtain a worker and assign a task, and construct a geometry instance
  37841. // when the task completes.
  37842. var geometryPending = this._getWorker(taskID, taskCost).then(_worker => {
  37843. worker = _worker;
  37844. return new Promise((resolve, reject) => {
  37845. worker._callbacks[taskID] = {
  37846. resolve,
  37847. reject
  37848. };
  37849. worker.postMessage({
  37850. type: 'decode',
  37851. id: taskID,
  37852. taskConfig,
  37853. buffer
  37854. }, [buffer]); // this.debug();
  37855. });
  37856. }).then(message => this._createGeometry(message.geometry)); // Remove task from the task list.
  37857. // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416)
  37858. geometryPending.catch(() => true).then(() => {
  37859. if (worker && taskID) {
  37860. this._releaseTask(worker, taskID); // this.debug();
  37861. }
  37862. }); // Cache the task result.
  37863. DRACOLoader.taskCache.set(buffer, {
  37864. key: taskKey,
  37865. promise: geometryPending
  37866. });
  37867. return geometryPending;
  37868. },
  37869. _createGeometry: function (geometryData) {
  37870. var geometry = new _threeModule.BufferGeometry();
  37871. if (geometryData.index) {
  37872. geometry.setIndex(new _threeModule.BufferAttribute(geometryData.index.array, 1));
  37873. }
  37874. for (var i = 0; i < geometryData.attributes.length; i++) {
  37875. var attribute = geometryData.attributes[i];
  37876. var name = attribute.name;
  37877. var array = attribute.array;
  37878. var itemSize = attribute.itemSize;
  37879. geometry.setAttribute(name, new _threeModule.BufferAttribute(array, itemSize));
  37880. }
  37881. return geometry;
  37882. },
  37883. _loadLibrary: function (url, responseType) {
  37884. var loader = new _threeModule.FileLoader(this.manager);
  37885. loader.setPath(this.decoderPath);
  37886. loader.setResponseType(responseType);
  37887. loader.setWithCredentials(this.withCredentials);
  37888. return new Promise((resolve, reject) => {
  37889. loader.load(url, resolve, undefined, reject);
  37890. });
  37891. },
  37892. preload: function () {
  37893. this._initDecoder();
  37894. return this;
  37895. },
  37896. _initDecoder: function () {
  37897. if (this.decoderPending) return this.decoderPending;
  37898. var useJS = typeof WebAssembly !== 'object' || this.decoderConfig.type === 'js';
  37899. var librariesPending = [];
  37900. if (useJS) {
  37901. librariesPending.push(this._loadLibrary('draco_decoder.js', 'text'));
  37902. } else {
  37903. librariesPending.push(this._loadLibrary('draco_wasm_wrapper.js', 'text'));
  37904. librariesPending.push(this._loadLibrary('draco_decoder.wasm', 'arraybuffer'));
  37905. }
  37906. this.decoderPending = Promise.all(librariesPending).then(libraries => {
  37907. var jsContent = libraries[0];
  37908. if (!useJS) {
  37909. this.decoderConfig.wasmBinary = libraries[1];
  37910. }
  37911. var fn = DRACOLoader.DRACOWorker.toString();
  37912. var body = ['/* draco decoder */', jsContent, '', '/* worker */', fn.substring(fn.indexOf('{') + 1, fn.lastIndexOf('}'))].join('\n');
  37913. this.workerSourceURL = URL.createObjectURL(new Blob([body]));
  37914. });
  37915. return this.decoderPending;
  37916. },
  37917. _getWorker: function (taskID, taskCost) {
  37918. return this._initDecoder().then(() => {
  37919. if (this.workerPool.length < this.workerLimit) {
  37920. var worker = new Worker(this.workerSourceURL);
  37921. worker._callbacks = {};
  37922. worker._taskCosts = {};
  37923. worker._taskLoad = 0;
  37924. worker.postMessage({
  37925. type: 'init',
  37926. decoderConfig: this.decoderConfig
  37927. });
  37928. worker.onmessage = function (e) {
  37929. var message = e.data;
  37930. switch (message.type) {
  37931. case 'decode':
  37932. worker._callbacks[message.id].resolve(message);
  37933. break;
  37934. case 'error':
  37935. worker._callbacks[message.id].reject(message);
  37936. break;
  37937. default:
  37938. console.error('THREE.DRACOLoader: Unexpected message, "' + message.type + '"');
  37939. }
  37940. };
  37941. this.workerPool.push(worker);
  37942. } else {
  37943. this.workerPool.sort(function (a, b) {
  37944. return a._taskLoad > b._taskLoad ? -1 : 1;
  37945. });
  37946. }
  37947. var worker = this.workerPool[this.workerPool.length - 1];
  37948. worker._taskCosts[taskID] = taskCost;
  37949. worker._taskLoad += taskCost;
  37950. return worker;
  37951. });
  37952. },
  37953. _releaseTask: function (worker, taskID) {
  37954. worker._taskLoad -= worker._taskCosts[taskID];
  37955. delete worker._callbacks[taskID];
  37956. delete worker._taskCosts[taskID];
  37957. },
  37958. debug: function () {
  37959. console.log('Task load: ', this.workerPool.map(worker => worker._taskLoad));
  37960. },
  37961. dispose: function () {
  37962. for (var i = 0; i < this.workerPool.length; ++i) {
  37963. this.workerPool[i].terminate();
  37964. }
  37965. this.workerPool.length = 0;
  37966. return this;
  37967. }
  37968. });
  37969. /* WEB WORKER */
  37970. DRACOLoader.DRACOWorker = function () {
  37971. var decoderConfig;
  37972. var decoderPending;
  37973. onmessage = function (e) {
  37974. var message = e.data;
  37975. switch (message.type) {
  37976. case 'init':
  37977. decoderConfig = message.decoderConfig;
  37978. decoderPending = new Promise(function (resolve
  37979. /*, reject*/
  37980. ) {
  37981. decoderConfig.onModuleLoaded = function (draco) {
  37982. // Module is Promise-like. Wrap before resolving to avoid loop.
  37983. resolve({
  37984. draco: draco
  37985. });
  37986. };
  37987. DracoDecoderModule(decoderConfig); // eslint-disable-line no-undef
  37988. });
  37989. break;
  37990. case 'decode':
  37991. var buffer = message.buffer;
  37992. var taskConfig = message.taskConfig;
  37993. decoderPending.then(module => {
  37994. var draco = module.draco;
  37995. var decoder = new draco.Decoder();
  37996. var decoderBuffer = new draco.DecoderBuffer();
  37997. decoderBuffer.Init(new Int8Array(buffer), buffer.byteLength);
  37998. try {
  37999. var geometry = decodeGeometry(draco, decoder, decoderBuffer, taskConfig);
  38000. var buffers = geometry.attributes.map(attr => attr.array.buffer);
  38001. if (geometry.index) buffers.push(geometry.index.array.buffer);
  38002. self.postMessage({
  38003. type: 'decode',
  38004. id: message.id,
  38005. geometry
  38006. }, buffers);
  38007. } catch (error) {
  38008. console.error(error);
  38009. self.postMessage({
  38010. type: 'error',
  38011. id: message.id,
  38012. error: error.message
  38013. });
  38014. } finally {
  38015. draco.destroy(decoderBuffer);
  38016. draco.destroy(decoder);
  38017. }
  38018. });
  38019. break;
  38020. }
  38021. };
  38022. function decodeGeometry(draco, decoder, decoderBuffer, taskConfig) {
  38023. var attributeIDs = taskConfig.attributeIDs;
  38024. var attributeTypes = taskConfig.attributeTypes;
  38025. var dracoGeometry;
  38026. var decodingStatus;
  38027. var geometryType = decoder.GetEncodedGeometryType(decoderBuffer);
  38028. if (geometryType === draco.TRIANGULAR_MESH) {
  38029. dracoGeometry = new draco.Mesh();
  38030. decodingStatus = decoder.DecodeBufferToMesh(decoderBuffer, dracoGeometry);
  38031. } else if (geometryType === draco.POINT_CLOUD) {
  38032. dracoGeometry = new draco.PointCloud();
  38033. decodingStatus = decoder.DecodeBufferToPointCloud(decoderBuffer, dracoGeometry);
  38034. } else {
  38035. throw new Error('THREE.DRACOLoader: Unexpected geometry type.');
  38036. }
  38037. if (!decodingStatus.ok() || dracoGeometry.ptr === 0) {
  38038. throw new Error('THREE.DRACOLoader: Decoding failed: ' + decodingStatus.error_msg());
  38039. }
  38040. var geometry = {
  38041. index: null,
  38042. attributes: []
  38043. }; // Gather all vertex attributes.
  38044. for (var attributeName in attributeIDs) {
  38045. var attributeType = self[attributeTypes[attributeName]];
  38046. var attribute;
  38047. var attributeID; // A Draco file may be created with default vertex attributes, whose attribute IDs
  38048. // are mapped 1:1 from their semantic name (POSITION, NORMAL, ...). Alternatively,
  38049. // a Draco file may contain a custom set of attributes, identified by known unique
  38050. // IDs. glTF files always do the latter, and `.drc` files typically do the former.
  38051. if (taskConfig.useUniqueIDs) {
  38052. attributeID = attributeIDs[attributeName];
  38053. attribute = decoder.GetAttributeByUniqueId(dracoGeometry, attributeID);
  38054. } else {
  38055. attributeID = decoder.GetAttributeId(dracoGeometry, draco[attributeIDs[attributeName]]);
  38056. if (attributeID === -1) continue;
  38057. attribute = decoder.GetAttribute(dracoGeometry, attributeID);
  38058. }
  38059. geometry.attributes.push(decodeAttribute(draco, decoder, dracoGeometry, attributeName, attributeType, attribute));
  38060. } // Add index.
  38061. if (geometryType === draco.TRIANGULAR_MESH) {
  38062. geometry.index = decodeIndex(draco, decoder, dracoGeometry);
  38063. }
  38064. draco.destroy(dracoGeometry);
  38065. return geometry;
  38066. }
  38067. function decodeIndex(draco, decoder, dracoGeometry) {
  38068. var numFaces = dracoGeometry.num_faces();
  38069. var numIndices = numFaces * 3;
  38070. var byteLength = numIndices * 4;
  38071. var ptr = draco._malloc(byteLength);
  38072. decoder.GetTrianglesUInt32Array(dracoGeometry, byteLength, ptr);
  38073. var index = new Uint32Array(draco.HEAPF32.buffer, ptr, numIndices).slice();
  38074. draco._free(ptr);
  38075. return {
  38076. array: index,
  38077. itemSize: 1
  38078. };
  38079. }
  38080. function decodeAttribute(draco, decoder, dracoGeometry, attributeName, attributeType, attribute) {
  38081. var numComponents = attribute.num_components();
  38082. var numPoints = dracoGeometry.num_points();
  38083. var numValues = numPoints * numComponents;
  38084. var byteLength = numValues * attributeType.BYTES_PER_ELEMENT;
  38085. var dataType = getDracoDataType(draco, attributeType);
  38086. var ptr = draco._malloc(byteLength);
  38087. decoder.GetAttributeDataArrayForAllPoints(dracoGeometry, attribute, dataType, byteLength, ptr);
  38088. var array = new attributeType(draco.HEAPF32.buffer, ptr, numValues).slice();
  38089. draco._free(ptr);
  38090. return {
  38091. name: attributeName,
  38092. array: array,
  38093. itemSize: numComponents
  38094. };
  38095. }
  38096. function getDracoDataType(draco, attributeType) {
  38097. switch (attributeType) {
  38098. case Float32Array:
  38099. return draco.DT_FLOAT32;
  38100. case Int8Array:
  38101. return draco.DT_INT8;
  38102. case Int16Array:
  38103. return draco.DT_INT16;
  38104. case Int32Array:
  38105. return draco.DT_INT32;
  38106. case Uint8Array:
  38107. return draco.DT_UINT8;
  38108. case Uint16Array:
  38109. return draco.DT_UINT16;
  38110. case Uint32Array:
  38111. return draco.DT_UINT32;
  38112. }
  38113. }
  38114. };
  38115. DRACOLoader.taskCache = new WeakMap();
  38116. /** Deprecated static methods */
  38117. /** @deprecated */
  38118. DRACOLoader.setDecoderPath = function () {
  38119. console.warn('THREE.DRACOLoader: The .setDecoderPath() method has been removed. Use instance methods.');
  38120. };
  38121. /** @deprecated */
  38122. DRACOLoader.setDecoderConfig = function () {
  38123. console.warn('THREE.DRACOLoader: The .setDecoderConfig() method has been removed. Use instance methods.');
  38124. };
  38125. /** @deprecated */
  38126. DRACOLoader.releaseDecoderModule = function () {
  38127. console.warn('THREE.DRACOLoader: The .releaseDecoderModule() method has been removed. Use instance methods.');
  38128. };
  38129. /** @deprecated */
  38130. DRACOLoader.getDecoderModule = function () {
  38131. console.warn('THREE.DRACOLoader: The .getDecoderModule() method has been removed. Use instance methods.');
  38132. };
  38133. },{"../../../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) {
  38134. "use strict";
  38135. Object.defineProperty(exports, "__esModule", {
  38136. value: true
  38137. });
  38138. exports.default = exports.GUI = exports.gui = exports.dom = exports.controllers = exports.color = void 0;
  38139. /**
  38140. * dat-gui JavaScript Controller Library
  38141. * http://code.google.com/p/dat-gui
  38142. *
  38143. * Copyright 2011 Data Arts Team, Google Creative Lab
  38144. *
  38145. * Licensed under the Apache License, Version 2.0 (the "License");
  38146. * you may not use this file except in compliance with the License.
  38147. * You may obtain a copy of the License at
  38148. *
  38149. * http://www.apache.org/licenses/LICENSE-2.0
  38150. */
  38151. function ___$insertStyle(css) {
  38152. if (!css) {
  38153. return;
  38154. }
  38155. if (typeof window === 'undefined') {
  38156. return;
  38157. }
  38158. var style = document.createElement('style');
  38159. style.setAttribute('type', 'text/css');
  38160. style.innerHTML = css;
  38161. document.head.appendChild(style);
  38162. return css;
  38163. }
  38164. function colorToString(color, forceCSSHex) {
  38165. var colorFormat = color.__state.conversionName.toString();
  38166. var r = Math.round(color.r);
  38167. var g = Math.round(color.g);
  38168. var b = Math.round(color.b);
  38169. var a = color.a;
  38170. var h = Math.round(color.h);
  38171. var s = color.s.toFixed(1);
  38172. var v = color.v.toFixed(1);
  38173. if (forceCSSHex || colorFormat === 'THREE_CHAR_HEX' || colorFormat === 'SIX_CHAR_HEX') {
  38174. var str = color.hex.toString(16);
  38175. while (str.length < 6) {
  38176. str = '0' + str;
  38177. }
  38178. return '#' + str;
  38179. } else if (colorFormat === 'CSS_RGB') {
  38180. return 'rgb(' + r + ',' + g + ',' + b + ')';
  38181. } else if (colorFormat === 'CSS_RGBA') {
  38182. return 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
  38183. } else if (colorFormat === 'HEX') {
  38184. return '0x' + color.hex.toString(16);
  38185. } else if (colorFormat === 'RGB_ARRAY') {
  38186. return '[' + r + ',' + g + ',' + b + ']';
  38187. } else if (colorFormat === 'RGBA_ARRAY') {
  38188. return '[' + r + ',' + g + ',' + b + ',' + a + ']';
  38189. } else if (colorFormat === 'RGB_OBJ') {
  38190. return '{r:' + r + ',g:' + g + ',b:' + b + '}';
  38191. } else if (colorFormat === 'RGBA_OBJ') {
  38192. return '{r:' + r + ',g:' + g + ',b:' + b + ',a:' + a + '}';
  38193. } else if (colorFormat === 'HSV_OBJ') {
  38194. return '{h:' + h + ',s:' + s + ',v:' + v + '}';
  38195. } else if (colorFormat === 'HSVA_OBJ') {
  38196. return '{h:' + h + ',s:' + s + ',v:' + v + ',a:' + a + '}';
  38197. }
  38198. return 'unknown format';
  38199. }
  38200. var ARR_EACH = Array.prototype.forEach;
  38201. var ARR_SLICE = Array.prototype.slice;
  38202. var Common = {
  38203. BREAK: {},
  38204. extend: function extend(target) {
  38205. this.each(ARR_SLICE.call(arguments, 1), function (obj) {
  38206. var keys = this.isObject(obj) ? Object.keys(obj) : [];
  38207. keys.forEach(function (key) {
  38208. if (!this.isUndefined(obj[key])) {
  38209. target[key] = obj[key];
  38210. }
  38211. }.bind(this));
  38212. }, this);
  38213. return target;
  38214. },
  38215. defaults: function defaults(target) {
  38216. this.each(ARR_SLICE.call(arguments, 1), function (obj) {
  38217. var keys = this.isObject(obj) ? Object.keys(obj) : [];
  38218. keys.forEach(function (key) {
  38219. if (this.isUndefined(target[key])) {
  38220. target[key] = obj[key];
  38221. }
  38222. }.bind(this));
  38223. }, this);
  38224. return target;
  38225. },
  38226. compose: function compose() {
  38227. var toCall = ARR_SLICE.call(arguments);
  38228. return function () {
  38229. var args = ARR_SLICE.call(arguments);
  38230. for (var i = toCall.length - 1; i >= 0; i--) {
  38231. args = [toCall[i].apply(this, args)];
  38232. }
  38233. return args[0];
  38234. };
  38235. },
  38236. each: function each(obj, itr, scope) {
  38237. if (!obj) {
  38238. return;
  38239. }
  38240. if (ARR_EACH && obj.forEach && obj.forEach === ARR_EACH) {
  38241. obj.forEach(itr, scope);
  38242. } else if (obj.length === obj.length + 0) {
  38243. var key = void 0;
  38244. var l = void 0;
  38245. for (key = 0, l = obj.length; key < l; key++) {
  38246. if (key in obj && itr.call(scope, obj[key], key) === this.BREAK) {
  38247. return;
  38248. }
  38249. }
  38250. } else {
  38251. for (var _key in obj) {
  38252. if (itr.call(scope, obj[_key], _key) === this.BREAK) {
  38253. return;
  38254. }
  38255. }
  38256. }
  38257. },
  38258. defer: function defer(fnc) {
  38259. setTimeout(fnc, 0);
  38260. },
  38261. debounce: function debounce(func, threshold, callImmediately) {
  38262. var timeout = void 0;
  38263. return function () {
  38264. var obj = this;
  38265. var args = arguments;
  38266. function delayed() {
  38267. timeout = null;
  38268. if (!callImmediately) func.apply(obj, args);
  38269. }
  38270. var callNow = callImmediately || !timeout;
  38271. clearTimeout(timeout);
  38272. timeout = setTimeout(delayed, threshold);
  38273. if (callNow) {
  38274. func.apply(obj, args);
  38275. }
  38276. };
  38277. },
  38278. toArray: function toArray(obj) {
  38279. if (obj.toArray) return obj.toArray();
  38280. return ARR_SLICE.call(obj);
  38281. },
  38282. isUndefined: function isUndefined(obj) {
  38283. return obj === undefined;
  38284. },
  38285. isNull: function isNull(obj) {
  38286. return obj === null;
  38287. },
  38288. isNaN: function (_isNaN) {
  38289. function isNaN() {
  38290. return _isNaN.apply(this, arguments);
  38291. }
  38292. isNaN.toString = function () {
  38293. return _isNaN.toString();
  38294. };
  38295. return isNaN;
  38296. }(function (obj) {
  38297. return isNaN(obj);
  38298. }),
  38299. isArray: Array.isArray || function (obj) {
  38300. return obj.constructor === Array;
  38301. },
  38302. isObject: function isObject(obj) {
  38303. return obj === Object(obj);
  38304. },
  38305. isNumber: function isNumber(obj) {
  38306. return obj === obj + 0;
  38307. },
  38308. isString: function isString(obj) {
  38309. return obj === obj + '';
  38310. },
  38311. isBoolean: function isBoolean(obj) {
  38312. return obj === false || obj === true;
  38313. },
  38314. isFunction: function isFunction(obj) {
  38315. return obj instanceof Function;
  38316. }
  38317. };
  38318. var INTERPRETATIONS = [{
  38319. litmus: Common.isString,
  38320. conversions: {
  38321. THREE_CHAR_HEX: {
  38322. read: function read(original) {
  38323. var test = original.match(/^#([A-F0-9])([A-F0-9])([A-F0-9])$/i);
  38324. if (test === null) {
  38325. return false;
  38326. }
  38327. return {
  38328. space: 'HEX',
  38329. hex: parseInt('0x' + test[1].toString() + test[1].toString() + test[2].toString() + test[2].toString() + test[3].toString() + test[3].toString(), 0)
  38330. };
  38331. },
  38332. write: colorToString
  38333. },
  38334. SIX_CHAR_HEX: {
  38335. read: function read(original) {
  38336. var test = original.match(/^#([A-F0-9]{6})$/i);
  38337. if (test === null) {
  38338. return false;
  38339. }
  38340. return {
  38341. space: 'HEX',
  38342. hex: parseInt('0x' + test[1].toString(), 0)
  38343. };
  38344. },
  38345. write: colorToString
  38346. },
  38347. CSS_RGB: {
  38348. read: function read(original) {
  38349. var test = original.match(/^rgb\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);
  38350. if (test === null) {
  38351. return false;
  38352. }
  38353. return {
  38354. space: 'RGB',
  38355. r: parseFloat(test[1]),
  38356. g: parseFloat(test[2]),
  38357. b: parseFloat(test[3])
  38358. };
  38359. },
  38360. write: colorToString
  38361. },
  38362. CSS_RGBA: {
  38363. read: function read(original) {
  38364. var test = original.match(/^rgba\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);
  38365. if (test === null) {
  38366. return false;
  38367. }
  38368. return {
  38369. space: 'RGB',
  38370. r: parseFloat(test[1]),
  38371. g: parseFloat(test[2]),
  38372. b: parseFloat(test[3]),
  38373. a: parseFloat(test[4])
  38374. };
  38375. },
  38376. write: colorToString
  38377. }
  38378. }
  38379. }, {
  38380. litmus: Common.isNumber,
  38381. conversions: {
  38382. HEX: {
  38383. read: function read(original) {
  38384. return {
  38385. space: 'HEX',
  38386. hex: original,
  38387. conversionName: 'HEX'
  38388. };
  38389. },
  38390. write: function write(color) {
  38391. return color.hex;
  38392. }
  38393. }
  38394. }
  38395. }, {
  38396. litmus: Common.isArray,
  38397. conversions: {
  38398. RGB_ARRAY: {
  38399. read: function read(original) {
  38400. if (original.length !== 3) {
  38401. return false;
  38402. }
  38403. return {
  38404. space: 'RGB',
  38405. r: original[0],
  38406. g: original[1],
  38407. b: original[2]
  38408. };
  38409. },
  38410. write: function write(color) {
  38411. return [color.r, color.g, color.b];
  38412. }
  38413. },
  38414. RGBA_ARRAY: {
  38415. read: function read(original) {
  38416. if (original.length !== 4) return false;
  38417. return {
  38418. space: 'RGB',
  38419. r: original[0],
  38420. g: original[1],
  38421. b: original[2],
  38422. a: original[3]
  38423. };
  38424. },
  38425. write: function write(color) {
  38426. return [color.r, color.g, color.b, color.a];
  38427. }
  38428. }
  38429. }
  38430. }, {
  38431. litmus: Common.isObject,
  38432. conversions: {
  38433. RGBA_OBJ: {
  38434. read: function read(original) {
  38435. if (Common.isNumber(original.r) && Common.isNumber(original.g) && Common.isNumber(original.b) && Common.isNumber(original.a)) {
  38436. return {
  38437. space: 'RGB',
  38438. r: original.r,
  38439. g: original.g,
  38440. b: original.b,
  38441. a: original.a
  38442. };
  38443. }
  38444. return false;
  38445. },
  38446. write: function write(color) {
  38447. return {
  38448. r: color.r,
  38449. g: color.g,
  38450. b: color.b,
  38451. a: color.a
  38452. };
  38453. }
  38454. },
  38455. RGB_OBJ: {
  38456. read: function read(original) {
  38457. if (Common.isNumber(original.r) && Common.isNumber(original.g) && Common.isNumber(original.b)) {
  38458. return {
  38459. space: 'RGB',
  38460. r: original.r,
  38461. g: original.g,
  38462. b: original.b
  38463. };
  38464. }
  38465. return false;
  38466. },
  38467. write: function write(color) {
  38468. return {
  38469. r: color.r,
  38470. g: color.g,
  38471. b: color.b
  38472. };
  38473. }
  38474. },
  38475. HSVA_OBJ: {
  38476. read: function read(original) {
  38477. if (Common.isNumber(original.h) && Common.isNumber(original.s) && Common.isNumber(original.v) && Common.isNumber(original.a)) {
  38478. return {
  38479. space: 'HSV',
  38480. h: original.h,
  38481. s: original.s,
  38482. v: original.v,
  38483. a: original.a
  38484. };
  38485. }
  38486. return false;
  38487. },
  38488. write: function write(color) {
  38489. return {
  38490. h: color.h,
  38491. s: color.s,
  38492. v: color.v,
  38493. a: color.a
  38494. };
  38495. }
  38496. },
  38497. HSV_OBJ: {
  38498. read: function read(original) {
  38499. if (Common.isNumber(original.h) && Common.isNumber(original.s) && Common.isNumber(original.v)) {
  38500. return {
  38501. space: 'HSV',
  38502. h: original.h,
  38503. s: original.s,
  38504. v: original.v
  38505. };
  38506. }
  38507. return false;
  38508. },
  38509. write: function write(color) {
  38510. return {
  38511. h: color.h,
  38512. s: color.s,
  38513. v: color.v
  38514. };
  38515. }
  38516. }
  38517. }
  38518. }];
  38519. var result = void 0;
  38520. var toReturn = void 0;
  38521. var interpret = function interpret() {
  38522. toReturn = false;
  38523. var original = arguments.length > 1 ? Common.toArray(arguments) : arguments[0];
  38524. Common.each(INTERPRETATIONS, function (family) {
  38525. if (family.litmus(original)) {
  38526. Common.each(family.conversions, function (conversion, conversionName) {
  38527. result = conversion.read(original);
  38528. if (toReturn === false && result !== false) {
  38529. toReturn = result;
  38530. result.conversionName = conversionName;
  38531. result.conversion = conversion;
  38532. return Common.BREAK;
  38533. }
  38534. });
  38535. return Common.BREAK;
  38536. }
  38537. });
  38538. return toReturn;
  38539. };
  38540. var tmpComponent = void 0;
  38541. var ColorMath = {
  38542. hsv_to_rgb: function hsv_to_rgb(h, s, v) {
  38543. var hi = Math.floor(h / 60) % 6;
  38544. var f = h / 60 - Math.floor(h / 60);
  38545. var p = v * (1.0 - s);
  38546. var q = v * (1.0 - f * s);
  38547. var t = v * (1.0 - (1.0 - f) * s);
  38548. var c = [[v, t, p], [q, v, p], [p, v, t], [p, q, v], [t, p, v], [v, p, q]][hi];
  38549. return {
  38550. r: c[0] * 255,
  38551. g: c[1] * 255,
  38552. b: c[2] * 255
  38553. };
  38554. },
  38555. rgb_to_hsv: function rgb_to_hsv(r, g, b) {
  38556. var min = Math.min(r, g, b);
  38557. var max = Math.max(r, g, b);
  38558. var delta = max - min;
  38559. var h = void 0;
  38560. var s = void 0;
  38561. if (max !== 0) {
  38562. s = delta / max;
  38563. } else {
  38564. return {
  38565. h: NaN,
  38566. s: 0,
  38567. v: 0
  38568. };
  38569. }
  38570. if (r === max) {
  38571. h = (g - b) / delta;
  38572. } else if (g === max) {
  38573. h = 2 + (b - r) / delta;
  38574. } else {
  38575. h = 4 + (r - g) / delta;
  38576. }
  38577. h /= 6;
  38578. if (h < 0) {
  38579. h += 1;
  38580. }
  38581. return {
  38582. h: h * 360,
  38583. s: s,
  38584. v: max / 255
  38585. };
  38586. },
  38587. rgb_to_hex: function rgb_to_hex(r, g, b) {
  38588. var hex = this.hex_with_component(0, 2, r);
  38589. hex = this.hex_with_component(hex, 1, g);
  38590. hex = this.hex_with_component(hex, 0, b);
  38591. return hex;
  38592. },
  38593. component_from_hex: function component_from_hex(hex, componentIndex) {
  38594. return hex >> componentIndex * 8 & 0xFF;
  38595. },
  38596. hex_with_component: function hex_with_component(hex, componentIndex, value) {
  38597. return value << (tmpComponent = componentIndex * 8) | hex & ~(0xFF << tmpComponent);
  38598. }
  38599. };
  38600. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  38601. return typeof obj;
  38602. } : function (obj) {
  38603. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  38604. };
  38605. var classCallCheck = function (instance, Constructor) {
  38606. if (!(instance instanceof Constructor)) {
  38607. throw new TypeError("Cannot call a class as a function");
  38608. }
  38609. };
  38610. var createClass = function () {
  38611. function defineProperties(target, props) {
  38612. for (var i = 0; i < props.length; i++) {
  38613. var descriptor = props[i];
  38614. descriptor.enumerable = descriptor.enumerable || false;
  38615. descriptor.configurable = true;
  38616. if ("value" in descriptor) descriptor.writable = true;
  38617. Object.defineProperty(target, descriptor.key, descriptor);
  38618. }
  38619. }
  38620. return function (Constructor, protoProps, staticProps) {
  38621. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  38622. if (staticProps) defineProperties(Constructor, staticProps);
  38623. return Constructor;
  38624. };
  38625. }();
  38626. var get = function get(object, property, receiver) {
  38627. if (object === null) object = Function.prototype;
  38628. var desc = Object.getOwnPropertyDescriptor(object, property);
  38629. if (desc === undefined) {
  38630. var parent = Object.getPrototypeOf(object);
  38631. if (parent === null) {
  38632. return undefined;
  38633. } else {
  38634. return get(parent, property, receiver);
  38635. }
  38636. } else if ("value" in desc) {
  38637. return desc.value;
  38638. } else {
  38639. var getter = desc.get;
  38640. if (getter === undefined) {
  38641. return undefined;
  38642. }
  38643. return getter.call(receiver);
  38644. }
  38645. };
  38646. var inherits = function (subClass, superClass) {
  38647. if (typeof superClass !== "function" && superClass !== null) {
  38648. throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
  38649. }
  38650. subClass.prototype = Object.create(superClass && superClass.prototype, {
  38651. constructor: {
  38652. value: subClass,
  38653. enumerable: false,
  38654. writable: true,
  38655. configurable: true
  38656. }
  38657. });
  38658. if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
  38659. };
  38660. var possibleConstructorReturn = function (self, call) {
  38661. if (!self) {
  38662. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  38663. }
  38664. return call && (typeof call === "object" || typeof call === "function") ? call : self;
  38665. };
  38666. var Color = function () {
  38667. function Color() {
  38668. classCallCheck(this, Color);
  38669. this.__state = interpret.apply(this, arguments);
  38670. if (this.__state === false) {
  38671. throw new Error('Failed to interpret color arguments');
  38672. }
  38673. this.__state.a = this.__state.a || 1;
  38674. }
  38675. createClass(Color, [{
  38676. key: 'toString',
  38677. value: function toString() {
  38678. return colorToString(this);
  38679. }
  38680. }, {
  38681. key: 'toHexString',
  38682. value: function toHexString() {
  38683. return colorToString(this, true);
  38684. }
  38685. }, {
  38686. key: 'toOriginal',
  38687. value: function toOriginal() {
  38688. return this.__state.conversion.write(this);
  38689. }
  38690. }]);
  38691. return Color;
  38692. }();
  38693. function defineRGBComponent(target, component, componentHexIndex) {
  38694. Object.defineProperty(target, component, {
  38695. get: function get$$1() {
  38696. if (this.__state.space === 'RGB') {
  38697. return this.__state[component];
  38698. }
  38699. Color.recalculateRGB(this, component, componentHexIndex);
  38700. return this.__state[component];
  38701. },
  38702. set: function set$$1(v) {
  38703. if (this.__state.space !== 'RGB') {
  38704. Color.recalculateRGB(this, component, componentHexIndex);
  38705. this.__state.space = 'RGB';
  38706. }
  38707. this.__state[component] = v;
  38708. }
  38709. });
  38710. }
  38711. function defineHSVComponent(target, component) {
  38712. Object.defineProperty(target, component, {
  38713. get: function get$$1() {
  38714. if (this.__state.space === 'HSV') {
  38715. return this.__state[component];
  38716. }
  38717. Color.recalculateHSV(this);
  38718. return this.__state[component];
  38719. },
  38720. set: function set$$1(v) {
  38721. if (this.__state.space !== 'HSV') {
  38722. Color.recalculateHSV(this);
  38723. this.__state.space = 'HSV';
  38724. }
  38725. this.__state[component] = v;
  38726. }
  38727. });
  38728. }
  38729. Color.recalculateRGB = function (color, component, componentHexIndex) {
  38730. if (color.__state.space === 'HEX') {
  38731. color.__state[component] = ColorMath.component_from_hex(color.__state.hex, componentHexIndex);
  38732. } else if (color.__state.space === 'HSV') {
  38733. Common.extend(color.__state, ColorMath.hsv_to_rgb(color.__state.h, color.__state.s, color.__state.v));
  38734. } else {
  38735. throw new Error('Corrupted color state');
  38736. }
  38737. };
  38738. Color.recalculateHSV = function (color) {
  38739. var result = ColorMath.rgb_to_hsv(color.r, color.g, color.b);
  38740. Common.extend(color.__state, {
  38741. s: result.s,
  38742. v: result.v
  38743. });
  38744. if (!Common.isNaN(result.h)) {
  38745. color.__state.h = result.h;
  38746. } else if (Common.isUndefined(color.__state.h)) {
  38747. color.__state.h = 0;
  38748. }
  38749. };
  38750. Color.COMPONENTS = ['r', 'g', 'b', 'h', 's', 'v', 'hex', 'a'];
  38751. defineRGBComponent(Color.prototype, 'r', 2);
  38752. defineRGBComponent(Color.prototype, 'g', 1);
  38753. defineRGBComponent(Color.prototype, 'b', 0);
  38754. defineHSVComponent(Color.prototype, 'h');
  38755. defineHSVComponent(Color.prototype, 's');
  38756. defineHSVComponent(Color.prototype, 'v');
  38757. Object.defineProperty(Color.prototype, 'a', {
  38758. get: function get$$1() {
  38759. return this.__state.a;
  38760. },
  38761. set: function set$$1(v) {
  38762. this.__state.a = v;
  38763. }
  38764. });
  38765. Object.defineProperty(Color.prototype, 'hex', {
  38766. get: function get$$1() {
  38767. if (this.__state.space !== 'HEX') {
  38768. this.__state.hex = ColorMath.rgb_to_hex(this.r, this.g, this.b);
  38769. this.__state.space = 'HEX';
  38770. }
  38771. return this.__state.hex;
  38772. },
  38773. set: function set$$1(v) {
  38774. this.__state.space = 'HEX';
  38775. this.__state.hex = v;
  38776. }
  38777. });
  38778. var Controller = function () {
  38779. function Controller(object, property) {
  38780. classCallCheck(this, Controller);
  38781. this.initialValue = object[property];
  38782. this.domElement = document.createElement('div');
  38783. this.object = object;
  38784. this.property = property;
  38785. this.__onChange = undefined;
  38786. this.__onFinishChange = undefined;
  38787. }
  38788. createClass(Controller, [{
  38789. key: 'onChange',
  38790. value: function onChange(fnc) {
  38791. this.__onChange = fnc;
  38792. return this;
  38793. }
  38794. }, {
  38795. key: 'onFinishChange',
  38796. value: function onFinishChange(fnc) {
  38797. this.__onFinishChange = fnc;
  38798. return this;
  38799. }
  38800. }, {
  38801. key: 'setValue',
  38802. value: function setValue(newValue) {
  38803. this.object[this.property] = newValue;
  38804. if (this.__onChange) {
  38805. this.__onChange.call(this, newValue);
  38806. }
  38807. this.updateDisplay();
  38808. return this;
  38809. }
  38810. }, {
  38811. key: 'getValue',
  38812. value: function getValue() {
  38813. return this.object[this.property];
  38814. }
  38815. }, {
  38816. key: 'updateDisplay',
  38817. value: function updateDisplay() {
  38818. return this;
  38819. }
  38820. }, {
  38821. key: 'isModified',
  38822. value: function isModified() {
  38823. return this.initialValue !== this.getValue();
  38824. }
  38825. }]);
  38826. return Controller;
  38827. }();
  38828. var EVENT_MAP = {
  38829. HTMLEvents: ['change'],
  38830. MouseEvents: ['click', 'mousemove', 'mousedown', 'mouseup', 'mouseover'],
  38831. KeyboardEvents: ['keydown']
  38832. };
  38833. var EVENT_MAP_INV = {};
  38834. Common.each(EVENT_MAP, function (v, k) {
  38835. Common.each(v, function (e) {
  38836. EVENT_MAP_INV[e] = k;
  38837. });
  38838. });
  38839. var CSS_VALUE_PIXELS = /(\d+(\.\d+)?)px/;
  38840. function cssValueToPixels(val) {
  38841. if (val === '0' || Common.isUndefined(val)) {
  38842. return 0;
  38843. }
  38844. var match = val.match(CSS_VALUE_PIXELS);
  38845. if (!Common.isNull(match)) {
  38846. return parseFloat(match[1]);
  38847. }
  38848. return 0;
  38849. }
  38850. var dom = {
  38851. makeSelectable: function makeSelectable(elem, selectable) {
  38852. if (elem === undefined || elem.style === undefined) return;
  38853. elem.onselectstart = selectable ? function () {
  38854. return false;
  38855. } : function () {};
  38856. elem.style.MozUserSelect = selectable ? 'auto' : 'none';
  38857. elem.style.KhtmlUserSelect = selectable ? 'auto' : 'none';
  38858. elem.unselectable = selectable ? 'on' : 'off';
  38859. },
  38860. makeFullscreen: function makeFullscreen(elem, hor, vert) {
  38861. var vertical = vert;
  38862. var horizontal = hor;
  38863. if (Common.isUndefined(horizontal)) {
  38864. horizontal = true;
  38865. }
  38866. if (Common.isUndefined(vertical)) {
  38867. vertical = true;
  38868. }
  38869. elem.style.position = 'absolute';
  38870. if (horizontal) {
  38871. elem.style.left = 0;
  38872. elem.style.right = 0;
  38873. }
  38874. if (vertical) {
  38875. elem.style.top = 0;
  38876. elem.style.bottom = 0;
  38877. }
  38878. },
  38879. fakeEvent: function fakeEvent(elem, eventType, pars, aux) {
  38880. var params = pars || {};
  38881. var className = EVENT_MAP_INV[eventType];
  38882. if (!className) {
  38883. throw new Error('Event type ' + eventType + ' not supported.');
  38884. }
  38885. var evt = document.createEvent(className);
  38886. switch (className) {
  38887. case 'MouseEvents':
  38888. {
  38889. var clientX = params.x || params.clientX || 0;
  38890. var clientY = params.y || params.clientY || 0;
  38891. evt.initMouseEvent(eventType, params.bubbles || false, params.cancelable || true, window, params.clickCount || 1, 0, 0, clientX, clientY, false, false, false, false, 0, null);
  38892. break;
  38893. }
  38894. case 'KeyboardEvents':
  38895. {
  38896. var init = evt.initKeyboardEvent || evt.initKeyEvent;
  38897. Common.defaults(params, {
  38898. cancelable: true,
  38899. ctrlKey: false,
  38900. altKey: false,
  38901. shiftKey: false,
  38902. metaKey: false,
  38903. keyCode: undefined,
  38904. charCode: undefined
  38905. });
  38906. init(eventType, params.bubbles || false, params.cancelable, window, params.ctrlKey, params.altKey, params.shiftKey, params.metaKey, params.keyCode, params.charCode);
  38907. break;
  38908. }
  38909. default:
  38910. {
  38911. evt.initEvent(eventType, params.bubbles || false, params.cancelable || true);
  38912. break;
  38913. }
  38914. }
  38915. Common.defaults(evt, aux);
  38916. elem.dispatchEvent(evt);
  38917. },
  38918. bind: function bind(elem, event, func, newBool) {
  38919. var bool = newBool || false;
  38920. if (elem.addEventListener) {
  38921. elem.addEventListener(event, func, bool);
  38922. } else if (elem.attachEvent) {
  38923. elem.attachEvent('on' + event, func);
  38924. }
  38925. return dom;
  38926. },
  38927. unbind: function unbind(elem, event, func, newBool) {
  38928. var bool = newBool || false;
  38929. if (elem.removeEventListener) {
  38930. elem.removeEventListener(event, func, bool);
  38931. } else if (elem.detachEvent) {
  38932. elem.detachEvent('on' + event, func);
  38933. }
  38934. return dom;
  38935. },
  38936. addClass: function addClass(elem, className) {
  38937. if (elem.className === undefined) {
  38938. elem.className = className;
  38939. } else if (elem.className !== className) {
  38940. var classes = elem.className.split(/ +/);
  38941. if (classes.indexOf(className) === -1) {
  38942. classes.push(className);
  38943. elem.className = classes.join(' ').replace(/^\s+/, '').replace(/\s+$/, '');
  38944. }
  38945. }
  38946. return dom;
  38947. },
  38948. removeClass: function removeClass(elem, className) {
  38949. if (className) {
  38950. if (elem.className === className) {
  38951. elem.removeAttribute('class');
  38952. } else {
  38953. var classes = elem.className.split(/ +/);
  38954. var index = classes.indexOf(className);
  38955. if (index !== -1) {
  38956. classes.splice(index, 1);
  38957. elem.className = classes.join(' ');
  38958. }
  38959. }
  38960. } else {
  38961. elem.className = undefined;
  38962. }
  38963. return dom;
  38964. },
  38965. hasClass: function hasClass(elem, className) {
  38966. return new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)').test(elem.className) || false;
  38967. },
  38968. getWidth: function getWidth(elem) {
  38969. var style = getComputedStyle(elem);
  38970. return cssValueToPixels(style['border-left-width']) + cssValueToPixels(style['border-right-width']) + cssValueToPixels(style['padding-left']) + cssValueToPixels(style['padding-right']) + cssValueToPixels(style.width);
  38971. },
  38972. getHeight: function getHeight(elem) {
  38973. var style = getComputedStyle(elem);
  38974. return cssValueToPixels(style['border-top-width']) + cssValueToPixels(style['border-bottom-width']) + cssValueToPixels(style['padding-top']) + cssValueToPixels(style['padding-bottom']) + cssValueToPixels(style.height);
  38975. },
  38976. getOffset: function getOffset(el) {
  38977. var elem = el;
  38978. var offset = {
  38979. left: 0,
  38980. top: 0
  38981. };
  38982. if (elem.offsetParent) {
  38983. do {
  38984. offset.left += elem.offsetLeft;
  38985. offset.top += elem.offsetTop;
  38986. elem = elem.offsetParent;
  38987. } while (elem);
  38988. }
  38989. return offset;
  38990. },
  38991. isActive: function isActive(elem) {
  38992. return elem === document.activeElement && (elem.type || elem.href);
  38993. }
  38994. };
  38995. var BooleanController = function (_Controller) {
  38996. inherits(BooleanController, _Controller);
  38997. function BooleanController(object, property) {
  38998. classCallCheck(this, BooleanController);
  38999. var _this2 = possibleConstructorReturn(this, (BooleanController.__proto__ || Object.getPrototypeOf(BooleanController)).call(this, object, property));
  39000. var _this = _this2;
  39001. _this2.__prev = _this2.getValue();
  39002. _this2.__checkbox = document.createElement('input');
  39003. _this2.__checkbox.setAttribute('type', 'checkbox');
  39004. function onChange() {
  39005. _this.setValue(!_this.__prev);
  39006. }
  39007. dom.bind(_this2.__checkbox, 'change', onChange, false);
  39008. _this2.domElement.appendChild(_this2.__checkbox);
  39009. _this2.updateDisplay();
  39010. return _this2;
  39011. }
  39012. createClass(BooleanController, [{
  39013. key: 'setValue',
  39014. value: function setValue(v) {
  39015. var toReturn = get(BooleanController.prototype.__proto__ || Object.getPrototypeOf(BooleanController.prototype), 'setValue', this).call(this, v);
  39016. if (this.__onFinishChange) {
  39017. this.__onFinishChange.call(this, this.getValue());
  39018. }
  39019. this.__prev = this.getValue();
  39020. return toReturn;
  39021. }
  39022. }, {
  39023. key: 'updateDisplay',
  39024. value: function updateDisplay() {
  39025. if (this.getValue() === true) {
  39026. this.__checkbox.setAttribute('checked', 'checked');
  39027. this.__checkbox.checked = true;
  39028. this.__prev = true;
  39029. } else {
  39030. this.__checkbox.checked = false;
  39031. this.__prev = false;
  39032. }
  39033. return get(BooleanController.prototype.__proto__ || Object.getPrototypeOf(BooleanController.prototype), 'updateDisplay', this).call(this);
  39034. }
  39035. }]);
  39036. return BooleanController;
  39037. }(Controller);
  39038. var OptionController = function (_Controller) {
  39039. inherits(OptionController, _Controller);
  39040. function OptionController(object, property, opts) {
  39041. classCallCheck(this, OptionController);
  39042. var _this2 = possibleConstructorReturn(this, (OptionController.__proto__ || Object.getPrototypeOf(OptionController)).call(this, object, property));
  39043. var options = opts;
  39044. var _this = _this2;
  39045. _this2.__select = document.createElement('select');
  39046. if (Common.isArray(options)) {
  39047. var map = {};
  39048. Common.each(options, function (element) {
  39049. map[element] = element;
  39050. });
  39051. options = map;
  39052. }
  39053. Common.each(options, function (value, key) {
  39054. var opt = document.createElement('option');
  39055. opt.innerHTML = key;
  39056. opt.setAttribute('value', value);
  39057. _this.__select.appendChild(opt);
  39058. });
  39059. _this2.updateDisplay();
  39060. dom.bind(_this2.__select, 'change', function () {
  39061. var desiredValue = this.options[this.selectedIndex].value;
  39062. _this.setValue(desiredValue);
  39063. });
  39064. _this2.domElement.appendChild(_this2.__select);
  39065. return _this2;
  39066. }
  39067. createClass(OptionController, [{
  39068. key: 'setValue',
  39069. value: function setValue(v) {
  39070. var toReturn = get(OptionController.prototype.__proto__ || Object.getPrototypeOf(OptionController.prototype), 'setValue', this).call(this, v);
  39071. if (this.__onFinishChange) {
  39072. this.__onFinishChange.call(this, this.getValue());
  39073. }
  39074. return toReturn;
  39075. }
  39076. }, {
  39077. key: 'updateDisplay',
  39078. value: function updateDisplay() {
  39079. if (dom.isActive(this.__select)) return this;
  39080. this.__select.value = this.getValue();
  39081. return get(OptionController.prototype.__proto__ || Object.getPrototypeOf(OptionController.prototype), 'updateDisplay', this).call(this);
  39082. }
  39083. }]);
  39084. return OptionController;
  39085. }(Controller);
  39086. var StringController = function (_Controller) {
  39087. inherits(StringController, _Controller);
  39088. function StringController(object, property) {
  39089. classCallCheck(this, StringController);
  39090. var _this2 = possibleConstructorReturn(this, (StringController.__proto__ || Object.getPrototypeOf(StringController)).call(this, object, property));
  39091. var _this = _this2;
  39092. function onChange() {
  39093. _this.setValue(_this.__input.value);
  39094. }
  39095. function onBlur() {
  39096. if (_this.__onFinishChange) {
  39097. _this.__onFinishChange.call(_this, _this.getValue());
  39098. }
  39099. }
  39100. _this2.__input = document.createElement('input');
  39101. _this2.__input.setAttribute('type', 'text');
  39102. dom.bind(_this2.__input, 'keyup', onChange);
  39103. dom.bind(_this2.__input, 'change', onChange);
  39104. dom.bind(_this2.__input, 'blur', onBlur);
  39105. dom.bind(_this2.__input, 'keydown', function (e) {
  39106. if (e.keyCode === 13) {
  39107. this.blur();
  39108. }
  39109. });
  39110. _this2.updateDisplay();
  39111. _this2.domElement.appendChild(_this2.__input);
  39112. return _this2;
  39113. }
  39114. createClass(StringController, [{
  39115. key: 'updateDisplay',
  39116. value: function updateDisplay() {
  39117. if (!dom.isActive(this.__input)) {
  39118. this.__input.value = this.getValue();
  39119. }
  39120. return get(StringController.prototype.__proto__ || Object.getPrototypeOf(StringController.prototype), 'updateDisplay', this).call(this);
  39121. }
  39122. }]);
  39123. return StringController;
  39124. }(Controller);
  39125. function numDecimals(x) {
  39126. var _x = x.toString();
  39127. if (_x.indexOf('.') > -1) {
  39128. return _x.length - _x.indexOf('.') - 1;
  39129. }
  39130. return 0;
  39131. }
  39132. var NumberController = function (_Controller) {
  39133. inherits(NumberController, _Controller);
  39134. function NumberController(object, property, params) {
  39135. classCallCheck(this, NumberController);
  39136. var _this = possibleConstructorReturn(this, (NumberController.__proto__ || Object.getPrototypeOf(NumberController)).call(this, object, property));
  39137. var _params = params || {};
  39138. _this.__min = _params.min;
  39139. _this.__max = _params.max;
  39140. _this.__step = _params.step;
  39141. if (Common.isUndefined(_this.__step)) {
  39142. if (_this.initialValue === 0) {
  39143. _this.__impliedStep = 1;
  39144. } else {
  39145. _this.__impliedStep = Math.pow(10, Math.floor(Math.log(Math.abs(_this.initialValue)) / Math.LN10)) / 10;
  39146. }
  39147. } else {
  39148. _this.__impliedStep = _this.__step;
  39149. }
  39150. _this.__precision = numDecimals(_this.__impliedStep);
  39151. return _this;
  39152. }
  39153. createClass(NumberController, [{
  39154. key: 'setValue',
  39155. value: function setValue(v) {
  39156. var _v = v;
  39157. if (this.__min !== undefined && _v < this.__min) {
  39158. _v = this.__min;
  39159. } else if (this.__max !== undefined && _v > this.__max) {
  39160. _v = this.__max;
  39161. }
  39162. if (this.__step !== undefined && _v % this.__step !== 0) {
  39163. _v = Math.round(_v / this.__step) * this.__step;
  39164. }
  39165. return get(NumberController.prototype.__proto__ || Object.getPrototypeOf(NumberController.prototype), 'setValue', this).call(this, _v);
  39166. }
  39167. }, {
  39168. key: 'min',
  39169. value: function min(minValue) {
  39170. this.__min = minValue;
  39171. return this;
  39172. }
  39173. }, {
  39174. key: 'max',
  39175. value: function max(maxValue) {
  39176. this.__max = maxValue;
  39177. return this;
  39178. }
  39179. }, {
  39180. key: 'step',
  39181. value: function step(stepValue) {
  39182. this.__step = stepValue;
  39183. this.__impliedStep = stepValue;
  39184. this.__precision = numDecimals(stepValue);
  39185. return this;
  39186. }
  39187. }]);
  39188. return NumberController;
  39189. }(Controller);
  39190. function roundToDecimal(value, decimals) {
  39191. var tenTo = Math.pow(10, decimals);
  39192. return Math.round(value * tenTo) / tenTo;
  39193. }
  39194. var NumberControllerBox = function (_NumberController) {
  39195. inherits(NumberControllerBox, _NumberController);
  39196. function NumberControllerBox(object, property, params) {
  39197. classCallCheck(this, NumberControllerBox);
  39198. var _this2 = possibleConstructorReturn(this, (NumberControllerBox.__proto__ || Object.getPrototypeOf(NumberControllerBox)).call(this, object, property, params));
  39199. _this2.__truncationSuspended = false;
  39200. var _this = _this2;
  39201. var prevY = void 0;
  39202. function onChange() {
  39203. var attempted = parseFloat(_this.__input.value);
  39204. if (!Common.isNaN(attempted)) {
  39205. _this.setValue(attempted);
  39206. }
  39207. }
  39208. function onFinish() {
  39209. if (_this.__onFinishChange) {
  39210. _this.__onFinishChange.call(_this, _this.getValue());
  39211. }
  39212. }
  39213. function onBlur() {
  39214. onFinish();
  39215. }
  39216. function onMouseDrag(e) {
  39217. var diff = prevY - e.clientY;
  39218. _this.setValue(_this.getValue() + diff * _this.__impliedStep);
  39219. prevY = e.clientY;
  39220. }
  39221. function onMouseUp() {
  39222. dom.unbind(window, 'mousemove', onMouseDrag);
  39223. dom.unbind(window, 'mouseup', onMouseUp);
  39224. onFinish();
  39225. }
  39226. function onMouseDown(e) {
  39227. dom.bind(window, 'mousemove', onMouseDrag);
  39228. dom.bind(window, 'mouseup', onMouseUp);
  39229. prevY = e.clientY;
  39230. }
  39231. _this2.__input = document.createElement('input');
  39232. _this2.__input.setAttribute('type', 'text');
  39233. dom.bind(_this2.__input, 'change', onChange);
  39234. dom.bind(_this2.__input, 'blur', onBlur);
  39235. dom.bind(_this2.__input, 'mousedown', onMouseDown);
  39236. dom.bind(_this2.__input, 'keydown', function (e) {
  39237. if (e.keyCode === 13) {
  39238. _this.__truncationSuspended = true;
  39239. this.blur();
  39240. _this.__truncationSuspended = false;
  39241. onFinish();
  39242. }
  39243. });
  39244. _this2.updateDisplay();
  39245. _this2.domElement.appendChild(_this2.__input);
  39246. return _this2;
  39247. }
  39248. createClass(NumberControllerBox, [{
  39249. key: 'updateDisplay',
  39250. value: function updateDisplay() {
  39251. this.__input.value = this.__truncationSuspended ? this.getValue() : roundToDecimal(this.getValue(), this.__precision);
  39252. return get(NumberControllerBox.prototype.__proto__ || Object.getPrototypeOf(NumberControllerBox.prototype), 'updateDisplay', this).call(this);
  39253. }
  39254. }]);
  39255. return NumberControllerBox;
  39256. }(NumberController);
  39257. function map(v, i1, i2, o1, o2) {
  39258. return o1 + (o2 - o1) * ((v - i1) / (i2 - i1));
  39259. }
  39260. var NumberControllerSlider = function (_NumberController) {
  39261. inherits(NumberControllerSlider, _NumberController);
  39262. function NumberControllerSlider(object, property, min, max, step) {
  39263. classCallCheck(this, NumberControllerSlider);
  39264. var _this2 = possibleConstructorReturn(this, (NumberControllerSlider.__proto__ || Object.getPrototypeOf(NumberControllerSlider)).call(this, object, property, {
  39265. min: min,
  39266. max: max,
  39267. step: step
  39268. }));
  39269. var _this = _this2;
  39270. _this2.__background = document.createElement('div');
  39271. _this2.__foreground = document.createElement('div');
  39272. dom.bind(_this2.__background, 'mousedown', onMouseDown);
  39273. dom.bind(_this2.__background, 'touchstart', onTouchStart);
  39274. dom.addClass(_this2.__background, 'slider');
  39275. dom.addClass(_this2.__foreground, 'slider-fg');
  39276. function onMouseDown(e) {
  39277. document.activeElement.blur();
  39278. dom.bind(window, 'mousemove', onMouseDrag);
  39279. dom.bind(window, 'mouseup', onMouseUp);
  39280. onMouseDrag(e);
  39281. }
  39282. function onMouseDrag(e) {
  39283. e.preventDefault();
  39284. var bgRect = _this.__background.getBoundingClientRect();
  39285. _this.setValue(map(e.clientX, bgRect.left, bgRect.right, _this.__min, _this.__max));
  39286. return false;
  39287. }
  39288. function onMouseUp() {
  39289. dom.unbind(window, 'mousemove', onMouseDrag);
  39290. dom.unbind(window, 'mouseup', onMouseUp);
  39291. if (_this.__onFinishChange) {
  39292. _this.__onFinishChange.call(_this, _this.getValue());
  39293. }
  39294. }
  39295. function onTouchStart(e) {
  39296. if (e.touches.length !== 1) {
  39297. return;
  39298. }
  39299. dom.bind(window, 'touchmove', onTouchMove);
  39300. dom.bind(window, 'touchend', onTouchEnd);
  39301. onTouchMove(e);
  39302. }
  39303. function onTouchMove(e) {
  39304. var clientX = e.touches[0].clientX;
  39305. var bgRect = _this.__background.getBoundingClientRect();
  39306. _this.setValue(map(clientX, bgRect.left, bgRect.right, _this.__min, _this.__max));
  39307. }
  39308. function onTouchEnd() {
  39309. dom.unbind(window, 'touchmove', onTouchMove);
  39310. dom.unbind(window, 'touchend', onTouchEnd);
  39311. if (_this.__onFinishChange) {
  39312. _this.__onFinishChange.call(_this, _this.getValue());
  39313. }
  39314. }
  39315. _this2.updateDisplay();
  39316. _this2.__background.appendChild(_this2.__foreground);
  39317. _this2.domElement.appendChild(_this2.__background);
  39318. return _this2;
  39319. }
  39320. createClass(NumberControllerSlider, [{
  39321. key: 'updateDisplay',
  39322. value: function updateDisplay() {
  39323. var pct = (this.getValue() - this.__min) / (this.__max - this.__min);
  39324. this.__foreground.style.width = pct * 100 + '%';
  39325. return get(NumberControllerSlider.prototype.__proto__ || Object.getPrototypeOf(NumberControllerSlider.prototype), 'updateDisplay', this).call(this);
  39326. }
  39327. }]);
  39328. return NumberControllerSlider;
  39329. }(NumberController);
  39330. var FunctionController = function (_Controller) {
  39331. inherits(FunctionController, _Controller);
  39332. function FunctionController(object, property, text) {
  39333. classCallCheck(this, FunctionController);
  39334. var _this2 = possibleConstructorReturn(this, (FunctionController.__proto__ || Object.getPrototypeOf(FunctionController)).call(this, object, property));
  39335. var _this = _this2;
  39336. _this2.__button = document.createElement('div');
  39337. _this2.__button.innerHTML = text === undefined ? 'Fire' : text;
  39338. dom.bind(_this2.__button, 'click', function (e) {
  39339. e.preventDefault();
  39340. _this.fire();
  39341. return false;
  39342. });
  39343. dom.addClass(_this2.__button, 'button');
  39344. _this2.domElement.appendChild(_this2.__button);
  39345. return _this2;
  39346. }
  39347. createClass(FunctionController, [{
  39348. key: 'fire',
  39349. value: function fire() {
  39350. if (this.__onChange) {
  39351. this.__onChange.call(this);
  39352. }
  39353. this.getValue().call(this.object);
  39354. if (this.__onFinishChange) {
  39355. this.__onFinishChange.call(this, this.getValue());
  39356. }
  39357. }
  39358. }]);
  39359. return FunctionController;
  39360. }(Controller);
  39361. var ColorController = function (_Controller) {
  39362. inherits(ColorController, _Controller);
  39363. function ColorController(object, property) {
  39364. classCallCheck(this, ColorController);
  39365. var _this2 = possibleConstructorReturn(this, (ColorController.__proto__ || Object.getPrototypeOf(ColorController)).call(this, object, property));
  39366. _this2.__color = new Color(_this2.getValue());
  39367. _this2.__temp = new Color(0);
  39368. var _this = _this2;
  39369. _this2.domElement = document.createElement('div');
  39370. dom.makeSelectable(_this2.domElement, false);
  39371. _this2.__selector = document.createElement('div');
  39372. _this2.__selector.className = 'selector';
  39373. _this2.__saturation_field = document.createElement('div');
  39374. _this2.__saturation_field.className = 'saturation-field';
  39375. _this2.__field_knob = document.createElement('div');
  39376. _this2.__field_knob.className = 'field-knob';
  39377. _this2.__field_knob_border = '2px solid ';
  39378. _this2.__hue_knob = document.createElement('div');
  39379. _this2.__hue_knob.className = 'hue-knob';
  39380. _this2.__hue_field = document.createElement('div');
  39381. _this2.__hue_field.className = 'hue-field';
  39382. _this2.__input = document.createElement('input');
  39383. _this2.__input.type = 'text';
  39384. _this2.__input_textShadow = '0 1px 1px ';
  39385. dom.bind(_this2.__input, 'keydown', function (e) {
  39386. if (e.keyCode === 13) {
  39387. onBlur.call(this);
  39388. }
  39389. });
  39390. dom.bind(_this2.__input, 'blur', onBlur);
  39391. dom.bind(_this2.__selector, 'mousedown', function () {
  39392. dom.addClass(this, 'drag').bind(window, 'mouseup', function () {
  39393. dom.removeClass(_this.__selector, 'drag');
  39394. });
  39395. });
  39396. dom.bind(_this2.__selector, 'touchstart', function () {
  39397. dom.addClass(this, 'drag').bind(window, 'touchend', function () {
  39398. dom.removeClass(_this.__selector, 'drag');
  39399. });
  39400. });
  39401. var valueField = document.createElement('div');
  39402. Common.extend(_this2.__selector.style, {
  39403. width: '122px',
  39404. height: '102px',
  39405. padding: '3px',
  39406. backgroundColor: '#222',
  39407. boxShadow: '0px 1px 3px rgba(0,0,0,0.3)'
  39408. });
  39409. Common.extend(_this2.__field_knob.style, {
  39410. position: 'absolute',
  39411. width: '12px',
  39412. height: '12px',
  39413. border: _this2.__field_knob_border + (_this2.__color.v < 0.5 ? '#fff' : '#000'),
  39414. boxShadow: '0px 1px 3px rgba(0,0,0,0.5)',
  39415. borderRadius: '12px',
  39416. zIndex: 1
  39417. });
  39418. Common.extend(_this2.__hue_knob.style, {
  39419. position: 'absolute',
  39420. width: '15px',
  39421. height: '2px',
  39422. borderRight: '4px solid #fff',
  39423. zIndex: 1
  39424. });
  39425. Common.extend(_this2.__saturation_field.style, {
  39426. width: '100px',
  39427. height: '100px',
  39428. border: '1px solid #555',
  39429. marginRight: '3px',
  39430. display: 'inline-block',
  39431. cursor: 'pointer'
  39432. });
  39433. Common.extend(valueField.style, {
  39434. width: '100%',
  39435. height: '100%',
  39436. background: 'none'
  39437. });
  39438. linearGradient(valueField, 'top', 'rgba(0,0,0,0)', '#000');
  39439. Common.extend(_this2.__hue_field.style, {
  39440. width: '15px',
  39441. height: '100px',
  39442. border: '1px solid #555',
  39443. cursor: 'ns-resize',
  39444. position: 'absolute',
  39445. top: '3px',
  39446. right: '3px'
  39447. });
  39448. hueGradient(_this2.__hue_field);
  39449. Common.extend(_this2.__input.style, {
  39450. outline: 'none',
  39451. textAlign: 'center',
  39452. color: '#fff',
  39453. border: 0,
  39454. fontWeight: 'bold',
  39455. textShadow: _this2.__input_textShadow + 'rgba(0,0,0,0.7)'
  39456. });
  39457. dom.bind(_this2.__saturation_field, 'mousedown', fieldDown);
  39458. dom.bind(_this2.__saturation_field, 'touchstart', fieldDown);
  39459. dom.bind(_this2.__field_knob, 'mousedown', fieldDown);
  39460. dom.bind(_this2.__field_knob, 'touchstart', fieldDown);
  39461. dom.bind(_this2.__hue_field, 'mousedown', fieldDownH);
  39462. dom.bind(_this2.__hue_field, 'touchstart', fieldDownH);
  39463. function fieldDown(e) {
  39464. setSV(e);
  39465. dom.bind(window, 'mousemove', setSV);
  39466. dom.bind(window, 'touchmove', setSV);
  39467. dom.bind(window, 'mouseup', fieldUpSV);
  39468. dom.bind(window, 'touchend', fieldUpSV);
  39469. }
  39470. function fieldDownH(e) {
  39471. setH(e);
  39472. dom.bind(window, 'mousemove', setH);
  39473. dom.bind(window, 'touchmove', setH);
  39474. dom.bind(window, 'mouseup', fieldUpH);
  39475. dom.bind(window, 'touchend', fieldUpH);
  39476. }
  39477. function fieldUpSV() {
  39478. dom.unbind(window, 'mousemove', setSV);
  39479. dom.unbind(window, 'touchmove', setSV);
  39480. dom.unbind(window, 'mouseup', fieldUpSV);
  39481. dom.unbind(window, 'touchend', fieldUpSV);
  39482. onFinish();
  39483. }
  39484. function fieldUpH() {
  39485. dom.unbind(window, 'mousemove', setH);
  39486. dom.unbind(window, 'touchmove', setH);
  39487. dom.unbind(window, 'mouseup', fieldUpH);
  39488. dom.unbind(window, 'touchend', fieldUpH);
  39489. onFinish();
  39490. }
  39491. function onBlur() {
  39492. var i = interpret(this.value);
  39493. if (i !== false) {
  39494. _this.__color.__state = i;
  39495. _this.setValue(_this.__color.toOriginal());
  39496. } else {
  39497. this.value = _this.__color.toString();
  39498. }
  39499. }
  39500. function onFinish() {
  39501. if (_this.__onFinishChange) {
  39502. _this.__onFinishChange.call(_this, _this.__color.toOriginal());
  39503. }
  39504. }
  39505. _this2.__saturation_field.appendChild(valueField);
  39506. _this2.__selector.appendChild(_this2.__field_knob);
  39507. _this2.__selector.appendChild(_this2.__saturation_field);
  39508. _this2.__selector.appendChild(_this2.__hue_field);
  39509. _this2.__hue_field.appendChild(_this2.__hue_knob);
  39510. _this2.domElement.appendChild(_this2.__input);
  39511. _this2.domElement.appendChild(_this2.__selector);
  39512. _this2.updateDisplay();
  39513. function setSV(e) {
  39514. if (e.type.indexOf('touch') === -1) {
  39515. e.preventDefault();
  39516. }
  39517. var fieldRect = _this.__saturation_field.getBoundingClientRect();
  39518. var _ref = e.touches && e.touches[0] || e,
  39519. clientX = _ref.clientX,
  39520. clientY = _ref.clientY;
  39521. var s = (clientX - fieldRect.left) / (fieldRect.right - fieldRect.left);
  39522. var v = 1 - (clientY - fieldRect.top) / (fieldRect.bottom - fieldRect.top);
  39523. if (v > 1) {
  39524. v = 1;
  39525. } else if (v < 0) {
  39526. v = 0;
  39527. }
  39528. if (s > 1) {
  39529. s = 1;
  39530. } else if (s < 0) {
  39531. s = 0;
  39532. }
  39533. _this.__color.v = v;
  39534. _this.__color.s = s;
  39535. _this.setValue(_this.__color.toOriginal());
  39536. return false;
  39537. }
  39538. function setH(e) {
  39539. if (e.type.indexOf('touch') === -1) {
  39540. e.preventDefault();
  39541. }
  39542. var fieldRect = _this.__hue_field.getBoundingClientRect();
  39543. var _ref2 = e.touches && e.touches[0] || e,
  39544. clientY = _ref2.clientY;
  39545. var h = 1 - (clientY - fieldRect.top) / (fieldRect.bottom - fieldRect.top);
  39546. if (h > 1) {
  39547. h = 1;
  39548. } else if (h < 0) {
  39549. h = 0;
  39550. }
  39551. _this.__color.h = h * 360;
  39552. _this.setValue(_this.__color.toOriginal());
  39553. return false;
  39554. }
  39555. return _this2;
  39556. }
  39557. createClass(ColorController, [{
  39558. key: 'updateDisplay',
  39559. value: function updateDisplay() {
  39560. var i = interpret(this.getValue());
  39561. if (i !== false) {
  39562. var mismatch = false;
  39563. Common.each(Color.COMPONENTS, function (component) {
  39564. if (!Common.isUndefined(i[component]) && !Common.isUndefined(this.__color.__state[component]) && i[component] !== this.__color.__state[component]) {
  39565. mismatch = true;
  39566. return {};
  39567. }
  39568. }, this);
  39569. if (mismatch) {
  39570. Common.extend(this.__color.__state, i);
  39571. }
  39572. }
  39573. Common.extend(this.__temp.__state, this.__color.__state);
  39574. this.__temp.a = 1;
  39575. var flip = this.__color.v < 0.5 || this.__color.s > 0.5 ? 255 : 0;
  39576. var _flip = 255 - flip;
  39577. Common.extend(this.__field_knob.style, {
  39578. marginLeft: 100 * this.__color.s - 7 + 'px',
  39579. marginTop: 100 * (1 - this.__color.v) - 7 + 'px',
  39580. backgroundColor: this.__temp.toHexString(),
  39581. border: this.__field_knob_border + 'rgb(' + flip + ',' + flip + ',' + flip + ')'
  39582. });
  39583. this.__hue_knob.style.marginTop = (1 - this.__color.h / 360) * 100 + 'px';
  39584. this.__temp.s = 1;
  39585. this.__temp.v = 1;
  39586. linearGradient(this.__saturation_field, 'left', '#fff', this.__temp.toHexString());
  39587. this.__input.value = this.__color.toString();
  39588. Common.extend(this.__input.style, {
  39589. backgroundColor: this.__color.toHexString(),
  39590. color: 'rgb(' + flip + ',' + flip + ',' + flip + ')',
  39591. textShadow: this.__input_textShadow + 'rgba(' + _flip + ',' + _flip + ',' + _flip + ',.7)'
  39592. });
  39593. }
  39594. }]);
  39595. return ColorController;
  39596. }(Controller);
  39597. var vendors = ['-moz-', '-o-', '-webkit-', '-ms-', ''];
  39598. function linearGradient(elem, x, a, b) {
  39599. elem.style.background = '';
  39600. Common.each(vendors, function (vendor) {
  39601. elem.style.cssText += 'background: ' + vendor + 'linear-gradient(' + x + ', ' + a + ' 0%, ' + b + ' 100%); ';
  39602. });
  39603. }
  39604. function hueGradient(elem) {
  39605. elem.style.background = '';
  39606. elem.style.cssText += 'background: -moz-linear-gradient(top, #ff0000 0%, #ff00ff 17%, #0000ff 34%, #00ffff 50%, #00ff00 67%, #ffff00 84%, #ff0000 100%);';
  39607. elem.style.cssText += 'background: -webkit-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  39608. elem.style.cssText += 'background: -o-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  39609. elem.style.cssText += 'background: -ms-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  39610. elem.style.cssText += 'background: linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  39611. }
  39612. var css = {
  39613. load: function load(url, indoc) {
  39614. var doc = indoc || document;
  39615. var link = doc.createElement('link');
  39616. link.type = 'text/css';
  39617. link.rel = 'stylesheet';
  39618. link.href = url;
  39619. doc.getElementsByTagName('head')[0].appendChild(link);
  39620. },
  39621. inject: function inject(cssContent, indoc) {
  39622. var doc = indoc || document;
  39623. var injected = document.createElement('style');
  39624. injected.type = 'text/css';
  39625. injected.innerHTML = cssContent;
  39626. var head = doc.getElementsByTagName('head')[0];
  39627. try {
  39628. head.appendChild(injected);
  39629. } catch (e) {}
  39630. }
  39631. };
  39632. 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>";
  39633. var ControllerFactory = function ControllerFactory(object, property) {
  39634. var initialValue = object[property];
  39635. if (Common.isArray(arguments[2]) || Common.isObject(arguments[2])) {
  39636. return new OptionController(object, property, arguments[2]);
  39637. }
  39638. if (Common.isNumber(initialValue)) {
  39639. if (Common.isNumber(arguments[2]) && Common.isNumber(arguments[3])) {
  39640. if (Common.isNumber(arguments[4])) {
  39641. return new NumberControllerSlider(object, property, arguments[2], arguments[3], arguments[4]);
  39642. }
  39643. return new NumberControllerSlider(object, property, arguments[2], arguments[3]);
  39644. }
  39645. if (Common.isNumber(arguments[4])) {
  39646. return new NumberControllerBox(object, property, {
  39647. min: arguments[2],
  39648. max: arguments[3],
  39649. step: arguments[4]
  39650. });
  39651. }
  39652. return new NumberControllerBox(object, property, {
  39653. min: arguments[2],
  39654. max: arguments[3]
  39655. });
  39656. }
  39657. if (Common.isString(initialValue)) {
  39658. return new StringController(object, property);
  39659. }
  39660. if (Common.isFunction(initialValue)) {
  39661. return new FunctionController(object, property, '');
  39662. }
  39663. if (Common.isBoolean(initialValue)) {
  39664. return new BooleanController(object, property);
  39665. }
  39666. return null;
  39667. };
  39668. function requestAnimationFrame(callback) {
  39669. setTimeout(callback, 1000 / 60);
  39670. }
  39671. var requestAnimationFrame$1 = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || requestAnimationFrame;
  39672. var CenteredDiv = function () {
  39673. function CenteredDiv() {
  39674. classCallCheck(this, CenteredDiv);
  39675. this.backgroundElement = document.createElement('div');
  39676. Common.extend(this.backgroundElement.style, {
  39677. backgroundColor: 'rgba(0,0,0,0.8)',
  39678. top: 0,
  39679. left: 0,
  39680. display: 'none',
  39681. zIndex: '1000',
  39682. opacity: 0,
  39683. WebkitTransition: 'opacity 0.2s linear',
  39684. transition: 'opacity 0.2s linear'
  39685. });
  39686. dom.makeFullscreen(this.backgroundElement);
  39687. this.backgroundElement.style.position = 'fixed';
  39688. this.domElement = document.createElement('div');
  39689. Common.extend(this.domElement.style, {
  39690. position: 'fixed',
  39691. display: 'none',
  39692. zIndex: '1001',
  39693. opacity: 0,
  39694. WebkitTransition: '-webkit-transform 0.2s ease-out, opacity 0.2s linear',
  39695. transition: 'transform 0.2s ease-out, opacity 0.2s linear'
  39696. });
  39697. document.body.appendChild(this.backgroundElement);
  39698. document.body.appendChild(this.domElement);
  39699. var _this = this;
  39700. dom.bind(this.backgroundElement, 'click', function () {
  39701. _this.hide();
  39702. });
  39703. }
  39704. createClass(CenteredDiv, [{
  39705. key: 'show',
  39706. value: function show() {
  39707. var _this = this;
  39708. this.backgroundElement.style.display = 'block';
  39709. this.domElement.style.display = 'block';
  39710. this.domElement.style.opacity = 0;
  39711. this.domElement.style.webkitTransform = 'scale(1.1)';
  39712. this.layout();
  39713. Common.defer(function () {
  39714. _this.backgroundElement.style.opacity = 1;
  39715. _this.domElement.style.opacity = 1;
  39716. _this.domElement.style.webkitTransform = 'scale(1)';
  39717. });
  39718. }
  39719. }, {
  39720. key: 'hide',
  39721. value: function hide() {
  39722. var _this = this;
  39723. var hide = function hide() {
  39724. _this.domElement.style.display = 'none';
  39725. _this.backgroundElement.style.display = 'none';
  39726. dom.unbind(_this.domElement, 'webkitTransitionEnd', hide);
  39727. dom.unbind(_this.domElement, 'transitionend', hide);
  39728. dom.unbind(_this.domElement, 'oTransitionEnd', hide);
  39729. };
  39730. dom.bind(this.domElement, 'webkitTransitionEnd', hide);
  39731. dom.bind(this.domElement, 'transitionend', hide);
  39732. dom.bind(this.domElement, 'oTransitionEnd', hide);
  39733. this.backgroundElement.style.opacity = 0;
  39734. this.domElement.style.opacity = 0;
  39735. this.domElement.style.webkitTransform = 'scale(1.1)';
  39736. }
  39737. }, {
  39738. key: 'layout',
  39739. value: function layout() {
  39740. this.domElement.style.left = window.innerWidth / 2 - dom.getWidth(this.domElement) / 2 + 'px';
  39741. this.domElement.style.top = window.innerHeight / 2 - dom.getHeight(this.domElement) / 2 + 'px';
  39742. }
  39743. }]);
  39744. return CenteredDiv;
  39745. }();
  39746. 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");
  39747. css.inject(styleSheet);
  39748. var CSS_NAMESPACE = 'dg';
  39749. var HIDE_KEY_CODE = 72;
  39750. var CLOSE_BUTTON_HEIGHT = 20;
  39751. var DEFAULT_DEFAULT_PRESET_NAME = 'Default';
  39752. var SUPPORTS_LOCAL_STORAGE = function () {
  39753. try {
  39754. return !!window.localStorage;
  39755. } catch (e) {
  39756. return false;
  39757. }
  39758. }();
  39759. var SAVE_DIALOGUE = void 0;
  39760. var autoPlaceVirgin = true;
  39761. var autoPlaceContainer = void 0;
  39762. var hide = false;
  39763. var hideableGuis = [];
  39764. var GUI = function GUI(pars) {
  39765. var _this = this;
  39766. var params = pars || {};
  39767. this.domElement = document.createElement('div');
  39768. this.__ul = document.createElement('ul');
  39769. this.domElement.appendChild(this.__ul);
  39770. dom.addClass(this.domElement, CSS_NAMESPACE);
  39771. this.__folders = {};
  39772. this.__controllers = [];
  39773. this.__rememberedObjects = [];
  39774. this.__rememberedObjectIndecesToControllers = [];
  39775. this.__listening = [];
  39776. params = Common.defaults(params, {
  39777. closeOnTop: false,
  39778. autoPlace: true,
  39779. width: GUI.DEFAULT_WIDTH
  39780. });
  39781. params = Common.defaults(params, {
  39782. resizable: params.autoPlace,
  39783. hideable: params.autoPlace
  39784. });
  39785. if (!Common.isUndefined(params.load)) {
  39786. if (params.preset) {
  39787. params.load.preset = params.preset;
  39788. }
  39789. } else {
  39790. params.load = {
  39791. preset: DEFAULT_DEFAULT_PRESET_NAME
  39792. };
  39793. }
  39794. if (Common.isUndefined(params.parent) && params.hideable) {
  39795. hideableGuis.push(this);
  39796. }
  39797. params.resizable = Common.isUndefined(params.parent) && params.resizable;
  39798. if (params.autoPlace && Common.isUndefined(params.scrollable)) {
  39799. params.scrollable = true;
  39800. }
  39801. var useLocalStorage = SUPPORTS_LOCAL_STORAGE && localStorage.getItem(getLocalStorageHash(this, 'isLocal')) === 'true';
  39802. var saveToLocalStorage = void 0;
  39803. var titleRow = void 0;
  39804. Object.defineProperties(this, {
  39805. parent: {
  39806. get: function get$$1() {
  39807. return params.parent;
  39808. }
  39809. },
  39810. scrollable: {
  39811. get: function get$$1() {
  39812. return params.scrollable;
  39813. }
  39814. },
  39815. autoPlace: {
  39816. get: function get$$1() {
  39817. return params.autoPlace;
  39818. }
  39819. },
  39820. closeOnTop: {
  39821. get: function get$$1() {
  39822. return params.closeOnTop;
  39823. }
  39824. },
  39825. preset: {
  39826. get: function get$$1() {
  39827. if (_this.parent) {
  39828. return _this.getRoot().preset;
  39829. }
  39830. return params.load.preset;
  39831. },
  39832. set: function set$$1(v) {
  39833. if (_this.parent) {
  39834. _this.getRoot().preset = v;
  39835. } else {
  39836. params.load.preset = v;
  39837. }
  39838. setPresetSelectIndex(this);
  39839. _this.revert();
  39840. }
  39841. },
  39842. width: {
  39843. get: function get$$1() {
  39844. return params.width;
  39845. },
  39846. set: function set$$1(v) {
  39847. params.width = v;
  39848. setWidth(_this, v);
  39849. }
  39850. },
  39851. name: {
  39852. get: function get$$1() {
  39853. return params.name;
  39854. },
  39855. set: function set$$1(v) {
  39856. params.name = v;
  39857. if (titleRow) {
  39858. titleRow.innerHTML = params.name;
  39859. }
  39860. }
  39861. },
  39862. closed: {
  39863. get: function get$$1() {
  39864. return params.closed;
  39865. },
  39866. set: function set$$1(v) {
  39867. params.closed = v;
  39868. if (params.closed) {
  39869. dom.addClass(_this.__ul, GUI.CLASS_CLOSED);
  39870. } else {
  39871. dom.removeClass(_this.__ul, GUI.CLASS_CLOSED);
  39872. }
  39873. this.onResize();
  39874. if (_this.__closeButton) {
  39875. _this.__closeButton.innerHTML = v ? GUI.TEXT_OPEN : GUI.TEXT_CLOSED;
  39876. }
  39877. }
  39878. },
  39879. load: {
  39880. get: function get$$1() {
  39881. return params.load;
  39882. }
  39883. },
  39884. useLocalStorage: {
  39885. get: function get$$1() {
  39886. return useLocalStorage;
  39887. },
  39888. set: function set$$1(bool) {
  39889. if (SUPPORTS_LOCAL_STORAGE) {
  39890. useLocalStorage = bool;
  39891. if (bool) {
  39892. dom.bind(window, 'unload', saveToLocalStorage);
  39893. } else {
  39894. dom.unbind(window, 'unload', saveToLocalStorage);
  39895. }
  39896. localStorage.setItem(getLocalStorageHash(_this, 'isLocal'), bool);
  39897. }
  39898. }
  39899. }
  39900. });
  39901. if (Common.isUndefined(params.parent)) {
  39902. this.closed = params.closed || false;
  39903. dom.addClass(this.domElement, GUI.CLASS_MAIN);
  39904. dom.makeSelectable(this.domElement, false);
  39905. if (SUPPORTS_LOCAL_STORAGE) {
  39906. if (useLocalStorage) {
  39907. _this.useLocalStorage = true;
  39908. var savedGui = localStorage.getItem(getLocalStorageHash(this, 'gui'));
  39909. if (savedGui) {
  39910. params.load = JSON.parse(savedGui);
  39911. }
  39912. }
  39913. }
  39914. this.__closeButton = document.createElement('div');
  39915. this.__closeButton.innerHTML = GUI.TEXT_CLOSED;
  39916. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BUTTON);
  39917. if (params.closeOnTop) {
  39918. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_TOP);
  39919. this.domElement.insertBefore(this.__closeButton, this.domElement.childNodes[0]);
  39920. } else {
  39921. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BOTTOM);
  39922. this.domElement.appendChild(this.__closeButton);
  39923. }
  39924. dom.bind(this.__closeButton, 'click', function () {
  39925. _this.closed = !_this.closed;
  39926. });
  39927. } else {
  39928. if (params.closed === undefined) {
  39929. params.closed = true;
  39930. }
  39931. var titleRowName = document.createTextNode(params.name);
  39932. dom.addClass(titleRowName, 'controller-name');
  39933. titleRow = addRow(_this, titleRowName);
  39934. var onClickTitle = function onClickTitle(e) {
  39935. e.preventDefault();
  39936. _this.closed = !_this.closed;
  39937. return false;
  39938. };
  39939. dom.addClass(this.__ul, GUI.CLASS_CLOSED);
  39940. dom.addClass(titleRow, 'title');
  39941. dom.bind(titleRow, 'click', onClickTitle);
  39942. if (!params.closed) {
  39943. this.closed = false;
  39944. }
  39945. }
  39946. if (params.autoPlace) {
  39947. if (Common.isUndefined(params.parent)) {
  39948. if (autoPlaceVirgin) {
  39949. autoPlaceContainer = document.createElement('div');
  39950. dom.addClass(autoPlaceContainer, CSS_NAMESPACE);
  39951. dom.addClass(autoPlaceContainer, GUI.CLASS_AUTO_PLACE_CONTAINER);
  39952. document.body.appendChild(autoPlaceContainer);
  39953. autoPlaceVirgin = false;
  39954. }
  39955. autoPlaceContainer.appendChild(this.domElement);
  39956. dom.addClass(this.domElement, GUI.CLASS_AUTO_PLACE);
  39957. }
  39958. if (!this.parent) {
  39959. setWidth(_this, params.width);
  39960. }
  39961. }
  39962. this.__resizeHandler = function () {
  39963. _this.onResizeDebounced();
  39964. };
  39965. dom.bind(window, 'resize', this.__resizeHandler);
  39966. dom.bind(this.__ul, 'webkitTransitionEnd', this.__resizeHandler);
  39967. dom.bind(this.__ul, 'transitionend', this.__resizeHandler);
  39968. dom.bind(this.__ul, 'oTransitionEnd', this.__resizeHandler);
  39969. this.onResize();
  39970. if (params.resizable) {
  39971. addResizeHandle(this);
  39972. }
  39973. saveToLocalStorage = function saveToLocalStorage() {
  39974. if (SUPPORTS_LOCAL_STORAGE && localStorage.getItem(getLocalStorageHash(_this, 'isLocal')) === 'true') {
  39975. localStorage.setItem(getLocalStorageHash(_this, 'gui'), JSON.stringify(_this.getSaveObject()));
  39976. }
  39977. };
  39978. this.saveToLocalStorageIfPossible = saveToLocalStorage;
  39979. function resetWidth() {
  39980. var root = _this.getRoot();
  39981. root.width += 1;
  39982. Common.defer(function () {
  39983. root.width -= 1;
  39984. });
  39985. }
  39986. if (!params.parent) {
  39987. resetWidth();
  39988. }
  39989. };
  39990. GUI.toggleHide = function () {
  39991. hide = !hide;
  39992. Common.each(hideableGuis, function (gui) {
  39993. gui.domElement.style.display = hide ? 'none' : '';
  39994. });
  39995. };
  39996. GUI.CLASS_AUTO_PLACE = 'a';
  39997. GUI.CLASS_AUTO_PLACE_CONTAINER = 'ac';
  39998. GUI.CLASS_MAIN = 'main';
  39999. GUI.CLASS_CONTROLLER_ROW = 'cr';
  40000. GUI.CLASS_TOO_TALL = 'taller-than-window';
  40001. GUI.CLASS_CLOSED = 'closed';
  40002. GUI.CLASS_CLOSE_BUTTON = 'close-button';
  40003. GUI.CLASS_CLOSE_TOP = 'close-top';
  40004. GUI.CLASS_CLOSE_BOTTOM = 'close-bottom';
  40005. GUI.CLASS_DRAG = 'drag';
  40006. GUI.DEFAULT_WIDTH = 245;
  40007. GUI.TEXT_CLOSED = 'Close Controls';
  40008. GUI.TEXT_OPEN = 'Open Controls';
  40009. GUI._keydownHandler = function (e) {
  40010. if (document.activeElement.type !== 'text' && (e.which === HIDE_KEY_CODE || e.keyCode === HIDE_KEY_CODE)) {
  40011. GUI.toggleHide();
  40012. }
  40013. };
  40014. dom.bind(window, 'keydown', GUI._keydownHandler, false);
  40015. Common.extend(GUI.prototype, {
  40016. add: function add(object, property) {
  40017. return _add(this, object, property, {
  40018. factoryArgs: Array.prototype.slice.call(arguments, 2)
  40019. });
  40020. },
  40021. addColor: function addColor(object, property) {
  40022. return _add(this, object, property, {
  40023. color: true
  40024. });
  40025. },
  40026. remove: function remove(controller) {
  40027. this.__ul.removeChild(controller.__li);
  40028. this.__controllers.splice(this.__controllers.indexOf(controller), 1);
  40029. var _this = this;
  40030. Common.defer(function () {
  40031. _this.onResize();
  40032. });
  40033. },
  40034. destroy: function destroy() {
  40035. if (this.parent) {
  40036. throw new Error('Only the root GUI should be removed with .destroy(). ' + 'For subfolders, use gui.removeFolder(folder) instead.');
  40037. }
  40038. if (this.autoPlace) {
  40039. autoPlaceContainer.removeChild(this.domElement);
  40040. }
  40041. var _this = this;
  40042. Common.each(this.__folders, function (subfolder) {
  40043. _this.removeFolder(subfolder);
  40044. });
  40045. dom.unbind(window, 'keydown', GUI._keydownHandler, false);
  40046. removeListeners(this);
  40047. },
  40048. addFolder: function addFolder(name) {
  40049. if (this.__folders[name] !== undefined) {
  40050. throw new Error('You already have a folder in this GUI by the' + ' name "' + name + '"');
  40051. }
  40052. var newGuiParams = {
  40053. name: name,
  40054. parent: this
  40055. };
  40056. newGuiParams.autoPlace = this.autoPlace;
  40057. if (this.load && this.load.folders && this.load.folders[name]) {
  40058. newGuiParams.closed = this.load.folders[name].closed;
  40059. newGuiParams.load = this.load.folders[name];
  40060. }
  40061. var gui = new GUI(newGuiParams);
  40062. this.__folders[name] = gui;
  40063. var li = addRow(this, gui.domElement);
  40064. dom.addClass(li, 'folder');
  40065. return gui;
  40066. },
  40067. removeFolder: function removeFolder(folder) {
  40068. this.__ul.removeChild(folder.domElement.parentElement);
  40069. delete this.__folders[folder.name];
  40070. if (this.load && this.load.folders && this.load.folders[folder.name]) {
  40071. delete this.load.folders[folder.name];
  40072. }
  40073. removeListeners(folder);
  40074. var _this = this;
  40075. Common.each(folder.__folders, function (subfolder) {
  40076. folder.removeFolder(subfolder);
  40077. });
  40078. Common.defer(function () {
  40079. _this.onResize();
  40080. });
  40081. },
  40082. open: function open() {
  40083. this.closed = false;
  40084. },
  40085. close: function close() {
  40086. this.closed = true;
  40087. },
  40088. hide: function hide() {
  40089. this.domElement.style.display = 'none';
  40090. },
  40091. show: function show() {
  40092. this.domElement.style.display = '';
  40093. },
  40094. onResize: function onResize() {
  40095. var root = this.getRoot();
  40096. if (root.scrollable) {
  40097. var top = dom.getOffset(root.__ul).top;
  40098. var h = 0;
  40099. Common.each(root.__ul.childNodes, function (node) {
  40100. if (!(root.autoPlace && node === root.__save_row)) {
  40101. h += dom.getHeight(node);
  40102. }
  40103. });
  40104. if (window.innerHeight - top - CLOSE_BUTTON_HEIGHT < h) {
  40105. dom.addClass(root.domElement, GUI.CLASS_TOO_TALL);
  40106. root.__ul.style.height = window.innerHeight - top - CLOSE_BUTTON_HEIGHT + 'px';
  40107. } else {
  40108. dom.removeClass(root.domElement, GUI.CLASS_TOO_TALL);
  40109. root.__ul.style.height = 'auto';
  40110. }
  40111. }
  40112. if (root.__resize_handle) {
  40113. Common.defer(function () {
  40114. root.__resize_handle.style.height = root.__ul.offsetHeight + 'px';
  40115. });
  40116. }
  40117. if (root.__closeButton) {
  40118. root.__closeButton.style.width = root.width + 'px';
  40119. }
  40120. },
  40121. onResizeDebounced: Common.debounce(function () {
  40122. this.onResize();
  40123. }, 50),
  40124. remember: function remember() {
  40125. if (Common.isUndefined(SAVE_DIALOGUE)) {
  40126. SAVE_DIALOGUE = new CenteredDiv();
  40127. SAVE_DIALOGUE.domElement.innerHTML = saveDialogContents;
  40128. }
  40129. if (this.parent) {
  40130. throw new Error('You can only call remember on a top level GUI.');
  40131. }
  40132. var _this = this;
  40133. Common.each(Array.prototype.slice.call(arguments), function (object) {
  40134. if (_this.__rememberedObjects.length === 0) {
  40135. addSaveMenu(_this);
  40136. }
  40137. if (_this.__rememberedObjects.indexOf(object) === -1) {
  40138. _this.__rememberedObjects.push(object);
  40139. }
  40140. });
  40141. if (this.autoPlace) {
  40142. setWidth(this, this.width);
  40143. }
  40144. },
  40145. getRoot: function getRoot() {
  40146. var gui = this;
  40147. while (gui.parent) {
  40148. gui = gui.parent;
  40149. }
  40150. return gui;
  40151. },
  40152. getSaveObject: function getSaveObject() {
  40153. var toReturn = this.load;
  40154. toReturn.closed = this.closed;
  40155. if (this.__rememberedObjects.length > 0) {
  40156. toReturn.preset = this.preset;
  40157. if (!toReturn.remembered) {
  40158. toReturn.remembered = {};
  40159. }
  40160. toReturn.remembered[this.preset] = getCurrentPreset(this);
  40161. }
  40162. toReturn.folders = {};
  40163. Common.each(this.__folders, function (element, key) {
  40164. toReturn.folders[key] = element.getSaveObject();
  40165. });
  40166. return toReturn;
  40167. },
  40168. save: function save() {
  40169. if (!this.load.remembered) {
  40170. this.load.remembered = {};
  40171. }
  40172. this.load.remembered[this.preset] = getCurrentPreset(this);
  40173. markPresetModified(this, false);
  40174. this.saveToLocalStorageIfPossible();
  40175. },
  40176. saveAs: function saveAs(presetName) {
  40177. if (!this.load.remembered) {
  40178. this.load.remembered = {};
  40179. this.load.remembered[DEFAULT_DEFAULT_PRESET_NAME] = getCurrentPreset(this, true);
  40180. }
  40181. this.load.remembered[presetName] = getCurrentPreset(this);
  40182. this.preset = presetName;
  40183. addPresetOption(this, presetName, true);
  40184. this.saveToLocalStorageIfPossible();
  40185. },
  40186. revert: function revert(gui) {
  40187. Common.each(this.__controllers, function (controller) {
  40188. if (!this.getRoot().load.remembered) {
  40189. controller.setValue(controller.initialValue);
  40190. } else {
  40191. recallSavedValue(gui || this.getRoot(), controller);
  40192. }
  40193. if (controller.__onFinishChange) {
  40194. controller.__onFinishChange.call(controller, controller.getValue());
  40195. }
  40196. }, this);
  40197. Common.each(this.__folders, function (folder) {
  40198. folder.revert(folder);
  40199. });
  40200. if (!gui) {
  40201. markPresetModified(this.getRoot(), false);
  40202. }
  40203. },
  40204. listen: function listen(controller) {
  40205. var init = this.__listening.length === 0;
  40206. this.__listening.push(controller);
  40207. if (init) {
  40208. updateDisplays(this.__listening);
  40209. }
  40210. },
  40211. updateDisplay: function updateDisplay() {
  40212. Common.each(this.__controllers, function (controller) {
  40213. controller.updateDisplay();
  40214. });
  40215. Common.each(this.__folders, function (folder) {
  40216. folder.updateDisplay();
  40217. });
  40218. }
  40219. });
  40220. function addRow(gui, newDom, liBefore) {
  40221. var li = document.createElement('li');
  40222. if (newDom) {
  40223. li.appendChild(newDom);
  40224. }
  40225. if (liBefore) {
  40226. gui.__ul.insertBefore(li, liBefore);
  40227. } else {
  40228. gui.__ul.appendChild(li);
  40229. }
  40230. gui.onResize();
  40231. return li;
  40232. }
  40233. function removeListeners(gui) {
  40234. dom.unbind(window, 'resize', gui.__resizeHandler);
  40235. if (gui.saveToLocalStorageIfPossible) {
  40236. dom.unbind(window, 'unload', gui.saveToLocalStorageIfPossible);
  40237. }
  40238. }
  40239. function markPresetModified(gui, modified) {
  40240. var opt = gui.__preset_select[gui.__preset_select.selectedIndex];
  40241. if (modified) {
  40242. opt.innerHTML = opt.value + '*';
  40243. } else {
  40244. opt.innerHTML = opt.value;
  40245. }
  40246. }
  40247. function augmentController(gui, li, controller) {
  40248. controller.__li = li;
  40249. controller.__gui = gui;
  40250. Common.extend(controller, {
  40251. options: function options(_options) {
  40252. if (arguments.length > 1) {
  40253. var nextSibling = controller.__li.nextElementSibling;
  40254. controller.remove();
  40255. return _add(gui, controller.object, controller.property, {
  40256. before: nextSibling,
  40257. factoryArgs: [Common.toArray(arguments)]
  40258. });
  40259. }
  40260. if (Common.isArray(_options) || Common.isObject(_options)) {
  40261. var _nextSibling = controller.__li.nextElementSibling;
  40262. controller.remove();
  40263. return _add(gui, controller.object, controller.property, {
  40264. before: _nextSibling,
  40265. factoryArgs: [_options]
  40266. });
  40267. }
  40268. },
  40269. name: function name(_name) {
  40270. controller.__li.firstElementChild.firstElementChild.innerHTML = _name;
  40271. return controller;
  40272. },
  40273. listen: function listen() {
  40274. controller.__gui.listen(controller);
  40275. return controller;
  40276. },
  40277. remove: function remove() {
  40278. controller.__gui.remove(controller);
  40279. return controller;
  40280. }
  40281. });
  40282. if (controller instanceof NumberControllerSlider) {
  40283. var box = new NumberControllerBox(controller.object, controller.property, {
  40284. min: controller.__min,
  40285. max: controller.__max,
  40286. step: controller.__step
  40287. });
  40288. Common.each(['updateDisplay', 'onChange', 'onFinishChange', 'step', 'min', 'max'], function (method) {
  40289. var pc = controller[method];
  40290. var pb = box[method];
  40291. controller[method] = box[method] = function () {
  40292. var args = Array.prototype.slice.call(arguments);
  40293. pb.apply(box, args);
  40294. return pc.apply(controller, args);
  40295. };
  40296. });
  40297. dom.addClass(li, 'has-slider');
  40298. controller.domElement.insertBefore(box.domElement, controller.domElement.firstElementChild);
  40299. } else if (controller instanceof NumberControllerBox) {
  40300. var r = function r(returned) {
  40301. if (Common.isNumber(controller.__min) && Common.isNumber(controller.__max)) {
  40302. var oldName = controller.__li.firstElementChild.firstElementChild.innerHTML;
  40303. var wasListening = controller.__gui.__listening.indexOf(controller) > -1;
  40304. controller.remove();
  40305. var newController = _add(gui, controller.object, controller.property, {
  40306. before: controller.__li.nextElementSibling,
  40307. factoryArgs: [controller.__min, controller.__max, controller.__step]
  40308. });
  40309. newController.name(oldName);
  40310. if (wasListening) newController.listen();
  40311. return newController;
  40312. }
  40313. return returned;
  40314. };
  40315. controller.min = Common.compose(r, controller.min);
  40316. controller.max = Common.compose(r, controller.max);
  40317. } else if (controller instanceof BooleanController) {
  40318. dom.bind(li, 'click', function () {
  40319. dom.fakeEvent(controller.__checkbox, 'click');
  40320. });
  40321. dom.bind(controller.__checkbox, 'click', function (e) {
  40322. e.stopPropagation();
  40323. });
  40324. } else if (controller instanceof FunctionController) {
  40325. dom.bind(li, 'click', function () {
  40326. dom.fakeEvent(controller.__button, 'click');
  40327. });
  40328. dom.bind(li, 'mouseover', function () {
  40329. dom.addClass(controller.__button, 'hover');
  40330. });
  40331. dom.bind(li, 'mouseout', function () {
  40332. dom.removeClass(controller.__button, 'hover');
  40333. });
  40334. } else if (controller instanceof ColorController) {
  40335. dom.addClass(li, 'color');
  40336. controller.updateDisplay = Common.compose(function (val) {
  40337. li.style.borderLeftColor = controller.__color.toString();
  40338. return val;
  40339. }, controller.updateDisplay);
  40340. controller.updateDisplay();
  40341. }
  40342. controller.setValue = Common.compose(function (val) {
  40343. if (gui.getRoot().__preset_select && controller.isModified()) {
  40344. markPresetModified(gui.getRoot(), true);
  40345. }
  40346. return val;
  40347. }, controller.setValue);
  40348. }
  40349. function recallSavedValue(gui, controller) {
  40350. var root = gui.getRoot();
  40351. var matchedIndex = root.__rememberedObjects.indexOf(controller.object);
  40352. if (matchedIndex !== -1) {
  40353. var controllerMap = root.__rememberedObjectIndecesToControllers[matchedIndex];
  40354. if (controllerMap === undefined) {
  40355. controllerMap = {};
  40356. root.__rememberedObjectIndecesToControllers[matchedIndex] = controllerMap;
  40357. }
  40358. controllerMap[controller.property] = controller;
  40359. if (root.load && root.load.remembered) {
  40360. var presetMap = root.load.remembered;
  40361. var preset = void 0;
  40362. if (presetMap[gui.preset]) {
  40363. preset = presetMap[gui.preset];
  40364. } else if (presetMap[DEFAULT_DEFAULT_PRESET_NAME]) {
  40365. preset = presetMap[DEFAULT_DEFAULT_PRESET_NAME];
  40366. } else {
  40367. return;
  40368. }
  40369. if (preset[matchedIndex] && preset[matchedIndex][controller.property] !== undefined) {
  40370. var value = preset[matchedIndex][controller.property];
  40371. controller.initialValue = value;
  40372. controller.setValue(value);
  40373. }
  40374. }
  40375. }
  40376. }
  40377. function _add(gui, object, property, params) {
  40378. if (object[property] === undefined) {
  40379. throw new Error('Object "' + object + '" has no property "' + property + '"');
  40380. }
  40381. var controller = void 0;
  40382. if (params.color) {
  40383. controller = new ColorController(object, property);
  40384. } else {
  40385. var factoryArgs = [object, property].concat(params.factoryArgs);
  40386. controller = ControllerFactory.apply(gui, factoryArgs);
  40387. }
  40388. if (params.before instanceof Controller) {
  40389. params.before = params.before.__li;
  40390. }
  40391. recallSavedValue(gui, controller);
  40392. dom.addClass(controller.domElement, 'c');
  40393. var name = document.createElement('span');
  40394. dom.addClass(name, 'property-name');
  40395. name.innerHTML = controller.property;
  40396. var container = document.createElement('div');
  40397. container.appendChild(name);
  40398. container.appendChild(controller.domElement);
  40399. var li = addRow(gui, container, params.before);
  40400. dom.addClass(li, GUI.CLASS_CONTROLLER_ROW);
  40401. if (controller instanceof ColorController) {
  40402. dom.addClass(li, 'color');
  40403. } else {
  40404. dom.addClass(li, _typeof(controller.getValue()));
  40405. }
  40406. augmentController(gui, li, controller);
  40407. gui.__controllers.push(controller);
  40408. return controller;
  40409. }
  40410. function getLocalStorageHash(gui, key) {
  40411. return document.location.href + '.' + key;
  40412. }
  40413. function addPresetOption(gui, name, setSelected) {
  40414. var opt = document.createElement('option');
  40415. opt.innerHTML = name;
  40416. opt.value = name;
  40417. gui.__preset_select.appendChild(opt);
  40418. if (setSelected) {
  40419. gui.__preset_select.selectedIndex = gui.__preset_select.length - 1;
  40420. }
  40421. }
  40422. function showHideExplain(gui, explain) {
  40423. explain.style.display = gui.useLocalStorage ? 'block' : 'none';
  40424. }
  40425. function addSaveMenu(gui) {
  40426. var div = gui.__save_row = document.createElement('li');
  40427. dom.addClass(gui.domElement, 'has-save');
  40428. gui.__ul.insertBefore(div, gui.__ul.firstChild);
  40429. dom.addClass(div, 'save-row');
  40430. var gears = document.createElement('span');
  40431. gears.innerHTML = '&nbsp;';
  40432. dom.addClass(gears, 'button gears');
  40433. var button = document.createElement('span');
  40434. button.innerHTML = 'Save';
  40435. dom.addClass(button, 'button');
  40436. dom.addClass(button, 'save');
  40437. var button2 = document.createElement('span');
  40438. button2.innerHTML = 'New';
  40439. dom.addClass(button2, 'button');
  40440. dom.addClass(button2, 'save-as');
  40441. var button3 = document.createElement('span');
  40442. button3.innerHTML = 'Revert';
  40443. dom.addClass(button3, 'button');
  40444. dom.addClass(button3, 'revert');
  40445. var select = gui.__preset_select = document.createElement('select');
  40446. if (gui.load && gui.load.remembered) {
  40447. Common.each(gui.load.remembered, function (value, key) {
  40448. addPresetOption(gui, key, key === gui.preset);
  40449. });
  40450. } else {
  40451. addPresetOption(gui, DEFAULT_DEFAULT_PRESET_NAME, false);
  40452. }
  40453. dom.bind(select, 'change', function () {
  40454. for (var index = 0; index < gui.__preset_select.length; index++) {
  40455. gui.__preset_select[index].innerHTML = gui.__preset_select[index].value;
  40456. }
  40457. gui.preset = this.value;
  40458. });
  40459. div.appendChild(select);
  40460. div.appendChild(gears);
  40461. div.appendChild(button);
  40462. div.appendChild(button2);
  40463. div.appendChild(button3);
  40464. if (SUPPORTS_LOCAL_STORAGE) {
  40465. var explain = document.getElementById('dg-local-explain');
  40466. var localStorageCheckBox = document.getElementById('dg-local-storage');
  40467. var saveLocally = document.getElementById('dg-save-locally');
  40468. saveLocally.style.display = 'block';
  40469. if (localStorage.getItem(getLocalStorageHash(gui, 'isLocal')) === 'true') {
  40470. localStorageCheckBox.setAttribute('checked', 'checked');
  40471. }
  40472. showHideExplain(gui, explain);
  40473. dom.bind(localStorageCheckBox, 'change', function () {
  40474. gui.useLocalStorage = !gui.useLocalStorage;
  40475. showHideExplain(gui, explain);
  40476. });
  40477. }
  40478. var newConstructorTextArea = document.getElementById('dg-new-constructor');
  40479. dom.bind(newConstructorTextArea, 'keydown', function (e) {
  40480. if (e.metaKey && (e.which === 67 || e.keyCode === 67)) {
  40481. SAVE_DIALOGUE.hide();
  40482. }
  40483. });
  40484. dom.bind(gears, 'click', function () {
  40485. newConstructorTextArea.innerHTML = JSON.stringify(gui.getSaveObject(), undefined, 2);
  40486. SAVE_DIALOGUE.show();
  40487. newConstructorTextArea.focus();
  40488. newConstructorTextArea.select();
  40489. });
  40490. dom.bind(button, 'click', function () {
  40491. gui.save();
  40492. });
  40493. dom.bind(button2, 'click', function () {
  40494. var presetName = prompt('Enter a new preset name.');
  40495. if (presetName) {
  40496. gui.saveAs(presetName);
  40497. }
  40498. });
  40499. dom.bind(button3, 'click', function () {
  40500. gui.revert();
  40501. });
  40502. }
  40503. function addResizeHandle(gui) {
  40504. var pmouseX = void 0;
  40505. gui.__resize_handle = document.createElement('div');
  40506. Common.extend(gui.__resize_handle.style, {
  40507. width: '6px',
  40508. marginLeft: '-3px',
  40509. height: '200px',
  40510. cursor: 'ew-resize',
  40511. position: 'absolute'
  40512. });
  40513. function drag(e) {
  40514. e.preventDefault();
  40515. gui.width += pmouseX - e.clientX;
  40516. gui.onResize();
  40517. pmouseX = e.clientX;
  40518. return false;
  40519. }
  40520. function dragStop() {
  40521. dom.removeClass(gui.__closeButton, GUI.CLASS_DRAG);
  40522. dom.unbind(window, 'mousemove', drag);
  40523. dom.unbind(window, 'mouseup', dragStop);
  40524. }
  40525. function dragStart(e) {
  40526. e.preventDefault();
  40527. pmouseX = e.clientX;
  40528. dom.addClass(gui.__closeButton, GUI.CLASS_DRAG);
  40529. dom.bind(window, 'mousemove', drag);
  40530. dom.bind(window, 'mouseup', dragStop);
  40531. return false;
  40532. }
  40533. dom.bind(gui.__resize_handle, 'mousedown', dragStart);
  40534. dom.bind(gui.__closeButton, 'mousedown', dragStart);
  40535. gui.domElement.insertBefore(gui.__resize_handle, gui.domElement.firstElementChild);
  40536. }
  40537. function setWidth(gui, w) {
  40538. gui.domElement.style.width = w + 'px';
  40539. if (gui.__save_row && gui.autoPlace) {
  40540. gui.__save_row.style.width = w + 'px';
  40541. }
  40542. if (gui.__closeButton) {
  40543. gui.__closeButton.style.width = w + 'px';
  40544. }
  40545. }
  40546. function getCurrentPreset(gui, useInitialValues) {
  40547. var toReturn = {};
  40548. Common.each(gui.__rememberedObjects, function (val, index) {
  40549. var savedValues = {};
  40550. var controllerMap = gui.__rememberedObjectIndecesToControllers[index];
  40551. Common.each(controllerMap, function (controller, property) {
  40552. savedValues[property] = useInitialValues ? controller.initialValue : controller.getValue();
  40553. });
  40554. toReturn[index] = savedValues;
  40555. });
  40556. return toReturn;
  40557. }
  40558. function setPresetSelectIndex(gui) {
  40559. for (var index = 0; index < gui.__preset_select.length; index++) {
  40560. if (gui.__preset_select[index].value === gui.preset) {
  40561. gui.__preset_select.selectedIndex = index;
  40562. }
  40563. }
  40564. }
  40565. function updateDisplays(controllerArray) {
  40566. if (controllerArray.length !== 0) {
  40567. requestAnimationFrame$1.call(window, function () {
  40568. updateDisplays(controllerArray);
  40569. });
  40570. }
  40571. Common.each(controllerArray, function (c) {
  40572. c.updateDisplay();
  40573. });
  40574. }
  40575. var color = {
  40576. Color: Color,
  40577. math: ColorMath,
  40578. interpret: interpret
  40579. };
  40580. exports.color = color;
  40581. var controllers = {
  40582. Controller: Controller,
  40583. BooleanController: BooleanController,
  40584. OptionController: OptionController,
  40585. StringController: StringController,
  40586. NumberController: NumberController,
  40587. NumberControllerBox: NumberControllerBox,
  40588. NumberControllerSlider: NumberControllerSlider,
  40589. FunctionController: FunctionController,
  40590. ColorController: ColorController
  40591. };
  40592. exports.controllers = controllers;
  40593. var dom$1 = {
  40594. dom: dom
  40595. };
  40596. exports.dom = dom$1;
  40597. var gui = {
  40598. GUI: GUI
  40599. };
  40600. exports.gui = gui;
  40601. var GUI$1 = GUI;
  40602. exports.GUI = GUI$1;
  40603. var index = {
  40604. color: color,
  40605. controllers: controllers,
  40606. dom: dom$1,
  40607. gui: gui,
  40608. GUI: GUI$1
  40609. };
  40610. var _default = index;
  40611. exports.default = _default;
  40612. },{}],"../node_modules/three/examples/jsm/libs/stats.module.js":[function(require,module,exports) {
  40613. "use strict";
  40614. Object.defineProperty(exports, "__esModule", {
  40615. value: true
  40616. });
  40617. exports.default = void 0;
  40618. var Stats = function () {
  40619. var mode = 0;
  40620. var container = document.createElement('div');
  40621. container.style.cssText = 'position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000';
  40622. container.addEventListener('click', function (event) {
  40623. event.preventDefault();
  40624. showPanel(++mode % container.children.length);
  40625. }, false); //
  40626. function addPanel(panel) {
  40627. container.appendChild(panel.dom);
  40628. return panel;
  40629. }
  40630. function showPanel(id) {
  40631. for (var i = 0; i < container.children.length; i++) {
  40632. container.children[i].style.display = i === id ? 'block' : 'none';
  40633. }
  40634. mode = id;
  40635. } //
  40636. var beginTime = (performance || Date).now(),
  40637. prevTime = beginTime,
  40638. frames = 0;
  40639. var fpsPanel = addPanel(new Stats.Panel('FPS', '#0ff', '#002'));
  40640. var msPanel = addPanel(new Stats.Panel('MS', '#0f0', '#020'));
  40641. if (self.performance && self.performance.memory) {
  40642. var memPanel = addPanel(new Stats.Panel('MB', '#f08', '#201'));
  40643. }
  40644. showPanel(0);
  40645. return {
  40646. REVISION: 16,
  40647. dom: container,
  40648. addPanel: addPanel,
  40649. showPanel: showPanel,
  40650. begin: function () {
  40651. beginTime = (performance || Date).now();
  40652. },
  40653. end: function () {
  40654. frames++;
  40655. var time = (performance || Date).now();
  40656. msPanel.update(time - beginTime, 200);
  40657. if (time >= prevTime + 1000) {
  40658. fpsPanel.update(frames * 1000 / (time - prevTime), 100);
  40659. prevTime = time;
  40660. frames = 0;
  40661. if (memPanel) {
  40662. var memory = performance.memory;
  40663. memPanel.update(memory.usedJSHeapSize / 1048576, memory.jsHeapSizeLimit / 1048576);
  40664. }
  40665. }
  40666. return time;
  40667. },
  40668. update: function () {
  40669. beginTime = this.end();
  40670. },
  40671. // Backwards Compatibility
  40672. domElement: container,
  40673. setMode: showPanel
  40674. };
  40675. };
  40676. Stats.Panel = function (name, fg, bg) {
  40677. var min = Infinity,
  40678. max = 0,
  40679. round = Math.round;
  40680. var PR = round(window.devicePixelRatio || 1);
  40681. var WIDTH = 80 * PR,
  40682. HEIGHT = 48 * PR,
  40683. TEXT_X = 3 * PR,
  40684. TEXT_Y = 2 * PR,
  40685. GRAPH_X = 3 * PR,
  40686. GRAPH_Y = 15 * PR,
  40687. GRAPH_WIDTH = 74 * PR,
  40688. GRAPH_HEIGHT = 30 * PR;
  40689. var canvas = document.createElement('canvas');
  40690. canvas.width = WIDTH;
  40691. canvas.height = HEIGHT;
  40692. canvas.style.cssText = 'width:80px;height:48px';
  40693. var context = canvas.getContext('2d');
  40694. context.font = 'bold ' + 9 * PR + 'px Helvetica,Arial,sans-serif';
  40695. context.textBaseline = 'top';
  40696. context.fillStyle = bg;
  40697. context.fillRect(0, 0, WIDTH, HEIGHT);
  40698. context.fillStyle = fg;
  40699. context.fillText(name, TEXT_X, TEXT_Y);
  40700. context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
  40701. context.fillStyle = bg;
  40702. context.globalAlpha = 0.9;
  40703. context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
  40704. return {
  40705. dom: canvas,
  40706. update: function (value, maxValue) {
  40707. min = Math.min(min, value);
  40708. max = Math.max(max, value);
  40709. context.fillStyle = bg;
  40710. context.globalAlpha = 1;
  40711. context.fillRect(0, 0, WIDTH, GRAPH_Y);
  40712. context.fillStyle = fg;
  40713. context.fillText(round(value) + ' ' + name + ' (' + round(min) + '-' + round(max) + ')', TEXT_X, TEXT_Y);
  40714. context.drawImage(canvas, GRAPH_X + PR, GRAPH_Y, GRAPH_WIDTH - PR, GRAPH_HEIGHT, GRAPH_X, GRAPH_Y, GRAPH_WIDTH - PR, GRAPH_HEIGHT);
  40715. context.fillRect(GRAPH_X + GRAPH_WIDTH - PR, GRAPH_Y, PR, GRAPH_HEIGHT);
  40716. context.fillStyle = bg;
  40717. context.globalAlpha = 0.9;
  40718. context.fillRect(GRAPH_X + GRAPH_WIDTH - PR, GRAPH_Y, PR, round((1 - value / maxValue) * GRAPH_HEIGHT));
  40719. }
  40720. };
  40721. };
  40722. var _default = Stats;
  40723. exports.default = _default;
  40724. },{}],"index.js":[function(require,module,exports) {
  40725. "use strict";
  40726. var _index = require("../src/index.js");
  40727. var _three = require("three");
  40728. var _OrbitControls = require("three/examples/jsm/controls/OrbitControls.js");
  40729. var _BufferGeometryUtils = require("three/examples/jsm/utils/BufferGeometryUtils.js");
  40730. var _GLTFLoader = require("three/examples/jsm/loaders/GLTFLoader.js");
  40731. var _DRACOLoader = require("three/examples/jsm/loaders/DRACOLoader.js");
  40732. var dat = _interopRequireWildcard(require("three/examples/jsm/libs/dat.gui.module.js"));
  40733. var _statsModule = _interopRequireDefault(require("three/examples/jsm/libs/stats.module.js"));
  40734. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  40735. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
  40736. 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; }
  40737. var ALL_HITS = 1;
  40738. var FIRST_HIT_ONLY = 2;
  40739. var hashUrl = window.location.hash.replace(/^#/, '');
  40740. var camera, controls, scene, renderer, tiles, cameraHelper;
  40741. var thirdPersonCamera, thirdPersonRenderer, thirdPersonControls;
  40742. var secondRenderer, secondCameraHelper, secondControls, secondCamera;
  40743. var orthoCamera, orthoCameraHelper;
  40744. var box;
  40745. var raycaster, mouse, rayIntersect, lastHoveredElement;
  40746. var offsetParent;
  40747. var statsContainer, stats;
  40748. var params = {
  40749. 'enableUpdate': true,
  40750. 'raycast': _index.NONE,
  40751. 'enableCacheDisplay': false,
  40752. 'enableRendererStats': false,
  40753. 'orthographic': false,
  40754. 'errorTarget': 6,
  40755. 'errorThreshold': 60,
  40756. 'maxDepth': 15,
  40757. 'loadSiblings': true,
  40758. 'stopAtEmptyTiles': true,
  40759. 'displayActiveTiles': false,
  40760. 'resolutionScale': 1.0,
  40761. 'up': hashUrl ? '+Z' : '+Y',
  40762. 'displayBoxBounds': false,
  40763. 'colorMode': 0,
  40764. 'showThirdPerson': false,
  40765. 'showSecondView': false,
  40766. 'reload': reinstantiateTiles
  40767. };
  40768. init();
  40769. animate();
  40770. function reinstantiateTiles() {
  40771. var url = hashUrl || '../data/tileset.json';
  40772. if (tiles) {
  40773. offsetParent.remove(tiles.group);
  40774. tiles.dispose();
  40775. } // Note the DRACO compression files need to be supplied via an explicit source.
  40776. // We use unpkg here but in practice should be provided by the application.
  40777. var dracoLoader = new _DRACOLoader.DRACOLoader();
  40778. dracoLoader.setDecoderPath('https://unpkg.com/three@0.116.1/examples/js/libs/draco/gltf/');
  40779. tiles = new _index.DebugTilesRenderer(url);
  40780. tiles.fetchOptions.mode = 'cors';
  40781. tiles.manager.addHandler(/\.gltf$/, {
  40782. parse: function parse() {
  40783. var loader = new _GLTFLoader.GLTFLoader(tiles.manager);
  40784. loader.setDRACOLoader(dracoLoader);
  40785. return loader.parse.apply(loader, arguments);
  40786. }
  40787. });
  40788. offsetParent.add(tiles.group);
  40789. }
  40790. function init() {
  40791. scene = new _three.Scene(); // primary camera view
  40792. renderer = new _three.WebGLRenderer({
  40793. antialias: true
  40794. });
  40795. renderer.setPixelRatio(window.devicePixelRatio);
  40796. renderer.setSize(window.innerWidth, window.innerHeight);
  40797. renderer.setClearColor(0x151c1f);
  40798. renderer.outputEncoding = _three.sRGBEncoding;
  40799. document.body.appendChild(renderer.domElement);
  40800. camera = new _three.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 4000);
  40801. camera.position.set(400, 400, 400);
  40802. cameraHelper = new _three.CameraHelper(camera);
  40803. scene.add(cameraHelper);
  40804. orthoCamera = new _three.OrthographicCamera();
  40805. orthoCameraHelper = new _three.CameraHelper(orthoCamera);
  40806. scene.add(orthoCameraHelper); // secondary camera view
  40807. secondCamera = new _three.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 4000);
  40808. secondCamera.position.set(400, 400, -400);
  40809. secondCamera.lookAt(0, 0, 0);
  40810. secondRenderer = new _three.WebGLRenderer({
  40811. antialias: true
  40812. });
  40813. secondRenderer.setPixelRatio(window.devicePixelRatio);
  40814. secondRenderer.setSize(window.innerWidth, window.innerHeight);
  40815. secondRenderer.setClearColor(0x151c1f);
  40816. secondRenderer.outputEncoding = _three.sRGBEncoding;
  40817. document.body.appendChild(secondRenderer.domElement);
  40818. secondRenderer.domElement.style.position = 'absolute';
  40819. secondRenderer.domElement.style.right = '0';
  40820. secondRenderer.domElement.style.top = '0';
  40821. secondRenderer.domElement.style.outline = '#0f1416 solid 2px';
  40822. secondControls = new _OrbitControls.OrbitControls(secondCamera, secondRenderer.domElement);
  40823. secondControls.screenSpacePanning = false;
  40824. secondControls.minDistance = 1;
  40825. secondControls.maxDistance = 2000;
  40826. secondCameraHelper = new _three.CameraHelper(secondCamera);
  40827. scene.add(secondCameraHelper); // Third person camera view
  40828. thirdPersonCamera = new _three.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 4000);
  40829. thirdPersonCamera.position.set(50, 40, 40);
  40830. thirdPersonCamera.lookAt(0, 0, 0);
  40831. thirdPersonRenderer = new _three.WebGLRenderer({
  40832. antialias: true
  40833. });
  40834. thirdPersonRenderer.setPixelRatio(window.devicePixelRatio);
  40835. thirdPersonRenderer.setSize(window.innerWidth, window.innerHeight);
  40836. thirdPersonRenderer.setClearColor(0x0f1416);
  40837. thirdPersonRenderer.outputEncoding = _three.sRGBEncoding;
  40838. document.body.appendChild(thirdPersonRenderer.domElement);
  40839. thirdPersonRenderer.domElement.style.position = 'fixed';
  40840. thirdPersonRenderer.domElement.style.left = '5px';
  40841. thirdPersonRenderer.domElement.style.bottom = '5px';
  40842. thirdPersonControls = new _OrbitControls.OrbitControls(thirdPersonCamera, thirdPersonRenderer.domElement);
  40843. thirdPersonControls.screenSpacePanning = false;
  40844. thirdPersonControls.minDistance = 1;
  40845. thirdPersonControls.maxDistance = 2000; // controls
  40846. controls = new _OrbitControls.OrbitControls(camera, renderer.domElement);
  40847. controls.screenSpacePanning = false;
  40848. controls.minDistance = 1;
  40849. controls.maxDistance = 2000; // lights
  40850. var dirLight = new _three.DirectionalLight(0xffffff);
  40851. dirLight.position.set(1, 2, 3);
  40852. scene.add(dirLight);
  40853. var ambLight = new _three.AmbientLight(0xffffff, 0.2);
  40854. scene.add(ambLight);
  40855. box = new _three.Box3();
  40856. offsetParent = new _three.Group();
  40857. scene.add(offsetParent); // Raycasting init
  40858. raycaster = new _three.Raycaster();
  40859. mouse = new _three.Vector2();
  40860. rayIntersect = new _three.Group();
  40861. var rayIntersectMat = new _three.MeshBasicMaterial({
  40862. color: 0xe91e63
  40863. });
  40864. var rayMesh = new _three.Mesh(new _three.CylinderBufferGeometry(0.25, 0.25, 6), rayIntersectMat);
  40865. rayMesh.rotation.x = Math.PI / 2;
  40866. rayMesh.position.z += 3;
  40867. rayIntersect.add(rayMesh);
  40868. var rayRing = new _three.Mesh(new _three.TorusBufferGeometry(1.5, 0.2, 16, 100), rayIntersectMat);
  40869. rayIntersect.add(rayRing);
  40870. scene.add(rayIntersect);
  40871. rayIntersect.visible = false;
  40872. reinstantiateTiles();
  40873. onWindowResize();
  40874. window.addEventListener('resize', onWindowResize, false);
  40875. renderer.domElement.addEventListener('mousemove', onMouseMove, false);
  40876. renderer.domElement.addEventListener('mousedown', onMouseDown, false);
  40877. renderer.domElement.addEventListener('mouseup', onMouseUp, false);
  40878. renderer.domElement.addEventListener('mouseleave', onMouseLeave, false);
  40879. secondRenderer.domElement.addEventListener('mousemove', onMouseMove, false);
  40880. secondRenderer.domElement.addEventListener('mousedown', onMouseDown, false);
  40881. secondRenderer.domElement.addEventListener('mouseup', onMouseUp, false);
  40882. secondRenderer.domElement.addEventListener('mouseleave', onMouseLeave, false); // GUI
  40883. var gui = new dat.GUI();
  40884. gui.width = 300;
  40885. var tileOptions = gui.addFolder('Tiles Options');
  40886. tileOptions.add(params, 'loadSiblings');
  40887. tileOptions.add(params, 'stopAtEmptyTiles');
  40888. tileOptions.add(params, 'displayActiveTiles');
  40889. tileOptions.add(params, 'errorTarget').min(0).max(50);
  40890. tileOptions.add(params, 'errorThreshold').min(0).max(1000);
  40891. tileOptions.add(params, 'maxDepth').min(1).max(100);
  40892. tileOptions.add(params, 'up', ['+Y', '+Z', '-Z']);
  40893. tileOptions.open();
  40894. var debug = gui.addFolder('Debug Options');
  40895. debug.add(params, 'displayBoxBounds');
  40896. debug.add(params, 'colorMode', {
  40897. NONE: _index.NONE,
  40898. SCREEN_ERROR: _index.SCREEN_ERROR,
  40899. GEOMETRIC_ERROR: _index.GEOMETRIC_ERROR,
  40900. DISTANCE: _index.DISTANCE,
  40901. DEPTH: _index.DEPTH,
  40902. RELATIVE_DEPTH: _index.RELATIVE_DEPTH,
  40903. IS_LEAF: _index.IS_LEAF,
  40904. RANDOM_COLOR: _index.RANDOM_COLOR
  40905. });
  40906. debug.open();
  40907. var exampleOptions = gui.addFolder('Example Options');
  40908. exampleOptions.add(params, 'resolutionScale').min(0.01).max(2.0).step(0.01).onChange(onWindowResize);
  40909. exampleOptions.add(params, 'orthographic');
  40910. exampleOptions.add(params, 'showThirdPerson');
  40911. exampleOptions.add(params, 'showSecondView').onChange(onWindowResize);
  40912. exampleOptions.add(params, 'enableUpdate').onChange(function (v) {
  40913. tiles.parseQueue.autoUpdate = v;
  40914. tiles.downloadQueue.autoUpdate = v;
  40915. if (v) {
  40916. tiles.parseQueue.scheduleJobRun();
  40917. tiles.downloadQueue.scheduleJobRun();
  40918. }
  40919. });
  40920. exampleOptions.add(params, 'raycast', {
  40921. NONE: _index.NONE,
  40922. ALL_HITS: ALL_HITS,
  40923. FIRST_HIT_ONLY: FIRST_HIT_ONLY
  40924. });
  40925. exampleOptions.add(params, 'enableCacheDisplay');
  40926. exampleOptions.add(params, 'enableRendererStats');
  40927. exampleOptions.open();
  40928. gui.add(params, 'reload');
  40929. gui.open();
  40930. statsContainer = document.createElement('div');
  40931. statsContainer.style.position = 'absolute';
  40932. statsContainer.style.top = 0;
  40933. statsContainer.style.left = 0;
  40934. statsContainer.style.color = 'white';
  40935. statsContainer.style.width = '100%';
  40936. statsContainer.style.textAlign = 'center';
  40937. statsContainer.style.padding = '5px';
  40938. statsContainer.style.pointerEvents = 'none';
  40939. statsContainer.style.lineHeight = '1.5em';
  40940. document.body.appendChild(statsContainer); // Stats
  40941. stats = new _statsModule.default();
  40942. stats.showPanel(0);
  40943. document.body.appendChild(stats.dom);
  40944. }
  40945. function onWindowResize() {
  40946. thirdPersonCamera.aspect = window.innerWidth / window.innerHeight;
  40947. thirdPersonCamera.updateProjectionMatrix();
  40948. thirdPersonRenderer.setSize(Math.floor(window.innerWidth / 3), Math.floor(window.innerHeight / 3));
  40949. if (params.showSecondView) {
  40950. camera.aspect = 0.5 * window.innerWidth / window.innerHeight;
  40951. renderer.setSize(0.5 * window.innerWidth, window.innerHeight);
  40952. secondCamera.aspect = 0.5 * window.innerWidth / window.innerHeight;
  40953. secondRenderer.setSize(0.5 * window.innerWidth, window.innerHeight);
  40954. secondRenderer.domElement.style.display = 'block';
  40955. } else {
  40956. camera.aspect = window.innerWidth / window.innerHeight;
  40957. renderer.setSize(window.innerWidth, window.innerHeight);
  40958. secondRenderer.domElement.style.display = 'none';
  40959. }
  40960. camera.updateProjectionMatrix();
  40961. renderer.setPixelRatio(window.devicePixelRatio * params.resolutionScale);
  40962. secondCamera.updateProjectionMatrix();
  40963. secondRenderer.setPixelRatio(window.devicePixelRatio);
  40964. updateOrthoCamera();
  40965. }
  40966. function onMouseLeave(e) {
  40967. lastHoveredElement = null;
  40968. }
  40969. function onMouseMove(e) {
  40970. var bounds = this.getBoundingClientRect();
  40971. mouse.x = e.clientX - bounds.x;
  40972. mouse.y = e.clientY - bounds.y;
  40973. mouse.x = mouse.x / bounds.width * 2 - 1;
  40974. mouse.y = -(mouse.y / bounds.height) * 2 + 1;
  40975. lastHoveredElement = this;
  40976. }
  40977. var startPos = new _three.Vector2();
  40978. var endPos = new _three.Vector2();
  40979. function onMouseDown(e) {
  40980. var bounds = this.getBoundingClientRect();
  40981. startPos.set(e.clientX - bounds.x, e.clientY - bounds.y);
  40982. }
  40983. function onMouseUp(e) {
  40984. var bounds = this.getBoundingClientRect();
  40985. endPos.set(e.clientX - bounds.x, e.clientY - bounds.y);
  40986. if (startPos.distanceTo(endPos) > 2) {
  40987. return;
  40988. }
  40989. if (lastHoveredElement === secondRenderer.domElement) {
  40990. raycaster.setFromCamera(mouse, secondCamera);
  40991. } else {
  40992. raycaster.setFromCamera(mouse, params.orthographic ? orthoCamera : camera);
  40993. }
  40994. raycaster.firstHitOnly = true;
  40995. var results = raycaster.intersectObject(tiles.group, true);
  40996. if (results.length) {
  40997. var object = results[0].object;
  40998. var info = tiles.getTileInformationFromActiveObject(object);
  40999. var str = '';
  41000. for (var key in info) {
  41001. var val = info[key];
  41002. if (typeof val === 'number') {
  41003. val = Math.floor(val * 1e5) / 1e5;
  41004. }
  41005. var name = key;
  41006. while (name.length < 20) {
  41007. name += ' ';
  41008. }
  41009. str += "".concat(name, " : ").concat(val, "\n");
  41010. }
  41011. console.log(str);
  41012. }
  41013. }
  41014. function updateOrthoCamera() {
  41015. orthoCamera.position.copy(camera.position);
  41016. orthoCamera.rotation.copy(camera.rotation);
  41017. var scale = camera.position.distanceTo(controls.target) / 2.0;
  41018. var aspect = window.innerWidth / window.innerHeight;
  41019. if (params.showSecondView) {
  41020. aspect *= 0.5;
  41021. }
  41022. orthoCamera.left = -aspect * scale;
  41023. orthoCamera.right = aspect * scale;
  41024. orthoCamera.bottom = -scale;
  41025. orthoCamera.top = scale;
  41026. orthoCamera.near = camera.near;
  41027. orthoCamera.far = camera.far;
  41028. orthoCamera.updateProjectionMatrix();
  41029. }
  41030. function animate() {
  41031. requestAnimationFrame(animate); // update options
  41032. tiles.errorTarget = params.errorTarget;
  41033. tiles.errorThreshold = params.errorThreshold;
  41034. tiles.loadSiblings = params.loadSiblings;
  41035. tiles.stopAtEmptyTiles = params.stopAtEmptyTiles;
  41036. tiles.displayActiveTiles = params.displayActiveTiles;
  41037. tiles.maxDepth = params.maxDepth;
  41038. tiles.displayBoxBounds = params.displayBoxBounds;
  41039. tiles.colorMode = parseFloat(params.colorMode);
  41040. if (params.orthographic) {
  41041. tiles.deleteCamera(camera);
  41042. tiles.setCamera(orthoCamera);
  41043. tiles.setResolutionFromRenderer(orthoCamera, renderer);
  41044. } else {
  41045. tiles.deleteCamera(orthoCamera);
  41046. tiles.setCamera(camera);
  41047. tiles.setResolutionFromRenderer(camera, renderer);
  41048. }
  41049. if (params.showSecondView) {
  41050. tiles.setCamera(secondCamera);
  41051. tiles.setResolutionFromRenderer(secondCamera, secondRenderer);
  41052. } else {
  41053. tiles.deleteCamera(secondCamera);
  41054. }
  41055. offsetParent.rotation.set(0, 0, 0);
  41056. if (params.up === '-Z') {
  41057. offsetParent.rotation.x = Math.PI / 2;
  41058. } else if (params.up === '+Z') {
  41059. offsetParent.rotation.x = -Math.PI / 2;
  41060. }
  41061. offsetParent.updateMatrixWorld(true); // update tiles center
  41062. if (tiles.getBounds(box)) {
  41063. box.getCenter(tiles.group.position);
  41064. tiles.group.position.multiplyScalar(-1);
  41065. }
  41066. if (parseFloat(params.raycast) !== _index.NONE && lastHoveredElement !== null) {
  41067. if (lastHoveredElement === renderer.domElement) {
  41068. raycaster.setFromCamera(mouse, params.orthographic ? orthoCamera : camera);
  41069. } else {
  41070. raycaster.setFromCamera(mouse, secondCamera);
  41071. }
  41072. raycaster.firstHitOnly = parseFloat(params.raycast) === FIRST_HIT_ONLY;
  41073. var results = raycaster.intersectObject(tiles.group, true);
  41074. if (results.length) {
  41075. var closestHit = results[0];
  41076. var point = closestHit.point;
  41077. rayIntersect.position.copy(point); // If the display bounds are visible they get intersected
  41078. if (closestHit.face) {
  41079. var normal = closestHit.face.normal;
  41080. normal.transformDirection(closestHit.object.matrixWorld);
  41081. rayIntersect.lookAt(point.x + normal.x, point.y + normal.y, point.z + normal.z);
  41082. }
  41083. rayIntersect.visible = true;
  41084. } else {
  41085. rayIntersect.visible = false;
  41086. }
  41087. } else {
  41088. rayIntersect.visible = false;
  41089. } // update tiles
  41090. window.tiles = tiles;
  41091. if (params.enableUpdate) {
  41092. secondCamera.updateMatrixWorld();
  41093. camera.updateMatrixWorld();
  41094. orthoCamera.updateMatrixWorld();
  41095. tiles.update();
  41096. }
  41097. render();
  41098. stats.update();
  41099. }
  41100. function render() {
  41101. updateOrthoCamera();
  41102. cameraHelper.visible = false;
  41103. orthoCameraHelper.visible = false;
  41104. secondCameraHelper.visible = false; // render primary view
  41105. if (params.orthographic) {
  41106. var dist = orthoCamera.position.distanceTo(rayIntersect.position);
  41107. rayIntersect.scale.setScalar(dist / 150);
  41108. } else {
  41109. var _dist = camera.position.distanceTo(rayIntersect.position);
  41110. rayIntersect.scale.setScalar(_dist * camera.fov / 6000);
  41111. }
  41112. renderer.render(scene, params.orthographic ? orthoCamera : camera); // render secondary view
  41113. if (params.showSecondView) {
  41114. var _dist2 = secondCamera.position.distanceTo(rayIntersect.position);
  41115. rayIntersect.scale.setScalar(_dist2 * secondCamera.fov / 6000);
  41116. secondRenderer.render(scene, secondCamera);
  41117. } // render third person view
  41118. thirdPersonRenderer.domElement.style.visibility = params.showThirdPerson ? 'visible' : 'hidden';
  41119. if (params.showThirdPerson) {
  41120. cameraHelper.update();
  41121. cameraHelper.visible = !params.orthographic;
  41122. orthoCameraHelper.update();
  41123. orthoCameraHelper.visible = params.orthographic;
  41124. if (params.showSecondView) {
  41125. secondCameraHelper.update();
  41126. secondCameraHelper.visible = true;
  41127. }
  41128. var _dist3 = thirdPersonCamera.position.distanceTo(rayIntersect.position);
  41129. rayIntersect.scale.setScalar(_dist3 * thirdPersonCamera.fov / 6000);
  41130. thirdPersonRenderer.render(scene, thirdPersonCamera);
  41131. }
  41132. var cacheFullness = tiles.lruCache.itemList.length / tiles.lruCache.maxSize;
  41133. var str = "Downloading: ".concat(tiles.stats.downloading, " Parsing: ").concat(tiles.stats.parsing, " Visible: ").concat(tiles.group.children.length - 2);
  41134. if (params.enableCacheDisplay) {
  41135. var geomSet = new Set();
  41136. tiles.traverse(function (tile) {
  41137. var scene = tile.cached.scene;
  41138. if (scene) {
  41139. scene.traverse(function (c) {
  41140. if (c.geometry) {
  41141. geomSet.add(c.geometry);
  41142. }
  41143. });
  41144. }
  41145. });
  41146. var count = 0;
  41147. geomSet.forEach(function (g) {
  41148. count += _BufferGeometryUtils.BufferGeometryUtils.estimateBytesUsed(g);
  41149. });
  41150. str += "<br/>Cache: ".concat((100 * cacheFullness).toFixed(2), "% ~").concat((count / 1000 / 1000).toFixed(2), "mb");
  41151. }
  41152. if (params.enableRendererStats) {
  41153. var memory = renderer.info.memory;
  41154. var programCount = renderer.info.programs.length;
  41155. str += "<br/>Geometries: ".concat(memory.geometries, " Textures: ").concat(memory.textures, " Programs: ").concat(programCount);
  41156. }
  41157. if (statsContainer.innerHTML !== str) {
  41158. statsContainer.innerHTML = str;
  41159. }
  41160. }
  41161. },{"../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/loaders/GLTFLoader.js":"../node_modules/three/examples/jsm/loaders/GLTFLoader.js","three/examples/jsm/loaders/DRACOLoader.js":"../node_modules/three/examples/jsm/loaders/DRACOLoader.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) {
  41162. var global = arguments[3];
  41163. var OVERLAY_ID = '__parcel__error__overlay__';
  41164. var OldModule = module.bundle.Module;
  41165. function Module(moduleName) {
  41166. OldModule.call(this, moduleName);
  41167. this.hot = {
  41168. data: module.bundle.hotData,
  41169. _acceptCallbacks: [],
  41170. _disposeCallbacks: [],
  41171. accept: function (fn) {
  41172. this._acceptCallbacks.push(fn || function () {});
  41173. },
  41174. dispose: function (fn) {
  41175. this._disposeCallbacks.push(fn);
  41176. }
  41177. };
  41178. module.bundle.hotData = null;
  41179. }
  41180. module.bundle.Module = Module;
  41181. var checkedAssets, assetsToAccept;
  41182. var parent = module.bundle.parent;
  41183. if ((!parent || !parent.isParcelRequire) && typeof WebSocket !== 'undefined') {
  41184. var hostname = "" || location.hostname;
  41185. var protocol = location.protocol === 'https:' ? 'wss' : 'ws';
  41186. var ws = new WebSocket(protocol + '://' + hostname + ':' + "56952" + '/');
  41187. ws.onmessage = function (event) {
  41188. checkedAssets = {};
  41189. assetsToAccept = [];
  41190. var data = JSON.parse(event.data);
  41191. if (data.type === 'update') {
  41192. var handled = false;
  41193. data.assets.forEach(function (asset) {
  41194. if (!asset.isNew) {
  41195. var didAccept = hmrAcceptCheck(global.parcelRequire, asset.id);
  41196. if (didAccept) {
  41197. handled = true;
  41198. }
  41199. }
  41200. }); // Enable HMR for CSS by default.
  41201. handled = handled || data.assets.every(function (asset) {
  41202. return asset.type === 'css' && asset.generated.js;
  41203. });
  41204. if (handled) {
  41205. console.clear();
  41206. data.assets.forEach(function (asset) {
  41207. hmrApply(global.parcelRequire, asset);
  41208. });
  41209. assetsToAccept.forEach(function (v) {
  41210. hmrAcceptRun(v[0], v[1]);
  41211. });
  41212. } else if (location.reload) {
  41213. // `location` global exists in a web worker context but lacks `.reload()` function.
  41214. location.reload();
  41215. }
  41216. }
  41217. if (data.type === 'reload') {
  41218. ws.close();
  41219. ws.onclose = function () {
  41220. location.reload();
  41221. };
  41222. }
  41223. if (data.type === 'error-resolved') {
  41224. console.log('[parcel] ✨ Error resolved');
  41225. removeErrorOverlay();
  41226. }
  41227. if (data.type === 'error') {
  41228. console.error('[parcel] 🚨 ' + data.error.message + '\n' + data.error.stack);
  41229. removeErrorOverlay();
  41230. var overlay = createErrorOverlay(data);
  41231. document.body.appendChild(overlay);
  41232. }
  41233. };
  41234. }
  41235. function removeErrorOverlay() {
  41236. var overlay = document.getElementById(OVERLAY_ID);
  41237. if (overlay) {
  41238. overlay.remove();
  41239. }
  41240. }
  41241. function createErrorOverlay(data) {
  41242. var overlay = document.createElement('div');
  41243. overlay.id = OVERLAY_ID; // html encode message and stack trace
  41244. var message = document.createElement('div');
  41245. var stackTrace = document.createElement('pre');
  41246. message.innerText = data.error.message;
  41247. stackTrace.innerText = data.error.stack;
  41248. 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>';
  41249. return overlay;
  41250. }
  41251. function getParents(bundle, id) {
  41252. var modules = bundle.modules;
  41253. if (!modules) {
  41254. return [];
  41255. }
  41256. var parents = [];
  41257. var k, d, dep;
  41258. for (k in modules) {
  41259. for (d in modules[k][1]) {
  41260. dep = modules[k][1][d];
  41261. if (dep === id || Array.isArray(dep) && dep[dep.length - 1] === id) {
  41262. parents.push(k);
  41263. }
  41264. }
  41265. }
  41266. if (bundle.parent) {
  41267. parents = parents.concat(getParents(bundle.parent, id));
  41268. }
  41269. return parents;
  41270. }
  41271. function hmrApply(bundle, asset) {
  41272. var modules = bundle.modules;
  41273. if (!modules) {
  41274. return;
  41275. }
  41276. if (modules[asset.id] || !bundle.parent) {
  41277. var fn = new Function('require', 'module', 'exports', asset.generated.js);
  41278. asset.isNew = !modules[asset.id];
  41279. modules[asset.id] = [fn, asset.deps];
  41280. } else if (bundle.parent) {
  41281. hmrApply(bundle.parent, asset);
  41282. }
  41283. }
  41284. function hmrAcceptCheck(bundle, id) {
  41285. var modules = bundle.modules;
  41286. if (!modules) {
  41287. return;
  41288. }
  41289. if (!modules[id] && bundle.parent) {
  41290. return hmrAcceptCheck(bundle.parent, id);
  41291. }
  41292. if (checkedAssets[id]) {
  41293. return;
  41294. }
  41295. checkedAssets[id] = true;
  41296. var cached = bundle.cache[id];
  41297. assetsToAccept.push([bundle, id]);
  41298. if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
  41299. return true;
  41300. }
  41301. return getParents(global.parcelRequire, id).some(function (id) {
  41302. return hmrAcceptCheck(global.parcelRequire, id);
  41303. });
  41304. }
  41305. function hmrAcceptRun(bundle, id) {
  41306. var cached = bundle.cache[id];
  41307. bundle.hotData = {};
  41308. if (cached) {
  41309. cached.hot.data = bundle.hotData;
  41310. }
  41311. if (cached && cached.hot && cached.hot._disposeCallbacks.length) {
  41312. cached.hot._disposeCallbacks.forEach(function (cb) {
  41313. cb(bundle.hotData);
  41314. });
  41315. }
  41316. delete bundle.cache[id];
  41317. bundle(id);
  41318. cached = bundle.cache[id];
  41319. if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
  41320. cached.hot._acceptCallbacks.forEach(function (cb) {
  41321. cb();
  41322. });
  41323. return true;
  41324. }
  41325. }
  41326. },{}]},{},["../node_modules/parcel-bundler/src/builtins/hmr-runtime.js","index.js"], null)
  41327. //# sourceMappingURL=example.e31bb0bc.js.map