three.core.js 795 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097
  1. /**
  2. * @license
  3. * Copyright 2010-2025 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '174dev';
  7. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  8. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  9. const CullFaceNone = 0;
  10. const CullFaceBack = 1;
  11. const CullFaceFront = 2;
  12. const CullFaceFrontBack = 3;
  13. const BasicShadowMap = 0;
  14. const PCFShadowMap = 1;
  15. const PCFSoftShadowMap = 2;
  16. const VSMShadowMap = 3;
  17. const FrontSide = 0;
  18. const BackSide = 1;
  19. const DoubleSide = 2;
  20. const NoBlending = 0;
  21. const NormalBlending = 1;
  22. const AdditiveBlending = 2;
  23. const SubtractiveBlending = 3;
  24. const MultiplyBlending = 4;
  25. const CustomBlending = 5;
  26. const AddEquation = 100;
  27. const SubtractEquation = 101;
  28. const ReverseSubtractEquation = 102;
  29. const MinEquation = 103;
  30. const MaxEquation = 104;
  31. const ZeroFactor = 200;
  32. const OneFactor = 201;
  33. const SrcColorFactor = 202;
  34. const OneMinusSrcColorFactor = 203;
  35. const SrcAlphaFactor = 204;
  36. const OneMinusSrcAlphaFactor = 205;
  37. const DstAlphaFactor = 206;
  38. const OneMinusDstAlphaFactor = 207;
  39. const DstColorFactor = 208;
  40. const OneMinusDstColorFactor = 209;
  41. const SrcAlphaSaturateFactor = 210;
  42. const ConstantColorFactor = 211;
  43. const OneMinusConstantColorFactor = 212;
  44. const ConstantAlphaFactor = 213;
  45. const OneMinusConstantAlphaFactor = 214;
  46. const NeverDepth = 0;
  47. const AlwaysDepth = 1;
  48. const LessDepth = 2;
  49. const LessEqualDepth = 3;
  50. const EqualDepth = 4;
  51. const GreaterEqualDepth = 5;
  52. const GreaterDepth = 6;
  53. const NotEqualDepth = 7;
  54. const MultiplyOperation = 0;
  55. const MixOperation = 1;
  56. const AddOperation = 2;
  57. const NoToneMapping = 0;
  58. const LinearToneMapping = 1;
  59. const ReinhardToneMapping = 2;
  60. const CineonToneMapping = 3;
  61. const ACESFilmicToneMapping = 4;
  62. const CustomToneMapping = 5;
  63. const AgXToneMapping = 6;
  64. const NeutralToneMapping = 7;
  65. const AttachedBindMode = 'attached';
  66. const DetachedBindMode = 'detached';
  67. const UVMapping = 300;
  68. const CubeReflectionMapping = 301;
  69. const CubeRefractionMapping = 302;
  70. const EquirectangularReflectionMapping = 303;
  71. const EquirectangularRefractionMapping = 304;
  72. const CubeUVReflectionMapping = 306;
  73. const RepeatWrapping = 1000;
  74. const ClampToEdgeWrapping = 1001;
  75. const MirroredRepeatWrapping = 1002;
  76. const NearestFilter = 1003;
  77. const NearestMipmapNearestFilter = 1004;
  78. const NearestMipMapNearestFilter = 1004;
  79. const NearestMipmapLinearFilter = 1005;
  80. const NearestMipMapLinearFilter = 1005;
  81. const LinearFilter = 1006;
  82. const LinearMipmapNearestFilter = 1007;
  83. const LinearMipMapNearestFilter = 1007;
  84. const LinearMipmapLinearFilter = 1008;
  85. const LinearMipMapLinearFilter = 1008;
  86. const UnsignedByteType = 1009;
  87. const ByteType = 1010;
  88. const ShortType = 1011;
  89. const UnsignedShortType = 1012;
  90. const IntType = 1013;
  91. const UnsignedIntType = 1014;
  92. const FloatType = 1015;
  93. const HalfFloatType = 1016;
  94. const UnsignedShort4444Type = 1017;
  95. const UnsignedShort5551Type = 1018;
  96. const UnsignedInt248Type = 1020;
  97. const UnsignedInt5999Type = 35902;
  98. const AlphaFormat = 1021;
  99. const RGBFormat = 1022;
  100. const RGBAFormat = 1023;
  101. const LuminanceFormat = 1024;
  102. const LuminanceAlphaFormat = 1025;
  103. const DepthFormat = 1026;
  104. const DepthStencilFormat = 1027;
  105. const RedFormat = 1028;
  106. const RedIntegerFormat = 1029;
  107. const RGFormat = 1030;
  108. const RGIntegerFormat = 1031;
  109. const RGBIntegerFormat = 1032;
  110. const RGBAIntegerFormat = 1033;
  111. const RGB_S3TC_DXT1_Format = 33776;
  112. const RGBA_S3TC_DXT1_Format = 33777;
  113. const RGBA_S3TC_DXT3_Format = 33778;
  114. const RGBA_S3TC_DXT5_Format = 33779;
  115. const RGB_PVRTC_4BPPV1_Format = 35840;
  116. const RGB_PVRTC_2BPPV1_Format = 35841;
  117. const RGBA_PVRTC_4BPPV1_Format = 35842;
  118. const RGBA_PVRTC_2BPPV1_Format = 35843;
  119. const RGB_ETC1_Format = 36196;
  120. const RGB_ETC2_Format = 37492;
  121. const RGBA_ETC2_EAC_Format = 37496;
  122. const RGBA_ASTC_4x4_Format = 37808;
  123. const RGBA_ASTC_5x4_Format = 37809;
  124. const RGBA_ASTC_5x5_Format = 37810;
  125. const RGBA_ASTC_6x5_Format = 37811;
  126. const RGBA_ASTC_6x6_Format = 37812;
  127. const RGBA_ASTC_8x5_Format = 37813;
  128. const RGBA_ASTC_8x6_Format = 37814;
  129. const RGBA_ASTC_8x8_Format = 37815;
  130. const RGBA_ASTC_10x5_Format = 37816;
  131. const RGBA_ASTC_10x6_Format = 37817;
  132. const RGBA_ASTC_10x8_Format = 37818;
  133. const RGBA_ASTC_10x10_Format = 37819;
  134. const RGBA_ASTC_12x10_Format = 37820;
  135. const RGBA_ASTC_12x12_Format = 37821;
  136. const RGBA_BPTC_Format = 36492;
  137. const RGB_BPTC_SIGNED_Format = 36494;
  138. const RGB_BPTC_UNSIGNED_Format = 36495;
  139. const RED_RGTC1_Format = 36283;
  140. const SIGNED_RED_RGTC1_Format = 36284;
  141. const RED_GREEN_RGTC2_Format = 36285;
  142. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  143. const LoopOnce = 2200;
  144. const LoopRepeat = 2201;
  145. const LoopPingPong = 2202;
  146. const InterpolateDiscrete = 2300;
  147. const InterpolateLinear = 2301;
  148. const InterpolateSmooth = 2302;
  149. const ZeroCurvatureEnding = 2400;
  150. const ZeroSlopeEnding = 2401;
  151. const WrapAroundEnding = 2402;
  152. const NormalAnimationBlendMode = 2500;
  153. const AdditiveAnimationBlendMode = 2501;
  154. const TrianglesDrawMode = 0;
  155. const TriangleStripDrawMode = 1;
  156. const TriangleFanDrawMode = 2;
  157. const BasicDepthPacking = 3200;
  158. const RGBADepthPacking = 3201;
  159. const RGBDepthPacking = 3202;
  160. const RGDepthPacking = 3203;
  161. const TangentSpaceNormalMap = 0;
  162. const ObjectSpaceNormalMap = 1;
  163. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  164. const NoColorSpace = '';
  165. const SRGBColorSpace = 'srgb';
  166. const LinearSRGBColorSpace = 'srgb-linear';
  167. const LinearTransfer = 'linear';
  168. const SRGBTransfer = 'srgb';
  169. const ZeroStencilOp = 0;
  170. const KeepStencilOp = 7680;
  171. const ReplaceStencilOp = 7681;
  172. const IncrementStencilOp = 7682;
  173. const DecrementStencilOp = 7683;
  174. const IncrementWrapStencilOp = 34055;
  175. const DecrementWrapStencilOp = 34056;
  176. const InvertStencilOp = 5386;
  177. const NeverStencilFunc = 512;
  178. const LessStencilFunc = 513;
  179. const EqualStencilFunc = 514;
  180. const LessEqualStencilFunc = 515;
  181. const GreaterStencilFunc = 516;
  182. const NotEqualStencilFunc = 517;
  183. const GreaterEqualStencilFunc = 518;
  184. const AlwaysStencilFunc = 519;
  185. const NeverCompare = 512;
  186. const LessCompare = 513;
  187. const EqualCompare = 514;
  188. const LessEqualCompare = 515;
  189. const GreaterCompare = 516;
  190. const NotEqualCompare = 517;
  191. const GreaterEqualCompare = 518;
  192. const AlwaysCompare = 519;
  193. const StaticDrawUsage = 35044;
  194. const DynamicDrawUsage = 35048;
  195. const StreamDrawUsage = 35040;
  196. const StaticReadUsage = 35045;
  197. const DynamicReadUsage = 35049;
  198. const StreamReadUsage = 35041;
  199. const StaticCopyUsage = 35046;
  200. const DynamicCopyUsage = 35050;
  201. const StreamCopyUsage = 35042;
  202. const GLSL1 = '100';
  203. const GLSL3 = '300 es';
  204. const WebGLCoordinateSystem = 2000;
  205. const WebGPUCoordinateSystem = 2001;
  206. const TimestampQuery = {
  207. COMPUTE: 'compute',
  208. RENDER: 'render'
  209. };
  210. /**
  211. * This modules allows to dispatch event objects on custom JavaScript objects.
  212. *
  213. * Main repository: [eventdispatcher.js]{@link https://github.com/mrdoob/eventdispatcher.js/}
  214. *
  215. * Code Example:
  216. * ```js
  217. * class Car extends EventDispatcher {
  218. * start() {
  219. * this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } );
  220. * }
  221. *};
  222. *
  223. * // Using events with the custom object
  224. * const car = new Car();
  225. * car.addEventListener( 'start', function ( event ) {
  226. * alert( event.message );
  227. * } );
  228. *
  229. * car.start();
  230. * ```
  231. */
  232. class EventDispatcher {
  233. /**
  234. * Adds the given event listener to the given event type.
  235. *
  236. * @param {string} type - The type of event to listen to.
  237. * @param {Function} listener - The function that gets called when the event is fired.
  238. */
  239. addEventListener( type, listener ) {
  240. if ( this._listeners === undefined ) this._listeners = {};
  241. const listeners = this._listeners;
  242. if ( listeners[ type ] === undefined ) {
  243. listeners[ type ] = [];
  244. }
  245. if ( listeners[ type ].indexOf( listener ) === -1 ) {
  246. listeners[ type ].push( listener );
  247. }
  248. }
  249. /**
  250. * Returns `true` if the given event listener has been added to the given event type.
  251. *
  252. * @param {string} type - The type of event.
  253. * @param {Function} listener - The listener to check.
  254. * @return {boolean} Whether the given event listener has been added to the given event type.
  255. */
  256. hasEventListener( type, listener ) {
  257. const listeners = this._listeners;
  258. if ( listeners === undefined ) return false;
  259. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== -1;
  260. }
  261. /**
  262. * Removes the given event listener from the given event type.
  263. *
  264. * @param {string} type - The type of event.
  265. * @param {Function} listener - The listener to remove.
  266. */
  267. removeEventListener( type, listener ) {
  268. const listeners = this._listeners;
  269. if ( listeners === undefined ) return;
  270. const listenerArray = listeners[ type ];
  271. if ( listenerArray !== undefined ) {
  272. const index = listenerArray.indexOf( listener );
  273. if ( index !== -1 ) {
  274. listenerArray.splice( index, 1 );
  275. }
  276. }
  277. }
  278. /**
  279. * Dispatches an event object.
  280. *
  281. * @param {Object} event - The event that gets fired.
  282. */
  283. dispatchEvent( event ) {
  284. const listeners = this._listeners;
  285. if ( listeners === undefined ) return;
  286. const listenerArray = listeners[ event.type ];
  287. if ( listenerArray !== undefined ) {
  288. event.target = this;
  289. // Make a copy, in case listeners are removed while iterating.
  290. const array = listenerArray.slice( 0 );
  291. for ( let i = 0, l = array.length; i < l; i ++ ) {
  292. array[ i ].call( this, event );
  293. }
  294. event.target = null;
  295. }
  296. }
  297. }
  298. const _lut = [ '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0a', '0b', '0c', '0d', '0e', '0f', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '1a', '1b', '1c', '1d', '1e', '1f', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '2a', '2b', '2c', '2d', '2e', '2f', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '3a', '3b', '3c', '3d', '3e', '3f', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '4a', '4b', '4c', '4d', '4e', '4f', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '5a', '5b', '5c', '5d', '5e', '5f', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '6a', '6b', '6c', '6d', '6e', '6f', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '7a', '7b', '7c', '7d', '7e', '7f', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '8a', '8b', '8c', '8d', '8e', '8f', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '9a', '9b', '9c', '9d', '9e', '9f', 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'aa', 'ab', 'ac', 'ad', 'ae', 'af', 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'ba', 'bb', 'bc', 'bd', 'be', 'bf', 'c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'ca', 'cb', 'cc', 'cd', 'ce', 'cf', 'd0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9', 'da', 'db', 'dc', 'dd', 'de', 'df', 'e0', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'e9', 'ea', 'eb', 'ec', 'ed', 'ee', 'ef', 'f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'fa', 'fb', 'fc', 'fd', 'fe', 'ff' ];
  299. let _seed = 1234567;
  300. const DEG2RAD = Math.PI / 180;
  301. const RAD2DEG = 180 / Math.PI;
  302. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  303. function generateUUID() {
  304. const d0 = Math.random() * 0xffffffff | 0;
  305. const d1 = Math.random() * 0xffffffff | 0;
  306. const d2 = Math.random() * 0xffffffff | 0;
  307. const d3 = Math.random() * 0xffffffff | 0;
  308. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  309. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  310. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  311. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  312. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  313. return uuid.toLowerCase();
  314. }
  315. function clamp( value, min, max ) {
  316. return Math.max( min, Math.min( max, value ) );
  317. }
  318. // compute euclidean modulo of m % n
  319. // https://en.wikipedia.org/wiki/Modulo_operation
  320. function euclideanModulo( n, m ) {
  321. return ( ( n % m ) + m ) % m;
  322. }
  323. // Linear mapping from range <a1, a2> to range <b1, b2>
  324. function mapLinear( x, a1, a2, b1, b2 ) {
  325. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  326. }
  327. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  328. function inverseLerp( x, y, value ) {
  329. if ( x !== y ) {
  330. return ( value - x ) / ( y - x );
  331. } else {
  332. return 0;
  333. }
  334. }
  335. // https://en.wikipedia.org/wiki/Linear_interpolation
  336. function lerp( x, y, t ) {
  337. return ( 1 - t ) * x + t * y;
  338. }
  339. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  340. function damp( x, y, lambda, dt ) {
  341. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  342. }
  343. // https://www.desmos.com/calculator/vcsjnyz7x4
  344. function pingpong( x, length = 1 ) {
  345. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  346. }
  347. // http://en.wikipedia.org/wiki/Smoothstep
  348. function smoothstep( x, min, max ) {
  349. if ( x <= min ) return 0;
  350. if ( x >= max ) return 1;
  351. x = ( x - min ) / ( max - min );
  352. return x * x * ( 3 - 2 * x );
  353. }
  354. function smootherstep( x, min, max ) {
  355. if ( x <= min ) return 0;
  356. if ( x >= max ) return 1;
  357. x = ( x - min ) / ( max - min );
  358. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  359. }
  360. // Random integer from <low, high> interval
  361. function randInt( low, high ) {
  362. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  363. }
  364. // Random float from <low, high> interval
  365. function randFloat( low, high ) {
  366. return low + Math.random() * ( high - low );
  367. }
  368. // Random float from <-range/2, range/2> interval
  369. function randFloatSpread( range ) {
  370. return range * ( 0.5 - Math.random() );
  371. }
  372. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  373. function seededRandom( s ) {
  374. if ( s !== undefined ) _seed = s;
  375. // Mulberry32 generator
  376. let t = _seed += 0x6D2B79F5;
  377. t = Math.imul( t ^ t >>> 15, t | 1 );
  378. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  379. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  380. }
  381. function degToRad( degrees ) {
  382. return degrees * DEG2RAD;
  383. }
  384. function radToDeg( radians ) {
  385. return radians * RAD2DEG;
  386. }
  387. function isPowerOfTwo( value ) {
  388. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  389. }
  390. function ceilPowerOfTwo( value ) {
  391. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  392. }
  393. function floorPowerOfTwo( value ) {
  394. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  395. }
  396. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  397. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  398. // rotations are applied to the axes in the order specified by 'order'
  399. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  400. // angles are in radians
  401. const cos = Math.cos;
  402. const sin = Math.sin;
  403. const c2 = cos( b / 2 );
  404. const s2 = sin( b / 2 );
  405. const c13 = cos( ( a + c ) / 2 );
  406. const s13 = sin( ( a + c ) / 2 );
  407. const c1_3 = cos( ( a - c ) / 2 );
  408. const s1_3 = sin( ( a - c ) / 2 );
  409. const c3_1 = cos( ( c - a ) / 2 );
  410. const s3_1 = sin( ( c - a ) / 2 );
  411. switch ( order ) {
  412. case 'XYX':
  413. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  414. break;
  415. case 'YZY':
  416. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  417. break;
  418. case 'ZXZ':
  419. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  420. break;
  421. case 'XZX':
  422. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  423. break;
  424. case 'YXY':
  425. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  426. break;
  427. case 'ZYZ':
  428. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  429. break;
  430. default:
  431. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  432. }
  433. }
  434. function denormalize( value, array ) {
  435. switch ( array.constructor ) {
  436. case Float32Array:
  437. return value;
  438. case Uint32Array:
  439. return value / 4294967295.0;
  440. case Uint16Array:
  441. return value / 65535.0;
  442. case Uint8Array:
  443. return value / 255.0;
  444. case Int32Array:
  445. return Math.max( value / 2147483647.0, -1 );
  446. case Int16Array:
  447. return Math.max( value / 32767.0, -1 );
  448. case Int8Array:
  449. return Math.max( value / 127.0, -1 );
  450. default:
  451. throw new Error( 'Invalid component type.' );
  452. }
  453. }
  454. function normalize( value, array ) {
  455. switch ( array.constructor ) {
  456. case Float32Array:
  457. return value;
  458. case Uint32Array:
  459. return Math.round( value * 4294967295.0 );
  460. case Uint16Array:
  461. return Math.round( value * 65535.0 );
  462. case Uint8Array:
  463. return Math.round( value * 255.0 );
  464. case Int32Array:
  465. return Math.round( value * 2147483647.0 );
  466. case Int16Array:
  467. return Math.round( value * 32767.0 );
  468. case Int8Array:
  469. return Math.round( value * 127.0 );
  470. default:
  471. throw new Error( 'Invalid component type.' );
  472. }
  473. }
  474. const MathUtils = {
  475. DEG2RAD: DEG2RAD,
  476. RAD2DEG: RAD2DEG,
  477. generateUUID: generateUUID,
  478. clamp: clamp,
  479. euclideanModulo: euclideanModulo,
  480. mapLinear: mapLinear,
  481. inverseLerp: inverseLerp,
  482. lerp: lerp,
  483. damp: damp,
  484. pingpong: pingpong,
  485. smoothstep: smoothstep,
  486. smootherstep: smootherstep,
  487. randInt: randInt,
  488. randFloat: randFloat,
  489. randFloatSpread: randFloatSpread,
  490. seededRandom: seededRandom,
  491. degToRad: degToRad,
  492. radToDeg: radToDeg,
  493. isPowerOfTwo: isPowerOfTwo,
  494. ceilPowerOfTwo: ceilPowerOfTwo,
  495. floorPowerOfTwo: floorPowerOfTwo,
  496. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  497. normalize: normalize,
  498. denormalize: denormalize
  499. };
  500. class Vector2 {
  501. constructor( x = 0, y = 0 ) {
  502. Vector2.prototype.isVector2 = true;
  503. this.x = x;
  504. this.y = y;
  505. }
  506. get width() {
  507. return this.x;
  508. }
  509. set width( value ) {
  510. this.x = value;
  511. }
  512. get height() {
  513. return this.y;
  514. }
  515. set height( value ) {
  516. this.y = value;
  517. }
  518. set( x, y ) {
  519. this.x = x;
  520. this.y = y;
  521. return this;
  522. }
  523. setScalar( scalar ) {
  524. this.x = scalar;
  525. this.y = scalar;
  526. return this;
  527. }
  528. setX( x ) {
  529. this.x = x;
  530. return this;
  531. }
  532. setY( y ) {
  533. this.y = y;
  534. return this;
  535. }
  536. setComponent( index, value ) {
  537. switch ( index ) {
  538. case 0: this.x = value; break;
  539. case 1: this.y = value; break;
  540. default: throw new Error( 'index is out of range: ' + index );
  541. }
  542. return this;
  543. }
  544. getComponent( index ) {
  545. switch ( index ) {
  546. case 0: return this.x;
  547. case 1: return this.y;
  548. default: throw new Error( 'index is out of range: ' + index );
  549. }
  550. }
  551. clone() {
  552. return new this.constructor( this.x, this.y );
  553. }
  554. copy( v ) {
  555. this.x = v.x;
  556. this.y = v.y;
  557. return this;
  558. }
  559. add( v ) {
  560. this.x += v.x;
  561. this.y += v.y;
  562. return this;
  563. }
  564. addScalar( s ) {
  565. this.x += s;
  566. this.y += s;
  567. return this;
  568. }
  569. addVectors( a, b ) {
  570. this.x = a.x + b.x;
  571. this.y = a.y + b.y;
  572. return this;
  573. }
  574. addScaledVector( v, s ) {
  575. this.x += v.x * s;
  576. this.y += v.y * s;
  577. return this;
  578. }
  579. sub( v ) {
  580. this.x -= v.x;
  581. this.y -= v.y;
  582. return this;
  583. }
  584. subScalar( s ) {
  585. this.x -= s;
  586. this.y -= s;
  587. return this;
  588. }
  589. subVectors( a, b ) {
  590. this.x = a.x - b.x;
  591. this.y = a.y - b.y;
  592. return this;
  593. }
  594. multiply( v ) {
  595. this.x *= v.x;
  596. this.y *= v.y;
  597. return this;
  598. }
  599. multiplyScalar( scalar ) {
  600. this.x *= scalar;
  601. this.y *= scalar;
  602. return this;
  603. }
  604. divide( v ) {
  605. this.x /= v.x;
  606. this.y /= v.y;
  607. return this;
  608. }
  609. divideScalar( scalar ) {
  610. return this.multiplyScalar( 1 / scalar );
  611. }
  612. applyMatrix3( m ) {
  613. const x = this.x, y = this.y;
  614. const e = m.elements;
  615. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  616. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  617. return this;
  618. }
  619. min( v ) {
  620. this.x = Math.min( this.x, v.x );
  621. this.y = Math.min( this.y, v.y );
  622. return this;
  623. }
  624. max( v ) {
  625. this.x = Math.max( this.x, v.x );
  626. this.y = Math.max( this.y, v.y );
  627. return this;
  628. }
  629. clamp( min, max ) {
  630. // assumes min < max, componentwise
  631. this.x = clamp( this.x, min.x, max.x );
  632. this.y = clamp( this.y, min.y, max.y );
  633. return this;
  634. }
  635. clampScalar( minVal, maxVal ) {
  636. this.x = clamp( this.x, minVal, maxVal );
  637. this.y = clamp( this.y, minVal, maxVal );
  638. return this;
  639. }
  640. clampLength( min, max ) {
  641. const length = this.length();
  642. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  643. }
  644. floor() {
  645. this.x = Math.floor( this.x );
  646. this.y = Math.floor( this.y );
  647. return this;
  648. }
  649. ceil() {
  650. this.x = Math.ceil( this.x );
  651. this.y = Math.ceil( this.y );
  652. return this;
  653. }
  654. round() {
  655. this.x = Math.round( this.x );
  656. this.y = Math.round( this.y );
  657. return this;
  658. }
  659. roundToZero() {
  660. this.x = Math.trunc( this.x );
  661. this.y = Math.trunc( this.y );
  662. return this;
  663. }
  664. negate() {
  665. this.x = - this.x;
  666. this.y = - this.y;
  667. return this;
  668. }
  669. dot( v ) {
  670. return this.x * v.x + this.y * v.y;
  671. }
  672. cross( v ) {
  673. return this.x * v.y - this.y * v.x;
  674. }
  675. lengthSq() {
  676. return this.x * this.x + this.y * this.y;
  677. }
  678. length() {
  679. return Math.sqrt( this.x * this.x + this.y * this.y );
  680. }
  681. manhattanLength() {
  682. return Math.abs( this.x ) + Math.abs( this.y );
  683. }
  684. normalize() {
  685. return this.divideScalar( this.length() || 1 );
  686. }
  687. angle() {
  688. // computes the angle in radians with respect to the positive x-axis
  689. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  690. return angle;
  691. }
  692. angleTo( v ) {
  693. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  694. if ( denominator === 0 ) return Math.PI / 2;
  695. const theta = this.dot( v ) / denominator;
  696. // clamp, to handle numerical problems
  697. return Math.acos( clamp( theta, -1, 1 ) );
  698. }
  699. distanceTo( v ) {
  700. return Math.sqrt( this.distanceToSquared( v ) );
  701. }
  702. distanceToSquared( v ) {
  703. const dx = this.x - v.x, dy = this.y - v.y;
  704. return dx * dx + dy * dy;
  705. }
  706. manhattanDistanceTo( v ) {
  707. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  708. }
  709. setLength( length ) {
  710. return this.normalize().multiplyScalar( length );
  711. }
  712. lerp( v, alpha ) {
  713. this.x += ( v.x - this.x ) * alpha;
  714. this.y += ( v.y - this.y ) * alpha;
  715. return this;
  716. }
  717. lerpVectors( v1, v2, alpha ) {
  718. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  719. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  720. return this;
  721. }
  722. equals( v ) {
  723. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  724. }
  725. fromArray( array, offset = 0 ) {
  726. this.x = array[ offset ];
  727. this.y = array[ offset + 1 ];
  728. return this;
  729. }
  730. toArray( array = [], offset = 0 ) {
  731. array[ offset ] = this.x;
  732. array[ offset + 1 ] = this.y;
  733. return array;
  734. }
  735. fromBufferAttribute( attribute, index ) {
  736. this.x = attribute.getX( index );
  737. this.y = attribute.getY( index );
  738. return this;
  739. }
  740. rotateAround( center, angle ) {
  741. const c = Math.cos( angle ), s = Math.sin( angle );
  742. const x = this.x - center.x;
  743. const y = this.y - center.y;
  744. this.x = x * c - y * s + center.x;
  745. this.y = x * s + y * c + center.y;
  746. return this;
  747. }
  748. random() {
  749. this.x = Math.random();
  750. this.y = Math.random();
  751. return this;
  752. }
  753. *[ Symbol.iterator ]() {
  754. yield this.x;
  755. yield this.y;
  756. }
  757. }
  758. class Matrix3 {
  759. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  760. Matrix3.prototype.isMatrix3 = true;
  761. this.elements = [
  762. 1, 0, 0,
  763. 0, 1, 0,
  764. 0, 0, 1
  765. ];
  766. if ( n11 !== undefined ) {
  767. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  768. }
  769. }
  770. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  771. const te = this.elements;
  772. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  773. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  774. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  775. return this;
  776. }
  777. identity() {
  778. this.set(
  779. 1, 0, 0,
  780. 0, 1, 0,
  781. 0, 0, 1
  782. );
  783. return this;
  784. }
  785. copy( m ) {
  786. const te = this.elements;
  787. const me = m.elements;
  788. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  789. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  790. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  791. return this;
  792. }
  793. extractBasis( xAxis, yAxis, zAxis ) {
  794. xAxis.setFromMatrix3Column( this, 0 );
  795. yAxis.setFromMatrix3Column( this, 1 );
  796. zAxis.setFromMatrix3Column( this, 2 );
  797. return this;
  798. }
  799. setFromMatrix4( m ) {
  800. const me = m.elements;
  801. this.set(
  802. me[ 0 ], me[ 4 ], me[ 8 ],
  803. me[ 1 ], me[ 5 ], me[ 9 ],
  804. me[ 2 ], me[ 6 ], me[ 10 ]
  805. );
  806. return this;
  807. }
  808. multiply( m ) {
  809. return this.multiplyMatrices( this, m );
  810. }
  811. premultiply( m ) {
  812. return this.multiplyMatrices( m, this );
  813. }
  814. multiplyMatrices( a, b ) {
  815. const ae = a.elements;
  816. const be = b.elements;
  817. const te = this.elements;
  818. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  819. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  820. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  821. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  822. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  823. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  824. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  825. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  826. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  827. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  828. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  829. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  830. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  831. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  832. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  833. return this;
  834. }
  835. multiplyScalar( s ) {
  836. const te = this.elements;
  837. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  838. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  839. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  840. return this;
  841. }
  842. determinant() {
  843. const te = this.elements;
  844. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  845. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  846. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  847. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  848. }
  849. invert() {
  850. const te = this.elements,
  851. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  852. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  853. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  854. t11 = n33 * n22 - n32 * n23,
  855. t12 = n32 * n13 - n33 * n12,
  856. t13 = n23 * n12 - n22 * n13,
  857. det = n11 * t11 + n21 * t12 + n31 * t13;
  858. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  859. const detInv = 1 / det;
  860. te[ 0 ] = t11 * detInv;
  861. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  862. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  863. te[ 3 ] = t12 * detInv;
  864. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  865. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  866. te[ 6 ] = t13 * detInv;
  867. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  868. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  869. return this;
  870. }
  871. transpose() {
  872. let tmp;
  873. const m = this.elements;
  874. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  875. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  876. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  877. return this;
  878. }
  879. getNormalMatrix( matrix4 ) {
  880. return this.setFromMatrix4( matrix4 ).invert().transpose();
  881. }
  882. transposeIntoArray( r ) {
  883. const m = this.elements;
  884. r[ 0 ] = m[ 0 ];
  885. r[ 1 ] = m[ 3 ];
  886. r[ 2 ] = m[ 6 ];
  887. r[ 3 ] = m[ 1 ];
  888. r[ 4 ] = m[ 4 ];
  889. r[ 5 ] = m[ 7 ];
  890. r[ 6 ] = m[ 2 ];
  891. r[ 7 ] = m[ 5 ];
  892. r[ 8 ] = m[ 8 ];
  893. return this;
  894. }
  895. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  896. const c = Math.cos( rotation );
  897. const s = Math.sin( rotation );
  898. this.set(
  899. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  900. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  901. 0, 0, 1
  902. );
  903. return this;
  904. }
  905. //
  906. scale( sx, sy ) {
  907. this.premultiply( _m3.makeScale( sx, sy ) );
  908. return this;
  909. }
  910. rotate( theta ) {
  911. this.premultiply( _m3.makeRotation( - theta ) );
  912. return this;
  913. }
  914. translate( tx, ty ) {
  915. this.premultiply( _m3.makeTranslation( tx, ty ) );
  916. return this;
  917. }
  918. // for 2D Transforms
  919. makeTranslation( x, y ) {
  920. if ( x.isVector2 ) {
  921. this.set(
  922. 1, 0, x.x,
  923. 0, 1, x.y,
  924. 0, 0, 1
  925. );
  926. } else {
  927. this.set(
  928. 1, 0, x,
  929. 0, 1, y,
  930. 0, 0, 1
  931. );
  932. }
  933. return this;
  934. }
  935. makeRotation( theta ) {
  936. // counterclockwise
  937. const c = Math.cos( theta );
  938. const s = Math.sin( theta );
  939. this.set(
  940. c, - s, 0,
  941. s, c, 0,
  942. 0, 0, 1
  943. );
  944. return this;
  945. }
  946. makeScale( x, y ) {
  947. this.set(
  948. x, 0, 0,
  949. 0, y, 0,
  950. 0, 0, 1
  951. );
  952. return this;
  953. }
  954. //
  955. equals( matrix ) {
  956. const te = this.elements;
  957. const me = matrix.elements;
  958. for ( let i = 0; i < 9; i ++ ) {
  959. if ( te[ i ] !== me[ i ] ) return false;
  960. }
  961. return true;
  962. }
  963. fromArray( array, offset = 0 ) {
  964. for ( let i = 0; i < 9; i ++ ) {
  965. this.elements[ i ] = array[ i + offset ];
  966. }
  967. return this;
  968. }
  969. toArray( array = [], offset = 0 ) {
  970. const te = this.elements;
  971. array[ offset ] = te[ 0 ];
  972. array[ offset + 1 ] = te[ 1 ];
  973. array[ offset + 2 ] = te[ 2 ];
  974. array[ offset + 3 ] = te[ 3 ];
  975. array[ offset + 4 ] = te[ 4 ];
  976. array[ offset + 5 ] = te[ 5 ];
  977. array[ offset + 6 ] = te[ 6 ];
  978. array[ offset + 7 ] = te[ 7 ];
  979. array[ offset + 8 ] = te[ 8 ];
  980. return array;
  981. }
  982. clone() {
  983. return new this.constructor().fromArray( this.elements );
  984. }
  985. }
  986. const _m3 = /*@__PURE__*/ new Matrix3();
  987. function arrayNeedsUint32( array ) {
  988. // assumes larger values usually on last
  989. for ( let i = array.length - 1; i >= 0; -- i ) {
  990. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  991. }
  992. return false;
  993. }
  994. const TYPED_ARRAYS = {
  995. Int8Array: Int8Array,
  996. Uint8Array: Uint8Array,
  997. Uint8ClampedArray: Uint8ClampedArray,
  998. Int16Array: Int16Array,
  999. Uint16Array: Uint16Array,
  1000. Int32Array: Int32Array,
  1001. Uint32Array: Uint32Array,
  1002. Float32Array: Float32Array,
  1003. Float64Array: Float64Array
  1004. };
  1005. function getTypedArray( type, buffer ) {
  1006. return new TYPED_ARRAYS[ type ]( buffer );
  1007. }
  1008. function createElementNS( name ) {
  1009. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  1010. }
  1011. function createCanvasElement() {
  1012. const canvas = createElementNS( 'canvas' );
  1013. canvas.style.display = 'block';
  1014. return canvas;
  1015. }
  1016. const _cache = {};
  1017. function warnOnce( message ) {
  1018. if ( message in _cache ) return;
  1019. _cache[ message ] = true;
  1020. console.warn( message );
  1021. }
  1022. function probeAsync( gl, sync, interval ) {
  1023. return new Promise( function ( resolve, reject ) {
  1024. function probe() {
  1025. switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
  1026. case gl.WAIT_FAILED:
  1027. reject();
  1028. break;
  1029. case gl.TIMEOUT_EXPIRED:
  1030. setTimeout( probe, interval );
  1031. break;
  1032. default:
  1033. resolve();
  1034. }
  1035. }
  1036. setTimeout( probe, interval );
  1037. } );
  1038. }
  1039. function toNormalizedProjectionMatrix( projectionMatrix ) {
  1040. const m = projectionMatrix.elements;
  1041. // Convert [-1, 1] to [0, 1] projection matrix
  1042. m[ 2 ] = 0.5 * m[ 2 ] + 0.5 * m[ 3 ];
  1043. m[ 6 ] = 0.5 * m[ 6 ] + 0.5 * m[ 7 ];
  1044. m[ 10 ] = 0.5 * m[ 10 ] + 0.5 * m[ 11 ];
  1045. m[ 14 ] = 0.5 * m[ 14 ] + 0.5 * m[ 15 ];
  1046. }
  1047. function toReversedProjectionMatrix( projectionMatrix ) {
  1048. const m = projectionMatrix.elements;
  1049. const isPerspectiveMatrix = m[ 11 ] === -1;
  1050. // Reverse [0, 1] projection matrix
  1051. if ( isPerspectiveMatrix ) {
  1052. m[ 10 ] = - m[ 10 ] - 1;
  1053. m[ 14 ] = - m[ 14 ];
  1054. } else {
  1055. m[ 10 ] = - m[ 10 ];
  1056. m[ 14 ] = - m[ 14 ] + 1;
  1057. }
  1058. }
  1059. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  1060. 0.4123908, 0.3575843, 0.1804808,
  1061. 0.2126390, 0.7151687, 0.0721923,
  1062. 0.0193308, 0.1191948, 0.9505322
  1063. );
  1064. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  1065. 3.2409699, -1.5373832, -0.4986108,
  1066. -0.9692436, 1.8759675, 0.0415551,
  1067. 0.0556301, -0.203977, 1.0569715
  1068. );
  1069. function createColorManagement() {
  1070. const ColorManagement = {
  1071. enabled: true,
  1072. workingColorSpace: LinearSRGBColorSpace,
  1073. /**
  1074. * Implementations of supported color spaces.
  1075. *
  1076. * Required:
  1077. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  1078. * - whitePoint: reference white [ x y ]
  1079. * - transfer: transfer function (pre-defined)
  1080. * - toXYZ: Matrix3 RGB to XYZ transform
  1081. * - fromXYZ: Matrix3 XYZ to RGB transform
  1082. * - luminanceCoefficients: RGB luminance coefficients
  1083. *
  1084. * Optional:
  1085. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace }
  1086. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  1087. *
  1088. * Reference:
  1089. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  1090. */
  1091. spaces: {},
  1092. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  1093. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  1094. return color;
  1095. }
  1096. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  1097. color.r = SRGBToLinear( color.r );
  1098. color.g = SRGBToLinear( color.g );
  1099. color.b = SRGBToLinear( color.b );
  1100. }
  1101. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  1102. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  1103. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  1104. }
  1105. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  1106. color.r = LinearToSRGB( color.r );
  1107. color.g = LinearToSRGB( color.g );
  1108. color.b = LinearToSRGB( color.b );
  1109. }
  1110. return color;
  1111. },
  1112. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  1113. return this.convert( color, this.workingColorSpace, targetColorSpace );
  1114. },
  1115. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  1116. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  1117. },
  1118. getPrimaries: function ( colorSpace ) {
  1119. return this.spaces[ colorSpace ].primaries;
  1120. },
  1121. getTransfer: function ( colorSpace ) {
  1122. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  1123. return this.spaces[ colorSpace ].transfer;
  1124. },
  1125. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  1126. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  1127. },
  1128. define: function ( colorSpaces ) {
  1129. Object.assign( this.spaces, colorSpaces );
  1130. },
  1131. // Internal APIs
  1132. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  1133. return targetMatrix
  1134. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  1135. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  1136. },
  1137. _getDrawingBufferColorSpace: function ( colorSpace ) {
  1138. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  1139. },
  1140. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  1141. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  1142. }
  1143. };
  1144. /******************************************************************************
  1145. * sRGB definitions
  1146. */
  1147. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  1148. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  1149. const D65 = [ 0.3127, 0.3290 ];
  1150. ColorManagement.define( {
  1151. [ LinearSRGBColorSpace ]: {
  1152. primaries: REC709_PRIMARIES,
  1153. whitePoint: D65,
  1154. transfer: LinearTransfer,
  1155. toXYZ: LINEAR_REC709_TO_XYZ,
  1156. fromXYZ: XYZ_TO_LINEAR_REC709,
  1157. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  1158. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  1159. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  1160. },
  1161. [ SRGBColorSpace ]: {
  1162. primaries: REC709_PRIMARIES,
  1163. whitePoint: D65,
  1164. transfer: SRGBTransfer,
  1165. toXYZ: LINEAR_REC709_TO_XYZ,
  1166. fromXYZ: XYZ_TO_LINEAR_REC709,
  1167. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  1168. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  1169. },
  1170. } );
  1171. return ColorManagement;
  1172. }
  1173. const ColorManagement = /*@__PURE__*/ createColorManagement();
  1174. function SRGBToLinear( c ) {
  1175. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  1176. }
  1177. function LinearToSRGB( c ) {
  1178. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  1179. }
  1180. let _canvas;
  1181. class ImageUtils {
  1182. static getDataURL( image ) {
  1183. if ( /^data:/i.test( image.src ) ) {
  1184. return image.src;
  1185. }
  1186. if ( typeof HTMLCanvasElement === 'undefined' ) {
  1187. return image.src;
  1188. }
  1189. let canvas;
  1190. if ( image instanceof HTMLCanvasElement ) {
  1191. canvas = image;
  1192. } else {
  1193. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1194. _canvas.width = image.width;
  1195. _canvas.height = image.height;
  1196. const context = _canvas.getContext( '2d' );
  1197. if ( image instanceof ImageData ) {
  1198. context.putImageData( image, 0, 0 );
  1199. } else {
  1200. context.drawImage( image, 0, 0, image.width, image.height );
  1201. }
  1202. canvas = _canvas;
  1203. }
  1204. return canvas.toDataURL( 'image/png' );
  1205. }
  1206. static sRGBToLinear( image ) {
  1207. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1208. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1209. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1210. const canvas = createElementNS( 'canvas' );
  1211. canvas.width = image.width;
  1212. canvas.height = image.height;
  1213. const context = canvas.getContext( '2d' );
  1214. context.drawImage( image, 0, 0, image.width, image.height );
  1215. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1216. const data = imageData.data;
  1217. for ( let i = 0; i < data.length; i ++ ) {
  1218. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1219. }
  1220. context.putImageData( imageData, 0, 0 );
  1221. return canvas;
  1222. } else if ( image.data ) {
  1223. const data = image.data.slice( 0 );
  1224. for ( let i = 0; i < data.length; i ++ ) {
  1225. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1226. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1227. } else {
  1228. // assuming float
  1229. data[ i ] = SRGBToLinear( data[ i ] );
  1230. }
  1231. }
  1232. return {
  1233. data: data,
  1234. width: image.width,
  1235. height: image.height
  1236. };
  1237. } else {
  1238. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1239. return image;
  1240. }
  1241. }
  1242. }
  1243. let _sourceId = 0;
  1244. class Source {
  1245. constructor( data = null ) {
  1246. this.isSource = true;
  1247. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  1248. this.uuid = generateUUID();
  1249. this.data = data;
  1250. this.dataReady = true;
  1251. this.version = 0;
  1252. }
  1253. set needsUpdate( value ) {
  1254. if ( value === true ) this.version ++;
  1255. }
  1256. toJSON( meta ) {
  1257. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1258. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1259. return meta.images[ this.uuid ];
  1260. }
  1261. const output = {
  1262. uuid: this.uuid,
  1263. url: ''
  1264. };
  1265. const data = this.data;
  1266. if ( data !== null ) {
  1267. let url;
  1268. if ( Array.isArray( data ) ) {
  1269. // cube texture
  1270. url = [];
  1271. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1272. if ( data[ i ].isDataTexture ) {
  1273. url.push( serializeImage( data[ i ].image ) );
  1274. } else {
  1275. url.push( serializeImage( data[ i ] ) );
  1276. }
  1277. }
  1278. } else {
  1279. // texture
  1280. url = serializeImage( data );
  1281. }
  1282. output.url = url;
  1283. }
  1284. if ( ! isRootObject ) {
  1285. meta.images[ this.uuid ] = output;
  1286. }
  1287. return output;
  1288. }
  1289. }
  1290. function serializeImage( image ) {
  1291. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1292. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1293. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1294. // default images
  1295. return ImageUtils.getDataURL( image );
  1296. } else {
  1297. if ( image.data ) {
  1298. // images of DataTexture
  1299. return {
  1300. data: Array.from( image.data ),
  1301. width: image.width,
  1302. height: image.height,
  1303. type: image.data.constructor.name
  1304. };
  1305. } else {
  1306. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1307. return {};
  1308. }
  1309. }
  1310. }
  1311. let _textureId = 0;
  1312. /**
  1313. * Base class for all textures.
  1314. *
  1315. * Note: After the initial use of a texture, its dimensions, format, and type
  1316. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  1317. *
  1318. * @augments EventDispatcher
  1319. */
  1320. class Texture extends EventDispatcher {
  1321. /**
  1322. * Constructs a new texture.
  1323. *
  1324. * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data.
  1325. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  1326. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  1327. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  1328. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  1329. * @param {number} [minFilter=LinearFilter] - The min filter value.
  1330. * @param {number} [format=RGABFormat] - The min filter value.
  1331. * @param {number} [type=UnsignedByteType] - The min filter value.
  1332. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The min filter value.
  1333. * @param {string} [colorSpace=NoColorSpace] - The min filter value.
  1334. */
  1335. constructor( image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = Texture.DEFAULT_ANISOTROPY, colorSpace = NoColorSpace ) {
  1336. super();
  1337. /**
  1338. * This flag can be used for type testing.
  1339. *
  1340. * @type {boolean}
  1341. * @readonly
  1342. * @default true
  1343. */
  1344. this.isTexture = true;
  1345. /**
  1346. * The ID of the texture.
  1347. *
  1348. * @name Texture#id
  1349. * @type {number}
  1350. * @readonly
  1351. */
  1352. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  1353. /**
  1354. * The UUID of the material.
  1355. *
  1356. * @type {string}
  1357. * @readonly
  1358. */
  1359. this.uuid = generateUUID();
  1360. /**
  1361. * The name of the material.
  1362. *
  1363. * @type {string}
  1364. */
  1365. this.name = '';
  1366. /**
  1367. * The data definition of a texture. A reference to the data source can be
  1368. * shared across textures. This is often useful in context of spritesheets
  1369. * where multiple textures render the same data but with different texture
  1370. * transformations.
  1371. *
  1372. * @type {Source}
  1373. */
  1374. this.source = new Source( image );
  1375. /**
  1376. * An array holding user-defined mipmaps.
  1377. *
  1378. * @type {Array<Object>}
  1379. */
  1380. this.mipmaps = [];
  1381. /**
  1382. * How the texture is applied to the object. The value `UVMapping`
  1383. * is the default, where texture or uv coordinates are used to apply the map.
  1384. *
  1385. * @type {(UVMapping|CubeReflectionMapping|CubeRefractionMapping|EquirectangularReflectionMapping|EquirectangularRefractionMapping|CubeUVReflectionMapping)}
  1386. * @default UVMapping
  1387. */
  1388. this.mapping = mapping;
  1389. /**
  1390. * Lets you select the uv attribute to map the texture to. `0` for `uv`,
  1391. * `1` for `uv1`, `2` for `uv2` and `3` for `uv3`.
  1392. *
  1393. * @type {number}
  1394. * @default 0
  1395. */
  1396. this.channel = 0;
  1397. /**
  1398. * This defines how the texture is wrapped horizontally and corresponds to
  1399. * *U* in UV mapping.
  1400. *
  1401. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  1402. * @default ClampToEdgeWrapping
  1403. */
  1404. this.wrapS = wrapS;
  1405. /**
  1406. * This defines how the texture is wrapped horizontally and corresponds to
  1407. * *V* in UV mapping.
  1408. *
  1409. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  1410. * @default ClampToEdgeWrapping
  1411. */
  1412. this.wrapT = wrapT;
  1413. /**
  1414. * How the texture is sampled when a texel covers more than one pixel.
  1415. *
  1416. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  1417. * @default LinearFilter
  1418. */
  1419. this.magFilter = magFilter;
  1420. /**
  1421. * How the texture is sampled when a texel covers less than one pixel.
  1422. *
  1423. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  1424. * @default LinearMipmapLinearFilter
  1425. */
  1426. this.minFilter = minFilter;
  1427. /**
  1428. * The number of samples taken along the axis through the pixel that has the
  1429. * highest density of texels. By default, this value is `1`. A higher value
  1430. * gives a less blurry result than a basic mipmap, at the cost of more
  1431. * texture samples being used.
  1432. *
  1433. * @type {number}
  1434. * @default 0
  1435. */
  1436. this.anisotropy = anisotropy;
  1437. /**
  1438. * The format of the texture.
  1439. *
  1440. * @type {number}
  1441. * @default RGBAFormat
  1442. */
  1443. this.format = format;
  1444. /**
  1445. * The default internal format is derived from {@link Texture#format} and {@link Texture#type} and
  1446. * defines how the texture data is going to be stored on the GPU.
  1447. *
  1448. * This property allows to overwrite the default format.
  1449. *
  1450. * @type {?string}
  1451. * @default null
  1452. */
  1453. this.internalFormat = null;
  1454. /**
  1455. * The data type of the texture.
  1456. *
  1457. * @type {number}
  1458. * @default UnsignedByteType
  1459. */
  1460. this.type = type;
  1461. /**
  1462. * How much a single repetition of the texture is offset from the beginning,
  1463. * in each direction U and V. Typical range is `0.0` to `1.0`.
  1464. *
  1465. * @type {Vector2}
  1466. * @default (0,0)
  1467. */
  1468. this.offset = new Vector2( 0, 0 );
  1469. /**
  1470. * How many times the texture is repeated across the surface, in each
  1471. * direction U and V. If repeat is set greater than `1` in either direction,
  1472. * the corresponding wrap parameter should also be set to `RepeatWrapping`
  1473. * or `MirroredRepeatWrapping` to achieve the desired tiling effect.
  1474. *
  1475. * @type {Vector2}
  1476. * @default (1,1)
  1477. */
  1478. this.repeat = new Vector2( 1, 1 );
  1479. /**
  1480. * The point around which rotation occurs. A value of `(0.5, 0.5)` corresponds
  1481. * to the center of the texture. Default is `(0, 0)`, the lower left.
  1482. *
  1483. * @type {Vector2}
  1484. * @default (0,0)
  1485. */
  1486. this.center = new Vector2( 0, 0 );
  1487. /**
  1488. * How much the texture is rotated around the center point, in radians.
  1489. * Positive values are counter-clockwise.
  1490. *
  1491. * @type {number}
  1492. * @default 0
  1493. */
  1494. this.rotation = 0;
  1495. /**
  1496. * Whether to update the texture's uv-transformation {@link Texture#matrix}
  1497. * from the properties {@link Texture#offset}, {@link Texture#repeat},
  1498. * {@link Texture#rotation}, and {@link Texture#center}.
  1499. *
  1500. * Set this to `false` if you are specifying the uv-transform matrix directly.
  1501. *
  1502. * @type {boolean}
  1503. * @default true
  1504. */
  1505. this.matrixAutoUpdate = true;
  1506. /**
  1507. * The uv-transformation matrix of the texture.
  1508. *
  1509. * @type {Matrix3}
  1510. */
  1511. this.matrix = new Matrix3();
  1512. /**
  1513. * Whether to generate mipmaps (if possible) for a texture.
  1514. *
  1515. * Set this to `false` if you are creating mipmaps manually.
  1516. *
  1517. * @type {boolean}
  1518. * @default true
  1519. */
  1520. this.generateMipmaps = true;
  1521. /**
  1522. * If set to `true`, the alpha channel, if present, is multiplied into the
  1523. * color channels when the texture is uploaded to the GPU.
  1524. *
  1525. * Note that this property has no effect when using `ImageBitmap`. You need to
  1526. * configure premultiply alpha on bitmap creation instead.
  1527. *
  1528. * @type {boolean}
  1529. * @default false
  1530. */
  1531. this.premultiplyAlpha = false;
  1532. /**
  1533. * If set to `true`, the texture is flipped along the vertical axis when
  1534. * uploaded to the GPU.
  1535. *
  1536. * Note that this property has no effect when using `ImageBitmap`. You need to
  1537. * configure the flip on bitmap creation instead.
  1538. *
  1539. * @type {boolean}
  1540. * @default true
  1541. */
  1542. this.flipY = true;
  1543. /**
  1544. * Specifies the alignment requirements for the start of each pixel row in memory.
  1545. * The allowable values are `1` (byte-alignment), `2` (rows aligned to even-numbered bytes),
  1546. * `4` (word-alignment), and `8` (rows start on double-word boundaries).
  1547. *
  1548. * @type {number}
  1549. * @default 4
  1550. */
  1551. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1552. /**
  1553. * Textures containing color data should be annotated with `SRGBColorSpace` or `LinearSRGBColorSpace`.
  1554. *
  1555. * @type {string}
  1556. * @default NoColorSpace
  1557. */
  1558. this.colorSpace = colorSpace;
  1559. /**
  1560. * An object that can be used to store custom data about the texture. It
  1561. * should not hold references to functions as these will not be cloned.
  1562. *
  1563. * @type {Object}
  1564. */
  1565. this.userData = {};
  1566. /**
  1567. * This starts at `0` and counts how many times {@link Texture#needsUpdate} is set to `true`.
  1568. *
  1569. * @type {number}
  1570. * @readonly
  1571. * @default 0
  1572. */
  1573. this.version = 0;
  1574. /**
  1575. * A callback function, called when the texture is updated (e.g., when
  1576. * {@link Texture#needsUpdate} has been set to true and then the texture is used).
  1577. *
  1578. * @type {?Function}
  1579. * @default null
  1580. */
  1581. this.onUpdate = null;
  1582. /**
  1583. * An optional back reference to the textures render target.
  1584. *
  1585. * @type {?(RenderTarget|WebGLRenderTarget)}
  1586. * @default null
  1587. */
  1588. this.renderTarget = null;
  1589. /**
  1590. * Indicates whether a texture belongs to a render target or not.
  1591. *
  1592. * @type {boolean}
  1593. * @readonly
  1594. * @default false
  1595. */
  1596. this.isRenderTargetTexture = false;
  1597. /**
  1598. * Indicates whether this texture should be processed by `PMREMGenerator` or not
  1599. * (only relevant for render target textures).
  1600. *
  1601. * @type {number}
  1602. * @readonly
  1603. * @default 0
  1604. */
  1605. this.pmremVersion = 0;
  1606. }
  1607. /**
  1608. * The image object holding the texture data.
  1609. *
  1610. * @type {?Object}
  1611. */
  1612. get image() {
  1613. return this.source.data;
  1614. }
  1615. set image( value = null ) {
  1616. this.source.data = value;
  1617. }
  1618. /**
  1619. * Updates the texture transformation matrix from the from the properties {@link Texture#offset},
  1620. * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
  1621. */
  1622. updateMatrix() {
  1623. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1624. }
  1625. /**
  1626. * Returns a new texture with copied values from this instance.
  1627. *
  1628. * @return {Texture} A clone of this instance.
  1629. */
  1630. clone() {
  1631. return new this.constructor().copy( this );
  1632. }
  1633. /**
  1634. * Copies the values of the given texture to this instance.
  1635. *
  1636. * @param {Texture} source - The texture to copy.
  1637. * @return {Texture} A reference to this instance.
  1638. */
  1639. copy( source ) {
  1640. this.name = source.name;
  1641. this.source = source.source;
  1642. this.mipmaps = source.mipmaps.slice( 0 );
  1643. this.mapping = source.mapping;
  1644. this.channel = source.channel;
  1645. this.wrapS = source.wrapS;
  1646. this.wrapT = source.wrapT;
  1647. this.magFilter = source.magFilter;
  1648. this.minFilter = source.minFilter;
  1649. this.anisotropy = source.anisotropy;
  1650. this.format = source.format;
  1651. this.internalFormat = source.internalFormat;
  1652. this.type = source.type;
  1653. this.offset.copy( source.offset );
  1654. this.repeat.copy( source.repeat );
  1655. this.center.copy( source.center );
  1656. this.rotation = source.rotation;
  1657. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1658. this.matrix.copy( source.matrix );
  1659. this.generateMipmaps = source.generateMipmaps;
  1660. this.premultiplyAlpha = source.premultiplyAlpha;
  1661. this.flipY = source.flipY;
  1662. this.unpackAlignment = source.unpackAlignment;
  1663. this.colorSpace = source.colorSpace;
  1664. this.renderTarget = source.renderTarget;
  1665. this.isRenderTargetTexture = source.isRenderTargetTexture;
  1666. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  1667. this.needsUpdate = true;
  1668. return this;
  1669. }
  1670. /**
  1671. * Serializes the texture into JSON.
  1672. *
  1673. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  1674. * @return {Object} A JSON object representing the serialized texture.
  1675. * @see {@link ObjectLoader#parse}
  1676. */
  1677. toJSON( meta ) {
  1678. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1679. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1680. return meta.textures[ this.uuid ];
  1681. }
  1682. const output = {
  1683. metadata: {
  1684. version: 4.6,
  1685. type: 'Texture',
  1686. generator: 'Texture.toJSON'
  1687. },
  1688. uuid: this.uuid,
  1689. name: this.name,
  1690. image: this.source.toJSON( meta ).uuid,
  1691. mapping: this.mapping,
  1692. channel: this.channel,
  1693. repeat: [ this.repeat.x, this.repeat.y ],
  1694. offset: [ this.offset.x, this.offset.y ],
  1695. center: [ this.center.x, this.center.y ],
  1696. rotation: this.rotation,
  1697. wrap: [ this.wrapS, this.wrapT ],
  1698. format: this.format,
  1699. internalFormat: this.internalFormat,
  1700. type: this.type,
  1701. colorSpace: this.colorSpace,
  1702. minFilter: this.minFilter,
  1703. magFilter: this.magFilter,
  1704. anisotropy: this.anisotropy,
  1705. flipY: this.flipY,
  1706. generateMipmaps: this.generateMipmaps,
  1707. premultiplyAlpha: this.premultiplyAlpha,
  1708. unpackAlignment: this.unpackAlignment
  1709. };
  1710. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  1711. if ( ! isRootObject ) {
  1712. meta.textures[ this.uuid ] = output;
  1713. }
  1714. return output;
  1715. }
  1716. /**
  1717. * Frees the GPU-related resources allocated by this instance. Call this
  1718. * method whenever this instance is no longer used in your app.
  1719. *
  1720. * @fires Texture#dispose
  1721. */
  1722. dispose() {
  1723. /**
  1724. * Fires when the texture has been disposed of.
  1725. *
  1726. * @event Texture#dispose
  1727. * @type {Object}
  1728. */
  1729. this.dispatchEvent( { type: 'dispose' } );
  1730. }
  1731. /**
  1732. * Transforms the given uv vector with the textures uv transformation matrix.
  1733. *
  1734. * @param {Vector2} uv - The uv vector.
  1735. * @return {Vector2} The transformed uv vector.
  1736. */
  1737. transformUv( uv ) {
  1738. if ( this.mapping !== UVMapping ) return uv;
  1739. uv.applyMatrix3( this.matrix );
  1740. if ( uv.x < 0 || uv.x > 1 ) {
  1741. switch ( this.wrapS ) {
  1742. case RepeatWrapping:
  1743. uv.x = uv.x - Math.floor( uv.x );
  1744. break;
  1745. case ClampToEdgeWrapping:
  1746. uv.x = uv.x < 0 ? 0 : 1;
  1747. break;
  1748. case MirroredRepeatWrapping:
  1749. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1750. uv.x = Math.ceil( uv.x ) - uv.x;
  1751. } else {
  1752. uv.x = uv.x - Math.floor( uv.x );
  1753. }
  1754. break;
  1755. }
  1756. }
  1757. if ( uv.y < 0 || uv.y > 1 ) {
  1758. switch ( this.wrapT ) {
  1759. case RepeatWrapping:
  1760. uv.y = uv.y - Math.floor( uv.y );
  1761. break;
  1762. case ClampToEdgeWrapping:
  1763. uv.y = uv.y < 0 ? 0 : 1;
  1764. break;
  1765. case MirroredRepeatWrapping:
  1766. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1767. uv.y = Math.ceil( uv.y ) - uv.y;
  1768. } else {
  1769. uv.y = uv.y - Math.floor( uv.y );
  1770. }
  1771. break;
  1772. }
  1773. }
  1774. if ( this.flipY ) {
  1775. uv.y = 1 - uv.y;
  1776. }
  1777. return uv;
  1778. }
  1779. /**
  1780. * Setting this property to `true` indicates the engine the texture
  1781. * must be updated in the next render. This triggers a texture upload
  1782. * to the GPU and ensures correct texture parameter configuration.
  1783. *
  1784. * @type {boolean}
  1785. * @default false
  1786. * @param {boolean} value
  1787. */
  1788. set needsUpdate( value ) {
  1789. if ( value === true ) {
  1790. this.version ++;
  1791. this.source.needsUpdate = true;
  1792. }
  1793. }
  1794. /**
  1795. * Setting this property to `true` indicates the engine the PMREM
  1796. * must be regenerated.
  1797. *
  1798. * @type {boolean}
  1799. * @default false
  1800. * @param {boolean} value
  1801. */
  1802. set needsPMREMUpdate( value ) {
  1803. if ( value === true ) {
  1804. this.pmremVersion ++;
  1805. }
  1806. }
  1807. }
  1808. /**
  1809. * The default image for all textures.
  1810. *
  1811. * @static
  1812. * @type {?Image}
  1813. * @default null
  1814. */
  1815. Texture.DEFAULT_IMAGE = null;
  1816. /**
  1817. * The default mapping for all textures.
  1818. *
  1819. * @static
  1820. * @type {number}
  1821. * @default UVMapping
  1822. */
  1823. Texture.DEFAULT_MAPPING = UVMapping;
  1824. /**
  1825. * The default anisotropy value for all textures.
  1826. *
  1827. * @static
  1828. * @type {number}
  1829. * @default 1
  1830. */
  1831. Texture.DEFAULT_ANISOTROPY = 1;
  1832. class Vector4 {
  1833. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1834. Vector4.prototype.isVector4 = true;
  1835. this.x = x;
  1836. this.y = y;
  1837. this.z = z;
  1838. this.w = w;
  1839. }
  1840. get width() {
  1841. return this.z;
  1842. }
  1843. set width( value ) {
  1844. this.z = value;
  1845. }
  1846. get height() {
  1847. return this.w;
  1848. }
  1849. set height( value ) {
  1850. this.w = value;
  1851. }
  1852. set( x, y, z, w ) {
  1853. this.x = x;
  1854. this.y = y;
  1855. this.z = z;
  1856. this.w = w;
  1857. return this;
  1858. }
  1859. setScalar( scalar ) {
  1860. this.x = scalar;
  1861. this.y = scalar;
  1862. this.z = scalar;
  1863. this.w = scalar;
  1864. return this;
  1865. }
  1866. setX( x ) {
  1867. this.x = x;
  1868. return this;
  1869. }
  1870. setY( y ) {
  1871. this.y = y;
  1872. return this;
  1873. }
  1874. setZ( z ) {
  1875. this.z = z;
  1876. return this;
  1877. }
  1878. setW( w ) {
  1879. this.w = w;
  1880. return this;
  1881. }
  1882. setComponent( index, value ) {
  1883. switch ( index ) {
  1884. case 0: this.x = value; break;
  1885. case 1: this.y = value; break;
  1886. case 2: this.z = value; break;
  1887. case 3: this.w = value; break;
  1888. default: throw new Error( 'index is out of range: ' + index );
  1889. }
  1890. return this;
  1891. }
  1892. getComponent( index ) {
  1893. switch ( index ) {
  1894. case 0: return this.x;
  1895. case 1: return this.y;
  1896. case 2: return this.z;
  1897. case 3: return this.w;
  1898. default: throw new Error( 'index is out of range: ' + index );
  1899. }
  1900. }
  1901. clone() {
  1902. return new this.constructor( this.x, this.y, this.z, this.w );
  1903. }
  1904. copy( v ) {
  1905. this.x = v.x;
  1906. this.y = v.y;
  1907. this.z = v.z;
  1908. this.w = ( v.w !== undefined ) ? v.w : 1;
  1909. return this;
  1910. }
  1911. add( v ) {
  1912. this.x += v.x;
  1913. this.y += v.y;
  1914. this.z += v.z;
  1915. this.w += v.w;
  1916. return this;
  1917. }
  1918. addScalar( s ) {
  1919. this.x += s;
  1920. this.y += s;
  1921. this.z += s;
  1922. this.w += s;
  1923. return this;
  1924. }
  1925. addVectors( a, b ) {
  1926. this.x = a.x + b.x;
  1927. this.y = a.y + b.y;
  1928. this.z = a.z + b.z;
  1929. this.w = a.w + b.w;
  1930. return this;
  1931. }
  1932. addScaledVector( v, s ) {
  1933. this.x += v.x * s;
  1934. this.y += v.y * s;
  1935. this.z += v.z * s;
  1936. this.w += v.w * s;
  1937. return this;
  1938. }
  1939. sub( v ) {
  1940. this.x -= v.x;
  1941. this.y -= v.y;
  1942. this.z -= v.z;
  1943. this.w -= v.w;
  1944. return this;
  1945. }
  1946. subScalar( s ) {
  1947. this.x -= s;
  1948. this.y -= s;
  1949. this.z -= s;
  1950. this.w -= s;
  1951. return this;
  1952. }
  1953. subVectors( a, b ) {
  1954. this.x = a.x - b.x;
  1955. this.y = a.y - b.y;
  1956. this.z = a.z - b.z;
  1957. this.w = a.w - b.w;
  1958. return this;
  1959. }
  1960. multiply( v ) {
  1961. this.x *= v.x;
  1962. this.y *= v.y;
  1963. this.z *= v.z;
  1964. this.w *= v.w;
  1965. return this;
  1966. }
  1967. multiplyScalar( scalar ) {
  1968. this.x *= scalar;
  1969. this.y *= scalar;
  1970. this.z *= scalar;
  1971. this.w *= scalar;
  1972. return this;
  1973. }
  1974. applyMatrix4( m ) {
  1975. const x = this.x, y = this.y, z = this.z, w = this.w;
  1976. const e = m.elements;
  1977. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1978. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1979. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1980. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1981. return this;
  1982. }
  1983. divide( v ) {
  1984. this.x /= v.x;
  1985. this.y /= v.y;
  1986. this.z /= v.z;
  1987. this.w /= v.w;
  1988. return this;
  1989. }
  1990. divideScalar( scalar ) {
  1991. return this.multiplyScalar( 1 / scalar );
  1992. }
  1993. setAxisAngleFromQuaternion( q ) {
  1994. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1995. // q is assumed to be normalized
  1996. this.w = 2 * Math.acos( q.w );
  1997. const s = Math.sqrt( 1 - q.w * q.w );
  1998. if ( s < 0.0001 ) {
  1999. this.x = 1;
  2000. this.y = 0;
  2001. this.z = 0;
  2002. } else {
  2003. this.x = q.x / s;
  2004. this.y = q.y / s;
  2005. this.z = q.z / s;
  2006. }
  2007. return this;
  2008. }
  2009. setAxisAngleFromRotationMatrix( m ) {
  2010. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  2011. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2012. let angle, x, y, z; // variables for result
  2013. const epsilon = 0.01, // margin to allow for rounding errors
  2014. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  2015. te = m.elements,
  2016. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2017. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2018. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  2019. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  2020. ( Math.abs( m13 - m31 ) < epsilon ) &&
  2021. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  2022. // singularity found
  2023. // first check for identity matrix which must have +1 for all terms
  2024. // in leading diagonal and zero in other terms
  2025. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  2026. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  2027. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  2028. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  2029. // this singularity is identity matrix so angle = 0
  2030. this.set( 1, 0, 0, 0 );
  2031. return this; // zero angle, arbitrary axis
  2032. }
  2033. // otherwise this singularity is angle = 180
  2034. angle = Math.PI;
  2035. const xx = ( m11 + 1 ) / 2;
  2036. const yy = ( m22 + 1 ) / 2;
  2037. const zz = ( m33 + 1 ) / 2;
  2038. const xy = ( m12 + m21 ) / 4;
  2039. const xz = ( m13 + m31 ) / 4;
  2040. const yz = ( m23 + m32 ) / 4;
  2041. if ( ( xx > yy ) && ( xx > zz ) ) {
  2042. // m11 is the largest diagonal term
  2043. if ( xx < epsilon ) {
  2044. x = 0;
  2045. y = 0.707106781;
  2046. z = 0.707106781;
  2047. } else {
  2048. x = Math.sqrt( xx );
  2049. y = xy / x;
  2050. z = xz / x;
  2051. }
  2052. } else if ( yy > zz ) {
  2053. // m22 is the largest diagonal term
  2054. if ( yy < epsilon ) {
  2055. x = 0.707106781;
  2056. y = 0;
  2057. z = 0.707106781;
  2058. } else {
  2059. y = Math.sqrt( yy );
  2060. x = xy / y;
  2061. z = yz / y;
  2062. }
  2063. } else {
  2064. // m33 is the largest diagonal term so base result on this
  2065. if ( zz < epsilon ) {
  2066. x = 0.707106781;
  2067. y = 0.707106781;
  2068. z = 0;
  2069. } else {
  2070. z = Math.sqrt( zz );
  2071. x = xz / z;
  2072. y = yz / z;
  2073. }
  2074. }
  2075. this.set( x, y, z, angle );
  2076. return this; // return 180 deg rotation
  2077. }
  2078. // as we have reached here there are no singularities so we can handle normally
  2079. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  2080. ( m13 - m31 ) * ( m13 - m31 ) +
  2081. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  2082. if ( Math.abs( s ) < 0.001 ) s = 1;
  2083. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  2084. // caught by singularity test above, but I've left it in just in case
  2085. this.x = ( m32 - m23 ) / s;
  2086. this.y = ( m13 - m31 ) / s;
  2087. this.z = ( m21 - m12 ) / s;
  2088. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  2089. return this;
  2090. }
  2091. setFromMatrixPosition( m ) {
  2092. const e = m.elements;
  2093. this.x = e[ 12 ];
  2094. this.y = e[ 13 ];
  2095. this.z = e[ 14 ];
  2096. this.w = e[ 15 ];
  2097. return this;
  2098. }
  2099. min( v ) {
  2100. this.x = Math.min( this.x, v.x );
  2101. this.y = Math.min( this.y, v.y );
  2102. this.z = Math.min( this.z, v.z );
  2103. this.w = Math.min( this.w, v.w );
  2104. return this;
  2105. }
  2106. max( v ) {
  2107. this.x = Math.max( this.x, v.x );
  2108. this.y = Math.max( this.y, v.y );
  2109. this.z = Math.max( this.z, v.z );
  2110. this.w = Math.max( this.w, v.w );
  2111. return this;
  2112. }
  2113. clamp( min, max ) {
  2114. // assumes min < max, componentwise
  2115. this.x = clamp( this.x, min.x, max.x );
  2116. this.y = clamp( this.y, min.y, max.y );
  2117. this.z = clamp( this.z, min.z, max.z );
  2118. this.w = clamp( this.w, min.w, max.w );
  2119. return this;
  2120. }
  2121. clampScalar( minVal, maxVal ) {
  2122. this.x = clamp( this.x, minVal, maxVal );
  2123. this.y = clamp( this.y, minVal, maxVal );
  2124. this.z = clamp( this.z, minVal, maxVal );
  2125. this.w = clamp( this.w, minVal, maxVal );
  2126. return this;
  2127. }
  2128. clampLength( min, max ) {
  2129. const length = this.length();
  2130. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  2131. }
  2132. floor() {
  2133. this.x = Math.floor( this.x );
  2134. this.y = Math.floor( this.y );
  2135. this.z = Math.floor( this.z );
  2136. this.w = Math.floor( this.w );
  2137. return this;
  2138. }
  2139. ceil() {
  2140. this.x = Math.ceil( this.x );
  2141. this.y = Math.ceil( this.y );
  2142. this.z = Math.ceil( this.z );
  2143. this.w = Math.ceil( this.w );
  2144. return this;
  2145. }
  2146. round() {
  2147. this.x = Math.round( this.x );
  2148. this.y = Math.round( this.y );
  2149. this.z = Math.round( this.z );
  2150. this.w = Math.round( this.w );
  2151. return this;
  2152. }
  2153. roundToZero() {
  2154. this.x = Math.trunc( this.x );
  2155. this.y = Math.trunc( this.y );
  2156. this.z = Math.trunc( this.z );
  2157. this.w = Math.trunc( this.w );
  2158. return this;
  2159. }
  2160. negate() {
  2161. this.x = - this.x;
  2162. this.y = - this.y;
  2163. this.z = - this.z;
  2164. this.w = - this.w;
  2165. return this;
  2166. }
  2167. dot( v ) {
  2168. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  2169. }
  2170. lengthSq() {
  2171. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  2172. }
  2173. length() {
  2174. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2175. }
  2176. manhattanLength() {
  2177. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  2178. }
  2179. normalize() {
  2180. return this.divideScalar( this.length() || 1 );
  2181. }
  2182. setLength( length ) {
  2183. return this.normalize().multiplyScalar( length );
  2184. }
  2185. lerp( v, alpha ) {
  2186. this.x += ( v.x - this.x ) * alpha;
  2187. this.y += ( v.y - this.y ) * alpha;
  2188. this.z += ( v.z - this.z ) * alpha;
  2189. this.w += ( v.w - this.w ) * alpha;
  2190. return this;
  2191. }
  2192. lerpVectors( v1, v2, alpha ) {
  2193. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2194. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2195. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2196. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  2197. return this;
  2198. }
  2199. equals( v ) {
  2200. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  2201. }
  2202. fromArray( array, offset = 0 ) {
  2203. this.x = array[ offset ];
  2204. this.y = array[ offset + 1 ];
  2205. this.z = array[ offset + 2 ];
  2206. this.w = array[ offset + 3 ];
  2207. return this;
  2208. }
  2209. toArray( array = [], offset = 0 ) {
  2210. array[ offset ] = this.x;
  2211. array[ offset + 1 ] = this.y;
  2212. array[ offset + 2 ] = this.z;
  2213. array[ offset + 3 ] = this.w;
  2214. return array;
  2215. }
  2216. fromBufferAttribute( attribute, index ) {
  2217. this.x = attribute.getX( index );
  2218. this.y = attribute.getY( index );
  2219. this.z = attribute.getZ( index );
  2220. this.w = attribute.getW( index );
  2221. return this;
  2222. }
  2223. random() {
  2224. this.x = Math.random();
  2225. this.y = Math.random();
  2226. this.z = Math.random();
  2227. this.w = Math.random();
  2228. return this;
  2229. }
  2230. *[ Symbol.iterator ]() {
  2231. yield this.x;
  2232. yield this.y;
  2233. yield this.z;
  2234. yield this.w;
  2235. }
  2236. }
  2237. /*
  2238. In options, we can specify:
  2239. * Texture parameters for an auto-generated target texture
  2240. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  2241. */
  2242. class RenderTarget extends EventDispatcher {
  2243. constructor( width = 1, height = 1, options = {} ) {
  2244. super();
  2245. this.isRenderTarget = true;
  2246. this.width = width;
  2247. this.height = height;
  2248. this.depth = 1;
  2249. this.scissor = new Vector4( 0, 0, width, height );
  2250. this.scissorTest = false;
  2251. this.viewport = new Vector4( 0, 0, width, height );
  2252. const image = { width: width, height: height, depth: 1 };
  2253. options = Object.assign( {
  2254. generateMipmaps: false,
  2255. internalFormat: null,
  2256. minFilter: LinearFilter,
  2257. depthBuffer: true,
  2258. stencilBuffer: false,
  2259. resolveDepthBuffer: true,
  2260. resolveStencilBuffer: true,
  2261. depthTexture: null,
  2262. samples: 0,
  2263. count: 1
  2264. }, options );
  2265. const texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  2266. texture.flipY = false;
  2267. texture.generateMipmaps = options.generateMipmaps;
  2268. texture.internalFormat = options.internalFormat;
  2269. this.textures = [];
  2270. const count = options.count;
  2271. for ( let i = 0; i < count; i ++ ) {
  2272. this.textures[ i ] = texture.clone();
  2273. this.textures[ i ].isRenderTargetTexture = true;
  2274. this.textures[ i ].renderTarget = this;
  2275. }
  2276. this.depthBuffer = options.depthBuffer;
  2277. this.stencilBuffer = options.stencilBuffer;
  2278. this.resolveDepthBuffer = options.resolveDepthBuffer;
  2279. this.resolveStencilBuffer = options.resolveStencilBuffer;
  2280. this._depthTexture = null;
  2281. this.depthTexture = options.depthTexture;
  2282. this.samples = options.samples;
  2283. }
  2284. get texture() {
  2285. return this.textures[ 0 ];
  2286. }
  2287. set texture( value ) {
  2288. this.textures[ 0 ] = value;
  2289. }
  2290. set depthTexture( current ) {
  2291. if ( this._depthTexture !== null ) this._depthTexture.renderTarget = null;
  2292. if ( current !== null ) current.renderTarget = this;
  2293. this._depthTexture = current;
  2294. }
  2295. get depthTexture() {
  2296. return this._depthTexture;
  2297. }
  2298. setSize( width, height, depth = 1 ) {
  2299. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  2300. this.width = width;
  2301. this.height = height;
  2302. this.depth = depth;
  2303. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  2304. this.textures[ i ].image.width = width;
  2305. this.textures[ i ].image.height = height;
  2306. this.textures[ i ].image.depth = depth;
  2307. }
  2308. this.dispose();
  2309. }
  2310. this.viewport.set( 0, 0, width, height );
  2311. this.scissor.set( 0, 0, width, height );
  2312. }
  2313. clone() {
  2314. return new this.constructor().copy( this );
  2315. }
  2316. copy( source ) {
  2317. this.width = source.width;
  2318. this.height = source.height;
  2319. this.depth = source.depth;
  2320. this.scissor.copy( source.scissor );
  2321. this.scissorTest = source.scissorTest;
  2322. this.viewport.copy( source.viewport );
  2323. this.textures.length = 0;
  2324. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  2325. this.textures[ i ] = source.textures[ i ].clone();
  2326. this.textures[ i ].isRenderTargetTexture = true;
  2327. this.textures[ i ].renderTarget = this;
  2328. }
  2329. // ensure image object is not shared, see #20328
  2330. const image = Object.assign( {}, source.texture.image );
  2331. this.texture.source = new Source( image );
  2332. this.depthBuffer = source.depthBuffer;
  2333. this.stencilBuffer = source.stencilBuffer;
  2334. this.resolveDepthBuffer = source.resolveDepthBuffer;
  2335. this.resolveStencilBuffer = source.resolveStencilBuffer;
  2336. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  2337. this.samples = source.samples;
  2338. return this;
  2339. }
  2340. dispose() {
  2341. this.dispatchEvent( { type: 'dispose' } );
  2342. }
  2343. }
  2344. class WebGLRenderTarget extends RenderTarget {
  2345. constructor( width = 1, height = 1, options = {} ) {
  2346. super( width, height, options );
  2347. this.isWebGLRenderTarget = true;
  2348. }
  2349. }
  2350. class DataArrayTexture extends Texture {
  2351. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  2352. super( null );
  2353. this.isDataArrayTexture = true;
  2354. this.image = { data, width, height, depth };
  2355. this.magFilter = NearestFilter;
  2356. this.minFilter = NearestFilter;
  2357. this.wrapR = ClampToEdgeWrapping;
  2358. this.generateMipmaps = false;
  2359. this.flipY = false;
  2360. this.unpackAlignment = 1;
  2361. this.layerUpdates = new Set();
  2362. }
  2363. addLayerUpdate( layerIndex ) {
  2364. this.layerUpdates.add( layerIndex );
  2365. }
  2366. clearLayerUpdates() {
  2367. this.layerUpdates.clear();
  2368. }
  2369. }
  2370. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  2371. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  2372. super( width, height, options );
  2373. this.isWebGLArrayRenderTarget = true;
  2374. this.depth = depth;
  2375. this.texture = new DataArrayTexture( null, width, height, depth );
  2376. this.texture.isRenderTargetTexture = true;
  2377. }
  2378. }
  2379. class Data3DTexture extends Texture {
  2380. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  2381. // We're going to add .setXXX() methods for setting properties later.
  2382. // Users can still set in Data3DTexture directly.
  2383. //
  2384. // const texture = new THREE.Data3DTexture( data, width, height, depth );
  2385. // texture.anisotropy = 16;
  2386. //
  2387. // See #14839
  2388. super( null );
  2389. this.isData3DTexture = true;
  2390. this.image = { data, width, height, depth };
  2391. this.magFilter = NearestFilter;
  2392. this.minFilter = NearestFilter;
  2393. this.wrapR = ClampToEdgeWrapping;
  2394. this.generateMipmaps = false;
  2395. this.flipY = false;
  2396. this.unpackAlignment = 1;
  2397. }
  2398. }
  2399. class WebGL3DRenderTarget extends WebGLRenderTarget {
  2400. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  2401. super( width, height, options );
  2402. this.isWebGL3DRenderTarget = true;
  2403. this.depth = depth;
  2404. this.texture = new Data3DTexture( null, width, height, depth );
  2405. this.texture.isRenderTargetTexture = true;
  2406. }
  2407. }
  2408. class Quaternion {
  2409. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2410. this.isQuaternion = true;
  2411. this._x = x;
  2412. this._y = y;
  2413. this._z = z;
  2414. this._w = w;
  2415. }
  2416. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  2417. // fuzz-free, array-based Quaternion SLERP operation
  2418. let x0 = src0[ srcOffset0 + 0 ],
  2419. y0 = src0[ srcOffset0 + 1 ],
  2420. z0 = src0[ srcOffset0 + 2 ],
  2421. w0 = src0[ srcOffset0 + 3 ];
  2422. const x1 = src1[ srcOffset1 + 0 ],
  2423. y1 = src1[ srcOffset1 + 1 ],
  2424. z1 = src1[ srcOffset1 + 2 ],
  2425. w1 = src1[ srcOffset1 + 3 ];
  2426. if ( t === 0 ) {
  2427. dst[ dstOffset + 0 ] = x0;
  2428. dst[ dstOffset + 1 ] = y0;
  2429. dst[ dstOffset + 2 ] = z0;
  2430. dst[ dstOffset + 3 ] = w0;
  2431. return;
  2432. }
  2433. if ( t === 1 ) {
  2434. dst[ dstOffset + 0 ] = x1;
  2435. dst[ dstOffset + 1 ] = y1;
  2436. dst[ dstOffset + 2 ] = z1;
  2437. dst[ dstOffset + 3 ] = w1;
  2438. return;
  2439. }
  2440. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  2441. let s = 1 - t;
  2442. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2443. dir = ( cos >= 0 ? 1 : -1 ),
  2444. sqrSin = 1 - cos * cos;
  2445. // Skip the Slerp for tiny steps to avoid numeric problems:
  2446. if ( sqrSin > Number.EPSILON ) {
  2447. const sin = Math.sqrt( sqrSin ),
  2448. len = Math.atan2( sin, cos * dir );
  2449. s = Math.sin( s * len ) / sin;
  2450. t = Math.sin( t * len ) / sin;
  2451. }
  2452. const tDir = t * dir;
  2453. x0 = x0 * s + x1 * tDir;
  2454. y0 = y0 * s + y1 * tDir;
  2455. z0 = z0 * s + z1 * tDir;
  2456. w0 = w0 * s + w1 * tDir;
  2457. // Normalize in case we just did a lerp:
  2458. if ( s === 1 - t ) {
  2459. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2460. x0 *= f;
  2461. y0 *= f;
  2462. z0 *= f;
  2463. w0 *= f;
  2464. }
  2465. }
  2466. dst[ dstOffset ] = x0;
  2467. dst[ dstOffset + 1 ] = y0;
  2468. dst[ dstOffset + 2 ] = z0;
  2469. dst[ dstOffset + 3 ] = w0;
  2470. }
  2471. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2472. const x0 = src0[ srcOffset0 ];
  2473. const y0 = src0[ srcOffset0 + 1 ];
  2474. const z0 = src0[ srcOffset0 + 2 ];
  2475. const w0 = src0[ srcOffset0 + 3 ];
  2476. const x1 = src1[ srcOffset1 ];
  2477. const y1 = src1[ srcOffset1 + 1 ];
  2478. const z1 = src1[ srcOffset1 + 2 ];
  2479. const w1 = src1[ srcOffset1 + 3 ];
  2480. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2481. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2482. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2483. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2484. return dst;
  2485. }
  2486. get x() {
  2487. return this._x;
  2488. }
  2489. set x( value ) {
  2490. this._x = value;
  2491. this._onChangeCallback();
  2492. }
  2493. get y() {
  2494. return this._y;
  2495. }
  2496. set y( value ) {
  2497. this._y = value;
  2498. this._onChangeCallback();
  2499. }
  2500. get z() {
  2501. return this._z;
  2502. }
  2503. set z( value ) {
  2504. this._z = value;
  2505. this._onChangeCallback();
  2506. }
  2507. get w() {
  2508. return this._w;
  2509. }
  2510. set w( value ) {
  2511. this._w = value;
  2512. this._onChangeCallback();
  2513. }
  2514. set( x, y, z, w ) {
  2515. this._x = x;
  2516. this._y = y;
  2517. this._z = z;
  2518. this._w = w;
  2519. this._onChangeCallback();
  2520. return this;
  2521. }
  2522. clone() {
  2523. return new this.constructor( this._x, this._y, this._z, this._w );
  2524. }
  2525. copy( quaternion ) {
  2526. this._x = quaternion.x;
  2527. this._y = quaternion.y;
  2528. this._z = quaternion.z;
  2529. this._w = quaternion.w;
  2530. this._onChangeCallback();
  2531. return this;
  2532. }
  2533. setFromEuler( euler, update = true ) {
  2534. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2535. // http://www.mathworks.com/matlabcentral/fileexchange/
  2536. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2537. // content/SpinCalc.m
  2538. const cos = Math.cos;
  2539. const sin = Math.sin;
  2540. const c1 = cos( x / 2 );
  2541. const c2 = cos( y / 2 );
  2542. const c3 = cos( z / 2 );
  2543. const s1 = sin( x / 2 );
  2544. const s2 = sin( y / 2 );
  2545. const s3 = sin( z / 2 );
  2546. switch ( order ) {
  2547. case 'XYZ':
  2548. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2549. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2550. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2551. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2552. break;
  2553. case 'YXZ':
  2554. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2555. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2556. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2557. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2558. break;
  2559. case 'ZXY':
  2560. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2561. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2562. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2563. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2564. break;
  2565. case 'ZYX':
  2566. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2567. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2568. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2569. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2570. break;
  2571. case 'YZX':
  2572. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2573. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2574. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2575. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2576. break;
  2577. case 'XZY':
  2578. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2579. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2580. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2581. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2582. break;
  2583. default:
  2584. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2585. }
  2586. if ( update === true ) this._onChangeCallback();
  2587. return this;
  2588. }
  2589. setFromAxisAngle( axis, angle ) {
  2590. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2591. // assumes axis is normalized
  2592. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2593. this._x = axis.x * s;
  2594. this._y = axis.y * s;
  2595. this._z = axis.z * s;
  2596. this._w = Math.cos( halfAngle );
  2597. this._onChangeCallback();
  2598. return this;
  2599. }
  2600. setFromRotationMatrix( m ) {
  2601. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2602. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2603. const te = m.elements,
  2604. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2605. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2606. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2607. trace = m11 + m22 + m33;
  2608. if ( trace > 0 ) {
  2609. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2610. this._w = 0.25 / s;
  2611. this._x = ( m32 - m23 ) * s;
  2612. this._y = ( m13 - m31 ) * s;
  2613. this._z = ( m21 - m12 ) * s;
  2614. } else if ( m11 > m22 && m11 > m33 ) {
  2615. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2616. this._w = ( m32 - m23 ) / s;
  2617. this._x = 0.25 * s;
  2618. this._y = ( m12 + m21 ) / s;
  2619. this._z = ( m13 + m31 ) / s;
  2620. } else if ( m22 > m33 ) {
  2621. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2622. this._w = ( m13 - m31 ) / s;
  2623. this._x = ( m12 + m21 ) / s;
  2624. this._y = 0.25 * s;
  2625. this._z = ( m23 + m32 ) / s;
  2626. } else {
  2627. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2628. this._w = ( m21 - m12 ) / s;
  2629. this._x = ( m13 + m31 ) / s;
  2630. this._y = ( m23 + m32 ) / s;
  2631. this._z = 0.25 * s;
  2632. }
  2633. this._onChangeCallback();
  2634. return this;
  2635. }
  2636. setFromUnitVectors( vFrom, vTo ) {
  2637. // assumes direction vectors vFrom and vTo are normalized
  2638. let r = vFrom.dot( vTo ) + 1;
  2639. if ( r < Number.EPSILON ) {
  2640. // vFrom and vTo point in opposite directions
  2641. r = 0;
  2642. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2643. this._x = - vFrom.y;
  2644. this._y = vFrom.x;
  2645. this._z = 0;
  2646. this._w = r;
  2647. } else {
  2648. this._x = 0;
  2649. this._y = - vFrom.z;
  2650. this._z = vFrom.y;
  2651. this._w = r;
  2652. }
  2653. } else {
  2654. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2655. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2656. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2657. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2658. this._w = r;
  2659. }
  2660. return this.normalize();
  2661. }
  2662. angleTo( q ) {
  2663. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), -1, 1 ) ) );
  2664. }
  2665. rotateTowards( q, step ) {
  2666. const angle = this.angleTo( q );
  2667. if ( angle === 0 ) return this;
  2668. const t = Math.min( 1, step / angle );
  2669. this.slerp( q, t );
  2670. return this;
  2671. }
  2672. identity() {
  2673. return this.set( 0, 0, 0, 1 );
  2674. }
  2675. invert() {
  2676. // quaternion is assumed to have unit length
  2677. return this.conjugate();
  2678. }
  2679. conjugate() {
  2680. this._x *= -1;
  2681. this._y *= -1;
  2682. this._z *= -1;
  2683. this._onChangeCallback();
  2684. return this;
  2685. }
  2686. dot( v ) {
  2687. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2688. }
  2689. lengthSq() {
  2690. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2691. }
  2692. length() {
  2693. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2694. }
  2695. normalize() {
  2696. let l = this.length();
  2697. if ( l === 0 ) {
  2698. this._x = 0;
  2699. this._y = 0;
  2700. this._z = 0;
  2701. this._w = 1;
  2702. } else {
  2703. l = 1 / l;
  2704. this._x = this._x * l;
  2705. this._y = this._y * l;
  2706. this._z = this._z * l;
  2707. this._w = this._w * l;
  2708. }
  2709. this._onChangeCallback();
  2710. return this;
  2711. }
  2712. multiply( q ) {
  2713. return this.multiplyQuaternions( this, q );
  2714. }
  2715. premultiply( q ) {
  2716. return this.multiplyQuaternions( q, this );
  2717. }
  2718. multiplyQuaternions( a, b ) {
  2719. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2720. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2721. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2722. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2723. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2724. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2725. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2726. this._onChangeCallback();
  2727. return this;
  2728. }
  2729. slerp( qb, t ) {
  2730. if ( t === 0 ) return this;
  2731. if ( t === 1 ) return this.copy( qb );
  2732. const x = this._x, y = this._y, z = this._z, w = this._w;
  2733. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2734. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2735. if ( cosHalfTheta < 0 ) {
  2736. this._w = - qb._w;
  2737. this._x = - qb._x;
  2738. this._y = - qb._y;
  2739. this._z = - qb._z;
  2740. cosHalfTheta = - cosHalfTheta;
  2741. } else {
  2742. this.copy( qb );
  2743. }
  2744. if ( cosHalfTheta >= 1.0 ) {
  2745. this._w = w;
  2746. this._x = x;
  2747. this._y = y;
  2748. this._z = z;
  2749. return this;
  2750. }
  2751. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2752. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2753. const s = 1 - t;
  2754. this._w = s * w + t * this._w;
  2755. this._x = s * x + t * this._x;
  2756. this._y = s * y + t * this._y;
  2757. this._z = s * z + t * this._z;
  2758. this.normalize(); // normalize calls _onChangeCallback()
  2759. return this;
  2760. }
  2761. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2762. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2763. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2764. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2765. this._w = ( w * ratioA + this._w * ratioB );
  2766. this._x = ( x * ratioA + this._x * ratioB );
  2767. this._y = ( y * ratioA + this._y * ratioB );
  2768. this._z = ( z * ratioA + this._z * ratioB );
  2769. this._onChangeCallback();
  2770. return this;
  2771. }
  2772. slerpQuaternions( qa, qb, t ) {
  2773. return this.copy( qa ).slerp( qb, t );
  2774. }
  2775. random() {
  2776. // sets this quaternion to a uniform random unit quaternnion
  2777. // Ken Shoemake
  2778. // Uniform random rotations
  2779. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  2780. const theta1 = 2 * Math.PI * Math.random();
  2781. const theta2 = 2 * Math.PI * Math.random();
  2782. const x0 = Math.random();
  2783. const r1 = Math.sqrt( 1 - x0 );
  2784. const r2 = Math.sqrt( x0 );
  2785. return this.set(
  2786. r1 * Math.sin( theta1 ),
  2787. r1 * Math.cos( theta1 ),
  2788. r2 * Math.sin( theta2 ),
  2789. r2 * Math.cos( theta2 ),
  2790. );
  2791. }
  2792. equals( quaternion ) {
  2793. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2794. }
  2795. fromArray( array, offset = 0 ) {
  2796. this._x = array[ offset ];
  2797. this._y = array[ offset + 1 ];
  2798. this._z = array[ offset + 2 ];
  2799. this._w = array[ offset + 3 ];
  2800. this._onChangeCallback();
  2801. return this;
  2802. }
  2803. toArray( array = [], offset = 0 ) {
  2804. array[ offset ] = this._x;
  2805. array[ offset + 1 ] = this._y;
  2806. array[ offset + 2 ] = this._z;
  2807. array[ offset + 3 ] = this._w;
  2808. return array;
  2809. }
  2810. fromBufferAttribute( attribute, index ) {
  2811. this._x = attribute.getX( index );
  2812. this._y = attribute.getY( index );
  2813. this._z = attribute.getZ( index );
  2814. this._w = attribute.getW( index );
  2815. this._onChangeCallback();
  2816. return this;
  2817. }
  2818. toJSON() {
  2819. return this.toArray();
  2820. }
  2821. _onChange( callback ) {
  2822. this._onChangeCallback = callback;
  2823. return this;
  2824. }
  2825. _onChangeCallback() {}
  2826. *[ Symbol.iterator ]() {
  2827. yield this._x;
  2828. yield this._y;
  2829. yield this._z;
  2830. yield this._w;
  2831. }
  2832. }
  2833. class Vector3 {
  2834. constructor( x = 0, y = 0, z = 0 ) {
  2835. Vector3.prototype.isVector3 = true;
  2836. this.x = x;
  2837. this.y = y;
  2838. this.z = z;
  2839. }
  2840. set( x, y, z ) {
  2841. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2842. this.x = x;
  2843. this.y = y;
  2844. this.z = z;
  2845. return this;
  2846. }
  2847. setScalar( scalar ) {
  2848. this.x = scalar;
  2849. this.y = scalar;
  2850. this.z = scalar;
  2851. return this;
  2852. }
  2853. setX( x ) {
  2854. this.x = x;
  2855. return this;
  2856. }
  2857. setY( y ) {
  2858. this.y = y;
  2859. return this;
  2860. }
  2861. setZ( z ) {
  2862. this.z = z;
  2863. return this;
  2864. }
  2865. setComponent( index, value ) {
  2866. switch ( index ) {
  2867. case 0: this.x = value; break;
  2868. case 1: this.y = value; break;
  2869. case 2: this.z = value; break;
  2870. default: throw new Error( 'index is out of range: ' + index );
  2871. }
  2872. return this;
  2873. }
  2874. getComponent( index ) {
  2875. switch ( index ) {
  2876. case 0: return this.x;
  2877. case 1: return this.y;
  2878. case 2: return this.z;
  2879. default: throw new Error( 'index is out of range: ' + index );
  2880. }
  2881. }
  2882. clone() {
  2883. return new this.constructor( this.x, this.y, this.z );
  2884. }
  2885. copy( v ) {
  2886. this.x = v.x;
  2887. this.y = v.y;
  2888. this.z = v.z;
  2889. return this;
  2890. }
  2891. add( v ) {
  2892. this.x += v.x;
  2893. this.y += v.y;
  2894. this.z += v.z;
  2895. return this;
  2896. }
  2897. addScalar( s ) {
  2898. this.x += s;
  2899. this.y += s;
  2900. this.z += s;
  2901. return this;
  2902. }
  2903. addVectors( a, b ) {
  2904. this.x = a.x + b.x;
  2905. this.y = a.y + b.y;
  2906. this.z = a.z + b.z;
  2907. return this;
  2908. }
  2909. addScaledVector( v, s ) {
  2910. this.x += v.x * s;
  2911. this.y += v.y * s;
  2912. this.z += v.z * s;
  2913. return this;
  2914. }
  2915. sub( v ) {
  2916. this.x -= v.x;
  2917. this.y -= v.y;
  2918. this.z -= v.z;
  2919. return this;
  2920. }
  2921. subScalar( s ) {
  2922. this.x -= s;
  2923. this.y -= s;
  2924. this.z -= s;
  2925. return this;
  2926. }
  2927. subVectors( a, b ) {
  2928. this.x = a.x - b.x;
  2929. this.y = a.y - b.y;
  2930. this.z = a.z - b.z;
  2931. return this;
  2932. }
  2933. multiply( v ) {
  2934. this.x *= v.x;
  2935. this.y *= v.y;
  2936. this.z *= v.z;
  2937. return this;
  2938. }
  2939. multiplyScalar( scalar ) {
  2940. this.x *= scalar;
  2941. this.y *= scalar;
  2942. this.z *= scalar;
  2943. return this;
  2944. }
  2945. multiplyVectors( a, b ) {
  2946. this.x = a.x * b.x;
  2947. this.y = a.y * b.y;
  2948. this.z = a.z * b.z;
  2949. return this;
  2950. }
  2951. applyEuler( euler ) {
  2952. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2953. }
  2954. applyAxisAngle( axis, angle ) {
  2955. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2956. }
  2957. applyMatrix3( m ) {
  2958. const x = this.x, y = this.y, z = this.z;
  2959. const e = m.elements;
  2960. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2961. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2962. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2963. return this;
  2964. }
  2965. applyNormalMatrix( m ) {
  2966. return this.applyMatrix3( m ).normalize();
  2967. }
  2968. applyMatrix4( m ) {
  2969. const x = this.x, y = this.y, z = this.z;
  2970. const e = m.elements;
  2971. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2972. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2973. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2974. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2975. return this;
  2976. }
  2977. applyQuaternion( q ) {
  2978. // quaternion q is assumed to have unit length
  2979. const vx = this.x, vy = this.y, vz = this.z;
  2980. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2981. // t = 2 * cross( q.xyz, v );
  2982. const tx = 2 * ( qy * vz - qz * vy );
  2983. const ty = 2 * ( qz * vx - qx * vz );
  2984. const tz = 2 * ( qx * vy - qy * vx );
  2985. // v + q.w * t + cross( q.xyz, t );
  2986. this.x = vx + qw * tx + qy * tz - qz * ty;
  2987. this.y = vy + qw * ty + qz * tx - qx * tz;
  2988. this.z = vz + qw * tz + qx * ty - qy * tx;
  2989. return this;
  2990. }
  2991. project( camera ) {
  2992. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2993. }
  2994. unproject( camera ) {
  2995. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2996. }
  2997. transformDirection( m ) {
  2998. // input: THREE.Matrix4 affine matrix
  2999. // vector interpreted as a direction
  3000. const x = this.x, y = this.y, z = this.z;
  3001. const e = m.elements;
  3002. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  3003. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  3004. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  3005. return this.normalize();
  3006. }
  3007. divide( v ) {
  3008. this.x /= v.x;
  3009. this.y /= v.y;
  3010. this.z /= v.z;
  3011. return this;
  3012. }
  3013. divideScalar( scalar ) {
  3014. return this.multiplyScalar( 1 / scalar );
  3015. }
  3016. min( v ) {
  3017. this.x = Math.min( this.x, v.x );
  3018. this.y = Math.min( this.y, v.y );
  3019. this.z = Math.min( this.z, v.z );
  3020. return this;
  3021. }
  3022. max( v ) {
  3023. this.x = Math.max( this.x, v.x );
  3024. this.y = Math.max( this.y, v.y );
  3025. this.z = Math.max( this.z, v.z );
  3026. return this;
  3027. }
  3028. clamp( min, max ) {
  3029. // assumes min < max, componentwise
  3030. this.x = clamp( this.x, min.x, max.x );
  3031. this.y = clamp( this.y, min.y, max.y );
  3032. this.z = clamp( this.z, min.z, max.z );
  3033. return this;
  3034. }
  3035. clampScalar( minVal, maxVal ) {
  3036. this.x = clamp( this.x, minVal, maxVal );
  3037. this.y = clamp( this.y, minVal, maxVal );
  3038. this.z = clamp( this.z, minVal, maxVal );
  3039. return this;
  3040. }
  3041. clampLength( min, max ) {
  3042. const length = this.length();
  3043. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  3044. }
  3045. floor() {
  3046. this.x = Math.floor( this.x );
  3047. this.y = Math.floor( this.y );
  3048. this.z = Math.floor( this.z );
  3049. return this;
  3050. }
  3051. ceil() {
  3052. this.x = Math.ceil( this.x );
  3053. this.y = Math.ceil( this.y );
  3054. this.z = Math.ceil( this.z );
  3055. return this;
  3056. }
  3057. round() {
  3058. this.x = Math.round( this.x );
  3059. this.y = Math.round( this.y );
  3060. this.z = Math.round( this.z );
  3061. return this;
  3062. }
  3063. roundToZero() {
  3064. this.x = Math.trunc( this.x );
  3065. this.y = Math.trunc( this.y );
  3066. this.z = Math.trunc( this.z );
  3067. return this;
  3068. }
  3069. negate() {
  3070. this.x = - this.x;
  3071. this.y = - this.y;
  3072. this.z = - this.z;
  3073. return this;
  3074. }
  3075. dot( v ) {
  3076. return this.x * v.x + this.y * v.y + this.z * v.z;
  3077. }
  3078. // TODO lengthSquared?
  3079. lengthSq() {
  3080. return this.x * this.x + this.y * this.y + this.z * this.z;
  3081. }
  3082. length() {
  3083. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  3084. }
  3085. manhattanLength() {
  3086. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  3087. }
  3088. normalize() {
  3089. return this.divideScalar( this.length() || 1 );
  3090. }
  3091. setLength( length ) {
  3092. return this.normalize().multiplyScalar( length );
  3093. }
  3094. lerp( v, alpha ) {
  3095. this.x += ( v.x - this.x ) * alpha;
  3096. this.y += ( v.y - this.y ) * alpha;
  3097. this.z += ( v.z - this.z ) * alpha;
  3098. return this;
  3099. }
  3100. lerpVectors( v1, v2, alpha ) {
  3101. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  3102. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  3103. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  3104. return this;
  3105. }
  3106. cross( v ) {
  3107. return this.crossVectors( this, v );
  3108. }
  3109. crossVectors( a, b ) {
  3110. const ax = a.x, ay = a.y, az = a.z;
  3111. const bx = b.x, by = b.y, bz = b.z;
  3112. this.x = ay * bz - az * by;
  3113. this.y = az * bx - ax * bz;
  3114. this.z = ax * by - ay * bx;
  3115. return this;
  3116. }
  3117. projectOnVector( v ) {
  3118. const denominator = v.lengthSq();
  3119. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  3120. const scalar = v.dot( this ) / denominator;
  3121. return this.copy( v ).multiplyScalar( scalar );
  3122. }
  3123. projectOnPlane( planeNormal ) {
  3124. _vector$c.copy( this ).projectOnVector( planeNormal );
  3125. return this.sub( _vector$c );
  3126. }
  3127. reflect( normal ) {
  3128. // reflect incident vector off plane orthogonal to normal
  3129. // normal is assumed to have unit length
  3130. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  3131. }
  3132. angleTo( v ) {
  3133. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  3134. if ( denominator === 0 ) return Math.PI / 2;
  3135. const theta = this.dot( v ) / denominator;
  3136. // clamp, to handle numerical problems
  3137. return Math.acos( clamp( theta, -1, 1 ) );
  3138. }
  3139. distanceTo( v ) {
  3140. return Math.sqrt( this.distanceToSquared( v ) );
  3141. }
  3142. distanceToSquared( v ) {
  3143. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  3144. return dx * dx + dy * dy + dz * dz;
  3145. }
  3146. manhattanDistanceTo( v ) {
  3147. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  3148. }
  3149. setFromSpherical( s ) {
  3150. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  3151. }
  3152. setFromSphericalCoords( radius, phi, theta ) {
  3153. const sinPhiRadius = Math.sin( phi ) * radius;
  3154. this.x = sinPhiRadius * Math.sin( theta );
  3155. this.y = Math.cos( phi ) * radius;
  3156. this.z = sinPhiRadius * Math.cos( theta );
  3157. return this;
  3158. }
  3159. setFromCylindrical( c ) {
  3160. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  3161. }
  3162. setFromCylindricalCoords( radius, theta, y ) {
  3163. this.x = radius * Math.sin( theta );
  3164. this.y = y;
  3165. this.z = radius * Math.cos( theta );
  3166. return this;
  3167. }
  3168. setFromMatrixPosition( m ) {
  3169. const e = m.elements;
  3170. this.x = e[ 12 ];
  3171. this.y = e[ 13 ];
  3172. this.z = e[ 14 ];
  3173. return this;
  3174. }
  3175. setFromMatrixScale( m ) {
  3176. const sx = this.setFromMatrixColumn( m, 0 ).length();
  3177. const sy = this.setFromMatrixColumn( m, 1 ).length();
  3178. const sz = this.setFromMatrixColumn( m, 2 ).length();
  3179. this.x = sx;
  3180. this.y = sy;
  3181. this.z = sz;
  3182. return this;
  3183. }
  3184. setFromMatrixColumn( m, index ) {
  3185. return this.fromArray( m.elements, index * 4 );
  3186. }
  3187. setFromMatrix3Column( m, index ) {
  3188. return this.fromArray( m.elements, index * 3 );
  3189. }
  3190. setFromEuler( e ) {
  3191. this.x = e._x;
  3192. this.y = e._y;
  3193. this.z = e._z;
  3194. return this;
  3195. }
  3196. setFromColor( c ) {
  3197. this.x = c.r;
  3198. this.y = c.g;
  3199. this.z = c.b;
  3200. return this;
  3201. }
  3202. equals( v ) {
  3203. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  3204. }
  3205. fromArray( array, offset = 0 ) {
  3206. this.x = array[ offset ];
  3207. this.y = array[ offset + 1 ];
  3208. this.z = array[ offset + 2 ];
  3209. return this;
  3210. }
  3211. toArray( array = [], offset = 0 ) {
  3212. array[ offset ] = this.x;
  3213. array[ offset + 1 ] = this.y;
  3214. array[ offset + 2 ] = this.z;
  3215. return array;
  3216. }
  3217. fromBufferAttribute( attribute, index ) {
  3218. this.x = attribute.getX( index );
  3219. this.y = attribute.getY( index );
  3220. this.z = attribute.getZ( index );
  3221. return this;
  3222. }
  3223. random() {
  3224. this.x = Math.random();
  3225. this.y = Math.random();
  3226. this.z = Math.random();
  3227. return this;
  3228. }
  3229. randomDirection() {
  3230. // https://mathworld.wolfram.com/SpherePointPicking.html
  3231. const theta = Math.random() * Math.PI * 2;
  3232. const u = Math.random() * 2 - 1;
  3233. const c = Math.sqrt( 1 - u * u );
  3234. this.x = c * Math.cos( theta );
  3235. this.y = u;
  3236. this.z = c * Math.sin( theta );
  3237. return this;
  3238. }
  3239. *[ Symbol.iterator ]() {
  3240. yield this.x;
  3241. yield this.y;
  3242. yield this.z;
  3243. }
  3244. }
  3245. const _vector$c = /*@__PURE__*/ new Vector3();
  3246. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  3247. /**
  3248. * Represents an axis-aligned bounding box (AABB) in 3D space.
  3249. */
  3250. class Box3 {
  3251. /**
  3252. * Constructs a new bounding box.
  3253. *
  3254. * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box.
  3255. * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  3256. */
  3257. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  3258. /**
  3259. * This flag can be used for type testing.
  3260. *
  3261. * @type {boolean}
  3262. * @readonly
  3263. * @default true
  3264. */
  3265. this.isBox3 = true;
  3266. /**
  3267. * The lower boundary of the box.
  3268. *
  3269. * @type {Vector3}
  3270. */
  3271. this.min = min;
  3272. /**
  3273. * The upper boundary of the box.
  3274. *
  3275. * @type {Vector3}
  3276. */
  3277. this.max = max;
  3278. }
  3279. /**
  3280. * Sets the lower and upper boundaries of this box.
  3281. * Please note that this method only copies the values from the given objects.
  3282. *
  3283. * @param {Vector3} min - The lower boundary of the box.
  3284. * @param {Vector3} max - The upper boundary of the box.
  3285. * @return {Box3} A reference to this bounding box.
  3286. */
  3287. set( min, max ) {
  3288. this.min.copy( min );
  3289. this.max.copy( max );
  3290. return this;
  3291. }
  3292. /**
  3293. * Sets the upper and lower bounds of this box so it encloses the position data
  3294. * in the given array.
  3295. *
  3296. * @param {Array<number>} array - An array holding 3D position data.
  3297. * @return {Box3} A reference to this bounding box.
  3298. */
  3299. setFromArray( array ) {
  3300. this.makeEmpty();
  3301. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  3302. this.expandByPoint( _vector$b.fromArray( array, i ) );
  3303. }
  3304. return this;
  3305. }
  3306. /**
  3307. * Sets the upper and lower bounds of this box so it encloses the position data
  3308. * in the given buffer attribute.
  3309. *
  3310. * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data.
  3311. * @return {Box3} A reference to this bounding box.
  3312. */
  3313. setFromBufferAttribute( attribute ) {
  3314. this.makeEmpty();
  3315. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  3316. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  3317. }
  3318. return this;
  3319. }
  3320. /**
  3321. * Sets the upper and lower bounds of this box so it encloses the position data
  3322. * in the given array.
  3323. *
  3324. * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}.
  3325. * @return {Box3} A reference to this bounding box.
  3326. */
  3327. setFromPoints( points ) {
  3328. this.makeEmpty();
  3329. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3330. this.expandByPoint( points[ i ] );
  3331. }
  3332. return this;
  3333. }
  3334. /**
  3335. * Centers this box on the given center vector and sets this box's width, height and
  3336. * depth to the given size values.
  3337. *
  3338. * @param {Vector3} center - The center of the box.
  3339. * @param {Vector3} size - The x, y and z dimensions of the box.
  3340. * @return {Box3} A reference to this bounding box.
  3341. */
  3342. setFromCenterAndSize( center, size ) {
  3343. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  3344. this.min.copy( center ).sub( halfSize );
  3345. this.max.copy( center ).add( halfSize );
  3346. return this;
  3347. }
  3348. /**
  3349. * Computes the world-axis-aligned bounding box for the given 3D object
  3350. * (including its children), accounting for the object's, and children's,
  3351. * world transforms. The function may result in a larger box than strictly necessary.
  3352. *
  3353. * @param {Object3D} object - The 3D object to compute the bounding box for.
  3354. * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest
  3355. * world-axis-aligned bounding box at the expense of more computation.
  3356. * @return {Box3} A reference to this bounding box.
  3357. */
  3358. setFromObject( object, precise = false ) {
  3359. this.makeEmpty();
  3360. return this.expandByObject( object, precise );
  3361. }
  3362. /**
  3363. * Returns a new box with copied values from this instance.
  3364. *
  3365. * @return {Box3} A clone of this instance.
  3366. */
  3367. clone() {
  3368. return new this.constructor().copy( this );
  3369. }
  3370. /**
  3371. * Copies the values of the given box to this instance.
  3372. *
  3373. * @param {Box3} box - The box to copy.
  3374. * @return {Box3} A reference to this bounding box.
  3375. */
  3376. copy( box ) {
  3377. this.min.copy( box.min );
  3378. this.max.copy( box.max );
  3379. return this;
  3380. }
  3381. /**
  3382. * Makes this box empty which means in encloses a zero space in 3D.
  3383. *
  3384. * @return {Box3} A reference to this bounding box.
  3385. */
  3386. makeEmpty() {
  3387. this.min.x = this.min.y = this.min.z = + Infinity;
  3388. this.max.x = this.max.y = this.max.z = - Infinity;
  3389. return this;
  3390. }
  3391. /**
  3392. * Returns true if this box includes zero points within its bounds.
  3393. * Note that a box with equal lower and upper bounds still includes one
  3394. * point, the one both bounds share.
  3395. *
  3396. * @return {boolean} Whether this box is empty or not.
  3397. */
  3398. isEmpty() {
  3399. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3400. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  3401. }
  3402. /**
  3403. * Returns the center point of this box.
  3404. *
  3405. * @param {Vector3} target - The target vector that is used to store the method's result.
  3406. * @return {Vector3} The center point.
  3407. */
  3408. getCenter( target ) {
  3409. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  3410. }
  3411. /**
  3412. * Returns the dimensions of this box.
  3413. *
  3414. * @param {Vector3} target - The target vector that is used to store the method's result.
  3415. * @return {Vector3} The size.
  3416. */
  3417. getSize( target ) {
  3418. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  3419. }
  3420. /**
  3421. * Expands the boundaries of this box to include the given point.
  3422. *
  3423. * @param {Vector3} point - The point that should be included by the bounding box.
  3424. * @return {Box3} A reference to this bounding box.
  3425. */
  3426. expandByPoint( point ) {
  3427. this.min.min( point );
  3428. this.max.max( point );
  3429. return this;
  3430. }
  3431. /**
  3432. * Expands this box equilaterally by the given vector. The width of this
  3433. * box will be expanded by the x component of the vector in both
  3434. * directions. The height of this box will be expanded by the y component of
  3435. * the vector in both directions. The depth of this box will be
  3436. * expanded by the z component of the vector in both directions.
  3437. *
  3438. * @param {Vector3} vector - The vector that should expand the bounding box.
  3439. * @return {Box3} A reference to this bounding box.
  3440. */
  3441. expandByVector( vector ) {
  3442. this.min.sub( vector );
  3443. this.max.add( vector );
  3444. return this;
  3445. }
  3446. /**
  3447. * Expands each dimension of the box by the given scalar. If negative, the
  3448. * dimensions of the box will be contracted.
  3449. *
  3450. * @param {number} scalar - The scalar value that should expand the bounding box.
  3451. * @return {Box3} A reference to this bounding box.
  3452. */
  3453. expandByScalar( scalar ) {
  3454. this.min.addScalar( - scalar );
  3455. this.max.addScalar( scalar );
  3456. return this;
  3457. }
  3458. /**
  3459. * Expands the boundaries of this box to include the given 3D object and
  3460. * its children, accounting for the object's, and children's, world
  3461. * transforms. The function may result in a larger box than strictly
  3462. * necessary (unless the precise parameter is set to true).
  3463. *
  3464. * @param {Object3D} object - The 3D object that should expand the bounding box.
  3465. * @param {boolean} precise - If set to `true`, the method expands the bounding box
  3466. * as little as necessary at the expense of more computation.
  3467. * @return {Box3} A reference to this bounding box.
  3468. */
  3469. expandByObject( object, precise = false ) {
  3470. // Computes the world-axis-aligned bounding box of an object (including its children),
  3471. // accounting for both the object's, and children's, world transforms
  3472. object.updateWorldMatrix( false, false );
  3473. const geometry = object.geometry;
  3474. if ( geometry !== undefined ) {
  3475. const positionAttribute = geometry.getAttribute( 'position' );
  3476. // precise AABB computation based on vertex data requires at least a position attribute.
  3477. // instancing isn't supported so far and uses the normal (conservative) code path.
  3478. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  3479. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  3480. if ( object.isMesh === true ) {
  3481. object.getVertexPosition( i, _vector$b );
  3482. } else {
  3483. _vector$b.fromBufferAttribute( positionAttribute, i );
  3484. }
  3485. _vector$b.applyMatrix4( object.matrixWorld );
  3486. this.expandByPoint( _vector$b );
  3487. }
  3488. } else {
  3489. if ( object.boundingBox !== undefined ) {
  3490. // object-level bounding box
  3491. if ( object.boundingBox === null ) {
  3492. object.computeBoundingBox();
  3493. }
  3494. _box$4.copy( object.boundingBox );
  3495. } else {
  3496. // geometry-level bounding box
  3497. if ( geometry.boundingBox === null ) {
  3498. geometry.computeBoundingBox();
  3499. }
  3500. _box$4.copy( geometry.boundingBox );
  3501. }
  3502. _box$4.applyMatrix4( object.matrixWorld );
  3503. this.union( _box$4 );
  3504. }
  3505. }
  3506. const children = object.children;
  3507. for ( let i = 0, l = children.length; i < l; i ++ ) {
  3508. this.expandByObject( children[ i ], precise );
  3509. }
  3510. return this;
  3511. }
  3512. /**
  3513. * Returns `true` if the given point lies within or on the boundaries of this box.
  3514. *
  3515. * @param {Vector3} point - The point to test.
  3516. * @return {boolean} Whether the bounding box contains the given point or not.
  3517. */
  3518. containsPoint( point ) {
  3519. return point.x >= this.min.x && point.x <= this.max.x &&
  3520. point.y >= this.min.y && point.y <= this.max.y &&
  3521. point.z >= this.min.z && point.z <= this.max.z;
  3522. }
  3523. /**
  3524. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  3525. * If this box and the given one are identical, this function also returns `true`.
  3526. *
  3527. * @param {Box3} box - The bounding box to test.
  3528. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  3529. */
  3530. containsBox( box ) {
  3531. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  3532. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  3533. this.min.z <= box.min.z && box.max.z <= this.max.z;
  3534. }
  3535. /**
  3536. * Returns a point as a proportion of this box's width, height and depth.
  3537. *
  3538. * @param {Vector3} point - A point in 3D space.
  3539. * @param {Vector3} target - The target vector that is used to store the method's result.
  3540. * @return {Vector3} A point as a proportion of this box's width, height and depth.
  3541. */
  3542. getParameter( point, target ) {
  3543. // This can potentially have a divide by zero if the box
  3544. // has a size dimension of 0.
  3545. return target.set(
  3546. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  3547. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  3548. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  3549. );
  3550. }
  3551. /**
  3552. * Returns `true` if the given bounding box intersects with this bounding box.
  3553. *
  3554. * @param {Box3} box - The bounding box to test.
  3555. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  3556. */
  3557. intersectsBox( box ) {
  3558. // using 6 splitting planes to rule out intersections.
  3559. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  3560. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  3561. box.max.z >= this.min.z && box.min.z <= this.max.z;
  3562. }
  3563. /**
  3564. * Returns `true` if the given bounding sphere intersects with this bounding box.
  3565. *
  3566. * @param {Sphere} sphere - The bounding sphere to test.
  3567. * @return {boolean} Whether the given bounding sphere intersects with this bounding box.
  3568. */
  3569. intersectsSphere( sphere ) {
  3570. // Find the point on the AABB closest to the sphere center.
  3571. this.clampPoint( sphere.center, _vector$b );
  3572. // If that point is inside the sphere, the AABB and sphere intersect.
  3573. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  3574. }
  3575. /**
  3576. * Returns `true` if the given plane intersects with this bounding box.
  3577. *
  3578. * @param {Plane} plane - The plane to test.
  3579. * @return {boolean} Whether the given plane intersects with this bounding box.
  3580. */
  3581. intersectsPlane( plane ) {
  3582. // We compute the minimum and maximum dot product values. If those values
  3583. // are on the same side (back or front) of the plane, then there is no intersection.
  3584. let min, max;
  3585. if ( plane.normal.x > 0 ) {
  3586. min = plane.normal.x * this.min.x;
  3587. max = plane.normal.x * this.max.x;
  3588. } else {
  3589. min = plane.normal.x * this.max.x;
  3590. max = plane.normal.x * this.min.x;
  3591. }
  3592. if ( plane.normal.y > 0 ) {
  3593. min += plane.normal.y * this.min.y;
  3594. max += plane.normal.y * this.max.y;
  3595. } else {
  3596. min += plane.normal.y * this.max.y;
  3597. max += plane.normal.y * this.min.y;
  3598. }
  3599. if ( plane.normal.z > 0 ) {
  3600. min += plane.normal.z * this.min.z;
  3601. max += plane.normal.z * this.max.z;
  3602. } else {
  3603. min += plane.normal.z * this.max.z;
  3604. max += plane.normal.z * this.min.z;
  3605. }
  3606. return ( min <= - plane.constant && max >= - plane.constant );
  3607. }
  3608. /**
  3609. * Returns `true` if the given triangle intersects with this bounding box.
  3610. *
  3611. * @param {Triangle} triangle - The triangle to test.
  3612. * @return {boolean} Whether the given triangle intersects with this bounding box.
  3613. */
  3614. intersectsTriangle( triangle ) {
  3615. if ( this.isEmpty() ) {
  3616. return false;
  3617. }
  3618. // compute box center and extents
  3619. this.getCenter( _center );
  3620. _extents.subVectors( this.max, _center );
  3621. // translate triangle to aabb origin
  3622. _v0$2.subVectors( triangle.a, _center );
  3623. _v1$7.subVectors( triangle.b, _center );
  3624. _v2$4.subVectors( triangle.c, _center );
  3625. // compute edge vectors for triangle
  3626. _f0.subVectors( _v1$7, _v0$2 );
  3627. _f1.subVectors( _v2$4, _v1$7 );
  3628. _f2.subVectors( _v0$2, _v2$4 );
  3629. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  3630. // 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
  3631. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  3632. let axes = [
  3633. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  3634. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  3635. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  3636. ];
  3637. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  3638. return false;
  3639. }
  3640. // test 3 face normals from the aabb
  3641. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  3642. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  3643. return false;
  3644. }
  3645. // finally testing the face normal of the triangle
  3646. // use already existing triangle edge vectors here
  3647. _triangleNormal.crossVectors( _f0, _f1 );
  3648. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  3649. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  3650. }
  3651. /**
  3652. * Clamps the given point within the bounds of this box.
  3653. *
  3654. * @param {Vector3} point - The point to clamp.
  3655. * @param {Vector3} target - The target vector that is used to store the method's result.
  3656. * @return {Vector3} The clamped point.
  3657. */
  3658. clampPoint( point, target ) {
  3659. return target.copy( point ).clamp( this.min, this.max );
  3660. }
  3661. /**
  3662. * Returns the euclidean distance from any edge of this box to the specified point. If
  3663. * the given point lies inside of this box, the distance will be `0`.
  3664. *
  3665. * @param {Vector3} point - The point to compute the distance to.
  3666. * @return {number} The euclidean distance.
  3667. */
  3668. distanceToPoint( point ) {
  3669. return this.clampPoint( point, _vector$b ).distanceTo( point );
  3670. }
  3671. /**
  3672. * Returns a bounding sphere that encloses this bounding box.
  3673. *
  3674. * @param {Sphere} target - The target sphere that is used to store the method's result.
  3675. * @return {Sphere} The bounding sphere that encloses this bounding box.
  3676. */
  3677. getBoundingSphere( target ) {
  3678. if ( this.isEmpty() ) {
  3679. target.makeEmpty();
  3680. } else {
  3681. this.getCenter( target.center );
  3682. target.radius = this.getSize( _vector$b ).length() * 0.5;
  3683. }
  3684. return target;
  3685. }
  3686. /**
  3687. * Computes the intersection of this bounding box and the given one, setting the upper
  3688. * bound of this box to the lesser of the two boxes' upper bounds and the
  3689. * lower bound of this box to the greater of the two boxes' lower bounds. If
  3690. * there's no overlap, makes this box empty.
  3691. *
  3692. * @param {Box3} box - The bounding box to intersect with.
  3693. * @return {Box3} A reference to this bounding box.
  3694. */
  3695. intersect( box ) {
  3696. this.min.max( box.min );
  3697. this.max.min( box.max );
  3698. // 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.
  3699. if ( this.isEmpty() ) this.makeEmpty();
  3700. return this;
  3701. }
  3702. /**
  3703. * Computes the union of this box and another and the given one, setting the upper
  3704. * bound of this box to the greater of the two boxes' upper bounds and the
  3705. * lower bound of this box to the lesser of the two boxes' lower bounds.
  3706. *
  3707. * @param {Box3} box - The bounding box that will be unioned with this instance.
  3708. * @return {Box3} A reference to this bounding box.
  3709. */
  3710. union( box ) {
  3711. this.min.min( box.min );
  3712. this.max.max( box.max );
  3713. return this;
  3714. }
  3715. /**
  3716. * Transforms this bounding box by the given 4x4 transformation matrix.
  3717. *
  3718. * @param {Matrix4} matrix - The transformation matrix.
  3719. * @return {Box3} A reference to this bounding box.
  3720. */
  3721. applyMatrix4( matrix ) {
  3722. // transform of empty box is an empty box.
  3723. if ( this.isEmpty() ) return this;
  3724. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3725. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3726. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3727. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3728. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3729. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3730. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3731. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3732. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3733. this.setFromPoints( _points );
  3734. return this;
  3735. }
  3736. /**
  3737. * Adds the given offset to both the upper and lower bounds of this bounding box,
  3738. * effectively moving it in 3D space.
  3739. *
  3740. * @param {Vector3} offset - The offset that should be used to translate the bounding box.
  3741. * @return {Box3} A reference to this bounding box.
  3742. */
  3743. translate( offset ) {
  3744. this.min.add( offset );
  3745. this.max.add( offset );
  3746. return this;
  3747. }
  3748. /**
  3749. * Returns `true` if this bounding box is equal with the given one.
  3750. *
  3751. * @param {Box3} box - The box to test for equality.
  3752. * @return {boolean} Whether this bounding box is equal with the given one.
  3753. */
  3754. equals( box ) {
  3755. return box.min.equals( this.min ) && box.max.equals( this.max );
  3756. }
  3757. }
  3758. const _points = [
  3759. /*@__PURE__*/ new Vector3(),
  3760. /*@__PURE__*/ new Vector3(),
  3761. /*@__PURE__*/ new Vector3(),
  3762. /*@__PURE__*/ new Vector3(),
  3763. /*@__PURE__*/ new Vector3(),
  3764. /*@__PURE__*/ new Vector3(),
  3765. /*@__PURE__*/ new Vector3(),
  3766. /*@__PURE__*/ new Vector3()
  3767. ];
  3768. const _vector$b = /*@__PURE__*/ new Vector3();
  3769. const _box$4 = /*@__PURE__*/ new Box3();
  3770. // triangle centered vertices
  3771. const _v0$2 = /*@__PURE__*/ new Vector3();
  3772. const _v1$7 = /*@__PURE__*/ new Vector3();
  3773. const _v2$4 = /*@__PURE__*/ new Vector3();
  3774. // triangle edge vectors
  3775. const _f0 = /*@__PURE__*/ new Vector3();
  3776. const _f1 = /*@__PURE__*/ new Vector3();
  3777. const _f2 = /*@__PURE__*/ new Vector3();
  3778. const _center = /*@__PURE__*/ new Vector3();
  3779. const _extents = /*@__PURE__*/ new Vector3();
  3780. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3781. const _testAxis = /*@__PURE__*/ new Vector3();
  3782. function satForAxes( axes, v0, v1, v2, extents ) {
  3783. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3784. _testAxis.fromArray( axes, i );
  3785. // project the aabb onto the separating axis
  3786. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3787. // project all 3 vertices of the triangle onto the separating axis
  3788. const p0 = v0.dot( _testAxis );
  3789. const p1 = v1.dot( _testAxis );
  3790. const p2 = v2.dot( _testAxis );
  3791. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3792. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3793. // points of the projected triangle are outside the projected half-length of the aabb
  3794. // the axis is separating and we can exit
  3795. return false;
  3796. }
  3797. }
  3798. return true;
  3799. }
  3800. const _box$3 = /*@__PURE__*/ new Box3();
  3801. const _v1$6 = /*@__PURE__*/ new Vector3();
  3802. const _v2$3 = /*@__PURE__*/ new Vector3();
  3803. class Sphere {
  3804. constructor( center = new Vector3(), radius = -1 ) {
  3805. this.isSphere = true;
  3806. this.center = center;
  3807. this.radius = radius;
  3808. }
  3809. set( center, radius ) {
  3810. this.center.copy( center );
  3811. this.radius = radius;
  3812. return this;
  3813. }
  3814. setFromPoints( points, optionalCenter ) {
  3815. const center = this.center;
  3816. if ( optionalCenter !== undefined ) {
  3817. center.copy( optionalCenter );
  3818. } else {
  3819. _box$3.setFromPoints( points ).getCenter( center );
  3820. }
  3821. let maxRadiusSq = 0;
  3822. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3823. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3824. }
  3825. this.radius = Math.sqrt( maxRadiusSq );
  3826. return this;
  3827. }
  3828. copy( sphere ) {
  3829. this.center.copy( sphere.center );
  3830. this.radius = sphere.radius;
  3831. return this;
  3832. }
  3833. isEmpty() {
  3834. return ( this.radius < 0 );
  3835. }
  3836. makeEmpty() {
  3837. this.center.set( 0, 0, 0 );
  3838. this.radius = -1;
  3839. return this;
  3840. }
  3841. containsPoint( point ) {
  3842. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3843. }
  3844. distanceToPoint( point ) {
  3845. return ( point.distanceTo( this.center ) - this.radius );
  3846. }
  3847. intersectsSphere( sphere ) {
  3848. const radiusSum = this.radius + sphere.radius;
  3849. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3850. }
  3851. intersectsBox( box ) {
  3852. return box.intersectsSphere( this );
  3853. }
  3854. intersectsPlane( plane ) {
  3855. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3856. }
  3857. clampPoint( point, target ) {
  3858. const deltaLengthSq = this.center.distanceToSquared( point );
  3859. target.copy( point );
  3860. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3861. target.sub( this.center ).normalize();
  3862. target.multiplyScalar( this.radius ).add( this.center );
  3863. }
  3864. return target;
  3865. }
  3866. getBoundingBox( target ) {
  3867. if ( this.isEmpty() ) {
  3868. // Empty sphere produces empty bounding box
  3869. target.makeEmpty();
  3870. return target;
  3871. }
  3872. target.set( this.center, this.center );
  3873. target.expandByScalar( this.radius );
  3874. return target;
  3875. }
  3876. applyMatrix4( matrix ) {
  3877. this.center.applyMatrix4( matrix );
  3878. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3879. return this;
  3880. }
  3881. translate( offset ) {
  3882. this.center.add( offset );
  3883. return this;
  3884. }
  3885. expandByPoint( point ) {
  3886. if ( this.isEmpty() ) {
  3887. this.center.copy( point );
  3888. this.radius = 0;
  3889. return this;
  3890. }
  3891. _v1$6.subVectors( point, this.center );
  3892. const lengthSq = _v1$6.lengthSq();
  3893. if ( lengthSq > ( this.radius * this.radius ) ) {
  3894. // calculate the minimal sphere
  3895. const length = Math.sqrt( lengthSq );
  3896. const delta = ( length - this.radius ) * 0.5;
  3897. this.center.addScaledVector( _v1$6, delta / length );
  3898. this.radius += delta;
  3899. }
  3900. return this;
  3901. }
  3902. union( sphere ) {
  3903. if ( sphere.isEmpty() ) {
  3904. return this;
  3905. }
  3906. if ( this.isEmpty() ) {
  3907. this.copy( sphere );
  3908. return this;
  3909. }
  3910. if ( this.center.equals( sphere.center ) === true ) {
  3911. this.radius = Math.max( this.radius, sphere.radius );
  3912. } else {
  3913. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  3914. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  3915. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  3916. }
  3917. return this;
  3918. }
  3919. equals( sphere ) {
  3920. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3921. }
  3922. clone() {
  3923. return new this.constructor().copy( this );
  3924. }
  3925. }
  3926. const _vector$a = /*@__PURE__*/ new Vector3();
  3927. const _segCenter = /*@__PURE__*/ new Vector3();
  3928. const _segDir = /*@__PURE__*/ new Vector3();
  3929. const _diff = /*@__PURE__*/ new Vector3();
  3930. const _edge1 = /*@__PURE__*/ new Vector3();
  3931. const _edge2 = /*@__PURE__*/ new Vector3();
  3932. const _normal$1 = /*@__PURE__*/ new Vector3();
  3933. class Ray {
  3934. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, -1 ) ) {
  3935. this.origin = origin;
  3936. this.direction = direction;
  3937. }
  3938. set( origin, direction ) {
  3939. this.origin.copy( origin );
  3940. this.direction.copy( direction );
  3941. return this;
  3942. }
  3943. copy( ray ) {
  3944. this.origin.copy( ray.origin );
  3945. this.direction.copy( ray.direction );
  3946. return this;
  3947. }
  3948. at( t, target ) {
  3949. return target.copy( this.origin ).addScaledVector( this.direction, t );
  3950. }
  3951. lookAt( v ) {
  3952. this.direction.copy( v ).sub( this.origin ).normalize();
  3953. return this;
  3954. }
  3955. recast( t ) {
  3956. this.origin.copy( this.at( t, _vector$a ) );
  3957. return this;
  3958. }
  3959. closestPointToPoint( point, target ) {
  3960. target.subVectors( point, this.origin );
  3961. const directionDistance = target.dot( this.direction );
  3962. if ( directionDistance < 0 ) {
  3963. return target.copy( this.origin );
  3964. }
  3965. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3966. }
  3967. distanceToPoint( point ) {
  3968. return Math.sqrt( this.distanceSqToPoint( point ) );
  3969. }
  3970. distanceSqToPoint( point ) {
  3971. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  3972. // point behind the ray
  3973. if ( directionDistance < 0 ) {
  3974. return this.origin.distanceToSquared( point );
  3975. }
  3976. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3977. return _vector$a.distanceToSquared( point );
  3978. }
  3979. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3980. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3981. // It returns the min distance between the ray and the segment
  3982. // defined by v0 and v1
  3983. // It can also set two optional targets :
  3984. // - The closest point on the ray
  3985. // - The closest point on the segment
  3986. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3987. _segDir.copy( v1 ).sub( v0 ).normalize();
  3988. _diff.copy( this.origin ).sub( _segCenter );
  3989. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3990. const a01 = - this.direction.dot( _segDir );
  3991. const b0 = _diff.dot( this.direction );
  3992. const b1 = - _diff.dot( _segDir );
  3993. const c = _diff.lengthSq();
  3994. const det = Math.abs( 1 - a01 * a01 );
  3995. let s0, s1, sqrDist, extDet;
  3996. if ( det > 0 ) {
  3997. // The ray and segment are not parallel.
  3998. s0 = a01 * b1 - b0;
  3999. s1 = a01 * b0 - b1;
  4000. extDet = segExtent * det;
  4001. if ( s0 >= 0 ) {
  4002. if ( s1 >= - extDet ) {
  4003. if ( s1 <= extDet ) {
  4004. // region 0
  4005. // Minimum at interior points of ray and segment.
  4006. const invDet = 1 / det;
  4007. s0 *= invDet;
  4008. s1 *= invDet;
  4009. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  4010. } else {
  4011. // region 1
  4012. s1 = segExtent;
  4013. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  4014. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  4015. }
  4016. } else {
  4017. // region 5
  4018. s1 = - segExtent;
  4019. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  4020. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  4021. }
  4022. } else {
  4023. if ( s1 <= - extDet ) {
  4024. // region 4
  4025. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  4026. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  4027. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  4028. } else if ( s1 <= extDet ) {
  4029. // region 3
  4030. s0 = 0;
  4031. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  4032. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  4033. } else {
  4034. // region 2
  4035. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  4036. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  4037. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  4038. }
  4039. }
  4040. } else {
  4041. // Ray and segment are parallel.
  4042. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  4043. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  4044. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  4045. }
  4046. if ( optionalPointOnRay ) {
  4047. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  4048. }
  4049. if ( optionalPointOnSegment ) {
  4050. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  4051. }
  4052. return sqrDist;
  4053. }
  4054. intersectSphere( sphere, target ) {
  4055. _vector$a.subVectors( sphere.center, this.origin );
  4056. const tca = _vector$a.dot( this.direction );
  4057. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  4058. const radius2 = sphere.radius * sphere.radius;
  4059. if ( d2 > radius2 ) return null;
  4060. const thc = Math.sqrt( radius2 - d2 );
  4061. // t0 = first intersect point - entrance on front of sphere
  4062. const t0 = tca - thc;
  4063. // t1 = second intersect point - exit point on back of sphere
  4064. const t1 = tca + thc;
  4065. // test to see if t1 is behind the ray - if so, return null
  4066. if ( t1 < 0 ) return null;
  4067. // test to see if t0 is behind the ray:
  4068. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  4069. // in order to always return an intersect point that is in front of the ray.
  4070. if ( t0 < 0 ) return this.at( t1, target );
  4071. // else t0 is in front of the ray, so return the first collision point scaled by t0
  4072. return this.at( t0, target );
  4073. }
  4074. intersectsSphere( sphere ) {
  4075. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  4076. }
  4077. distanceToPlane( plane ) {
  4078. const denominator = plane.normal.dot( this.direction );
  4079. if ( denominator === 0 ) {
  4080. // line is coplanar, return origin
  4081. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  4082. return 0;
  4083. }
  4084. // Null is preferable to undefined since undefined means.... it is undefined
  4085. return null;
  4086. }
  4087. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  4088. // Return if the ray never intersects the plane
  4089. return t >= 0 ? t : null;
  4090. }
  4091. intersectPlane( plane, target ) {
  4092. const t = this.distanceToPlane( plane );
  4093. if ( t === null ) {
  4094. return null;
  4095. }
  4096. return this.at( t, target );
  4097. }
  4098. intersectsPlane( plane ) {
  4099. // check if the ray lies on the plane first
  4100. const distToPoint = plane.distanceToPoint( this.origin );
  4101. if ( distToPoint === 0 ) {
  4102. return true;
  4103. }
  4104. const denominator = plane.normal.dot( this.direction );
  4105. if ( denominator * distToPoint < 0 ) {
  4106. return true;
  4107. }
  4108. // ray origin is behind the plane (and is pointing behind it)
  4109. return false;
  4110. }
  4111. intersectBox( box, target ) {
  4112. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  4113. const invdirx = 1 / this.direction.x,
  4114. invdiry = 1 / this.direction.y,
  4115. invdirz = 1 / this.direction.z;
  4116. const origin = this.origin;
  4117. if ( invdirx >= 0 ) {
  4118. tmin = ( box.min.x - origin.x ) * invdirx;
  4119. tmax = ( box.max.x - origin.x ) * invdirx;
  4120. } else {
  4121. tmin = ( box.max.x - origin.x ) * invdirx;
  4122. tmax = ( box.min.x - origin.x ) * invdirx;
  4123. }
  4124. if ( invdiry >= 0 ) {
  4125. tymin = ( box.min.y - origin.y ) * invdiry;
  4126. tymax = ( box.max.y - origin.y ) * invdiry;
  4127. } else {
  4128. tymin = ( box.max.y - origin.y ) * invdiry;
  4129. tymax = ( box.min.y - origin.y ) * invdiry;
  4130. }
  4131. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  4132. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  4133. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  4134. if ( invdirz >= 0 ) {
  4135. tzmin = ( box.min.z - origin.z ) * invdirz;
  4136. tzmax = ( box.max.z - origin.z ) * invdirz;
  4137. } else {
  4138. tzmin = ( box.max.z - origin.z ) * invdirz;
  4139. tzmax = ( box.min.z - origin.z ) * invdirz;
  4140. }
  4141. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  4142. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  4143. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  4144. //return point closest to the ray (positive side)
  4145. if ( tmax < 0 ) return null;
  4146. return this.at( tmin >= 0 ? tmin : tmax, target );
  4147. }
  4148. intersectsBox( box ) {
  4149. return this.intersectBox( box, _vector$a ) !== null;
  4150. }
  4151. intersectTriangle( a, b, c, backfaceCulling, target ) {
  4152. // Compute the offset origin, edges, and normal.
  4153. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  4154. _edge1.subVectors( b, a );
  4155. _edge2.subVectors( c, a );
  4156. _normal$1.crossVectors( _edge1, _edge2 );
  4157. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  4158. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  4159. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  4160. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  4161. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  4162. let DdN = this.direction.dot( _normal$1 );
  4163. let sign;
  4164. if ( DdN > 0 ) {
  4165. if ( backfaceCulling ) return null;
  4166. sign = 1;
  4167. } else if ( DdN < 0 ) {
  4168. sign = -1;
  4169. DdN = - DdN;
  4170. } else {
  4171. return null;
  4172. }
  4173. _diff.subVectors( this.origin, a );
  4174. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  4175. // b1 < 0, no intersection
  4176. if ( DdQxE2 < 0 ) {
  4177. return null;
  4178. }
  4179. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  4180. // b2 < 0, no intersection
  4181. if ( DdE1xQ < 0 ) {
  4182. return null;
  4183. }
  4184. // b1+b2 > 1, no intersection
  4185. if ( DdQxE2 + DdE1xQ > DdN ) {
  4186. return null;
  4187. }
  4188. // Line intersects triangle, check if ray does.
  4189. const QdN = - sign * _diff.dot( _normal$1 );
  4190. // t < 0, no intersection
  4191. if ( QdN < 0 ) {
  4192. return null;
  4193. }
  4194. // Ray intersects triangle.
  4195. return this.at( QdN / DdN, target );
  4196. }
  4197. applyMatrix4( matrix4 ) {
  4198. this.origin.applyMatrix4( matrix4 );
  4199. this.direction.transformDirection( matrix4 );
  4200. return this;
  4201. }
  4202. equals( ray ) {
  4203. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  4204. }
  4205. clone() {
  4206. return new this.constructor().copy( this );
  4207. }
  4208. }
  4209. class Matrix4 {
  4210. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  4211. Matrix4.prototype.isMatrix4 = true;
  4212. this.elements = [
  4213. 1, 0, 0, 0,
  4214. 0, 1, 0, 0,
  4215. 0, 0, 1, 0,
  4216. 0, 0, 0, 1
  4217. ];
  4218. if ( n11 !== undefined ) {
  4219. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  4220. }
  4221. }
  4222. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  4223. const te = this.elements;
  4224. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  4225. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  4226. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  4227. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  4228. return this;
  4229. }
  4230. identity() {
  4231. this.set(
  4232. 1, 0, 0, 0,
  4233. 0, 1, 0, 0,
  4234. 0, 0, 1, 0,
  4235. 0, 0, 0, 1
  4236. );
  4237. return this;
  4238. }
  4239. clone() {
  4240. return new Matrix4().fromArray( this.elements );
  4241. }
  4242. copy( m ) {
  4243. const te = this.elements;
  4244. const me = m.elements;
  4245. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  4246. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  4247. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  4248. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  4249. return this;
  4250. }
  4251. copyPosition( m ) {
  4252. const te = this.elements, me = m.elements;
  4253. te[ 12 ] = me[ 12 ];
  4254. te[ 13 ] = me[ 13 ];
  4255. te[ 14 ] = me[ 14 ];
  4256. return this;
  4257. }
  4258. setFromMatrix3( m ) {
  4259. const me = m.elements;
  4260. this.set(
  4261. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  4262. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  4263. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  4264. 0, 0, 0, 1
  4265. );
  4266. return this;
  4267. }
  4268. extractBasis( xAxis, yAxis, zAxis ) {
  4269. xAxis.setFromMatrixColumn( this, 0 );
  4270. yAxis.setFromMatrixColumn( this, 1 );
  4271. zAxis.setFromMatrixColumn( this, 2 );
  4272. return this;
  4273. }
  4274. makeBasis( xAxis, yAxis, zAxis ) {
  4275. this.set(
  4276. xAxis.x, yAxis.x, zAxis.x, 0,
  4277. xAxis.y, yAxis.y, zAxis.y, 0,
  4278. xAxis.z, yAxis.z, zAxis.z, 0,
  4279. 0, 0, 0, 1
  4280. );
  4281. return this;
  4282. }
  4283. extractRotation( m ) {
  4284. // this method does not support reflection matrices
  4285. const te = this.elements;
  4286. const me = m.elements;
  4287. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  4288. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  4289. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  4290. te[ 0 ] = me[ 0 ] * scaleX;
  4291. te[ 1 ] = me[ 1 ] * scaleX;
  4292. te[ 2 ] = me[ 2 ] * scaleX;
  4293. te[ 3 ] = 0;
  4294. te[ 4 ] = me[ 4 ] * scaleY;
  4295. te[ 5 ] = me[ 5 ] * scaleY;
  4296. te[ 6 ] = me[ 6 ] * scaleY;
  4297. te[ 7 ] = 0;
  4298. te[ 8 ] = me[ 8 ] * scaleZ;
  4299. te[ 9 ] = me[ 9 ] * scaleZ;
  4300. te[ 10 ] = me[ 10 ] * scaleZ;
  4301. te[ 11 ] = 0;
  4302. te[ 12 ] = 0;
  4303. te[ 13 ] = 0;
  4304. te[ 14 ] = 0;
  4305. te[ 15 ] = 1;
  4306. return this;
  4307. }
  4308. makeRotationFromEuler( euler ) {
  4309. const te = this.elements;
  4310. const x = euler.x, y = euler.y, z = euler.z;
  4311. const a = Math.cos( x ), b = Math.sin( x );
  4312. const c = Math.cos( y ), d = Math.sin( y );
  4313. const e = Math.cos( z ), f = Math.sin( z );
  4314. if ( euler.order === 'XYZ' ) {
  4315. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  4316. te[ 0 ] = c * e;
  4317. te[ 4 ] = - c * f;
  4318. te[ 8 ] = d;
  4319. te[ 1 ] = af + be * d;
  4320. te[ 5 ] = ae - bf * d;
  4321. te[ 9 ] = - b * c;
  4322. te[ 2 ] = bf - ae * d;
  4323. te[ 6 ] = be + af * d;
  4324. te[ 10 ] = a * c;
  4325. } else if ( euler.order === 'YXZ' ) {
  4326. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  4327. te[ 0 ] = ce + df * b;
  4328. te[ 4 ] = de * b - cf;
  4329. te[ 8 ] = a * d;
  4330. te[ 1 ] = a * f;
  4331. te[ 5 ] = a * e;
  4332. te[ 9 ] = - b;
  4333. te[ 2 ] = cf * b - de;
  4334. te[ 6 ] = df + ce * b;
  4335. te[ 10 ] = a * c;
  4336. } else if ( euler.order === 'ZXY' ) {
  4337. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  4338. te[ 0 ] = ce - df * b;
  4339. te[ 4 ] = - a * f;
  4340. te[ 8 ] = de + cf * b;
  4341. te[ 1 ] = cf + de * b;
  4342. te[ 5 ] = a * e;
  4343. te[ 9 ] = df - ce * b;
  4344. te[ 2 ] = - a * d;
  4345. te[ 6 ] = b;
  4346. te[ 10 ] = a * c;
  4347. } else if ( euler.order === 'ZYX' ) {
  4348. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  4349. te[ 0 ] = c * e;
  4350. te[ 4 ] = be * d - af;
  4351. te[ 8 ] = ae * d + bf;
  4352. te[ 1 ] = c * f;
  4353. te[ 5 ] = bf * d + ae;
  4354. te[ 9 ] = af * d - be;
  4355. te[ 2 ] = - d;
  4356. te[ 6 ] = b * c;
  4357. te[ 10 ] = a * c;
  4358. } else if ( euler.order === 'YZX' ) {
  4359. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  4360. te[ 0 ] = c * e;
  4361. te[ 4 ] = bd - ac * f;
  4362. te[ 8 ] = bc * f + ad;
  4363. te[ 1 ] = f;
  4364. te[ 5 ] = a * e;
  4365. te[ 9 ] = - b * e;
  4366. te[ 2 ] = - d * e;
  4367. te[ 6 ] = ad * f + bc;
  4368. te[ 10 ] = ac - bd * f;
  4369. } else if ( euler.order === 'XZY' ) {
  4370. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  4371. te[ 0 ] = c * e;
  4372. te[ 4 ] = - f;
  4373. te[ 8 ] = d * e;
  4374. te[ 1 ] = ac * f + bd;
  4375. te[ 5 ] = a * e;
  4376. te[ 9 ] = ad * f - bc;
  4377. te[ 2 ] = bc * f - ad;
  4378. te[ 6 ] = b * e;
  4379. te[ 10 ] = bd * f + ac;
  4380. }
  4381. // bottom row
  4382. te[ 3 ] = 0;
  4383. te[ 7 ] = 0;
  4384. te[ 11 ] = 0;
  4385. // last column
  4386. te[ 12 ] = 0;
  4387. te[ 13 ] = 0;
  4388. te[ 14 ] = 0;
  4389. te[ 15 ] = 1;
  4390. return this;
  4391. }
  4392. makeRotationFromQuaternion( q ) {
  4393. return this.compose( _zero, q, _one );
  4394. }
  4395. lookAt( eye, target, up ) {
  4396. const te = this.elements;
  4397. _z.subVectors( eye, target );
  4398. if ( _z.lengthSq() === 0 ) {
  4399. // eye and target are in the same position
  4400. _z.z = 1;
  4401. }
  4402. _z.normalize();
  4403. _x.crossVectors( up, _z );
  4404. if ( _x.lengthSq() === 0 ) {
  4405. // up and z are parallel
  4406. if ( Math.abs( up.z ) === 1 ) {
  4407. _z.x += 0.0001;
  4408. } else {
  4409. _z.z += 0.0001;
  4410. }
  4411. _z.normalize();
  4412. _x.crossVectors( up, _z );
  4413. }
  4414. _x.normalize();
  4415. _y.crossVectors( _z, _x );
  4416. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  4417. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  4418. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  4419. return this;
  4420. }
  4421. multiply( m ) {
  4422. return this.multiplyMatrices( this, m );
  4423. }
  4424. premultiply( m ) {
  4425. return this.multiplyMatrices( m, this );
  4426. }
  4427. multiplyMatrices( a, b ) {
  4428. const ae = a.elements;
  4429. const be = b.elements;
  4430. const te = this.elements;
  4431. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  4432. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  4433. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  4434. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  4435. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  4436. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  4437. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  4438. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  4439. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  4440. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  4441. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  4442. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  4443. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  4444. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  4445. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  4446. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  4447. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  4448. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  4449. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  4450. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  4451. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  4452. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  4453. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  4454. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  4455. return this;
  4456. }
  4457. multiplyScalar( s ) {
  4458. const te = this.elements;
  4459. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  4460. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  4461. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  4462. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  4463. return this;
  4464. }
  4465. determinant() {
  4466. const te = this.elements;
  4467. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  4468. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  4469. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  4470. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  4471. //TODO: make this more efficient
  4472. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  4473. return (
  4474. n41 * (
  4475. + n14 * n23 * n32
  4476. - n13 * n24 * n32
  4477. - n14 * n22 * n33
  4478. + n12 * n24 * n33
  4479. + n13 * n22 * n34
  4480. - n12 * n23 * n34
  4481. ) +
  4482. n42 * (
  4483. + n11 * n23 * n34
  4484. - n11 * n24 * n33
  4485. + n14 * n21 * n33
  4486. - n13 * n21 * n34
  4487. + n13 * n24 * n31
  4488. - n14 * n23 * n31
  4489. ) +
  4490. n43 * (
  4491. + n11 * n24 * n32
  4492. - n11 * n22 * n34
  4493. - n14 * n21 * n32
  4494. + n12 * n21 * n34
  4495. + n14 * n22 * n31
  4496. - n12 * n24 * n31
  4497. ) +
  4498. n44 * (
  4499. - n13 * n22 * n31
  4500. - n11 * n23 * n32
  4501. + n11 * n22 * n33
  4502. + n13 * n21 * n32
  4503. - n12 * n21 * n33
  4504. + n12 * n23 * n31
  4505. )
  4506. );
  4507. }
  4508. transpose() {
  4509. const te = this.elements;
  4510. let tmp;
  4511. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  4512. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  4513. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  4514. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  4515. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  4516. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  4517. return this;
  4518. }
  4519. setPosition( x, y, z ) {
  4520. const te = this.elements;
  4521. if ( x.isVector3 ) {
  4522. te[ 12 ] = x.x;
  4523. te[ 13 ] = x.y;
  4524. te[ 14 ] = x.z;
  4525. } else {
  4526. te[ 12 ] = x;
  4527. te[ 13 ] = y;
  4528. te[ 14 ] = z;
  4529. }
  4530. return this;
  4531. }
  4532. invert() {
  4533. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  4534. const te = this.elements,
  4535. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  4536. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  4537. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  4538. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  4539. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  4540. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  4541. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  4542. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  4543. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  4544. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  4545. const detInv = 1 / det;
  4546. te[ 0 ] = t11 * detInv;
  4547. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  4548. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  4549. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  4550. te[ 4 ] = t12 * detInv;
  4551. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  4552. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  4553. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  4554. te[ 8 ] = t13 * detInv;
  4555. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  4556. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  4557. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  4558. te[ 12 ] = t14 * detInv;
  4559. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  4560. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  4561. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  4562. return this;
  4563. }
  4564. scale( v ) {
  4565. const te = this.elements;
  4566. const x = v.x, y = v.y, z = v.z;
  4567. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  4568. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  4569. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  4570. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  4571. return this;
  4572. }
  4573. getMaxScaleOnAxis() {
  4574. const te = this.elements;
  4575. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  4576. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  4577. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  4578. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  4579. }
  4580. makeTranslation( x, y, z ) {
  4581. if ( x.isVector3 ) {
  4582. this.set(
  4583. 1, 0, 0, x.x,
  4584. 0, 1, 0, x.y,
  4585. 0, 0, 1, x.z,
  4586. 0, 0, 0, 1
  4587. );
  4588. } else {
  4589. this.set(
  4590. 1, 0, 0, x,
  4591. 0, 1, 0, y,
  4592. 0, 0, 1, z,
  4593. 0, 0, 0, 1
  4594. );
  4595. }
  4596. return this;
  4597. }
  4598. makeRotationX( theta ) {
  4599. const c = Math.cos( theta ), s = Math.sin( theta );
  4600. this.set(
  4601. 1, 0, 0, 0,
  4602. 0, c, - s, 0,
  4603. 0, s, c, 0,
  4604. 0, 0, 0, 1
  4605. );
  4606. return this;
  4607. }
  4608. makeRotationY( theta ) {
  4609. const c = Math.cos( theta ), s = Math.sin( theta );
  4610. this.set(
  4611. c, 0, s, 0,
  4612. 0, 1, 0, 0,
  4613. - s, 0, c, 0,
  4614. 0, 0, 0, 1
  4615. );
  4616. return this;
  4617. }
  4618. makeRotationZ( theta ) {
  4619. const c = Math.cos( theta ), s = Math.sin( theta );
  4620. this.set(
  4621. c, - s, 0, 0,
  4622. s, c, 0, 0,
  4623. 0, 0, 1, 0,
  4624. 0, 0, 0, 1
  4625. );
  4626. return this;
  4627. }
  4628. makeRotationAxis( axis, angle ) {
  4629. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4630. const c = Math.cos( angle );
  4631. const s = Math.sin( angle );
  4632. const t = 1 - c;
  4633. const x = axis.x, y = axis.y, z = axis.z;
  4634. const tx = t * x, ty = t * y;
  4635. this.set(
  4636. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  4637. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  4638. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  4639. 0, 0, 0, 1
  4640. );
  4641. return this;
  4642. }
  4643. makeScale( x, y, z ) {
  4644. this.set(
  4645. x, 0, 0, 0,
  4646. 0, y, 0, 0,
  4647. 0, 0, z, 0,
  4648. 0, 0, 0, 1
  4649. );
  4650. return this;
  4651. }
  4652. makeShear( xy, xz, yx, yz, zx, zy ) {
  4653. this.set(
  4654. 1, yx, zx, 0,
  4655. xy, 1, zy, 0,
  4656. xz, yz, 1, 0,
  4657. 0, 0, 0, 1
  4658. );
  4659. return this;
  4660. }
  4661. compose( position, quaternion, scale ) {
  4662. const te = this.elements;
  4663. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  4664. const x2 = x + x, y2 = y + y, z2 = z + z;
  4665. const xx = x * x2, xy = x * y2, xz = x * z2;
  4666. const yy = y * y2, yz = y * z2, zz = z * z2;
  4667. const wx = w * x2, wy = w * y2, wz = w * z2;
  4668. const sx = scale.x, sy = scale.y, sz = scale.z;
  4669. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  4670. te[ 1 ] = ( xy + wz ) * sx;
  4671. te[ 2 ] = ( xz - wy ) * sx;
  4672. te[ 3 ] = 0;
  4673. te[ 4 ] = ( xy - wz ) * sy;
  4674. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  4675. te[ 6 ] = ( yz + wx ) * sy;
  4676. te[ 7 ] = 0;
  4677. te[ 8 ] = ( xz + wy ) * sz;
  4678. te[ 9 ] = ( yz - wx ) * sz;
  4679. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  4680. te[ 11 ] = 0;
  4681. te[ 12 ] = position.x;
  4682. te[ 13 ] = position.y;
  4683. te[ 14 ] = position.z;
  4684. te[ 15 ] = 1;
  4685. return this;
  4686. }
  4687. decompose( position, quaternion, scale ) {
  4688. const te = this.elements;
  4689. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  4690. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  4691. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  4692. // if determine is negative, we need to invert one scale
  4693. const det = this.determinant();
  4694. if ( det < 0 ) sx = - sx;
  4695. position.x = te[ 12 ];
  4696. position.y = te[ 13 ];
  4697. position.z = te[ 14 ];
  4698. // scale the rotation part
  4699. _m1$2.copy( this );
  4700. const invSX = 1 / sx;
  4701. const invSY = 1 / sy;
  4702. const invSZ = 1 / sz;
  4703. _m1$2.elements[ 0 ] *= invSX;
  4704. _m1$2.elements[ 1 ] *= invSX;
  4705. _m1$2.elements[ 2 ] *= invSX;
  4706. _m1$2.elements[ 4 ] *= invSY;
  4707. _m1$2.elements[ 5 ] *= invSY;
  4708. _m1$2.elements[ 6 ] *= invSY;
  4709. _m1$2.elements[ 8 ] *= invSZ;
  4710. _m1$2.elements[ 9 ] *= invSZ;
  4711. _m1$2.elements[ 10 ] *= invSZ;
  4712. quaternion.setFromRotationMatrix( _m1$2 );
  4713. scale.x = sx;
  4714. scale.y = sy;
  4715. scale.z = sz;
  4716. return this;
  4717. }
  4718. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4719. const te = this.elements;
  4720. const x = 2 * near / ( right - left );
  4721. const y = 2 * near / ( top - bottom );
  4722. const a = ( right + left ) / ( right - left );
  4723. const b = ( top + bottom ) / ( top - bottom );
  4724. let c, d;
  4725. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4726. c = - ( far + near ) / ( far - near );
  4727. d = ( -2 * far * near ) / ( far - near );
  4728. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4729. c = - far / ( far - near );
  4730. d = ( - far * near ) / ( far - near );
  4731. } else {
  4732. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  4733. }
  4734. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  4735. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  4736. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4737. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = -1; te[ 15 ] = 0;
  4738. return this;
  4739. }
  4740. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4741. const te = this.elements;
  4742. const w = 1.0 / ( right - left );
  4743. const h = 1.0 / ( top - bottom );
  4744. const p = 1.0 / ( far - near );
  4745. const x = ( right + left ) * w;
  4746. const y = ( top + bottom ) * h;
  4747. let z, zInv;
  4748. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4749. z = ( far + near ) * p;
  4750. zInv = -2 * p;
  4751. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4752. z = near * p;
  4753. zInv = -1 * p;
  4754. } else {
  4755. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  4756. }
  4757. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4758. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4759. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = zInv; te[ 14 ] = - z;
  4760. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4761. return this;
  4762. }
  4763. equals( matrix ) {
  4764. const te = this.elements;
  4765. const me = matrix.elements;
  4766. for ( let i = 0; i < 16; i ++ ) {
  4767. if ( te[ i ] !== me[ i ] ) return false;
  4768. }
  4769. return true;
  4770. }
  4771. fromArray( array, offset = 0 ) {
  4772. for ( let i = 0; i < 16; i ++ ) {
  4773. this.elements[ i ] = array[ i + offset ];
  4774. }
  4775. return this;
  4776. }
  4777. toArray( array = [], offset = 0 ) {
  4778. const te = this.elements;
  4779. array[ offset ] = te[ 0 ];
  4780. array[ offset + 1 ] = te[ 1 ];
  4781. array[ offset + 2 ] = te[ 2 ];
  4782. array[ offset + 3 ] = te[ 3 ];
  4783. array[ offset + 4 ] = te[ 4 ];
  4784. array[ offset + 5 ] = te[ 5 ];
  4785. array[ offset + 6 ] = te[ 6 ];
  4786. array[ offset + 7 ] = te[ 7 ];
  4787. array[ offset + 8 ] = te[ 8 ];
  4788. array[ offset + 9 ] = te[ 9 ];
  4789. array[ offset + 10 ] = te[ 10 ];
  4790. array[ offset + 11 ] = te[ 11 ];
  4791. array[ offset + 12 ] = te[ 12 ];
  4792. array[ offset + 13 ] = te[ 13 ];
  4793. array[ offset + 14 ] = te[ 14 ];
  4794. array[ offset + 15 ] = te[ 15 ];
  4795. return array;
  4796. }
  4797. }
  4798. const _v1$5 = /*@__PURE__*/ new Vector3();
  4799. const _m1$2 = /*@__PURE__*/ new Matrix4();
  4800. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4801. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4802. const _x = /*@__PURE__*/ new Vector3();
  4803. const _y = /*@__PURE__*/ new Vector3();
  4804. const _z = /*@__PURE__*/ new Vector3();
  4805. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  4806. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  4807. class Euler {
  4808. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  4809. this.isEuler = true;
  4810. this._x = x;
  4811. this._y = y;
  4812. this._z = z;
  4813. this._order = order;
  4814. }
  4815. get x() {
  4816. return this._x;
  4817. }
  4818. set x( value ) {
  4819. this._x = value;
  4820. this._onChangeCallback();
  4821. }
  4822. get y() {
  4823. return this._y;
  4824. }
  4825. set y( value ) {
  4826. this._y = value;
  4827. this._onChangeCallback();
  4828. }
  4829. get z() {
  4830. return this._z;
  4831. }
  4832. set z( value ) {
  4833. this._z = value;
  4834. this._onChangeCallback();
  4835. }
  4836. get order() {
  4837. return this._order;
  4838. }
  4839. set order( value ) {
  4840. this._order = value;
  4841. this._onChangeCallback();
  4842. }
  4843. set( x, y, z, order = this._order ) {
  4844. this._x = x;
  4845. this._y = y;
  4846. this._z = z;
  4847. this._order = order;
  4848. this._onChangeCallback();
  4849. return this;
  4850. }
  4851. clone() {
  4852. return new this.constructor( this._x, this._y, this._z, this._order );
  4853. }
  4854. copy( euler ) {
  4855. this._x = euler._x;
  4856. this._y = euler._y;
  4857. this._z = euler._z;
  4858. this._order = euler._order;
  4859. this._onChangeCallback();
  4860. return this;
  4861. }
  4862. setFromRotationMatrix( m, order = this._order, update = true ) {
  4863. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4864. const te = m.elements;
  4865. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4866. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4867. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4868. switch ( order ) {
  4869. case 'XYZ':
  4870. this._y = Math.asin( clamp( m13, -1, 1 ) );
  4871. if ( Math.abs( m13 ) < 0.9999999 ) {
  4872. this._x = Math.atan2( - m23, m33 );
  4873. this._z = Math.atan2( - m12, m11 );
  4874. } else {
  4875. this._x = Math.atan2( m32, m22 );
  4876. this._z = 0;
  4877. }
  4878. break;
  4879. case 'YXZ':
  4880. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  4881. if ( Math.abs( m23 ) < 0.9999999 ) {
  4882. this._y = Math.atan2( m13, m33 );
  4883. this._z = Math.atan2( m21, m22 );
  4884. } else {
  4885. this._y = Math.atan2( - m31, m11 );
  4886. this._z = 0;
  4887. }
  4888. break;
  4889. case 'ZXY':
  4890. this._x = Math.asin( clamp( m32, -1, 1 ) );
  4891. if ( Math.abs( m32 ) < 0.9999999 ) {
  4892. this._y = Math.atan2( - m31, m33 );
  4893. this._z = Math.atan2( - m12, m22 );
  4894. } else {
  4895. this._y = 0;
  4896. this._z = Math.atan2( m21, m11 );
  4897. }
  4898. break;
  4899. case 'ZYX':
  4900. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  4901. if ( Math.abs( m31 ) < 0.9999999 ) {
  4902. this._x = Math.atan2( m32, m33 );
  4903. this._z = Math.atan2( m21, m11 );
  4904. } else {
  4905. this._x = 0;
  4906. this._z = Math.atan2( - m12, m22 );
  4907. }
  4908. break;
  4909. case 'YZX':
  4910. this._z = Math.asin( clamp( m21, -1, 1 ) );
  4911. if ( Math.abs( m21 ) < 0.9999999 ) {
  4912. this._x = Math.atan2( - m23, m22 );
  4913. this._y = Math.atan2( - m31, m11 );
  4914. } else {
  4915. this._x = 0;
  4916. this._y = Math.atan2( m13, m33 );
  4917. }
  4918. break;
  4919. case 'XZY':
  4920. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  4921. if ( Math.abs( m12 ) < 0.9999999 ) {
  4922. this._x = Math.atan2( m32, m22 );
  4923. this._y = Math.atan2( m13, m11 );
  4924. } else {
  4925. this._x = Math.atan2( - m23, m33 );
  4926. this._y = 0;
  4927. }
  4928. break;
  4929. default:
  4930. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4931. }
  4932. this._order = order;
  4933. if ( update === true ) this._onChangeCallback();
  4934. return this;
  4935. }
  4936. setFromQuaternion( q, order, update ) {
  4937. _matrix$2.makeRotationFromQuaternion( q );
  4938. return this.setFromRotationMatrix( _matrix$2, order, update );
  4939. }
  4940. setFromVector3( v, order = this._order ) {
  4941. return this.set( v.x, v.y, v.z, order );
  4942. }
  4943. reorder( newOrder ) {
  4944. // WARNING: this discards revolution information -bhouston
  4945. _quaternion$3.setFromEuler( this );
  4946. return this.setFromQuaternion( _quaternion$3, newOrder );
  4947. }
  4948. equals( euler ) {
  4949. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4950. }
  4951. fromArray( array ) {
  4952. this._x = array[ 0 ];
  4953. this._y = array[ 1 ];
  4954. this._z = array[ 2 ];
  4955. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4956. this._onChangeCallback();
  4957. return this;
  4958. }
  4959. toArray( array = [], offset = 0 ) {
  4960. array[ offset ] = this._x;
  4961. array[ offset + 1 ] = this._y;
  4962. array[ offset + 2 ] = this._z;
  4963. array[ offset + 3 ] = this._order;
  4964. return array;
  4965. }
  4966. _onChange( callback ) {
  4967. this._onChangeCallback = callback;
  4968. return this;
  4969. }
  4970. _onChangeCallback() {}
  4971. *[ Symbol.iterator ]() {
  4972. yield this._x;
  4973. yield this._y;
  4974. yield this._z;
  4975. yield this._order;
  4976. }
  4977. }
  4978. Euler.DEFAULT_ORDER = 'XYZ';
  4979. class Layers {
  4980. constructor() {
  4981. this.mask = 1 | 0;
  4982. }
  4983. set( channel ) {
  4984. this.mask = ( 1 << channel | 0 ) >>> 0;
  4985. }
  4986. enable( channel ) {
  4987. this.mask |= 1 << channel | 0;
  4988. }
  4989. enableAll() {
  4990. this.mask = 0xffffffff | 0;
  4991. }
  4992. toggle( channel ) {
  4993. this.mask ^= 1 << channel | 0;
  4994. }
  4995. disable( channel ) {
  4996. this.mask &= ~ ( 1 << channel | 0 );
  4997. }
  4998. disableAll() {
  4999. this.mask = 0;
  5000. }
  5001. test( layers ) {
  5002. return ( this.mask & layers.mask ) !== 0;
  5003. }
  5004. isEnabled( channel ) {
  5005. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  5006. }
  5007. }
  5008. let _object3DId = 0;
  5009. const _v1$4 = /*@__PURE__*/ new Vector3();
  5010. const _q1 = /*@__PURE__*/ new Quaternion();
  5011. const _m1$1 = /*@__PURE__*/ new Matrix4();
  5012. const _target = /*@__PURE__*/ new Vector3();
  5013. const _position$3 = /*@__PURE__*/ new Vector3();
  5014. const _scale$2 = /*@__PURE__*/ new Vector3();
  5015. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  5016. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  5017. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  5018. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  5019. /**
  5020. * Fires when the object has been added to its parent object.
  5021. *
  5022. * @event Object3D#added
  5023. * @type {Object}
  5024. */
  5025. const _addedEvent = { type: 'added' };
  5026. /**
  5027. * Fires when the object has been removed from its parent object.
  5028. *
  5029. * @event Object3D#removed
  5030. * @type {Object}
  5031. */
  5032. const _removedEvent = { type: 'removed' };
  5033. /**
  5034. * Fires when a new child object has been added.
  5035. *
  5036. * @event Object3D#childadded
  5037. * @type {Object}
  5038. */
  5039. const _childaddedEvent = { type: 'childadded', child: null };
  5040. /**
  5041. * Fires when a new child object has been added.
  5042. *
  5043. * @event Object3D#childremoved
  5044. * @type {Object}
  5045. */
  5046. const _childremovedEvent = { type: 'childremoved', child: null };
  5047. /**
  5048. * This is the base class for most objects in three.js and provides a set of
  5049. * properties and methods for manipulating objects in 3D space.
  5050. *
  5051. * @augments EventDispatcher
  5052. */
  5053. class Object3D extends EventDispatcher {
  5054. /**
  5055. * Constructs a new 3D object.
  5056. */
  5057. constructor() {
  5058. super();
  5059. /**
  5060. * This flag can be used for type testing.
  5061. *
  5062. * @type {boolean}
  5063. * @readonly
  5064. * @default true
  5065. */
  5066. this.isObject3D = true;
  5067. /**
  5068. * The ID of the 3D object.
  5069. *
  5070. * @name Object3D#id
  5071. * @type {number}
  5072. * @readonly
  5073. */
  5074. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  5075. /**
  5076. * The UUID of the 3D object.
  5077. *
  5078. * @type {string}
  5079. * @readonly
  5080. */
  5081. this.uuid = generateUUID();
  5082. /**
  5083. * The name of the 3D object.
  5084. *
  5085. * @type {string}
  5086. */
  5087. this.name = '';
  5088. /**
  5089. * The type property is used for detecting the object type
  5090. * in context of serialization/deserialization.
  5091. *
  5092. * @type {string}
  5093. * @readonly
  5094. */
  5095. this.type = 'Object3D';
  5096. /**
  5097. * A reference to the parent object.
  5098. *
  5099. * @type {?Object3D}
  5100. * @default null
  5101. */
  5102. this.parent = null;
  5103. /**
  5104. * An array holding the child 3D objects of this instance.
  5105. *
  5106. * @type {Array<Object3D>}
  5107. */
  5108. this.children = [];
  5109. /**
  5110. * Defines the `up` direction of the 3D object which influences
  5111. * the orientation via methods like {@link Object3D#lookAt}.
  5112. *
  5113. * The default values for all 3D objects is defined by `Object3D.DEFAULT_UP`.
  5114. *
  5115. * @type {Vector3}
  5116. */
  5117. this.up = Object3D.DEFAULT_UP.clone();
  5118. const position = new Vector3();
  5119. const rotation = new Euler();
  5120. const quaternion = new Quaternion();
  5121. const scale = new Vector3( 1, 1, 1 );
  5122. function onRotationChange() {
  5123. quaternion.setFromEuler( rotation, false );
  5124. }
  5125. function onQuaternionChange() {
  5126. rotation.setFromQuaternion( quaternion, undefined, false );
  5127. }
  5128. rotation._onChange( onRotationChange );
  5129. quaternion._onChange( onQuaternionChange );
  5130. Object.defineProperties( this, {
  5131. /**
  5132. * Represents the object's local position.
  5133. *
  5134. * @name Object3D#position
  5135. * @type {Vector3}
  5136. * @default (0,0,0)
  5137. */
  5138. position: {
  5139. configurable: true,
  5140. enumerable: true,
  5141. value: position
  5142. },
  5143. /**
  5144. * Represents the object's local rotation as Euler angles, in radians.
  5145. *
  5146. * @name Object3D#rotation
  5147. * @type {Euler}
  5148. * @default (0,0,0)
  5149. */
  5150. rotation: {
  5151. configurable: true,
  5152. enumerable: true,
  5153. value: rotation
  5154. },
  5155. /**
  5156. * Represents the object's local rotation as Quaterions.
  5157. *
  5158. * @name Object3D#quaternion
  5159. * @type {Quaternion}
  5160. */
  5161. quaternion: {
  5162. configurable: true,
  5163. enumerable: true,
  5164. value: quaternion
  5165. },
  5166. /**
  5167. * Represents the object's local scale.
  5168. *
  5169. * @name Object3D#scale
  5170. * @type {Vector3}
  5171. * @default (1,1,1)
  5172. */
  5173. scale: {
  5174. configurable: true,
  5175. enumerable: true,
  5176. value: scale
  5177. },
  5178. /**
  5179. * Represents the object's model-view matrix.
  5180. *
  5181. * @name Object3D#modelViewMatrix
  5182. * @type {Matrix4}
  5183. */
  5184. modelViewMatrix: {
  5185. value: new Matrix4()
  5186. },
  5187. /**
  5188. * Represents the object's normal matrix.
  5189. *
  5190. * @name Object3D#normalMatrix
  5191. * @type {Matrix3}
  5192. */
  5193. normalMatrix: {
  5194. value: new Matrix3()
  5195. }
  5196. } );
  5197. /**
  5198. * Represents the object's transformation matrix in local space.
  5199. *
  5200. * @type {Matrix4}
  5201. */
  5202. this.matrix = new Matrix4();
  5203. /**
  5204. * Represents the object's transformation matrix in world space.
  5205. * If the 3D object has no parent, then it's identical to the local transformation matrix
  5206. *
  5207. * @type {Matrix4}
  5208. */
  5209. this.matrixWorld = new Matrix4();
  5210. /**
  5211. * When set to `true`, the engine automatically computes the local matrix from position,
  5212. * rotation and scale every frame.
  5213. *
  5214. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_AUTO_UPDATE`.
  5215. *
  5216. * @type {boolean}
  5217. * @default true
  5218. */
  5219. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  5220. /**
  5221. * When set to `true`, the engine automatically computes the world matrix from the current local
  5222. * matrix and the object's transformation hierarchy.
  5223. *
  5224. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE`.
  5225. *
  5226. * @type {boolean}
  5227. * @default true
  5228. */
  5229. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  5230. /**
  5231. * When set to `true`, it calculates the world matrix in that frame and resets this property
  5232. * to `false`.
  5233. *
  5234. * @type {boolean}
  5235. * @default false
  5236. */
  5237. this.matrixWorldNeedsUpdate = false;
  5238. /**
  5239. * The layer membership of the 3D object. The 3D object is only visible if it has
  5240. * at least one layer in common with the camera in use. This property can also be
  5241. * used to filter out unwanted objects in ray-intersection tests when using {@link Raycaster}.
  5242. *
  5243. * @type {Layers}
  5244. */
  5245. this.layers = new Layers();
  5246. /**
  5247. * When set to `true`, the 3D object gets rendered.
  5248. *
  5249. * @type {boolean}
  5250. * @default true
  5251. */
  5252. this.visible = true;
  5253. /**
  5254. * When set to `true`, the 3D object gets rendered into shadow maps.
  5255. *
  5256. * @type {boolean}
  5257. * @default false
  5258. */
  5259. this.castShadow = false;
  5260. /**
  5261. * When set to `true`, the 3D object is affected by shadows in the scene.
  5262. *
  5263. * @type {boolean}
  5264. * @default false
  5265. */
  5266. this.receiveShadow = false;
  5267. /**
  5268. * When set to `true`, the 3D object is honored by view frustum culling.
  5269. *
  5270. * @type {boolean}
  5271. * @default true
  5272. */
  5273. this.frustumCulled = true;
  5274. /**
  5275. * This value allows the default rendering order of scene graph objects to be
  5276. * overridden although opaque and transparent objects remain sorted independently.
  5277. * When this property is set for an instance of {@link Group},all descendants
  5278. * objects will be sorted and rendered together. Sorting is from lowest to highest
  5279. * render order.
  5280. *
  5281. * @type {number}
  5282. * @default 0
  5283. */
  5284. this.renderOrder = 0;
  5285. /**
  5286. * An array holding the animation clips of the 3D object.
  5287. *
  5288. * @type {Array<AnimationClip>}
  5289. */
  5290. this.animations = [];
  5291. /**
  5292. * An object that can be used to store custom data about the 3D object. It
  5293. * should not hold references to functions as these will not be cloned.
  5294. *
  5295. * @type {Object}
  5296. */
  5297. this.userData = {};
  5298. }
  5299. /**
  5300. * A callback that is executed immediately before a 3D object is rendered to a shadow map.
  5301. *
  5302. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  5303. * @param {Object3D} object - The 3D object.
  5304. * @param {Camera} camera - The camera that is used to render the scene.
  5305. * @param {Camera} shadowCamera - The shadow camera.
  5306. * @param {BufferGeometry} geometry - The 3D object's geometry.
  5307. * @param {Material} depthMaterial - The depth material.
  5308. * @param {Object} group - The geometry group data.
  5309. */
  5310. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  5311. /**
  5312. * A callback that is executed immediately after a 3D object is rendered to a shadow map.
  5313. *
  5314. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  5315. * @param {Object3D} object - The 3D object.
  5316. * @param {Camera} camera - The camera that is used to render the scene.
  5317. * @param {Camera} shadowCamera - The shadow camera.
  5318. * @param {BufferGeometry} geometry - The 3D object's geometry.
  5319. * @param {Material} depthMaterial - The depth material.
  5320. * @param {Object} group - The geometry group data.
  5321. */
  5322. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  5323. /**
  5324. * A callback that is executed immediately before a 3D object is rendered.
  5325. *
  5326. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  5327. * @param {Object3D} object - The 3D object.
  5328. * @param {Camera} camera - The camera that is used to render the scene.
  5329. * @param {BufferGeometry} geometry - The 3D object's geometry.
  5330. * @param {Material} material - The 3D object's material.
  5331. * @param {Object} group - The geometry group data.
  5332. */
  5333. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  5334. /**
  5335. * A callback that is executed immediately after a 3D object is rendered.
  5336. *
  5337. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  5338. * @param {Object3D} object - The 3D object.
  5339. * @param {Camera} camera - The camera that is used to render the scene.
  5340. * @param {BufferGeometry} geometry - The 3D object's geometry.
  5341. * @param {Material} material - The 3D object's material.
  5342. * @param {Object} group - The geometry group data.
  5343. */
  5344. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  5345. /**
  5346. * Applies the given transformation matrix to the object and updates the object's position,
  5347. * rotation and scale.
  5348. *
  5349. * @param {Matrix4} matrix - The transformation matrix.
  5350. */
  5351. applyMatrix4( matrix ) {
  5352. if ( this.matrixAutoUpdate ) this.updateMatrix();
  5353. this.matrix.premultiply( matrix );
  5354. this.matrix.decompose( this.position, this.quaternion, this.scale );
  5355. }
  5356. /**
  5357. * Applies a rotation represented by given the quaternion to the 3D object.
  5358. *
  5359. * @param {Quaternion} q - The quaterion.
  5360. * @return {Object3D} A reference to this instance.
  5361. */
  5362. applyQuaternion( q ) {
  5363. this.quaternion.premultiply( q );
  5364. return this;
  5365. }
  5366. /**
  5367. * Sets the given rotation represented as an axis/angle couple to the 3D object.
  5368. *
  5369. * @param {Vector3} axis - The (normalized) axis vector.
  5370. * @param {number} angle - The angle in radians.
  5371. */
  5372. setRotationFromAxisAngle( axis, angle ) {
  5373. // assumes axis is normalized
  5374. this.quaternion.setFromAxisAngle( axis, angle );
  5375. }
  5376. /**
  5377. * Sets the given rotation represented as Euler angles to the 3D object.
  5378. *
  5379. * @param {Euler} euler - The Euler angles.
  5380. */
  5381. setRotationFromEuler( euler ) {
  5382. this.quaternion.setFromEuler( euler, true );
  5383. }
  5384. /**
  5385. * Sets the given rotation represented as rotation matrix to the 3D object.
  5386. *
  5387. * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
  5388. * a pure rotation matrix (i.e, unscaled).
  5389. */
  5390. setRotationFromMatrix( m ) {
  5391. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  5392. this.quaternion.setFromRotationMatrix( m );
  5393. }
  5394. /**
  5395. * Sets the given rotation represented as a Quanterion to the 3D object.
  5396. *
  5397. * @param {Quaternion} q - The Quanterion
  5398. */
  5399. setRotationFromQuaternion( q ) {
  5400. // assumes q is normalized
  5401. this.quaternion.copy( q );
  5402. }
  5403. /**
  5404. * Rotates the 3D object along an axis in local space.
  5405. *
  5406. * @param {Vector3} axis - The (normalized) axis vector.
  5407. * @param {number} angle - The angle in radians.
  5408. * @return {Object3D} A reference to this instance.
  5409. */
  5410. rotateOnAxis( axis, angle ) {
  5411. // rotate object on axis in object space
  5412. // axis is assumed to be normalized
  5413. _q1.setFromAxisAngle( axis, angle );
  5414. this.quaternion.multiply( _q1 );
  5415. return this;
  5416. }
  5417. /**
  5418. * Rotates the 3D object along an axis in world space.
  5419. *
  5420. * @param {Vector3} axis - The (normalized) axis vector.
  5421. * @param {number} angle - The angle in radians.
  5422. * @return {Object3D} A reference to this instance.
  5423. */
  5424. rotateOnWorldAxis( axis, angle ) {
  5425. // rotate object on axis in world space
  5426. // axis is assumed to be normalized
  5427. // method assumes no rotated parent
  5428. _q1.setFromAxisAngle( axis, angle );
  5429. this.quaternion.premultiply( _q1 );
  5430. return this;
  5431. }
  5432. /**
  5433. * Rotates the 3D object around its X axis in local space.
  5434. *
  5435. * @param {number} angle - The angle in radians.
  5436. * @return {Object3D} A reference to this instance.
  5437. */
  5438. rotateX( angle ) {
  5439. return this.rotateOnAxis( _xAxis, angle );
  5440. }
  5441. /**
  5442. * Rotates the 3D object around its Y axis in local space.
  5443. *
  5444. * @param {number} angle - The angle in radians.
  5445. * @return {Object3D} A reference to this instance.
  5446. */
  5447. rotateY( angle ) {
  5448. return this.rotateOnAxis( _yAxis, angle );
  5449. }
  5450. /**
  5451. * Rotates the 3D object around its Z axis in local space.
  5452. *
  5453. * @param {number} angle - The angle in radians.
  5454. * @return {Object3D} A reference to this instance.
  5455. */
  5456. rotateZ( angle ) {
  5457. return this.rotateOnAxis( _zAxis, angle );
  5458. }
  5459. /**
  5460. * Translate the 3D object by a distance along the given axis in local space.
  5461. *
  5462. * @param {Vector3} axis - The (normalized) axis vector.
  5463. * @param {number} distance - The distance in world units.
  5464. * @return {Object3D} A reference to this instance.
  5465. */
  5466. translateOnAxis( axis, distance ) {
  5467. // translate object by distance along axis in object space
  5468. // axis is assumed to be normalized
  5469. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  5470. this.position.add( _v1$4.multiplyScalar( distance ) );
  5471. return this;
  5472. }
  5473. /**
  5474. * Translate the 3D object by a distance along its X-axis in local space.
  5475. *
  5476. * @param {number} distance - The distance in world units.
  5477. * @return {Object3D} A reference to this instance.
  5478. */
  5479. translateX( distance ) {
  5480. return this.translateOnAxis( _xAxis, distance );
  5481. }
  5482. /**
  5483. * Translate the 3D object by a distance along its Y-axis in local space.
  5484. *
  5485. * @param {number} distance - The distance in world units.
  5486. * @return {Object3D} A reference to this instance.
  5487. */
  5488. translateY( distance ) {
  5489. return this.translateOnAxis( _yAxis, distance );
  5490. }
  5491. /**
  5492. * Translate the 3D object by a distance along its Z-axis in local space.
  5493. *
  5494. * @param {number} distance - The distance in world units.
  5495. * @return {Object3D} A reference to this instance.
  5496. */
  5497. translateZ( distance ) {
  5498. return this.translateOnAxis( _zAxis, distance );
  5499. }
  5500. /**
  5501. * Converts the given vector from this 3D object's local space to world space.
  5502. *
  5503. * @param {Vector3} vector - The vector to convert.
  5504. * @return {Vector3} The converted vector.
  5505. */
  5506. localToWorld( vector ) {
  5507. this.updateWorldMatrix( true, false );
  5508. return vector.applyMatrix4( this.matrixWorld );
  5509. }
  5510. /**
  5511. * Converts the given vector from this 3D object's word space to local space.
  5512. *
  5513. * @param {Vector3} vector - The vector to convert.
  5514. * @return {Vector3} The converted vector.
  5515. */
  5516. worldToLocal( vector ) {
  5517. this.updateWorldMatrix( true, false );
  5518. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  5519. }
  5520. /**
  5521. * Rotates the object to face a point in world space.
  5522. *
  5523. * This method does not support objects having non-uniformly-scaled parent(s).
  5524. *
  5525. * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
  5526. * @param {number} [y] - The y coordinate in world space.
  5527. * @param {number} [z] - The z coordinate in world space.
  5528. */
  5529. lookAt( x, y, z ) {
  5530. // This method does not support objects having non-uniformly-scaled parent(s)
  5531. if ( x.isVector3 ) {
  5532. _target.copy( x );
  5533. } else {
  5534. _target.set( x, y, z );
  5535. }
  5536. const parent = this.parent;
  5537. this.updateWorldMatrix( true, false );
  5538. _position$3.setFromMatrixPosition( this.matrixWorld );
  5539. if ( this.isCamera || this.isLight ) {
  5540. _m1$1.lookAt( _position$3, _target, this.up );
  5541. } else {
  5542. _m1$1.lookAt( _target, _position$3, this.up );
  5543. }
  5544. this.quaternion.setFromRotationMatrix( _m1$1 );
  5545. if ( parent ) {
  5546. _m1$1.extractRotation( parent.matrixWorld );
  5547. _q1.setFromRotationMatrix( _m1$1 );
  5548. this.quaternion.premultiply( _q1.invert() );
  5549. }
  5550. }
  5551. /**
  5552. * Adds the given 3D object as a child to this 3D object. An arbitrary number of
  5553. * objects may be added. Any current parent on an object passed in here will be
  5554. * removed, since an object can have at most one parent.
  5555. *
  5556. * @fires Object3D#added
  5557. * @fires Object3D#childadded
  5558. * @param {Object3D} object - The 3D object to add.
  5559. * @return {Object3D} A reference to this instance.
  5560. */
  5561. add( object ) {
  5562. if ( arguments.length > 1 ) {
  5563. for ( let i = 0; i < arguments.length; i ++ ) {
  5564. this.add( arguments[ i ] );
  5565. }
  5566. return this;
  5567. }
  5568. if ( object === this ) {
  5569. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  5570. return this;
  5571. }
  5572. if ( object && object.isObject3D ) {
  5573. object.removeFromParent();
  5574. object.parent = this;
  5575. this.children.push( object );
  5576. object.dispatchEvent( _addedEvent );
  5577. _childaddedEvent.child = object;
  5578. this.dispatchEvent( _childaddedEvent );
  5579. _childaddedEvent.child = null;
  5580. } else {
  5581. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  5582. }
  5583. return this;
  5584. }
  5585. /**
  5586. * Removes the given 3D object as child from this 3D object.
  5587. * An arbitrary number of objects may be removed.
  5588. *
  5589. * @fires Object3D#removed
  5590. * @fires Object3D#childremoved
  5591. * @param {Object3D} object - The 3D object to remove.
  5592. * @return {Object3D} A reference to this instance.
  5593. */
  5594. remove( object ) {
  5595. if ( arguments.length > 1 ) {
  5596. for ( let i = 0; i < arguments.length; i ++ ) {
  5597. this.remove( arguments[ i ] );
  5598. }
  5599. return this;
  5600. }
  5601. const index = this.children.indexOf( object );
  5602. if ( index !== -1 ) {
  5603. object.parent = null;
  5604. this.children.splice( index, 1 );
  5605. object.dispatchEvent( _removedEvent );
  5606. _childremovedEvent.child = object;
  5607. this.dispatchEvent( _childremovedEvent );
  5608. _childremovedEvent.child = null;
  5609. }
  5610. return this;
  5611. }
  5612. /**
  5613. * Removes this 3D object from its current parent.
  5614. *
  5615. * @fires Object3D#removed
  5616. * @fires Object3D#childremoved
  5617. * @return {Object3D} A reference to this instance.
  5618. */
  5619. removeFromParent() {
  5620. const parent = this.parent;
  5621. if ( parent !== null ) {
  5622. parent.remove( this );
  5623. }
  5624. return this;
  5625. }
  5626. /**
  5627. * Removes all child objects.
  5628. *
  5629. * @fires Object3D#removed
  5630. * @fires Object3D#childremoved
  5631. * @return {Object3D} A reference to this instance.
  5632. */
  5633. clear() {
  5634. return this.remove( ... this.children );
  5635. }
  5636. /**
  5637. * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
  5638. * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
  5639. *
  5640. * @fires Object3D#added
  5641. * @fires Object3D#childadded
  5642. * @param {Object3D} object - The 3D object to attach.
  5643. * @return {Object3D} A reference to this instance.
  5644. */
  5645. attach( object ) {
  5646. // adds object as a child of this, while maintaining the object's world transform
  5647. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  5648. this.updateWorldMatrix( true, false );
  5649. _m1$1.copy( this.matrixWorld ).invert();
  5650. if ( object.parent !== null ) {
  5651. object.parent.updateWorldMatrix( true, false );
  5652. _m1$1.multiply( object.parent.matrixWorld );
  5653. }
  5654. object.applyMatrix4( _m1$1 );
  5655. object.removeFromParent();
  5656. object.parent = this;
  5657. this.children.push( object );
  5658. object.updateWorldMatrix( false, true );
  5659. object.dispatchEvent( _addedEvent );
  5660. _childaddedEvent.child = object;
  5661. this.dispatchEvent( _childaddedEvent );
  5662. _childaddedEvent.child = null;
  5663. return this;
  5664. }
  5665. /**
  5666. * Searches through the 3D object and its children, starting with the 3D object
  5667. * itself, and returns the first with a matching ID.
  5668. *
  5669. * @param {number} id - The id.
  5670. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  5671. */
  5672. getObjectById( id ) {
  5673. return this.getObjectByProperty( 'id', id );
  5674. }
  5675. /**
  5676. * Searches through the 3D object and its children, starting with the 3D object
  5677. * itself, and returns the first with a matching name.
  5678. *
  5679. * @param {string} name - The name.
  5680. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  5681. */
  5682. getObjectByName( name ) {
  5683. return this.getObjectByProperty( 'name', name );
  5684. }
  5685. /**
  5686. * Searches through the 3D object and its children, starting with the 3D object
  5687. * itself, and returns the first with a matching property value.
  5688. *
  5689. * @param {string} name - The name of the property.
  5690. * @param {any} value - The value.
  5691. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  5692. */
  5693. getObjectByProperty( name, value ) {
  5694. if ( this[ name ] === value ) return this;
  5695. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  5696. const child = this.children[ i ];
  5697. const object = child.getObjectByProperty( name, value );
  5698. if ( object !== undefined ) {
  5699. return object;
  5700. }
  5701. }
  5702. return undefined;
  5703. }
  5704. /**
  5705. * Searches through the 3D object and its children, starting with the 3D object
  5706. * itself, and returns all 3D objects with a matching property value.
  5707. *
  5708. * @param {string} name - The name of the property.
  5709. * @param {any} value - The value.
  5710. * @param {Array<Object3D>} result - The method stores the result in this array.
  5711. * @return {Array<Object3D>} The found 3D objects.
  5712. */
  5713. getObjectsByProperty( name, value, result = [] ) {
  5714. if ( this[ name ] === value ) result.push( this );
  5715. const children = this.children;
  5716. for ( let i = 0, l = children.length; i < l; i ++ ) {
  5717. children[ i ].getObjectsByProperty( name, value, result );
  5718. }
  5719. return result;
  5720. }
  5721. /**
  5722. * Returns a vector representing the position of the 3D object in world space.
  5723. *
  5724. * @param {Vector3} target - The target vector the result is stored to.
  5725. * @return {Vector3} The 3D object's position in world space.
  5726. */
  5727. getWorldPosition( target ) {
  5728. this.updateWorldMatrix( true, false );
  5729. return target.setFromMatrixPosition( this.matrixWorld );
  5730. }
  5731. /**
  5732. * Returns a Quaternion representing the position of the 3D object in world space.
  5733. *
  5734. * @param {Quaternion} target - The target Quaternion the result is stored to.
  5735. * @return {Quaternion} The 3D object's rotation in world space.
  5736. */
  5737. getWorldQuaternion( target ) {
  5738. this.updateWorldMatrix( true, false );
  5739. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  5740. return target;
  5741. }
  5742. /**
  5743. * Returns a vector representing the scale of the 3D object in world space.
  5744. *
  5745. * @param {Vector3} target - The target vector the result is stored to.
  5746. * @return {Vector3} The 3D object's scale in world space.
  5747. */
  5748. getWorldScale( target ) {
  5749. this.updateWorldMatrix( true, false );
  5750. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  5751. return target;
  5752. }
  5753. /**
  5754. * Returns a vector representing the ("look") direction of the 3D object in world space.
  5755. *
  5756. * @param {Vector3} target - The target vector the result is stored to.
  5757. * @return {Vector3} The 3D object's direction in world space.
  5758. */
  5759. getWorldDirection( target ) {
  5760. this.updateWorldMatrix( true, false );
  5761. const e = this.matrixWorld.elements;
  5762. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  5763. }
  5764. /**
  5765. * Abstract method to get intersections between a casted ray and this
  5766. * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
  5767. * implement this method in order to use raycasting.
  5768. *
  5769. * @abstract
  5770. * @param {Raycaster} raycaster - The raycaster.
  5771. * @param {Array<Object>} intersects - An array holding the result of the method.
  5772. */
  5773. raycast( /* raycaster, intersects */ ) {}
  5774. /**
  5775. * Executes the callback on this 3D object and all descendants.
  5776. *
  5777. * Note: Modifying the scene graph inside the callback is discouraged.
  5778. *
  5779. * @param {Function} callback - A callback function that allows to process the current 3D object.
  5780. */
  5781. traverse( callback ) {
  5782. callback( this );
  5783. const children = this.children;
  5784. for ( let i = 0, l = children.length; i < l; i ++ ) {
  5785. children[ i ].traverse( callback );
  5786. }
  5787. }
  5788. /**
  5789. * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
  5790. * Descendants of invisible 3D objects are not traversed.
  5791. *
  5792. * Note: Modifying the scene graph inside the callback is discouraged.
  5793. *
  5794. * @param {Function} callback - A callback function that allows to process the current 3D object.
  5795. */
  5796. traverseVisible( callback ) {
  5797. if ( this.visible === false ) return;
  5798. callback( this );
  5799. const children = this.children;
  5800. for ( let i = 0, l = children.length; i < l; i ++ ) {
  5801. children[ i ].traverseVisible( callback );
  5802. }
  5803. }
  5804. /**
  5805. * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
  5806. *
  5807. * Note: Modifying the scene graph inside the callback is discouraged.
  5808. *
  5809. * @param {Function} callback - A callback function that allows to process the current 3D object.
  5810. */
  5811. traverseAncestors( callback ) {
  5812. const parent = this.parent;
  5813. if ( parent !== null ) {
  5814. callback( parent );
  5815. parent.traverseAncestors( callback );
  5816. }
  5817. }
  5818. /**
  5819. * Updates the transformation matrix in local space by computing it from the current
  5820. * positon, rotation and scale values.
  5821. */
  5822. updateMatrix() {
  5823. this.matrix.compose( this.position, this.quaternion, this.scale );
  5824. this.matrixWorldNeedsUpdate = true;
  5825. }
  5826. /**
  5827. * Updates the transformation matrix in world space of this 3D objects and its descendants.
  5828. *
  5829. * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
  5830. * local space. The computation of the local and world matrix can be controlled with the
  5831. * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
  5832. * `true` by default. Set these flags to `false` if you need more control over the update matrix process.
  5833. *
  5834. * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
  5835. * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`.
  5836. */
  5837. updateMatrixWorld( force ) {
  5838. if ( this.matrixAutoUpdate ) this.updateMatrix();
  5839. if ( this.matrixWorldNeedsUpdate || force ) {
  5840. if ( this.matrixWorldAutoUpdate === true ) {
  5841. if ( this.parent === null ) {
  5842. this.matrixWorld.copy( this.matrix );
  5843. } else {
  5844. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  5845. }
  5846. }
  5847. this.matrixWorldNeedsUpdate = false;
  5848. force = true;
  5849. }
  5850. // make sure descendants are updated if required
  5851. const children = this.children;
  5852. for ( let i = 0, l = children.length; i < l; i ++ ) {
  5853. const child = children[ i ];
  5854. child.updateMatrixWorld( force );
  5855. }
  5856. }
  5857. /**
  5858. * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
  5859. * update of ancestor and descendant nodes.
  5860. *
  5861. * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
  5862. * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
  5863. */
  5864. updateWorldMatrix( updateParents, updateChildren ) {
  5865. const parent = this.parent;
  5866. if ( updateParents === true && parent !== null ) {
  5867. parent.updateWorldMatrix( true, false );
  5868. }
  5869. if ( this.matrixAutoUpdate ) this.updateMatrix();
  5870. if ( this.matrixWorldAutoUpdate === true ) {
  5871. if ( this.parent === null ) {
  5872. this.matrixWorld.copy( this.matrix );
  5873. } else {
  5874. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  5875. }
  5876. }
  5877. // make sure descendants are updated
  5878. if ( updateChildren === true ) {
  5879. const children = this.children;
  5880. for ( let i = 0, l = children.length; i < l; i ++ ) {
  5881. const child = children[ i ];
  5882. child.updateWorldMatrix( false, true );
  5883. }
  5884. }
  5885. }
  5886. /**
  5887. * Serializes the 3D object into JSON.
  5888. *
  5889. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5890. * @return {Object} A JSON object representing the serialized 3D object.
  5891. * @see {@link ObjectLoader#parse}
  5892. */
  5893. toJSON( meta ) {
  5894. // meta is a string when called from JSON.stringify
  5895. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5896. const output = {};
  5897. // meta is a hash used to collect geometries, materials.
  5898. // not providing it implies that this is the root object
  5899. // being serialized.
  5900. if ( isRootObject ) {
  5901. // initialize meta obj
  5902. meta = {
  5903. geometries: {},
  5904. materials: {},
  5905. textures: {},
  5906. images: {},
  5907. shapes: {},
  5908. skeletons: {},
  5909. animations: {},
  5910. nodes: {}
  5911. };
  5912. output.metadata = {
  5913. version: 4.6,
  5914. type: 'Object',
  5915. generator: 'Object3D.toJSON'
  5916. };
  5917. }
  5918. // standard Object3D serialization
  5919. const object = {};
  5920. object.uuid = this.uuid;
  5921. object.type = this.type;
  5922. if ( this.name !== '' ) object.name = this.name;
  5923. if ( this.castShadow === true ) object.castShadow = true;
  5924. if ( this.receiveShadow === true ) object.receiveShadow = true;
  5925. if ( this.visible === false ) object.visible = false;
  5926. if ( this.frustumCulled === false ) object.frustumCulled = false;
  5927. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  5928. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  5929. object.layers = this.layers.mask;
  5930. object.matrix = this.matrix.toArray();
  5931. object.up = this.up.toArray();
  5932. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  5933. // object specific properties
  5934. if ( this.isInstancedMesh ) {
  5935. object.type = 'InstancedMesh';
  5936. object.count = this.count;
  5937. object.instanceMatrix = this.instanceMatrix.toJSON();
  5938. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  5939. }
  5940. if ( this.isBatchedMesh ) {
  5941. object.type = 'BatchedMesh';
  5942. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  5943. object.sortObjects = this.sortObjects;
  5944. object.drawRanges = this._drawRanges;
  5945. object.reservedRanges = this._reservedRanges;
  5946. object.visibility = this._visibility;
  5947. object.active = this._active;
  5948. object.bounds = this._bounds.map( bound => ( {
  5949. boxInitialized: bound.boxInitialized,
  5950. boxMin: bound.box.min.toArray(),
  5951. boxMax: bound.box.max.toArray(),
  5952. sphereInitialized: bound.sphereInitialized,
  5953. sphereRadius: bound.sphere.radius,
  5954. sphereCenter: bound.sphere.center.toArray()
  5955. } ) );
  5956. object.maxInstanceCount = this._maxInstanceCount;
  5957. object.maxVertexCount = this._maxVertexCount;
  5958. object.maxIndexCount = this._maxIndexCount;
  5959. object.geometryInitialized = this._geometryInitialized;
  5960. object.geometryCount = this._geometryCount;
  5961. object.matricesTexture = this._matricesTexture.toJSON( meta );
  5962. if ( this._colorsTexture !== null ) object.colorsTexture = this._colorsTexture.toJSON( meta );
  5963. if ( this.boundingSphere !== null ) {
  5964. object.boundingSphere = {
  5965. center: object.boundingSphere.center.toArray(),
  5966. radius: object.boundingSphere.radius
  5967. };
  5968. }
  5969. if ( this.boundingBox !== null ) {
  5970. object.boundingBox = {
  5971. min: object.boundingBox.min.toArray(),
  5972. max: object.boundingBox.max.toArray()
  5973. };
  5974. }
  5975. }
  5976. //
  5977. function serialize( library, element ) {
  5978. if ( library[ element.uuid ] === undefined ) {
  5979. library[ element.uuid ] = element.toJSON( meta );
  5980. }
  5981. return element.uuid;
  5982. }
  5983. if ( this.isScene ) {
  5984. if ( this.background ) {
  5985. if ( this.background.isColor ) {
  5986. object.background = this.background.toJSON();
  5987. } else if ( this.background.isTexture ) {
  5988. object.background = this.background.toJSON( meta ).uuid;
  5989. }
  5990. }
  5991. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  5992. object.environment = this.environment.toJSON( meta ).uuid;
  5993. }
  5994. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  5995. object.geometry = serialize( meta.geometries, this.geometry );
  5996. const parameters = this.geometry.parameters;
  5997. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  5998. const shapes = parameters.shapes;
  5999. if ( Array.isArray( shapes ) ) {
  6000. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  6001. const shape = shapes[ i ];
  6002. serialize( meta.shapes, shape );
  6003. }
  6004. } else {
  6005. serialize( meta.shapes, shapes );
  6006. }
  6007. }
  6008. }
  6009. if ( this.isSkinnedMesh ) {
  6010. object.bindMode = this.bindMode;
  6011. object.bindMatrix = this.bindMatrix.toArray();
  6012. if ( this.skeleton !== undefined ) {
  6013. serialize( meta.skeletons, this.skeleton );
  6014. object.skeleton = this.skeleton.uuid;
  6015. }
  6016. }
  6017. if ( this.material !== undefined ) {
  6018. if ( Array.isArray( this.material ) ) {
  6019. const uuids = [];
  6020. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  6021. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  6022. }
  6023. object.material = uuids;
  6024. } else {
  6025. object.material = serialize( meta.materials, this.material );
  6026. }
  6027. }
  6028. //
  6029. if ( this.children.length > 0 ) {
  6030. object.children = [];
  6031. for ( let i = 0; i < this.children.length; i ++ ) {
  6032. object.children.push( this.children[ i ].toJSON( meta ).object );
  6033. }
  6034. }
  6035. //
  6036. if ( this.animations.length > 0 ) {
  6037. object.animations = [];
  6038. for ( let i = 0; i < this.animations.length; i ++ ) {
  6039. const animation = this.animations[ i ];
  6040. object.animations.push( serialize( meta.animations, animation ) );
  6041. }
  6042. }
  6043. if ( isRootObject ) {
  6044. const geometries = extractFromCache( meta.geometries );
  6045. const materials = extractFromCache( meta.materials );
  6046. const textures = extractFromCache( meta.textures );
  6047. const images = extractFromCache( meta.images );
  6048. const shapes = extractFromCache( meta.shapes );
  6049. const skeletons = extractFromCache( meta.skeletons );
  6050. const animations = extractFromCache( meta.animations );
  6051. const nodes = extractFromCache( meta.nodes );
  6052. if ( geometries.length > 0 ) output.geometries = geometries;
  6053. if ( materials.length > 0 ) output.materials = materials;
  6054. if ( textures.length > 0 ) output.textures = textures;
  6055. if ( images.length > 0 ) output.images = images;
  6056. if ( shapes.length > 0 ) output.shapes = shapes;
  6057. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  6058. if ( animations.length > 0 ) output.animations = animations;
  6059. if ( nodes.length > 0 ) output.nodes = nodes;
  6060. }
  6061. output.object = object;
  6062. return output;
  6063. // extract data from the cache hash
  6064. // remove metadata on each item
  6065. // and return as array
  6066. function extractFromCache( cache ) {
  6067. const values = [];
  6068. for ( const key in cache ) {
  6069. const data = cache[ key ];
  6070. delete data.metadata;
  6071. values.push( data );
  6072. }
  6073. return values;
  6074. }
  6075. }
  6076. /**
  6077. * Returns a new 3D object with copied values from this instance.
  6078. *
  6079. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
  6080. * @return {Object3D} A clone of this instance.
  6081. */
  6082. clone( recursive ) {
  6083. return new this.constructor().copy( this, recursive );
  6084. }
  6085. /**
  6086. * Copies the values of the given 3D object to this instance.
  6087. *
  6088. * @param {Object3D} source - The 3D object to copy.
  6089. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
  6090. * @return {Object3D} A reference to this instance.
  6091. */
  6092. copy( source, recursive = true ) {
  6093. this.name = source.name;
  6094. this.up.copy( source.up );
  6095. this.position.copy( source.position );
  6096. this.rotation.order = source.rotation.order;
  6097. this.quaternion.copy( source.quaternion );
  6098. this.scale.copy( source.scale );
  6099. this.matrix.copy( source.matrix );
  6100. this.matrixWorld.copy( source.matrixWorld );
  6101. this.matrixAutoUpdate = source.matrixAutoUpdate;
  6102. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  6103. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  6104. this.layers.mask = source.layers.mask;
  6105. this.visible = source.visible;
  6106. this.castShadow = source.castShadow;
  6107. this.receiveShadow = source.receiveShadow;
  6108. this.frustumCulled = source.frustumCulled;
  6109. this.renderOrder = source.renderOrder;
  6110. this.animations = source.animations.slice();
  6111. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  6112. if ( recursive === true ) {
  6113. for ( let i = 0; i < source.children.length; i ++ ) {
  6114. const child = source.children[ i ];
  6115. this.add( child.clone() );
  6116. }
  6117. }
  6118. return this;
  6119. }
  6120. }
  6121. /**
  6122. * The default up direction for objects, also used as the default
  6123. * position for {@link DirectionalLight} and {@link HemisphereLight}.
  6124. *
  6125. * @static
  6126. * @type {Vector3}
  6127. * @default (0,1,0)
  6128. */
  6129. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  6130. /**
  6131. * The default setting for {@link Object3D#matrixAutoUpdate} for
  6132. * newly created 3D objects.
  6133. *
  6134. * @static
  6135. * @type {boolean}
  6136. * @default true
  6137. */
  6138. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  6139. /**
  6140. * The default setting for {@link Object3D#matrixWorldAutoUpdate} for
  6141. * newly created 3D objects.
  6142. *
  6143. * @static
  6144. * @type {boolean}
  6145. * @default true
  6146. */
  6147. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  6148. const _v0$1 = /*@__PURE__*/ new Vector3();
  6149. const _v1$3 = /*@__PURE__*/ new Vector3();
  6150. const _v2$2 = /*@__PURE__*/ new Vector3();
  6151. const _v3$2 = /*@__PURE__*/ new Vector3();
  6152. const _vab = /*@__PURE__*/ new Vector3();
  6153. const _vac = /*@__PURE__*/ new Vector3();
  6154. const _vbc = /*@__PURE__*/ new Vector3();
  6155. const _vap = /*@__PURE__*/ new Vector3();
  6156. const _vbp = /*@__PURE__*/ new Vector3();
  6157. const _vcp = /*@__PURE__*/ new Vector3();
  6158. const _v40 = /*@__PURE__*/ new Vector4();
  6159. const _v41 = /*@__PURE__*/ new Vector4();
  6160. const _v42 = /*@__PURE__*/ new Vector4();
  6161. class Triangle {
  6162. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  6163. this.a = a;
  6164. this.b = b;
  6165. this.c = c;
  6166. }
  6167. static getNormal( a, b, c, target ) {
  6168. target.subVectors( c, b );
  6169. _v0$1.subVectors( a, b );
  6170. target.cross( _v0$1 );
  6171. const targetLengthSq = target.lengthSq();
  6172. if ( targetLengthSq > 0 ) {
  6173. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  6174. }
  6175. return target.set( 0, 0, 0 );
  6176. }
  6177. // static/instance method to calculate barycentric coordinates
  6178. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  6179. static getBarycoord( point, a, b, c, target ) {
  6180. _v0$1.subVectors( c, a );
  6181. _v1$3.subVectors( b, a );
  6182. _v2$2.subVectors( point, a );
  6183. const dot00 = _v0$1.dot( _v0$1 );
  6184. const dot01 = _v0$1.dot( _v1$3 );
  6185. const dot02 = _v0$1.dot( _v2$2 );
  6186. const dot11 = _v1$3.dot( _v1$3 );
  6187. const dot12 = _v1$3.dot( _v2$2 );
  6188. const denom = ( dot00 * dot11 - dot01 * dot01 );
  6189. // collinear or singular triangle
  6190. if ( denom === 0 ) {
  6191. target.set( 0, 0, 0 );
  6192. return null;
  6193. }
  6194. const invDenom = 1 / denom;
  6195. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  6196. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  6197. // barycentric coordinates must always sum to 1
  6198. return target.set( 1 - u - v, v, u );
  6199. }
  6200. static containsPoint( point, a, b, c ) {
  6201. // if the triangle is degenerate then we can't contain a point
  6202. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  6203. return false;
  6204. }
  6205. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  6206. }
  6207. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  6208. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  6209. target.x = 0;
  6210. target.y = 0;
  6211. if ( 'z' in target ) target.z = 0;
  6212. if ( 'w' in target ) target.w = 0;
  6213. return null;
  6214. }
  6215. target.setScalar( 0 );
  6216. target.addScaledVector( v1, _v3$2.x );
  6217. target.addScaledVector( v2, _v3$2.y );
  6218. target.addScaledVector( v3, _v3$2.z );
  6219. return target;
  6220. }
  6221. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  6222. _v40.setScalar( 0 );
  6223. _v41.setScalar( 0 );
  6224. _v42.setScalar( 0 );
  6225. _v40.fromBufferAttribute( attr, i1 );
  6226. _v41.fromBufferAttribute( attr, i2 );
  6227. _v42.fromBufferAttribute( attr, i3 );
  6228. target.setScalar( 0 );
  6229. target.addScaledVector( _v40, barycoord.x );
  6230. target.addScaledVector( _v41, barycoord.y );
  6231. target.addScaledVector( _v42, barycoord.z );
  6232. return target;
  6233. }
  6234. static isFrontFacing( a, b, c, direction ) {
  6235. _v0$1.subVectors( c, b );
  6236. _v1$3.subVectors( a, b );
  6237. // strictly front facing
  6238. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  6239. }
  6240. set( a, b, c ) {
  6241. this.a.copy( a );
  6242. this.b.copy( b );
  6243. this.c.copy( c );
  6244. return this;
  6245. }
  6246. setFromPointsAndIndices( points, i0, i1, i2 ) {
  6247. this.a.copy( points[ i0 ] );
  6248. this.b.copy( points[ i1 ] );
  6249. this.c.copy( points[ i2 ] );
  6250. return this;
  6251. }
  6252. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  6253. this.a.fromBufferAttribute( attribute, i0 );
  6254. this.b.fromBufferAttribute( attribute, i1 );
  6255. this.c.fromBufferAttribute( attribute, i2 );
  6256. return this;
  6257. }
  6258. clone() {
  6259. return new this.constructor().copy( this );
  6260. }
  6261. copy( triangle ) {
  6262. this.a.copy( triangle.a );
  6263. this.b.copy( triangle.b );
  6264. this.c.copy( triangle.c );
  6265. return this;
  6266. }
  6267. getArea() {
  6268. _v0$1.subVectors( this.c, this.b );
  6269. _v1$3.subVectors( this.a, this.b );
  6270. return _v0$1.cross( _v1$3 ).length() * 0.5;
  6271. }
  6272. getMidpoint( target ) {
  6273. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  6274. }
  6275. getNormal( target ) {
  6276. return Triangle.getNormal( this.a, this.b, this.c, target );
  6277. }
  6278. getPlane( target ) {
  6279. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  6280. }
  6281. getBarycoord( point, target ) {
  6282. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  6283. }
  6284. getInterpolation( point, v1, v2, v3, target ) {
  6285. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  6286. }
  6287. containsPoint( point ) {
  6288. return Triangle.containsPoint( point, this.a, this.b, this.c );
  6289. }
  6290. isFrontFacing( direction ) {
  6291. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  6292. }
  6293. intersectsBox( box ) {
  6294. return box.intersectsTriangle( this );
  6295. }
  6296. closestPointToPoint( p, target ) {
  6297. const a = this.a, b = this.b, c = this.c;
  6298. let v, w;
  6299. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  6300. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  6301. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  6302. // basically, we're distinguishing which of the voronoi regions of the triangle
  6303. // the point lies in with the minimum amount of redundant computation.
  6304. _vab.subVectors( b, a );
  6305. _vac.subVectors( c, a );
  6306. _vap.subVectors( p, a );
  6307. const d1 = _vab.dot( _vap );
  6308. const d2 = _vac.dot( _vap );
  6309. if ( d1 <= 0 && d2 <= 0 ) {
  6310. // vertex region of A; barycentric coords (1, 0, 0)
  6311. return target.copy( a );
  6312. }
  6313. _vbp.subVectors( p, b );
  6314. const d3 = _vab.dot( _vbp );
  6315. const d4 = _vac.dot( _vbp );
  6316. if ( d3 >= 0 && d4 <= d3 ) {
  6317. // vertex region of B; barycentric coords (0, 1, 0)
  6318. return target.copy( b );
  6319. }
  6320. const vc = d1 * d4 - d3 * d2;
  6321. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  6322. v = d1 / ( d1 - d3 );
  6323. // edge region of AB; barycentric coords (1-v, v, 0)
  6324. return target.copy( a ).addScaledVector( _vab, v );
  6325. }
  6326. _vcp.subVectors( p, c );
  6327. const d5 = _vab.dot( _vcp );
  6328. const d6 = _vac.dot( _vcp );
  6329. if ( d6 >= 0 && d5 <= d6 ) {
  6330. // vertex region of C; barycentric coords (0, 0, 1)
  6331. return target.copy( c );
  6332. }
  6333. const vb = d5 * d2 - d1 * d6;
  6334. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  6335. w = d2 / ( d2 - d6 );
  6336. // edge region of AC; barycentric coords (1-w, 0, w)
  6337. return target.copy( a ).addScaledVector( _vac, w );
  6338. }
  6339. const va = d3 * d6 - d5 * d4;
  6340. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  6341. _vbc.subVectors( c, b );
  6342. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  6343. // edge region of BC; barycentric coords (0, 1-w, w)
  6344. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  6345. }
  6346. // face region
  6347. const denom = 1 / ( va + vb + vc );
  6348. // u = va * denom
  6349. v = vb * denom;
  6350. w = vc * denom;
  6351. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  6352. }
  6353. equals( triangle ) {
  6354. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  6355. }
  6356. }
  6357. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  6358. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  6359. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  6360. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  6361. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  6362. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  6363. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  6364. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  6365. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  6366. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  6367. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  6368. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  6369. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  6370. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  6371. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  6372. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  6373. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  6374. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  6375. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  6376. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  6377. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  6378. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  6379. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  6380. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  6381. const _hslA = { h: 0, s: 0, l: 0 };
  6382. const _hslB = { h: 0, s: 0, l: 0 };
  6383. function hue2rgb( p, q, t ) {
  6384. if ( t < 0 ) t += 1;
  6385. if ( t > 1 ) t -= 1;
  6386. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  6387. if ( t < 1 / 2 ) return q;
  6388. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  6389. return p;
  6390. }
  6391. class Color {
  6392. constructor( r, g, b ) {
  6393. this.isColor = true;
  6394. this.r = 1;
  6395. this.g = 1;
  6396. this.b = 1;
  6397. return this.set( r, g, b );
  6398. }
  6399. set( r, g, b ) {
  6400. if ( g === undefined && b === undefined ) {
  6401. // r is THREE.Color, hex or string
  6402. const value = r;
  6403. if ( value && value.isColor ) {
  6404. this.copy( value );
  6405. } else if ( typeof value === 'number' ) {
  6406. this.setHex( value );
  6407. } else if ( typeof value === 'string' ) {
  6408. this.setStyle( value );
  6409. }
  6410. } else {
  6411. this.setRGB( r, g, b );
  6412. }
  6413. return this;
  6414. }
  6415. setScalar( scalar ) {
  6416. this.r = scalar;
  6417. this.g = scalar;
  6418. this.b = scalar;
  6419. return this;
  6420. }
  6421. setHex( hex, colorSpace = SRGBColorSpace ) {
  6422. hex = Math.floor( hex );
  6423. this.r = ( hex >> 16 & 255 ) / 255;
  6424. this.g = ( hex >> 8 & 255 ) / 255;
  6425. this.b = ( hex & 255 ) / 255;
  6426. ColorManagement.toWorkingColorSpace( this, colorSpace );
  6427. return this;
  6428. }
  6429. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  6430. this.r = r;
  6431. this.g = g;
  6432. this.b = b;
  6433. ColorManagement.toWorkingColorSpace( this, colorSpace );
  6434. return this;
  6435. }
  6436. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  6437. // h,s,l ranges are in 0.0 - 1.0
  6438. h = euclideanModulo( h, 1 );
  6439. s = clamp( s, 0, 1 );
  6440. l = clamp( l, 0, 1 );
  6441. if ( s === 0 ) {
  6442. this.r = this.g = this.b = l;
  6443. } else {
  6444. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  6445. const q = ( 2 * l ) - p;
  6446. this.r = hue2rgb( q, p, h + 1 / 3 );
  6447. this.g = hue2rgb( q, p, h );
  6448. this.b = hue2rgb( q, p, h - 1 / 3 );
  6449. }
  6450. ColorManagement.toWorkingColorSpace( this, colorSpace );
  6451. return this;
  6452. }
  6453. setStyle( style, colorSpace = SRGBColorSpace ) {
  6454. function handleAlpha( string ) {
  6455. if ( string === undefined ) return;
  6456. if ( parseFloat( string ) < 1 ) {
  6457. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  6458. }
  6459. }
  6460. let m;
  6461. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  6462. // rgb / hsl
  6463. let color;
  6464. const name = m[ 1 ];
  6465. const components = m[ 2 ];
  6466. switch ( name ) {
  6467. case 'rgb':
  6468. case 'rgba':
  6469. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  6470. // rgb(255,0,0) rgba(255,0,0,0.5)
  6471. handleAlpha( color[ 4 ] );
  6472. return this.setRGB(
  6473. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  6474. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  6475. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  6476. colorSpace
  6477. );
  6478. }
  6479. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  6480. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  6481. handleAlpha( color[ 4 ] );
  6482. return this.setRGB(
  6483. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  6484. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  6485. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  6486. colorSpace
  6487. );
  6488. }
  6489. break;
  6490. case 'hsl':
  6491. case 'hsla':
  6492. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  6493. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  6494. handleAlpha( color[ 4 ] );
  6495. return this.setHSL(
  6496. parseFloat( color[ 1 ] ) / 360,
  6497. parseFloat( color[ 2 ] ) / 100,
  6498. parseFloat( color[ 3 ] ) / 100,
  6499. colorSpace
  6500. );
  6501. }
  6502. break;
  6503. default:
  6504. console.warn( 'THREE.Color: Unknown color model ' + style );
  6505. }
  6506. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  6507. // hex color
  6508. const hex = m[ 1 ];
  6509. const size = hex.length;
  6510. if ( size === 3 ) {
  6511. // #ff0
  6512. return this.setRGB(
  6513. parseInt( hex.charAt( 0 ), 16 ) / 15,
  6514. parseInt( hex.charAt( 1 ), 16 ) / 15,
  6515. parseInt( hex.charAt( 2 ), 16 ) / 15,
  6516. colorSpace
  6517. );
  6518. } else if ( size === 6 ) {
  6519. // #ff0000
  6520. return this.setHex( parseInt( hex, 16 ), colorSpace );
  6521. } else {
  6522. console.warn( 'THREE.Color: Invalid hex color ' + style );
  6523. }
  6524. } else if ( style && style.length > 0 ) {
  6525. return this.setColorName( style, colorSpace );
  6526. }
  6527. return this;
  6528. }
  6529. setColorName( style, colorSpace = SRGBColorSpace ) {
  6530. // color keywords
  6531. const hex = _colorKeywords[ style.toLowerCase() ];
  6532. if ( hex !== undefined ) {
  6533. // red
  6534. this.setHex( hex, colorSpace );
  6535. } else {
  6536. // unknown color
  6537. console.warn( 'THREE.Color: Unknown color ' + style );
  6538. }
  6539. return this;
  6540. }
  6541. clone() {
  6542. return new this.constructor( this.r, this.g, this.b );
  6543. }
  6544. copy( color ) {
  6545. this.r = color.r;
  6546. this.g = color.g;
  6547. this.b = color.b;
  6548. return this;
  6549. }
  6550. copySRGBToLinear( color ) {
  6551. this.r = SRGBToLinear( color.r );
  6552. this.g = SRGBToLinear( color.g );
  6553. this.b = SRGBToLinear( color.b );
  6554. return this;
  6555. }
  6556. copyLinearToSRGB( color ) {
  6557. this.r = LinearToSRGB( color.r );
  6558. this.g = LinearToSRGB( color.g );
  6559. this.b = LinearToSRGB( color.b );
  6560. return this;
  6561. }
  6562. convertSRGBToLinear() {
  6563. this.copySRGBToLinear( this );
  6564. return this;
  6565. }
  6566. convertLinearToSRGB() {
  6567. this.copyLinearToSRGB( this );
  6568. return this;
  6569. }
  6570. getHex( colorSpace = SRGBColorSpace ) {
  6571. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  6572. return Math.round( clamp( _color.r * 255, 0, 255 ) ) * 65536 + Math.round( clamp( _color.g * 255, 0, 255 ) ) * 256 + Math.round( clamp( _color.b * 255, 0, 255 ) );
  6573. }
  6574. getHexString( colorSpace = SRGBColorSpace ) {
  6575. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( -6 );
  6576. }
  6577. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  6578. // h,s,l ranges are in 0.0 - 1.0
  6579. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  6580. const r = _color.r, g = _color.g, b = _color.b;
  6581. const max = Math.max( r, g, b );
  6582. const min = Math.min( r, g, b );
  6583. let hue, saturation;
  6584. const lightness = ( min + max ) / 2.0;
  6585. if ( min === max ) {
  6586. hue = 0;
  6587. saturation = 0;
  6588. } else {
  6589. const delta = max - min;
  6590. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  6591. switch ( max ) {
  6592. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  6593. case g: hue = ( b - r ) / delta + 2; break;
  6594. case b: hue = ( r - g ) / delta + 4; break;
  6595. }
  6596. hue /= 6;
  6597. }
  6598. target.h = hue;
  6599. target.s = saturation;
  6600. target.l = lightness;
  6601. return target;
  6602. }
  6603. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  6604. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  6605. target.r = _color.r;
  6606. target.g = _color.g;
  6607. target.b = _color.b;
  6608. return target;
  6609. }
  6610. getStyle( colorSpace = SRGBColorSpace ) {
  6611. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  6612. const r = _color.r, g = _color.g, b = _color.b;
  6613. if ( colorSpace !== SRGBColorSpace ) {
  6614. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  6615. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  6616. }
  6617. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  6618. }
  6619. offsetHSL( h, s, l ) {
  6620. this.getHSL( _hslA );
  6621. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  6622. }
  6623. add( color ) {
  6624. this.r += color.r;
  6625. this.g += color.g;
  6626. this.b += color.b;
  6627. return this;
  6628. }
  6629. addColors( color1, color2 ) {
  6630. this.r = color1.r + color2.r;
  6631. this.g = color1.g + color2.g;
  6632. this.b = color1.b + color2.b;
  6633. return this;
  6634. }
  6635. addScalar( s ) {
  6636. this.r += s;
  6637. this.g += s;
  6638. this.b += s;
  6639. return this;
  6640. }
  6641. sub( color ) {
  6642. this.r = Math.max( 0, this.r - color.r );
  6643. this.g = Math.max( 0, this.g - color.g );
  6644. this.b = Math.max( 0, this.b - color.b );
  6645. return this;
  6646. }
  6647. multiply( color ) {
  6648. this.r *= color.r;
  6649. this.g *= color.g;
  6650. this.b *= color.b;
  6651. return this;
  6652. }
  6653. multiplyScalar( s ) {
  6654. this.r *= s;
  6655. this.g *= s;
  6656. this.b *= s;
  6657. return this;
  6658. }
  6659. lerp( color, alpha ) {
  6660. this.r += ( color.r - this.r ) * alpha;
  6661. this.g += ( color.g - this.g ) * alpha;
  6662. this.b += ( color.b - this.b ) * alpha;
  6663. return this;
  6664. }
  6665. lerpColors( color1, color2, alpha ) {
  6666. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  6667. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  6668. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  6669. return this;
  6670. }
  6671. lerpHSL( color, alpha ) {
  6672. this.getHSL( _hslA );
  6673. color.getHSL( _hslB );
  6674. const h = lerp( _hslA.h, _hslB.h, alpha );
  6675. const s = lerp( _hslA.s, _hslB.s, alpha );
  6676. const l = lerp( _hslA.l, _hslB.l, alpha );
  6677. this.setHSL( h, s, l );
  6678. return this;
  6679. }
  6680. setFromVector3( v ) {
  6681. this.r = v.x;
  6682. this.g = v.y;
  6683. this.b = v.z;
  6684. return this;
  6685. }
  6686. applyMatrix3( m ) {
  6687. const r = this.r, g = this.g, b = this.b;
  6688. const e = m.elements;
  6689. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  6690. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  6691. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  6692. return this;
  6693. }
  6694. equals( c ) {
  6695. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  6696. }
  6697. fromArray( array, offset = 0 ) {
  6698. this.r = array[ offset ];
  6699. this.g = array[ offset + 1 ];
  6700. this.b = array[ offset + 2 ];
  6701. return this;
  6702. }
  6703. toArray( array = [], offset = 0 ) {
  6704. array[ offset ] = this.r;
  6705. array[ offset + 1 ] = this.g;
  6706. array[ offset + 2 ] = this.b;
  6707. return array;
  6708. }
  6709. fromBufferAttribute( attribute, index ) {
  6710. this.r = attribute.getX( index );
  6711. this.g = attribute.getY( index );
  6712. this.b = attribute.getZ( index );
  6713. return this;
  6714. }
  6715. toJSON() {
  6716. return this.getHex();
  6717. }
  6718. *[ Symbol.iterator ]() {
  6719. yield this.r;
  6720. yield this.g;
  6721. yield this.b;
  6722. }
  6723. }
  6724. const _color = /*@__PURE__*/ new Color();
  6725. Color.NAMES = _colorKeywords;
  6726. let _materialId = 0;
  6727. /**
  6728. * Abstract base class for materials.
  6729. *
  6730. * Materials define the appearance of renderable 3D objects.
  6731. *
  6732. * @abstract
  6733. * @augments EventDispatcher
  6734. */
  6735. class Material extends EventDispatcher {
  6736. /**
  6737. * Constructs a new material.
  6738. */
  6739. constructor() {
  6740. super();
  6741. /**
  6742. * This flag can be used for type testing.
  6743. *
  6744. * @type {boolean}
  6745. * @readonly
  6746. * @default true
  6747. */
  6748. this.isMaterial = true;
  6749. /**
  6750. * The ID of the material.
  6751. *
  6752. * @name Material#id
  6753. * @type {number}
  6754. * @readonly
  6755. */
  6756. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  6757. /**
  6758. * The UUID of the material.
  6759. *
  6760. * @type {string}
  6761. * @readonly
  6762. */
  6763. this.uuid = generateUUID();
  6764. /**
  6765. * The name of the material.
  6766. *
  6767. * @type {string}
  6768. */
  6769. this.name = '';
  6770. /**
  6771. * The type property is used for detecting the object type
  6772. * in context of serialization/deserialization.
  6773. *
  6774. * @type {string}
  6775. * @readonly
  6776. */
  6777. this.type = 'Material';
  6778. /**
  6779. * Defines the blending type of the material.
  6780. *
  6781. * It must be set to `CustomBlending` if custom blending properties like
  6782. * {@link Material#blendSrc}, {@link Material#blendDst} or {@link Material#blendEquation}
  6783. * should have any effect.
  6784. *
  6785. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending)}
  6786. * @default NormalBlending
  6787. */
  6788. this.blending = NormalBlending;
  6789. /**
  6790. * Defines which side of faces will be rendered - front, back or both.
  6791. *
  6792. * @type {(FrontSide|BackSide|DoubleSide)}
  6793. * @default FrontSide
  6794. */
  6795. this.side = FrontSide;
  6796. /**
  6797. * If set to `true`, vertex colors should be used.
  6798. *
  6799. * The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or
  6800. * four (RGBA) component color buffer attribute is used.
  6801. *
  6802. * @type {boolean}
  6803. * @default false
  6804. */
  6805. this.vertexColors = false;
  6806. /**
  6807. * Defines how transparent the material is.
  6808. * A value of `0.0` indicates fully transparent, `1.0` is fully opaque.
  6809. *
  6810. * If the {@link Material#transparent} is not set to `true`,
  6811. * the material will remain fully opaque and this value will only affect its color.
  6812. *
  6813. * @type {number}
  6814. * @default 1
  6815. */
  6816. this.opacity = 1;
  6817. /**
  6818. * Defines whether this material is transparent. This has an effect on
  6819. * rendering as transparent objects need special treatment and are rendered
  6820. * after non-transparent objects.
  6821. *
  6822. * When set to true, the extent to which the material is transparent is
  6823. * controlled by {@link Material#opacity}.
  6824. *
  6825. * @type {boolean}
  6826. * @default false
  6827. */
  6828. this.transparent = false;
  6829. /**
  6830. * Enables alpha hashed transparency, an alternative to {@link Material#transparent} or
  6831. * {@link Material#alphaTest}. The material will not be rendered if opacity is lower than
  6832. * a random threshold. Randomization introduces some grain or noise, but approximates alpha
  6833. * blending without the associated problems of sorting. Using TAA can reduce the resulting noise.
  6834. *
  6835. * @type {boolean}
  6836. * @default false
  6837. */
  6838. this.alphaHash = false;
  6839. /**
  6840. * Defines the blending source factor.
  6841. *
  6842. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  6843. * @default SrcAlphaFactor
  6844. */
  6845. this.blendSrc = SrcAlphaFactor;
  6846. /**
  6847. * Defines the blending destination factor.
  6848. *
  6849. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  6850. * @default OneMinusSrcAlphaFactor
  6851. */
  6852. this.blendDst = OneMinusSrcAlphaFactor;
  6853. /**
  6854. * Defines the blending equation.
  6855. *
  6856. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  6857. * @default OneMinusSrcAlphaFactor
  6858. */
  6859. this.blendEquation = AddEquation;
  6860. /**
  6861. * Defines the blending source alpha factor.
  6862. *
  6863. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  6864. * @default null
  6865. */
  6866. this.blendSrcAlpha = null;
  6867. /**
  6868. * Defines the blending destination alpha factor.
  6869. *
  6870. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  6871. * @default null
  6872. */
  6873. this.blendDstAlpha = null;
  6874. /**
  6875. * Defines the blending equation of the alpha channel.
  6876. *
  6877. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  6878. * @default OneMinusSrcAlphaFactor
  6879. */
  6880. this.blendEquationAlpha = null;
  6881. /**
  6882. * Represents the RGB values of the constant blend color.
  6883. *
  6884. * This property has only an effect when using custom blending with `ConstantColor` or `OneMinusConstantColor`.
  6885. *
  6886. * @type {Color}
  6887. * @default (0,0,0)
  6888. */
  6889. this.blendColor = new Color( 0, 0, 0 );
  6890. /**
  6891. * Represents the alpha value of the constant blend color.
  6892. *
  6893. * This property has only an effect when using custom blending with `ConstantAlpha` or `OneMinusConstantAlpha`.
  6894. *
  6895. * @type {number}
  6896. * @default 0
  6897. */
  6898. this.blendAlpha = 0;
  6899. /**
  6900. * Defines the depth function.
  6901. *
  6902. * @type {(NeverDepth|AlwaysDepth|LessDepth|LessEqualDepth|EqualDepth|GreaterEqualDepth|GreaterDepth|NotEqualDepth)}
  6903. * @default LessEqualDepth
  6904. */
  6905. this.depthFunc = LessEqualDepth;
  6906. /**
  6907. * Whether to have depth test enabled when rendering this material.
  6908. * When the depth test is disabled, the depth write will also be implicitly disabled.
  6909. *
  6910. * @type {boolean}
  6911. * @default true
  6912. */
  6913. this.depthTest = true;
  6914. /**
  6915. * Whether rendering this material has any effect on the depth buffer.
  6916. *
  6917. * When drawing 2D overlays it can be useful to disable the depth writing in
  6918. * order to layer several things together without creating z-index artifacts.
  6919. *
  6920. * @type {boolean}
  6921. * @default true
  6922. */
  6923. this.depthWrite = true;
  6924. /**
  6925. * The bit mask to use when writing to the stencil buffer.
  6926. *
  6927. * @type {number}
  6928. * @default 0xff
  6929. */
  6930. this.stencilWriteMask = 0xff;
  6931. /**
  6932. * The stencil comparison function to use.
  6933. *
  6934. * @type {NeverStencilFunc|LessStencilFunc|EqualStencilFunc|LessEqualStencilFunc|GreaterStencilFunc|NotEqualStencilFunc|GreaterEqualStencilFunc|AlwaysStencilFunc}
  6935. * @default AlwaysStencilFunc
  6936. */
  6937. this.stencilFunc = AlwaysStencilFunc;
  6938. /**
  6939. * The value to use when performing stencil comparisons or stencil operations.
  6940. *
  6941. * @type {number}
  6942. * @default 0
  6943. */
  6944. this.stencilRef = 0;
  6945. /**
  6946. * The bit mask to use when comparing against the stencil buffer.
  6947. *
  6948. * @type {number}
  6949. * @default 0xff
  6950. */
  6951. this.stencilFuncMask = 0xff;
  6952. /**
  6953. * Which stencil operation to perform when the comparison function returns `false`.
  6954. *
  6955. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  6956. * @default KeepStencilOp
  6957. */
  6958. this.stencilFail = KeepStencilOp;
  6959. /**
  6960. * Which stencil operation to perform when the comparison function returns
  6961. * `true` but the depth test fails.
  6962. *
  6963. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  6964. * @default KeepStencilOp
  6965. */
  6966. this.stencilZFail = KeepStencilOp;
  6967. /**
  6968. * Which stencil operation to perform when the comparison function returns
  6969. * `true` and the depth test passes.
  6970. *
  6971. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  6972. * @default KeepStencilOp
  6973. */
  6974. this.stencilZPass = KeepStencilOp;
  6975. /**
  6976. * Whether stencil operations are performed against the stencil buffer. In
  6977. * order to perform writes or comparisons against the stencil buffer this
  6978. * value must be `true`.
  6979. *
  6980. * @type {boolean}
  6981. * @default false
  6982. */
  6983. this.stencilWrite = false;
  6984. /**
  6985. * User-defined clipping planes specified as THREE.Plane objects in world
  6986. * space. These planes apply to the objects this material is attached to.
  6987. * Points in space whose signed distance to the plane is negative are clipped
  6988. * (not rendered). This requires {@link WebGLRenderer#localClippingEnabled} to
  6989. * be `true`.
  6990. *
  6991. * @type {?Array<Plane>}
  6992. * @default null
  6993. */
  6994. this.clippingPlanes = null;
  6995. /**
  6996. * Changes the behavior of clipping planes so that only their intersection is
  6997. * clipped, rather than their union.
  6998. *
  6999. * @type {boolean}
  7000. * @default false
  7001. */
  7002. this.clipIntersection = false;
  7003. /**
  7004. * Defines whether to clip shadows according to the clipping planes specified
  7005. * on this material.
  7006. *
  7007. * @type {boolean}
  7008. * @default false
  7009. */
  7010. this.clipShadows = false;
  7011. /**
  7012. * Defines which side of faces cast shadows. If `null`, the side casting shadows
  7013. * is determined as follows:
  7014. *
  7015. * - When {@link Material#side} is set to `FrontSide`, the back side cast shadows.
  7016. * - When {@link Material#side} is set to `BackSide`, the front side cast shadows.
  7017. * - When {@link Material#side} is set to `DoubleSide`, both sides cast shadows.
  7018. *
  7019. * @type {?(FrontSide|BackSide|DoubleSide)}
  7020. * @default null
  7021. */
  7022. this.shadowSide = null;
  7023. /**
  7024. * Whether to render the material's color.
  7025. *
  7026. * This can be used in conjunction with {@link Object3D#renderOder} to create invisible
  7027. * objects that occlude other objects.
  7028. *
  7029. * @type {boolean}
  7030. * @default true
  7031. */
  7032. this.colorWrite = true;
  7033. /**
  7034. * Override the renderer's default precision for this material.
  7035. *
  7036. * @type {?('highp'|'mediump'|'lowp')}
  7037. * @default null
  7038. */
  7039. this.precision = null;
  7040. /**
  7041. * Whether to use polygon offset or not. When enabled, each fragment's depth value will
  7042. * be offset after it is interpolated from the depth values of the appropriate vertices.
  7043. * The offset is added before the depth test is performed and before the value is written
  7044. * into the depth buffer.
  7045. *
  7046. * Can be useful for rendering hidden-line images, for applying decals to surfaces, and for
  7047. * rendering solids with highlighted edges.
  7048. *
  7049. * @type {boolean}
  7050. * @default false
  7051. */
  7052. this.polygonOffset = false;
  7053. /**
  7054. * Specifies a scale factor that is used to create a variable depth offset for each polygon.
  7055. *
  7056. * @type {number}
  7057. * @default 0
  7058. */
  7059. this.polygonOffsetFactor = 0;
  7060. /**
  7061. * Is multiplied by an implementation-specific value to create a constant depth offset.
  7062. *
  7063. * @type {number}
  7064. * @default 0
  7065. */
  7066. this.polygonOffsetUnits = 0;
  7067. /**
  7068. * Whether to apply dithering to the color to remove the appearance of banding.
  7069. *
  7070. * @type {boolean}
  7071. * @default false
  7072. */
  7073. this.dithering = false;
  7074. /**
  7075. * Whether alpha to coverage should be enabled or not. Can only be used with MSAA-enabled contexts
  7076. * (meaning when the renderer was created with *antialias* parameter set to `true`). Enabling this
  7077. * will smooth aliasing on clip plane edges and alphaTest-clipped edges.
  7078. *
  7079. * @type {boolean}
  7080. * @default false
  7081. */
  7082. this.alphaToCoverage = false;
  7083. /**
  7084. * Whether to premultiply the alpha (transparency) value.
  7085. *
  7086. * @type {boolean}
  7087. * @default false
  7088. */
  7089. this.premultipliedAlpha = false;
  7090. /**
  7091. * Whether double-sided, transparent objects should be rendered with a single pass or not.
  7092. *
  7093. * The engine renders double-sided, transparent objects with two draw calls (back faces first,
  7094. * then front faces) to mitigate transparency artifacts. There are scenarios however where this
  7095. * approach produces no quality gains but still doubles draw calls e.g. when rendering flat
  7096. * vegetation like grass sprites. In these cases, set the `forceSinglePass` flag to `true` to
  7097. * disable the two pass rendering to avoid performance issues.
  7098. *
  7099. * @type {boolean}
  7100. * @default false
  7101. */
  7102. this.forceSinglePass = false;
  7103. /**
  7104. * Defines whether 3D objects using this material are visible.
  7105. *
  7106. * @type {boolean}
  7107. * @default true
  7108. */
  7109. this.visible = true;
  7110. /**
  7111. * Defines whether this material is tone mapped according to the renderer's tone mapping setting.
  7112. *
  7113. * It is ignored when rendering to a render target or using post processing or when using
  7114. * `WebGPURenderer`. In all these cases, all materials are honored by tone mapping.
  7115. *
  7116. * @type {boolean}
  7117. * @default true
  7118. */
  7119. this.toneMapped = true;
  7120. /**
  7121. * An object that can be used to store custom data about the Material. It
  7122. * should not hold references to functions as these will not be cloned.
  7123. *
  7124. * @type {Object}
  7125. */
  7126. this.userData = {};
  7127. /**
  7128. * This starts at `0` and counts how many times {@link Material#needsUpdate} is set to `true`.
  7129. *
  7130. * @type {number}
  7131. * @readonly
  7132. * @default 0
  7133. */
  7134. this.version = 0;
  7135. this._alphaTest = 0;
  7136. }
  7137. /**
  7138. * Sets the alpha value to be used when running an alpha test. The material
  7139. * will not be rendered if the opacity is lower than this value.
  7140. *
  7141. * @type {number}
  7142. * @readonly
  7143. * @default 0
  7144. */
  7145. get alphaTest() {
  7146. return this._alphaTest;
  7147. }
  7148. set alphaTest( value ) {
  7149. if ( this._alphaTest > 0 !== value > 0 ) {
  7150. this.version ++;
  7151. }
  7152. this._alphaTest = value;
  7153. }
  7154. /**
  7155. * An optional callback that is executed immediately before the material is used to render a 3D object.
  7156. *
  7157. * This method can only be used when rendering with {@link WebGLRenderer}.
  7158. *
  7159. * @param {WebGLRenderer} renderer - The renderer.
  7160. * @param {Scene} scene - The scene.
  7161. * @param {Camera} camera - The camera that is used to render the scene.
  7162. * @param {BufferGeometry} geometry - The 3D object's geometry.
  7163. * @param {Object3D} object - The 3D object.
  7164. * @param {Object} group - The geometry group data.
  7165. */
  7166. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  7167. /**
  7168. * An optional callback that is executed immediately before the shader
  7169. * program is compiled. This function is called with the shader source code
  7170. * as a parameter. Useful for the modification of built-in materials.
  7171. *
  7172. * This method can only be used when rendering with {@link WebGLRenderer}. The
  7173. * recommended approach when customizing materials is to use `WebGPURenderer` with the new
  7174. * Node Material system and [TSL]{@link https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language}.
  7175. *
  7176. * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
  7177. * @param {WebGLRenderer} renderer - A reference to the renderer.
  7178. */
  7179. onBeforeCompile( /* shaderobject, renderer */ ) {}
  7180. /**
  7181. * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
  7182. * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
  7183. * shader or recompile the shader for this material as needed.
  7184. *
  7185. * This method can only be used when rendering with {@link WebGLRenderer}.
  7186. *
  7187. * @return {string} The custom program cache key.
  7188. */
  7189. customProgramCacheKey() {
  7190. return this.onBeforeCompile.toString();
  7191. }
  7192. setValues( values ) {
  7193. if ( values === undefined ) return;
  7194. for ( const key in values ) {
  7195. const newValue = values[ key ];
  7196. if ( newValue === undefined ) {
  7197. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  7198. continue;
  7199. }
  7200. const currentValue = this[ key ];
  7201. if ( currentValue === undefined ) {
  7202. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  7203. continue;
  7204. }
  7205. if ( currentValue && currentValue.isColor ) {
  7206. currentValue.set( newValue );
  7207. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  7208. currentValue.copy( newValue );
  7209. } else {
  7210. this[ key ] = newValue;
  7211. }
  7212. }
  7213. }
  7214. /**
  7215. * Serializes the material into JSON.
  7216. *
  7217. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  7218. * @return {Object} A JSON object representing the serialized material.
  7219. * @see {@link ObjectLoader#parse}
  7220. */
  7221. toJSON( meta ) {
  7222. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  7223. if ( isRootObject ) {
  7224. meta = {
  7225. textures: {},
  7226. images: {}
  7227. };
  7228. }
  7229. const data = {
  7230. metadata: {
  7231. version: 4.6,
  7232. type: 'Material',
  7233. generator: 'Material.toJSON'
  7234. }
  7235. };
  7236. // standard Material serialization
  7237. data.uuid = this.uuid;
  7238. data.type = this.type;
  7239. if ( this.name !== '' ) data.name = this.name;
  7240. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  7241. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  7242. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  7243. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  7244. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  7245. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  7246. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  7247. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  7248. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  7249. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  7250. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  7251. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  7252. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  7253. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  7254. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  7255. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  7256. }
  7257. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  7258. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  7259. }
  7260. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  7261. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  7262. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  7263. }
  7264. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  7265. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  7266. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  7267. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  7268. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  7269. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  7270. }
  7271. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  7272. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  7273. }
  7274. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  7275. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  7276. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  7277. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  7278. }
  7279. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  7280. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  7281. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  7282. if ( this.lightMap && this.lightMap.isTexture ) {
  7283. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  7284. data.lightMapIntensity = this.lightMapIntensity;
  7285. }
  7286. if ( this.aoMap && this.aoMap.isTexture ) {
  7287. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  7288. data.aoMapIntensity = this.aoMapIntensity;
  7289. }
  7290. if ( this.bumpMap && this.bumpMap.isTexture ) {
  7291. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  7292. data.bumpScale = this.bumpScale;
  7293. }
  7294. if ( this.normalMap && this.normalMap.isTexture ) {
  7295. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  7296. data.normalMapType = this.normalMapType;
  7297. data.normalScale = this.normalScale.toArray();
  7298. }
  7299. if ( this.displacementMap && this.displacementMap.isTexture ) {
  7300. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  7301. data.displacementScale = this.displacementScale;
  7302. data.displacementBias = this.displacementBias;
  7303. }
  7304. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  7305. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  7306. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  7307. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  7308. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  7309. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  7310. if ( this.envMap && this.envMap.isTexture ) {
  7311. data.envMap = this.envMap.toJSON( meta ).uuid;
  7312. if ( this.combine !== undefined ) data.combine = this.combine;
  7313. }
  7314. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  7315. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  7316. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  7317. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  7318. if ( this.gradientMap && this.gradientMap.isTexture ) {
  7319. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  7320. }
  7321. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  7322. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  7323. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  7324. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  7325. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  7326. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  7327. if ( this.size !== undefined ) data.size = this.size;
  7328. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  7329. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  7330. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  7331. if ( this.side !== FrontSide ) data.side = this.side;
  7332. if ( this.vertexColors === true ) data.vertexColors = true;
  7333. if ( this.opacity < 1 ) data.opacity = this.opacity;
  7334. if ( this.transparent === true ) data.transparent = true;
  7335. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  7336. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  7337. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  7338. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  7339. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  7340. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  7341. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  7342. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  7343. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  7344. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  7345. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  7346. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  7347. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  7348. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  7349. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  7350. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  7351. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  7352. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  7353. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  7354. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  7355. // rotation (SpriteMaterial)
  7356. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  7357. if ( this.polygonOffset === true ) data.polygonOffset = true;
  7358. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  7359. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  7360. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  7361. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  7362. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  7363. if ( this.scale !== undefined ) data.scale = this.scale;
  7364. if ( this.dithering === true ) data.dithering = true;
  7365. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  7366. if ( this.alphaHash === true ) data.alphaHash = true;
  7367. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  7368. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  7369. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  7370. if ( this.wireframe === true ) data.wireframe = true;
  7371. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  7372. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  7373. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  7374. if ( this.flatShading === true ) data.flatShading = true;
  7375. if ( this.visible === false ) data.visible = false;
  7376. if ( this.toneMapped === false ) data.toneMapped = false;
  7377. if ( this.fog === false ) data.fog = false;
  7378. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  7379. // TODO: Copied from Object3D.toJSON
  7380. function extractFromCache( cache ) {
  7381. const values = [];
  7382. for ( const key in cache ) {
  7383. const data = cache[ key ];
  7384. delete data.metadata;
  7385. values.push( data );
  7386. }
  7387. return values;
  7388. }
  7389. if ( isRootObject ) {
  7390. const textures = extractFromCache( meta.textures );
  7391. const images = extractFromCache( meta.images );
  7392. if ( textures.length > 0 ) data.textures = textures;
  7393. if ( images.length > 0 ) data.images = images;
  7394. }
  7395. return data;
  7396. }
  7397. /**
  7398. * Returns a new material with copied values from this instance.
  7399. *
  7400. * @return {Material} A clone of this instance.
  7401. */
  7402. clone() {
  7403. return new this.constructor().copy( this );
  7404. }
  7405. /**
  7406. * Copies the values of the given material to this instance.
  7407. *
  7408. * @param {Material} source - The material to copy.
  7409. * @return {Material} A reference to this instance.
  7410. */
  7411. copy( source ) {
  7412. this.name = source.name;
  7413. this.blending = source.blending;
  7414. this.side = source.side;
  7415. this.vertexColors = source.vertexColors;
  7416. this.opacity = source.opacity;
  7417. this.transparent = source.transparent;
  7418. this.blendSrc = source.blendSrc;
  7419. this.blendDst = source.blendDst;
  7420. this.blendEquation = source.blendEquation;
  7421. this.blendSrcAlpha = source.blendSrcAlpha;
  7422. this.blendDstAlpha = source.blendDstAlpha;
  7423. this.blendEquationAlpha = source.blendEquationAlpha;
  7424. this.blendColor.copy( source.blendColor );
  7425. this.blendAlpha = source.blendAlpha;
  7426. this.depthFunc = source.depthFunc;
  7427. this.depthTest = source.depthTest;
  7428. this.depthWrite = source.depthWrite;
  7429. this.stencilWriteMask = source.stencilWriteMask;
  7430. this.stencilFunc = source.stencilFunc;
  7431. this.stencilRef = source.stencilRef;
  7432. this.stencilFuncMask = source.stencilFuncMask;
  7433. this.stencilFail = source.stencilFail;
  7434. this.stencilZFail = source.stencilZFail;
  7435. this.stencilZPass = source.stencilZPass;
  7436. this.stencilWrite = source.stencilWrite;
  7437. const srcPlanes = source.clippingPlanes;
  7438. let dstPlanes = null;
  7439. if ( srcPlanes !== null ) {
  7440. const n = srcPlanes.length;
  7441. dstPlanes = new Array( n );
  7442. for ( let i = 0; i !== n; ++ i ) {
  7443. dstPlanes[ i ] = srcPlanes[ i ].clone();
  7444. }
  7445. }
  7446. this.clippingPlanes = dstPlanes;
  7447. this.clipIntersection = source.clipIntersection;
  7448. this.clipShadows = source.clipShadows;
  7449. this.shadowSide = source.shadowSide;
  7450. this.colorWrite = source.colorWrite;
  7451. this.precision = source.precision;
  7452. this.polygonOffset = source.polygonOffset;
  7453. this.polygonOffsetFactor = source.polygonOffsetFactor;
  7454. this.polygonOffsetUnits = source.polygonOffsetUnits;
  7455. this.dithering = source.dithering;
  7456. this.alphaTest = source.alphaTest;
  7457. this.alphaHash = source.alphaHash;
  7458. this.alphaToCoverage = source.alphaToCoverage;
  7459. this.premultipliedAlpha = source.premultipliedAlpha;
  7460. this.forceSinglePass = source.forceSinglePass;
  7461. this.visible = source.visible;
  7462. this.toneMapped = source.toneMapped;
  7463. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  7464. return this;
  7465. }
  7466. /**
  7467. * Frees the GPU-related resources allocated by this instance. Call this
  7468. * method whenever this instance is no longer used in your app.
  7469. *
  7470. * @fires Material#dispose
  7471. */
  7472. dispose() {
  7473. /**
  7474. * Fires when the material has been disposed of.
  7475. *
  7476. * @event Material#dispose
  7477. * @type {Object}
  7478. */
  7479. this.dispatchEvent( { type: 'dispose' } );
  7480. }
  7481. /**
  7482. * Setting this property to `true` indicates the engine the material
  7483. * needs to be recompiled.
  7484. *
  7485. * @type {boolean}
  7486. * @default false
  7487. * @param {boolean} value
  7488. */
  7489. set needsUpdate( value ) {
  7490. if ( value === true ) this.version ++;
  7491. }
  7492. onBuild( /* shaderobject, renderer */ ) {
  7493. console.warn( 'Material: onBuild() has been removed.' ); // @deprecated, r166
  7494. }
  7495. }
  7496. class MeshBasicMaterial extends Material {
  7497. constructor( parameters ) {
  7498. super();
  7499. this.isMeshBasicMaterial = true;
  7500. this.type = 'MeshBasicMaterial';
  7501. this.color = new Color( 0xffffff ); // emissive
  7502. this.map = null;
  7503. this.lightMap = null;
  7504. this.lightMapIntensity = 1.0;
  7505. this.aoMap = null;
  7506. this.aoMapIntensity = 1.0;
  7507. this.specularMap = null;
  7508. this.alphaMap = null;
  7509. this.envMap = null;
  7510. this.envMapRotation = new Euler();
  7511. this.combine = MultiplyOperation;
  7512. this.reflectivity = 1;
  7513. this.refractionRatio = 0.98;
  7514. this.wireframe = false;
  7515. this.wireframeLinewidth = 1;
  7516. this.wireframeLinecap = 'round';
  7517. this.wireframeLinejoin = 'round';
  7518. this.fog = true;
  7519. this.setValues( parameters );
  7520. }
  7521. copy( source ) {
  7522. super.copy( source );
  7523. this.color.copy( source.color );
  7524. this.map = source.map;
  7525. this.lightMap = source.lightMap;
  7526. this.lightMapIntensity = source.lightMapIntensity;
  7527. this.aoMap = source.aoMap;
  7528. this.aoMapIntensity = source.aoMapIntensity;
  7529. this.specularMap = source.specularMap;
  7530. this.alphaMap = source.alphaMap;
  7531. this.envMap = source.envMap;
  7532. this.envMapRotation.copy( source.envMapRotation );
  7533. this.combine = source.combine;
  7534. this.reflectivity = source.reflectivity;
  7535. this.refractionRatio = source.refractionRatio;
  7536. this.wireframe = source.wireframe;
  7537. this.wireframeLinewidth = source.wireframeLinewidth;
  7538. this.wireframeLinecap = source.wireframeLinecap;
  7539. this.wireframeLinejoin = source.wireframeLinejoin;
  7540. this.fog = source.fog;
  7541. return this;
  7542. }
  7543. }
  7544. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  7545. const _tables = /*@__PURE__*/ _generateTables();
  7546. function _generateTables() {
  7547. // float32 to float16 helpers
  7548. const buffer = new ArrayBuffer( 4 );
  7549. const floatView = new Float32Array( buffer );
  7550. const uint32View = new Uint32Array( buffer );
  7551. const baseTable = new Uint32Array( 512 );
  7552. const shiftTable = new Uint32Array( 512 );
  7553. for ( let i = 0; i < 256; ++ i ) {
  7554. const e = i - 127;
  7555. // very small number (0, -0)
  7556. if ( e < -27 ) {
  7557. baseTable[ i ] = 0x0000;
  7558. baseTable[ i | 0x100 ] = 0x8000;
  7559. shiftTable[ i ] = 24;
  7560. shiftTable[ i | 0x100 ] = 24;
  7561. // small number (denorm)
  7562. } else if ( e < -14 ) {
  7563. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  7564. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  7565. shiftTable[ i ] = - e - 1;
  7566. shiftTable[ i | 0x100 ] = - e - 1;
  7567. // normal number
  7568. } else if ( e <= 15 ) {
  7569. baseTable[ i ] = ( e + 15 ) << 10;
  7570. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  7571. shiftTable[ i ] = 13;
  7572. shiftTable[ i | 0x100 ] = 13;
  7573. // large number (Infinity, -Infinity)
  7574. } else if ( e < 128 ) {
  7575. baseTable[ i ] = 0x7c00;
  7576. baseTable[ i | 0x100 ] = 0xfc00;
  7577. shiftTable[ i ] = 24;
  7578. shiftTable[ i | 0x100 ] = 24;
  7579. // stay (NaN, Infinity, -Infinity)
  7580. } else {
  7581. baseTable[ i ] = 0x7c00;
  7582. baseTable[ i | 0x100 ] = 0xfc00;
  7583. shiftTable[ i ] = 13;
  7584. shiftTable[ i | 0x100 ] = 13;
  7585. }
  7586. }
  7587. // float16 to float32 helpers
  7588. const mantissaTable = new Uint32Array( 2048 );
  7589. const exponentTable = new Uint32Array( 64 );
  7590. const offsetTable = new Uint32Array( 64 );
  7591. for ( let i = 1; i < 1024; ++ i ) {
  7592. let m = i << 13; // zero pad mantissa bits
  7593. let e = 0; // zero exponent
  7594. // normalized
  7595. while ( ( m & 0x00800000 ) === 0 ) {
  7596. m <<= 1;
  7597. e -= 0x00800000; // decrement exponent
  7598. }
  7599. m &= -8388609; // clear leading 1 bit
  7600. e += 0x38800000; // adjust bias
  7601. mantissaTable[ i ] = m | e;
  7602. }
  7603. for ( let i = 1024; i < 2048; ++ i ) {
  7604. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  7605. }
  7606. for ( let i = 1; i < 31; ++ i ) {
  7607. exponentTable[ i ] = i << 23;
  7608. }
  7609. exponentTable[ 31 ] = 0x47800000;
  7610. exponentTable[ 32 ] = 0x80000000;
  7611. for ( let i = 33; i < 63; ++ i ) {
  7612. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  7613. }
  7614. exponentTable[ 63 ] = 0xc7800000;
  7615. for ( let i = 1; i < 64; ++ i ) {
  7616. if ( i !== 32 ) {
  7617. offsetTable[ i ] = 1024;
  7618. }
  7619. }
  7620. return {
  7621. floatView: floatView,
  7622. uint32View: uint32View,
  7623. baseTable: baseTable,
  7624. shiftTable: shiftTable,
  7625. mantissaTable: mantissaTable,
  7626. exponentTable: exponentTable,
  7627. offsetTable: offsetTable
  7628. };
  7629. }
  7630. // float32 to float16
  7631. function toHalfFloat( val ) {
  7632. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  7633. val = clamp( val, -65504, 65504 );
  7634. _tables.floatView[ 0 ] = val;
  7635. const f = _tables.uint32View[ 0 ];
  7636. const e = ( f >> 23 ) & 0x1ff;
  7637. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  7638. }
  7639. // float16 to float32
  7640. function fromHalfFloat( val ) {
  7641. const m = val >> 10;
  7642. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  7643. return _tables.floatView[ 0 ];
  7644. }
  7645. const DataUtils = {
  7646. toHalfFloat: toHalfFloat,
  7647. fromHalfFloat: fromHalfFloat,
  7648. };
  7649. const _vector$9 = /*@__PURE__*/ new Vector3();
  7650. const _vector2$1 = /*@__PURE__*/ new Vector2();
  7651. let _id$2 = 0;
  7652. class BufferAttribute {
  7653. constructor( array, itemSize, normalized = false ) {
  7654. if ( Array.isArray( array ) ) {
  7655. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  7656. }
  7657. this.isBufferAttribute = true;
  7658. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  7659. this.name = '';
  7660. this.array = array;
  7661. this.itemSize = itemSize;
  7662. this.count = array !== undefined ? array.length / itemSize : 0;
  7663. this.normalized = normalized;
  7664. this.usage = StaticDrawUsage;
  7665. this.updateRanges = [];
  7666. this.gpuType = FloatType;
  7667. this.version = 0;
  7668. }
  7669. onUploadCallback() {}
  7670. set needsUpdate( value ) {
  7671. if ( value === true ) this.version ++;
  7672. }
  7673. setUsage( value ) {
  7674. this.usage = value;
  7675. return this;
  7676. }
  7677. addUpdateRange( start, count ) {
  7678. this.updateRanges.push( { start, count } );
  7679. }
  7680. clearUpdateRanges() {
  7681. this.updateRanges.length = 0;
  7682. }
  7683. copy( source ) {
  7684. this.name = source.name;
  7685. this.array = new source.array.constructor( source.array );
  7686. this.itemSize = source.itemSize;
  7687. this.count = source.count;
  7688. this.normalized = source.normalized;
  7689. this.usage = source.usage;
  7690. this.gpuType = source.gpuType;
  7691. return this;
  7692. }
  7693. copyAt( index1, attribute, index2 ) {
  7694. index1 *= this.itemSize;
  7695. index2 *= attribute.itemSize;
  7696. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  7697. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  7698. }
  7699. return this;
  7700. }
  7701. copyArray( array ) {
  7702. this.array.set( array );
  7703. return this;
  7704. }
  7705. applyMatrix3( m ) {
  7706. if ( this.itemSize === 2 ) {
  7707. for ( let i = 0, l = this.count; i < l; i ++ ) {
  7708. _vector2$1.fromBufferAttribute( this, i );
  7709. _vector2$1.applyMatrix3( m );
  7710. this.setXY( i, _vector2$1.x, _vector2$1.y );
  7711. }
  7712. } else if ( this.itemSize === 3 ) {
  7713. for ( let i = 0, l = this.count; i < l; i ++ ) {
  7714. _vector$9.fromBufferAttribute( this, i );
  7715. _vector$9.applyMatrix3( m );
  7716. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  7717. }
  7718. }
  7719. return this;
  7720. }
  7721. applyMatrix4( m ) {
  7722. for ( let i = 0, l = this.count; i < l; i ++ ) {
  7723. _vector$9.fromBufferAttribute( this, i );
  7724. _vector$9.applyMatrix4( m );
  7725. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  7726. }
  7727. return this;
  7728. }
  7729. applyNormalMatrix( m ) {
  7730. for ( let i = 0, l = this.count; i < l; i ++ ) {
  7731. _vector$9.fromBufferAttribute( this, i );
  7732. _vector$9.applyNormalMatrix( m );
  7733. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  7734. }
  7735. return this;
  7736. }
  7737. transformDirection( m ) {
  7738. for ( let i = 0, l = this.count; i < l; i ++ ) {
  7739. _vector$9.fromBufferAttribute( this, i );
  7740. _vector$9.transformDirection( m );
  7741. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  7742. }
  7743. return this;
  7744. }
  7745. set( value, offset = 0 ) {
  7746. // Matching BufferAttribute constructor, do not normalize the array.
  7747. this.array.set( value, offset );
  7748. return this;
  7749. }
  7750. getComponent( index, component ) {
  7751. let value = this.array[ index * this.itemSize + component ];
  7752. if ( this.normalized ) value = denormalize( value, this.array );
  7753. return value;
  7754. }
  7755. setComponent( index, component, value ) {
  7756. if ( this.normalized ) value = normalize( value, this.array );
  7757. this.array[ index * this.itemSize + component ] = value;
  7758. return this;
  7759. }
  7760. getX( index ) {
  7761. let x = this.array[ index * this.itemSize ];
  7762. if ( this.normalized ) x = denormalize( x, this.array );
  7763. return x;
  7764. }
  7765. setX( index, x ) {
  7766. if ( this.normalized ) x = normalize( x, this.array );
  7767. this.array[ index * this.itemSize ] = x;
  7768. return this;
  7769. }
  7770. getY( index ) {
  7771. let y = this.array[ index * this.itemSize + 1 ];
  7772. if ( this.normalized ) y = denormalize( y, this.array );
  7773. return y;
  7774. }
  7775. setY( index, y ) {
  7776. if ( this.normalized ) y = normalize( y, this.array );
  7777. this.array[ index * this.itemSize + 1 ] = y;
  7778. return this;
  7779. }
  7780. getZ( index ) {
  7781. let z = this.array[ index * this.itemSize + 2 ];
  7782. if ( this.normalized ) z = denormalize( z, this.array );
  7783. return z;
  7784. }
  7785. setZ( index, z ) {
  7786. if ( this.normalized ) z = normalize( z, this.array );
  7787. this.array[ index * this.itemSize + 2 ] = z;
  7788. return this;
  7789. }
  7790. getW( index ) {
  7791. let w = this.array[ index * this.itemSize + 3 ];
  7792. if ( this.normalized ) w = denormalize( w, this.array );
  7793. return w;
  7794. }
  7795. setW( index, w ) {
  7796. if ( this.normalized ) w = normalize( w, this.array );
  7797. this.array[ index * this.itemSize + 3 ] = w;
  7798. return this;
  7799. }
  7800. setXY( index, x, y ) {
  7801. index *= this.itemSize;
  7802. if ( this.normalized ) {
  7803. x = normalize( x, this.array );
  7804. y = normalize( y, this.array );
  7805. }
  7806. this.array[ index + 0 ] = x;
  7807. this.array[ index + 1 ] = y;
  7808. return this;
  7809. }
  7810. setXYZ( index, x, y, z ) {
  7811. index *= this.itemSize;
  7812. if ( this.normalized ) {
  7813. x = normalize( x, this.array );
  7814. y = normalize( y, this.array );
  7815. z = normalize( z, this.array );
  7816. }
  7817. this.array[ index + 0 ] = x;
  7818. this.array[ index + 1 ] = y;
  7819. this.array[ index + 2 ] = z;
  7820. return this;
  7821. }
  7822. setXYZW( index, x, y, z, w ) {
  7823. index *= this.itemSize;
  7824. if ( this.normalized ) {
  7825. x = normalize( x, this.array );
  7826. y = normalize( y, this.array );
  7827. z = normalize( z, this.array );
  7828. w = normalize( w, this.array );
  7829. }
  7830. this.array[ index + 0 ] = x;
  7831. this.array[ index + 1 ] = y;
  7832. this.array[ index + 2 ] = z;
  7833. this.array[ index + 3 ] = w;
  7834. return this;
  7835. }
  7836. onUpload( callback ) {
  7837. this.onUploadCallback = callback;
  7838. return this;
  7839. }
  7840. clone() {
  7841. return new this.constructor( this.array, this.itemSize ).copy( this );
  7842. }
  7843. toJSON() {
  7844. const data = {
  7845. itemSize: this.itemSize,
  7846. type: this.array.constructor.name,
  7847. array: Array.from( this.array ),
  7848. normalized: this.normalized
  7849. };
  7850. if ( this.name !== '' ) data.name = this.name;
  7851. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  7852. return data;
  7853. }
  7854. }
  7855. //
  7856. class Int8BufferAttribute extends BufferAttribute {
  7857. constructor( array, itemSize, normalized ) {
  7858. super( new Int8Array( array ), itemSize, normalized );
  7859. }
  7860. }
  7861. class Uint8BufferAttribute extends BufferAttribute {
  7862. constructor( array, itemSize, normalized ) {
  7863. super( new Uint8Array( array ), itemSize, normalized );
  7864. }
  7865. }
  7866. class Uint8ClampedBufferAttribute extends BufferAttribute {
  7867. constructor( array, itemSize, normalized ) {
  7868. super( new Uint8ClampedArray( array ), itemSize, normalized );
  7869. }
  7870. }
  7871. class Int16BufferAttribute extends BufferAttribute {
  7872. constructor( array, itemSize, normalized ) {
  7873. super( new Int16Array( array ), itemSize, normalized );
  7874. }
  7875. }
  7876. class Uint16BufferAttribute extends BufferAttribute {
  7877. constructor( array, itemSize, normalized ) {
  7878. super( new Uint16Array( array ), itemSize, normalized );
  7879. }
  7880. }
  7881. class Int32BufferAttribute extends BufferAttribute {
  7882. constructor( array, itemSize, normalized ) {
  7883. super( new Int32Array( array ), itemSize, normalized );
  7884. }
  7885. }
  7886. class Uint32BufferAttribute extends BufferAttribute {
  7887. constructor( array, itemSize, normalized ) {
  7888. super( new Uint32Array( array ), itemSize, normalized );
  7889. }
  7890. }
  7891. class Float16BufferAttribute extends BufferAttribute {
  7892. constructor( array, itemSize, normalized ) {
  7893. super( new Uint16Array( array ), itemSize, normalized );
  7894. this.isFloat16BufferAttribute = true;
  7895. }
  7896. getX( index ) {
  7897. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  7898. if ( this.normalized ) x = denormalize( x, this.array );
  7899. return x;
  7900. }
  7901. setX( index, x ) {
  7902. if ( this.normalized ) x = normalize( x, this.array );
  7903. this.array[ index * this.itemSize ] = toHalfFloat( x );
  7904. return this;
  7905. }
  7906. getY( index ) {
  7907. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  7908. if ( this.normalized ) y = denormalize( y, this.array );
  7909. return y;
  7910. }
  7911. setY( index, y ) {
  7912. if ( this.normalized ) y = normalize( y, this.array );
  7913. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  7914. return this;
  7915. }
  7916. getZ( index ) {
  7917. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  7918. if ( this.normalized ) z = denormalize( z, this.array );
  7919. return z;
  7920. }
  7921. setZ( index, z ) {
  7922. if ( this.normalized ) z = normalize( z, this.array );
  7923. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  7924. return this;
  7925. }
  7926. getW( index ) {
  7927. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  7928. if ( this.normalized ) w = denormalize( w, this.array );
  7929. return w;
  7930. }
  7931. setW( index, w ) {
  7932. if ( this.normalized ) w = normalize( w, this.array );
  7933. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  7934. return this;
  7935. }
  7936. setXY( index, x, y ) {
  7937. index *= this.itemSize;
  7938. if ( this.normalized ) {
  7939. x = normalize( x, this.array );
  7940. y = normalize( y, this.array );
  7941. }
  7942. this.array[ index + 0 ] = toHalfFloat( x );
  7943. this.array[ index + 1 ] = toHalfFloat( y );
  7944. return this;
  7945. }
  7946. setXYZ( index, x, y, z ) {
  7947. index *= this.itemSize;
  7948. if ( this.normalized ) {
  7949. x = normalize( x, this.array );
  7950. y = normalize( y, this.array );
  7951. z = normalize( z, this.array );
  7952. }
  7953. this.array[ index + 0 ] = toHalfFloat( x );
  7954. this.array[ index + 1 ] = toHalfFloat( y );
  7955. this.array[ index + 2 ] = toHalfFloat( z );
  7956. return this;
  7957. }
  7958. setXYZW( index, x, y, z, w ) {
  7959. index *= this.itemSize;
  7960. if ( this.normalized ) {
  7961. x = normalize( x, this.array );
  7962. y = normalize( y, this.array );
  7963. z = normalize( z, this.array );
  7964. w = normalize( w, this.array );
  7965. }
  7966. this.array[ index + 0 ] = toHalfFloat( x );
  7967. this.array[ index + 1 ] = toHalfFloat( y );
  7968. this.array[ index + 2 ] = toHalfFloat( z );
  7969. this.array[ index + 3 ] = toHalfFloat( w );
  7970. return this;
  7971. }
  7972. }
  7973. class Float32BufferAttribute extends BufferAttribute {
  7974. constructor( array, itemSize, normalized ) {
  7975. super( new Float32Array( array ), itemSize, normalized );
  7976. }
  7977. }
  7978. let _id$1 = 0;
  7979. const _m1 = /*@__PURE__*/ new Matrix4();
  7980. const _obj = /*@__PURE__*/ new Object3D();
  7981. const _offset = /*@__PURE__*/ new Vector3();
  7982. const _box$2 = /*@__PURE__*/ new Box3();
  7983. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  7984. const _vector$8 = /*@__PURE__*/ new Vector3();
  7985. class BufferGeometry extends EventDispatcher {
  7986. constructor() {
  7987. super();
  7988. this.isBufferGeometry = true;
  7989. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  7990. this.uuid = generateUUID();
  7991. this.name = '';
  7992. this.type = 'BufferGeometry';
  7993. this.index = null;
  7994. this.indirect = null;
  7995. this.attributes = {};
  7996. this.morphAttributes = {};
  7997. this.morphTargetsRelative = false;
  7998. this.groups = [];
  7999. this.boundingBox = null;
  8000. this.boundingSphere = null;
  8001. this.drawRange = { start: 0, count: Infinity };
  8002. this.userData = {};
  8003. }
  8004. getIndex() {
  8005. return this.index;
  8006. }
  8007. setIndex( index ) {
  8008. if ( Array.isArray( index ) ) {
  8009. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  8010. } else {
  8011. this.index = index;
  8012. }
  8013. return this;
  8014. }
  8015. setIndirect( indirect ) {
  8016. this.indirect = indirect;
  8017. return this;
  8018. }
  8019. getIndirect() {
  8020. return this.indirect;
  8021. }
  8022. getAttribute( name ) {
  8023. return this.attributes[ name ];
  8024. }
  8025. setAttribute( name, attribute ) {
  8026. this.attributes[ name ] = attribute;
  8027. return this;
  8028. }
  8029. deleteAttribute( name ) {
  8030. delete this.attributes[ name ];
  8031. return this;
  8032. }
  8033. hasAttribute( name ) {
  8034. return this.attributes[ name ] !== undefined;
  8035. }
  8036. addGroup( start, count, materialIndex = 0 ) {
  8037. this.groups.push( {
  8038. start: start,
  8039. count: count,
  8040. materialIndex: materialIndex
  8041. } );
  8042. }
  8043. clearGroups() {
  8044. this.groups = [];
  8045. }
  8046. setDrawRange( start, count ) {
  8047. this.drawRange.start = start;
  8048. this.drawRange.count = count;
  8049. }
  8050. applyMatrix4( matrix ) {
  8051. const position = this.attributes.position;
  8052. if ( position !== undefined ) {
  8053. position.applyMatrix4( matrix );
  8054. position.needsUpdate = true;
  8055. }
  8056. const normal = this.attributes.normal;
  8057. if ( normal !== undefined ) {
  8058. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  8059. normal.applyNormalMatrix( normalMatrix );
  8060. normal.needsUpdate = true;
  8061. }
  8062. const tangent = this.attributes.tangent;
  8063. if ( tangent !== undefined ) {
  8064. tangent.transformDirection( matrix );
  8065. tangent.needsUpdate = true;
  8066. }
  8067. if ( this.boundingBox !== null ) {
  8068. this.computeBoundingBox();
  8069. }
  8070. if ( this.boundingSphere !== null ) {
  8071. this.computeBoundingSphere();
  8072. }
  8073. return this;
  8074. }
  8075. applyQuaternion( q ) {
  8076. _m1.makeRotationFromQuaternion( q );
  8077. this.applyMatrix4( _m1 );
  8078. return this;
  8079. }
  8080. rotateX( angle ) {
  8081. // rotate geometry around world x-axis
  8082. _m1.makeRotationX( angle );
  8083. this.applyMatrix4( _m1 );
  8084. return this;
  8085. }
  8086. rotateY( angle ) {
  8087. // rotate geometry around world y-axis
  8088. _m1.makeRotationY( angle );
  8089. this.applyMatrix4( _m1 );
  8090. return this;
  8091. }
  8092. rotateZ( angle ) {
  8093. // rotate geometry around world z-axis
  8094. _m1.makeRotationZ( angle );
  8095. this.applyMatrix4( _m1 );
  8096. return this;
  8097. }
  8098. translate( x, y, z ) {
  8099. // translate geometry
  8100. _m1.makeTranslation( x, y, z );
  8101. this.applyMatrix4( _m1 );
  8102. return this;
  8103. }
  8104. scale( x, y, z ) {
  8105. // scale geometry
  8106. _m1.makeScale( x, y, z );
  8107. this.applyMatrix4( _m1 );
  8108. return this;
  8109. }
  8110. lookAt( vector ) {
  8111. _obj.lookAt( vector );
  8112. _obj.updateMatrix();
  8113. this.applyMatrix4( _obj.matrix );
  8114. return this;
  8115. }
  8116. center() {
  8117. this.computeBoundingBox();
  8118. this.boundingBox.getCenter( _offset ).negate();
  8119. this.translate( _offset.x, _offset.y, _offset.z );
  8120. return this;
  8121. }
  8122. setFromPoints( points ) {
  8123. const positionAttribute = this.getAttribute( 'position' );
  8124. if ( positionAttribute === undefined ) {
  8125. const position = [];
  8126. for ( let i = 0, l = points.length; i < l; i ++ ) {
  8127. const point = points[ i ];
  8128. position.push( point.x, point.y, point.z || 0 );
  8129. }
  8130. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  8131. } else {
  8132. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  8133. for ( let i = 0; i < l; i ++ ) {
  8134. const point = points[ i ];
  8135. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  8136. }
  8137. if ( points.length > positionAttribute.count ) {
  8138. console.warn( 'THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  8139. }
  8140. positionAttribute.needsUpdate = true;
  8141. }
  8142. return this;
  8143. }
  8144. computeBoundingBox() {
  8145. if ( this.boundingBox === null ) {
  8146. this.boundingBox = new Box3();
  8147. }
  8148. const position = this.attributes.position;
  8149. const morphAttributesPosition = this.morphAttributes.position;
  8150. if ( position && position.isGLBufferAttribute ) {
  8151. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  8152. this.boundingBox.set(
  8153. new Vector3( - Infinity, - Infinity, - Infinity ),
  8154. new Vector3( + Infinity, + Infinity, + Infinity )
  8155. );
  8156. return;
  8157. }
  8158. if ( position !== undefined ) {
  8159. this.boundingBox.setFromBufferAttribute( position );
  8160. // process morph attributes if present
  8161. if ( morphAttributesPosition ) {
  8162. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  8163. const morphAttribute = morphAttributesPosition[ i ];
  8164. _box$2.setFromBufferAttribute( morphAttribute );
  8165. if ( this.morphTargetsRelative ) {
  8166. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  8167. this.boundingBox.expandByPoint( _vector$8 );
  8168. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  8169. this.boundingBox.expandByPoint( _vector$8 );
  8170. } else {
  8171. this.boundingBox.expandByPoint( _box$2.min );
  8172. this.boundingBox.expandByPoint( _box$2.max );
  8173. }
  8174. }
  8175. }
  8176. } else {
  8177. this.boundingBox.makeEmpty();
  8178. }
  8179. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  8180. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  8181. }
  8182. }
  8183. computeBoundingSphere() {
  8184. if ( this.boundingSphere === null ) {
  8185. this.boundingSphere = new Sphere();
  8186. }
  8187. const position = this.attributes.position;
  8188. const morphAttributesPosition = this.morphAttributes.position;
  8189. if ( position && position.isGLBufferAttribute ) {
  8190. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  8191. this.boundingSphere.set( new Vector3(), Infinity );
  8192. return;
  8193. }
  8194. if ( position ) {
  8195. // first, find the center of the bounding sphere
  8196. const center = this.boundingSphere.center;
  8197. _box$2.setFromBufferAttribute( position );
  8198. // process morph attributes if present
  8199. if ( morphAttributesPosition ) {
  8200. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  8201. const morphAttribute = morphAttributesPosition[ i ];
  8202. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  8203. if ( this.morphTargetsRelative ) {
  8204. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  8205. _box$2.expandByPoint( _vector$8 );
  8206. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  8207. _box$2.expandByPoint( _vector$8 );
  8208. } else {
  8209. _box$2.expandByPoint( _boxMorphTargets.min );
  8210. _box$2.expandByPoint( _boxMorphTargets.max );
  8211. }
  8212. }
  8213. }
  8214. _box$2.getCenter( center );
  8215. // second, try to find a boundingSphere with a radius smaller than the
  8216. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  8217. let maxRadiusSq = 0;
  8218. for ( let i = 0, il = position.count; i < il; i ++ ) {
  8219. _vector$8.fromBufferAttribute( position, i );
  8220. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  8221. }
  8222. // process morph attributes if present
  8223. if ( morphAttributesPosition ) {
  8224. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  8225. const morphAttribute = morphAttributesPosition[ i ];
  8226. const morphTargetsRelative = this.morphTargetsRelative;
  8227. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  8228. _vector$8.fromBufferAttribute( morphAttribute, j );
  8229. if ( morphTargetsRelative ) {
  8230. _offset.fromBufferAttribute( position, j );
  8231. _vector$8.add( _offset );
  8232. }
  8233. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  8234. }
  8235. }
  8236. }
  8237. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  8238. if ( isNaN( this.boundingSphere.radius ) ) {
  8239. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  8240. }
  8241. }
  8242. }
  8243. computeTangents() {
  8244. const index = this.index;
  8245. const attributes = this.attributes;
  8246. // based on http://www.terathon.com/code/tangent.html
  8247. // (per vertex tangents)
  8248. if ( index === null ||
  8249. attributes.position === undefined ||
  8250. attributes.normal === undefined ||
  8251. attributes.uv === undefined ) {
  8252. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  8253. return;
  8254. }
  8255. const positionAttribute = attributes.position;
  8256. const normalAttribute = attributes.normal;
  8257. const uvAttribute = attributes.uv;
  8258. if ( this.hasAttribute( 'tangent' ) === false ) {
  8259. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  8260. }
  8261. const tangentAttribute = this.getAttribute( 'tangent' );
  8262. const tan1 = [], tan2 = [];
  8263. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  8264. tan1[ i ] = new Vector3();
  8265. tan2[ i ] = new Vector3();
  8266. }
  8267. const vA = new Vector3(),
  8268. vB = new Vector3(),
  8269. vC = new Vector3(),
  8270. uvA = new Vector2(),
  8271. uvB = new Vector2(),
  8272. uvC = new Vector2(),
  8273. sdir = new Vector3(),
  8274. tdir = new Vector3();
  8275. function handleTriangle( a, b, c ) {
  8276. vA.fromBufferAttribute( positionAttribute, a );
  8277. vB.fromBufferAttribute( positionAttribute, b );
  8278. vC.fromBufferAttribute( positionAttribute, c );
  8279. uvA.fromBufferAttribute( uvAttribute, a );
  8280. uvB.fromBufferAttribute( uvAttribute, b );
  8281. uvC.fromBufferAttribute( uvAttribute, c );
  8282. vB.sub( vA );
  8283. vC.sub( vA );
  8284. uvB.sub( uvA );
  8285. uvC.sub( uvA );
  8286. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  8287. // silently ignore degenerate uv triangles having coincident or colinear vertices
  8288. if ( ! isFinite( r ) ) return;
  8289. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  8290. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  8291. tan1[ a ].add( sdir );
  8292. tan1[ b ].add( sdir );
  8293. tan1[ c ].add( sdir );
  8294. tan2[ a ].add( tdir );
  8295. tan2[ b ].add( tdir );
  8296. tan2[ c ].add( tdir );
  8297. }
  8298. let groups = this.groups;
  8299. if ( groups.length === 0 ) {
  8300. groups = [ {
  8301. start: 0,
  8302. count: index.count
  8303. } ];
  8304. }
  8305. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  8306. const group = groups[ i ];
  8307. const start = group.start;
  8308. const count = group.count;
  8309. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  8310. handleTriangle(
  8311. index.getX( j + 0 ),
  8312. index.getX( j + 1 ),
  8313. index.getX( j + 2 )
  8314. );
  8315. }
  8316. }
  8317. const tmp = new Vector3(), tmp2 = new Vector3();
  8318. const n = new Vector3(), n2 = new Vector3();
  8319. function handleVertex( v ) {
  8320. n.fromBufferAttribute( normalAttribute, v );
  8321. n2.copy( n );
  8322. const t = tan1[ v ];
  8323. // Gram-Schmidt orthogonalize
  8324. tmp.copy( t );
  8325. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  8326. // Calculate handedness
  8327. tmp2.crossVectors( n2, t );
  8328. const test = tmp2.dot( tan2[ v ] );
  8329. const w = ( test < 0.0 ) ? -1 : 1.0;
  8330. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  8331. }
  8332. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  8333. const group = groups[ i ];
  8334. const start = group.start;
  8335. const count = group.count;
  8336. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  8337. handleVertex( index.getX( j + 0 ) );
  8338. handleVertex( index.getX( j + 1 ) );
  8339. handleVertex( index.getX( j + 2 ) );
  8340. }
  8341. }
  8342. }
  8343. computeVertexNormals() {
  8344. const index = this.index;
  8345. const positionAttribute = this.getAttribute( 'position' );
  8346. if ( positionAttribute !== undefined ) {
  8347. let normalAttribute = this.getAttribute( 'normal' );
  8348. if ( normalAttribute === undefined ) {
  8349. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  8350. this.setAttribute( 'normal', normalAttribute );
  8351. } else {
  8352. // reset existing normals to zero
  8353. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  8354. normalAttribute.setXYZ( i, 0, 0, 0 );
  8355. }
  8356. }
  8357. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  8358. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  8359. const cb = new Vector3(), ab = new Vector3();
  8360. // indexed elements
  8361. if ( index ) {
  8362. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  8363. const vA = index.getX( i + 0 );
  8364. const vB = index.getX( i + 1 );
  8365. const vC = index.getX( i + 2 );
  8366. pA.fromBufferAttribute( positionAttribute, vA );
  8367. pB.fromBufferAttribute( positionAttribute, vB );
  8368. pC.fromBufferAttribute( positionAttribute, vC );
  8369. cb.subVectors( pC, pB );
  8370. ab.subVectors( pA, pB );
  8371. cb.cross( ab );
  8372. nA.fromBufferAttribute( normalAttribute, vA );
  8373. nB.fromBufferAttribute( normalAttribute, vB );
  8374. nC.fromBufferAttribute( normalAttribute, vC );
  8375. nA.add( cb );
  8376. nB.add( cb );
  8377. nC.add( cb );
  8378. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  8379. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  8380. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  8381. }
  8382. } else {
  8383. // non-indexed elements (unconnected triangle soup)
  8384. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  8385. pA.fromBufferAttribute( positionAttribute, i + 0 );
  8386. pB.fromBufferAttribute( positionAttribute, i + 1 );
  8387. pC.fromBufferAttribute( positionAttribute, i + 2 );
  8388. cb.subVectors( pC, pB );
  8389. ab.subVectors( pA, pB );
  8390. cb.cross( ab );
  8391. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  8392. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  8393. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  8394. }
  8395. }
  8396. this.normalizeNormals();
  8397. normalAttribute.needsUpdate = true;
  8398. }
  8399. }
  8400. normalizeNormals() {
  8401. const normals = this.attributes.normal;
  8402. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  8403. _vector$8.fromBufferAttribute( normals, i );
  8404. _vector$8.normalize();
  8405. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  8406. }
  8407. }
  8408. toNonIndexed() {
  8409. function convertBufferAttribute( attribute, indices ) {
  8410. const array = attribute.array;
  8411. const itemSize = attribute.itemSize;
  8412. const normalized = attribute.normalized;
  8413. const array2 = new array.constructor( indices.length * itemSize );
  8414. let index = 0, index2 = 0;
  8415. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  8416. if ( attribute.isInterleavedBufferAttribute ) {
  8417. index = indices[ i ] * attribute.data.stride + attribute.offset;
  8418. } else {
  8419. index = indices[ i ] * itemSize;
  8420. }
  8421. for ( let j = 0; j < itemSize; j ++ ) {
  8422. array2[ index2 ++ ] = array[ index ++ ];
  8423. }
  8424. }
  8425. return new BufferAttribute( array2, itemSize, normalized );
  8426. }
  8427. //
  8428. if ( this.index === null ) {
  8429. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  8430. return this;
  8431. }
  8432. const geometry2 = new BufferGeometry();
  8433. const indices = this.index.array;
  8434. const attributes = this.attributes;
  8435. // attributes
  8436. for ( const name in attributes ) {
  8437. const attribute = attributes[ name ];
  8438. const newAttribute = convertBufferAttribute( attribute, indices );
  8439. geometry2.setAttribute( name, newAttribute );
  8440. }
  8441. // morph attributes
  8442. const morphAttributes = this.morphAttributes;
  8443. for ( const name in morphAttributes ) {
  8444. const morphArray = [];
  8445. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  8446. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  8447. const attribute = morphAttribute[ i ];
  8448. const newAttribute = convertBufferAttribute( attribute, indices );
  8449. morphArray.push( newAttribute );
  8450. }
  8451. geometry2.morphAttributes[ name ] = morphArray;
  8452. }
  8453. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  8454. // groups
  8455. const groups = this.groups;
  8456. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  8457. const group = groups[ i ];
  8458. geometry2.addGroup( group.start, group.count, group.materialIndex );
  8459. }
  8460. return geometry2;
  8461. }
  8462. toJSON() {
  8463. const data = {
  8464. metadata: {
  8465. version: 4.6,
  8466. type: 'BufferGeometry',
  8467. generator: 'BufferGeometry.toJSON'
  8468. }
  8469. };
  8470. // standard BufferGeometry serialization
  8471. data.uuid = this.uuid;
  8472. data.type = this.type;
  8473. if ( this.name !== '' ) data.name = this.name;
  8474. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  8475. if ( this.parameters !== undefined ) {
  8476. const parameters = this.parameters;
  8477. for ( const key in parameters ) {
  8478. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  8479. }
  8480. return data;
  8481. }
  8482. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  8483. data.data = { attributes: {} };
  8484. const index = this.index;
  8485. if ( index !== null ) {
  8486. data.data.index = {
  8487. type: index.array.constructor.name,
  8488. array: Array.prototype.slice.call( index.array )
  8489. };
  8490. }
  8491. const attributes = this.attributes;
  8492. for ( const key in attributes ) {
  8493. const attribute = attributes[ key ];
  8494. data.data.attributes[ key ] = attribute.toJSON( data.data );
  8495. }
  8496. const morphAttributes = {};
  8497. let hasMorphAttributes = false;
  8498. for ( const key in this.morphAttributes ) {
  8499. const attributeArray = this.morphAttributes[ key ];
  8500. const array = [];
  8501. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  8502. const attribute = attributeArray[ i ];
  8503. array.push( attribute.toJSON( data.data ) );
  8504. }
  8505. if ( array.length > 0 ) {
  8506. morphAttributes[ key ] = array;
  8507. hasMorphAttributes = true;
  8508. }
  8509. }
  8510. if ( hasMorphAttributes ) {
  8511. data.data.morphAttributes = morphAttributes;
  8512. data.data.morphTargetsRelative = this.morphTargetsRelative;
  8513. }
  8514. const groups = this.groups;
  8515. if ( groups.length > 0 ) {
  8516. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  8517. }
  8518. const boundingSphere = this.boundingSphere;
  8519. if ( boundingSphere !== null ) {
  8520. data.data.boundingSphere = {
  8521. center: boundingSphere.center.toArray(),
  8522. radius: boundingSphere.radius
  8523. };
  8524. }
  8525. return data;
  8526. }
  8527. clone() {
  8528. return new this.constructor().copy( this );
  8529. }
  8530. copy( source ) {
  8531. // reset
  8532. this.index = null;
  8533. this.attributes = {};
  8534. this.morphAttributes = {};
  8535. this.groups = [];
  8536. this.boundingBox = null;
  8537. this.boundingSphere = null;
  8538. // used for storing cloned, shared data
  8539. const data = {};
  8540. // name
  8541. this.name = source.name;
  8542. // index
  8543. const index = source.index;
  8544. if ( index !== null ) {
  8545. this.setIndex( index.clone( data ) );
  8546. }
  8547. // attributes
  8548. const attributes = source.attributes;
  8549. for ( const name in attributes ) {
  8550. const attribute = attributes[ name ];
  8551. this.setAttribute( name, attribute.clone( data ) );
  8552. }
  8553. // morph attributes
  8554. const morphAttributes = source.morphAttributes;
  8555. for ( const name in morphAttributes ) {
  8556. const array = [];
  8557. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  8558. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  8559. array.push( morphAttribute[ i ].clone( data ) );
  8560. }
  8561. this.morphAttributes[ name ] = array;
  8562. }
  8563. this.morphTargetsRelative = source.morphTargetsRelative;
  8564. // groups
  8565. const groups = source.groups;
  8566. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  8567. const group = groups[ i ];
  8568. this.addGroup( group.start, group.count, group.materialIndex );
  8569. }
  8570. // bounding box
  8571. const boundingBox = source.boundingBox;
  8572. if ( boundingBox !== null ) {
  8573. this.boundingBox = boundingBox.clone();
  8574. }
  8575. // bounding sphere
  8576. const boundingSphere = source.boundingSphere;
  8577. if ( boundingSphere !== null ) {
  8578. this.boundingSphere = boundingSphere.clone();
  8579. }
  8580. // draw range
  8581. this.drawRange.start = source.drawRange.start;
  8582. this.drawRange.count = source.drawRange.count;
  8583. // user data
  8584. this.userData = source.userData;
  8585. return this;
  8586. }
  8587. dispose() {
  8588. this.dispatchEvent( { type: 'dispose' } );
  8589. }
  8590. }
  8591. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  8592. const _ray$3 = /*@__PURE__*/ new Ray();
  8593. const _sphere$6 = /*@__PURE__*/ new Sphere();
  8594. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  8595. const _vA$1 = /*@__PURE__*/ new Vector3();
  8596. const _vB$1 = /*@__PURE__*/ new Vector3();
  8597. const _vC$1 = /*@__PURE__*/ new Vector3();
  8598. const _tempA = /*@__PURE__*/ new Vector3();
  8599. const _morphA = /*@__PURE__*/ new Vector3();
  8600. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  8601. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  8602. class Mesh extends Object3D {
  8603. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  8604. super();
  8605. this.isMesh = true;
  8606. this.type = 'Mesh';
  8607. this.geometry = geometry;
  8608. this.material = material;
  8609. this.updateMorphTargets();
  8610. }
  8611. copy( source, recursive ) {
  8612. super.copy( source, recursive );
  8613. if ( source.morphTargetInfluences !== undefined ) {
  8614. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  8615. }
  8616. if ( source.morphTargetDictionary !== undefined ) {
  8617. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  8618. }
  8619. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  8620. this.geometry = source.geometry;
  8621. return this;
  8622. }
  8623. updateMorphTargets() {
  8624. const geometry = this.geometry;
  8625. const morphAttributes = geometry.morphAttributes;
  8626. const keys = Object.keys( morphAttributes );
  8627. if ( keys.length > 0 ) {
  8628. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  8629. if ( morphAttribute !== undefined ) {
  8630. this.morphTargetInfluences = [];
  8631. this.morphTargetDictionary = {};
  8632. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  8633. const name = morphAttribute[ m ].name || String( m );
  8634. this.morphTargetInfluences.push( 0 );
  8635. this.morphTargetDictionary[ name ] = m;
  8636. }
  8637. }
  8638. }
  8639. }
  8640. getVertexPosition( index, target ) {
  8641. const geometry = this.geometry;
  8642. const position = geometry.attributes.position;
  8643. const morphPosition = geometry.morphAttributes.position;
  8644. const morphTargetsRelative = geometry.morphTargetsRelative;
  8645. target.fromBufferAttribute( position, index );
  8646. const morphInfluences = this.morphTargetInfluences;
  8647. if ( morphPosition && morphInfluences ) {
  8648. _morphA.set( 0, 0, 0 );
  8649. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  8650. const influence = morphInfluences[ i ];
  8651. const morphAttribute = morphPosition[ i ];
  8652. if ( influence === 0 ) continue;
  8653. _tempA.fromBufferAttribute( morphAttribute, index );
  8654. if ( morphTargetsRelative ) {
  8655. _morphA.addScaledVector( _tempA, influence );
  8656. } else {
  8657. _morphA.addScaledVector( _tempA.sub( target ), influence );
  8658. }
  8659. }
  8660. target.add( _morphA );
  8661. }
  8662. return target;
  8663. }
  8664. raycast( raycaster, intersects ) {
  8665. const geometry = this.geometry;
  8666. const material = this.material;
  8667. const matrixWorld = this.matrixWorld;
  8668. if ( material === undefined ) return;
  8669. // test with bounding sphere in world space
  8670. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8671. _sphere$6.copy( geometry.boundingSphere );
  8672. _sphere$6.applyMatrix4( matrixWorld );
  8673. // check distance from ray origin to bounding sphere
  8674. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  8675. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  8676. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  8677. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  8678. }
  8679. // convert ray to local space of mesh
  8680. _inverseMatrix$3.copy( matrixWorld ).invert();
  8681. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  8682. // test with bounding box in local space
  8683. if ( geometry.boundingBox !== null ) {
  8684. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  8685. }
  8686. // test for intersections with geometry
  8687. this._computeIntersections( raycaster, intersects, _ray$3 );
  8688. }
  8689. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  8690. let intersection;
  8691. const geometry = this.geometry;
  8692. const material = this.material;
  8693. const index = geometry.index;
  8694. const position = geometry.attributes.position;
  8695. const uv = geometry.attributes.uv;
  8696. const uv1 = geometry.attributes.uv1;
  8697. const normal = geometry.attributes.normal;
  8698. const groups = geometry.groups;
  8699. const drawRange = geometry.drawRange;
  8700. if ( index !== null ) {
  8701. // indexed buffer geometry
  8702. if ( Array.isArray( material ) ) {
  8703. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  8704. const group = groups[ i ];
  8705. const groupMaterial = material[ group.materialIndex ];
  8706. const start = Math.max( group.start, drawRange.start );
  8707. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  8708. for ( let j = start, jl = end; j < jl; j += 3 ) {
  8709. const a = index.getX( j );
  8710. const b = index.getX( j + 1 );
  8711. const c = index.getX( j + 2 );
  8712. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  8713. if ( intersection ) {
  8714. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  8715. intersection.face.materialIndex = group.materialIndex;
  8716. intersects.push( intersection );
  8717. }
  8718. }
  8719. }
  8720. } else {
  8721. const start = Math.max( 0, drawRange.start );
  8722. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  8723. for ( let i = start, il = end; i < il; i += 3 ) {
  8724. const a = index.getX( i );
  8725. const b = index.getX( i + 1 );
  8726. const c = index.getX( i + 2 );
  8727. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  8728. if ( intersection ) {
  8729. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  8730. intersects.push( intersection );
  8731. }
  8732. }
  8733. }
  8734. } else if ( position !== undefined ) {
  8735. // non-indexed buffer geometry
  8736. if ( Array.isArray( material ) ) {
  8737. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  8738. const group = groups[ i ];
  8739. const groupMaterial = material[ group.materialIndex ];
  8740. const start = Math.max( group.start, drawRange.start );
  8741. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  8742. for ( let j = start, jl = end; j < jl; j += 3 ) {
  8743. const a = j;
  8744. const b = j + 1;
  8745. const c = j + 2;
  8746. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  8747. if ( intersection ) {
  8748. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  8749. intersection.face.materialIndex = group.materialIndex;
  8750. intersects.push( intersection );
  8751. }
  8752. }
  8753. }
  8754. } else {
  8755. const start = Math.max( 0, drawRange.start );
  8756. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  8757. for ( let i = start, il = end; i < il; i += 3 ) {
  8758. const a = i;
  8759. const b = i + 1;
  8760. const c = i + 2;
  8761. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  8762. if ( intersection ) {
  8763. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  8764. intersects.push( intersection );
  8765. }
  8766. }
  8767. }
  8768. }
  8769. }
  8770. }
  8771. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  8772. let intersect;
  8773. if ( material.side === BackSide ) {
  8774. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  8775. } else {
  8776. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  8777. }
  8778. if ( intersect === null ) return null;
  8779. _intersectionPointWorld.copy( point );
  8780. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  8781. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  8782. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  8783. return {
  8784. distance: distance,
  8785. point: _intersectionPointWorld.clone(),
  8786. object: object
  8787. };
  8788. }
  8789. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  8790. object.getVertexPosition( a, _vA$1 );
  8791. object.getVertexPosition( b, _vB$1 );
  8792. object.getVertexPosition( c, _vC$1 );
  8793. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  8794. if ( intersection ) {
  8795. const barycoord = new Vector3();
  8796. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  8797. if ( uv ) {
  8798. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  8799. }
  8800. if ( uv1 ) {
  8801. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  8802. }
  8803. if ( normal ) {
  8804. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  8805. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  8806. intersection.normal.multiplyScalar( -1 );
  8807. }
  8808. }
  8809. const face = {
  8810. a: a,
  8811. b: b,
  8812. c: c,
  8813. normal: new Vector3(),
  8814. materialIndex: 0
  8815. };
  8816. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  8817. intersection.face = face;
  8818. intersection.barycoord = barycoord;
  8819. }
  8820. return intersection;
  8821. }
  8822. class BoxGeometry extends BufferGeometry {
  8823. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  8824. super();
  8825. this.type = 'BoxGeometry';
  8826. this.parameters = {
  8827. width: width,
  8828. height: height,
  8829. depth: depth,
  8830. widthSegments: widthSegments,
  8831. heightSegments: heightSegments,
  8832. depthSegments: depthSegments
  8833. };
  8834. const scope = this;
  8835. // segments
  8836. widthSegments = Math.floor( widthSegments );
  8837. heightSegments = Math.floor( heightSegments );
  8838. depthSegments = Math.floor( depthSegments );
  8839. // buffers
  8840. const indices = [];
  8841. const vertices = [];
  8842. const normals = [];
  8843. const uvs = [];
  8844. // helper variables
  8845. let numberOfVertices = 0;
  8846. let groupStart = 0;
  8847. // build each side of the box geometry
  8848. buildPlane( 'z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  8849. buildPlane( 'z', 'y', 'x', 1, -1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  8850. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  8851. buildPlane( 'x', 'z', 'y', 1, -1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  8852. buildPlane( 'x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  8853. buildPlane( 'x', 'y', 'z', -1, -1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  8854. // build geometry
  8855. this.setIndex( indices );
  8856. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  8857. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  8858. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  8859. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  8860. const segmentWidth = width / gridX;
  8861. const segmentHeight = height / gridY;
  8862. const widthHalf = width / 2;
  8863. const heightHalf = height / 2;
  8864. const depthHalf = depth / 2;
  8865. const gridX1 = gridX + 1;
  8866. const gridY1 = gridY + 1;
  8867. let vertexCounter = 0;
  8868. let groupCount = 0;
  8869. const vector = new Vector3();
  8870. // generate vertices, normals and uvs
  8871. for ( let iy = 0; iy < gridY1; iy ++ ) {
  8872. const y = iy * segmentHeight - heightHalf;
  8873. for ( let ix = 0; ix < gridX1; ix ++ ) {
  8874. const x = ix * segmentWidth - widthHalf;
  8875. // set values to correct vector component
  8876. vector[ u ] = x * udir;
  8877. vector[ v ] = y * vdir;
  8878. vector[ w ] = depthHalf;
  8879. // now apply vector to vertex buffer
  8880. vertices.push( vector.x, vector.y, vector.z );
  8881. // set values to correct vector component
  8882. vector[ u ] = 0;
  8883. vector[ v ] = 0;
  8884. vector[ w ] = depth > 0 ? 1 : -1;
  8885. // now apply vector to normal buffer
  8886. normals.push( vector.x, vector.y, vector.z );
  8887. // uvs
  8888. uvs.push( ix / gridX );
  8889. uvs.push( 1 - ( iy / gridY ) );
  8890. // counters
  8891. vertexCounter += 1;
  8892. }
  8893. }
  8894. // indices
  8895. // 1. you need three indices to draw a single face
  8896. // 2. a single segment consists of two faces
  8897. // 3. so we need to generate six (2*3) indices per segment
  8898. for ( let iy = 0; iy < gridY; iy ++ ) {
  8899. for ( let ix = 0; ix < gridX; ix ++ ) {
  8900. const a = numberOfVertices + ix + gridX1 * iy;
  8901. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  8902. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  8903. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  8904. // faces
  8905. indices.push( a, b, d );
  8906. indices.push( b, c, d );
  8907. // increase counter
  8908. groupCount += 6;
  8909. }
  8910. }
  8911. // add a group to the geometry. this will ensure multi material support
  8912. scope.addGroup( groupStart, groupCount, materialIndex );
  8913. // calculate new start value for groups
  8914. groupStart += groupCount;
  8915. // update total number of vertices
  8916. numberOfVertices += vertexCounter;
  8917. }
  8918. }
  8919. copy( source ) {
  8920. super.copy( source );
  8921. this.parameters = Object.assign( {}, source.parameters );
  8922. return this;
  8923. }
  8924. static fromJSON( data ) {
  8925. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  8926. }
  8927. }
  8928. /**
  8929. * Uniform Utilities
  8930. */
  8931. function cloneUniforms( src ) {
  8932. const dst = {};
  8933. for ( const u in src ) {
  8934. dst[ u ] = {};
  8935. for ( const p in src[ u ] ) {
  8936. const property = src[ u ][ p ];
  8937. if ( property && ( property.isColor ||
  8938. property.isMatrix3 || property.isMatrix4 ||
  8939. property.isVector2 || property.isVector3 || property.isVector4 ||
  8940. property.isTexture || property.isQuaternion ) ) {
  8941. if ( property.isRenderTargetTexture ) {
  8942. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  8943. dst[ u ][ p ] = null;
  8944. } else {
  8945. dst[ u ][ p ] = property.clone();
  8946. }
  8947. } else if ( Array.isArray( property ) ) {
  8948. dst[ u ][ p ] = property.slice();
  8949. } else {
  8950. dst[ u ][ p ] = property;
  8951. }
  8952. }
  8953. }
  8954. return dst;
  8955. }
  8956. function mergeUniforms( uniforms ) {
  8957. const merged = {};
  8958. for ( let u = 0; u < uniforms.length; u ++ ) {
  8959. const tmp = cloneUniforms( uniforms[ u ] );
  8960. for ( const p in tmp ) {
  8961. merged[ p ] = tmp[ p ];
  8962. }
  8963. }
  8964. return merged;
  8965. }
  8966. function cloneUniformsGroups( src ) {
  8967. const dst = [];
  8968. for ( let u = 0; u < src.length; u ++ ) {
  8969. dst.push( src[ u ].clone() );
  8970. }
  8971. return dst;
  8972. }
  8973. function getUnlitUniformColorSpace( renderer ) {
  8974. const currentRenderTarget = renderer.getRenderTarget();
  8975. if ( currentRenderTarget === null ) {
  8976. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  8977. return renderer.outputColorSpace;
  8978. }
  8979. // https://github.com/mrdoob/three.js/issues/27868
  8980. if ( currentRenderTarget.isXRRenderTarget === true ) {
  8981. return currentRenderTarget.texture.colorSpace;
  8982. }
  8983. return ColorManagement.workingColorSpace;
  8984. }
  8985. // Legacy
  8986. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  8987. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  8988. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  8989. class ShaderMaterial extends Material {
  8990. constructor( parameters ) {
  8991. super();
  8992. this.isShaderMaterial = true;
  8993. this.type = 'ShaderMaterial';
  8994. this.defines = {};
  8995. this.uniforms = {};
  8996. this.uniformsGroups = [];
  8997. this.vertexShader = default_vertex;
  8998. this.fragmentShader = default_fragment;
  8999. this.linewidth = 1;
  9000. this.wireframe = false;
  9001. this.wireframeLinewidth = 1;
  9002. this.fog = false; // set to use scene fog
  9003. this.lights = false; // set to use scene lights
  9004. this.clipping = false; // set to use user-defined clipping planes
  9005. this.forceSinglePass = true;
  9006. this.extensions = {
  9007. clipCullDistance: false, // set to use vertex shader clipping
  9008. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  9009. };
  9010. // When rendered geometry doesn't include these attributes but the material does,
  9011. // use these default values in WebGL. This avoids errors when buffer data is missing.
  9012. this.defaultAttributeValues = {
  9013. 'color': [ 1, 1, 1 ],
  9014. 'uv': [ 0, 0 ],
  9015. 'uv1': [ 0, 0 ]
  9016. };
  9017. this.index0AttributeName = undefined;
  9018. this.uniformsNeedUpdate = false;
  9019. this.glslVersion = null;
  9020. if ( parameters !== undefined ) {
  9021. this.setValues( parameters );
  9022. }
  9023. }
  9024. copy( source ) {
  9025. super.copy( source );
  9026. this.fragmentShader = source.fragmentShader;
  9027. this.vertexShader = source.vertexShader;
  9028. this.uniforms = cloneUniforms( source.uniforms );
  9029. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  9030. this.defines = Object.assign( {}, source.defines );
  9031. this.wireframe = source.wireframe;
  9032. this.wireframeLinewidth = source.wireframeLinewidth;
  9033. this.fog = source.fog;
  9034. this.lights = source.lights;
  9035. this.clipping = source.clipping;
  9036. this.extensions = Object.assign( {}, source.extensions );
  9037. this.glslVersion = source.glslVersion;
  9038. return this;
  9039. }
  9040. toJSON( meta ) {
  9041. const data = super.toJSON( meta );
  9042. data.glslVersion = this.glslVersion;
  9043. data.uniforms = {};
  9044. for ( const name in this.uniforms ) {
  9045. const uniform = this.uniforms[ name ];
  9046. const value = uniform.value;
  9047. if ( value && value.isTexture ) {
  9048. data.uniforms[ name ] = {
  9049. type: 't',
  9050. value: value.toJSON( meta ).uuid
  9051. };
  9052. } else if ( value && value.isColor ) {
  9053. data.uniforms[ name ] = {
  9054. type: 'c',
  9055. value: value.getHex()
  9056. };
  9057. } else if ( value && value.isVector2 ) {
  9058. data.uniforms[ name ] = {
  9059. type: 'v2',
  9060. value: value.toArray()
  9061. };
  9062. } else if ( value && value.isVector3 ) {
  9063. data.uniforms[ name ] = {
  9064. type: 'v3',
  9065. value: value.toArray()
  9066. };
  9067. } else if ( value && value.isVector4 ) {
  9068. data.uniforms[ name ] = {
  9069. type: 'v4',
  9070. value: value.toArray()
  9071. };
  9072. } else if ( value && value.isMatrix3 ) {
  9073. data.uniforms[ name ] = {
  9074. type: 'm3',
  9075. value: value.toArray()
  9076. };
  9077. } else if ( value && value.isMatrix4 ) {
  9078. data.uniforms[ name ] = {
  9079. type: 'm4',
  9080. value: value.toArray()
  9081. };
  9082. } else {
  9083. data.uniforms[ name ] = {
  9084. value: value
  9085. };
  9086. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  9087. }
  9088. }
  9089. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  9090. data.vertexShader = this.vertexShader;
  9091. data.fragmentShader = this.fragmentShader;
  9092. data.lights = this.lights;
  9093. data.clipping = this.clipping;
  9094. const extensions = {};
  9095. for ( const key in this.extensions ) {
  9096. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  9097. }
  9098. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  9099. return data;
  9100. }
  9101. }
  9102. class Camera extends Object3D {
  9103. constructor() {
  9104. super();
  9105. this.isCamera = true;
  9106. this.type = 'Camera';
  9107. this.matrixWorldInverse = new Matrix4();
  9108. this.projectionMatrix = new Matrix4();
  9109. this.projectionMatrixInverse = new Matrix4();
  9110. this.coordinateSystem = WebGLCoordinateSystem;
  9111. }
  9112. copy( source, recursive ) {
  9113. super.copy( source, recursive );
  9114. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  9115. this.projectionMatrix.copy( source.projectionMatrix );
  9116. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  9117. this.coordinateSystem = source.coordinateSystem;
  9118. return this;
  9119. }
  9120. getWorldDirection( target ) {
  9121. return super.getWorldDirection( target ).negate();
  9122. }
  9123. updateMatrixWorld( force ) {
  9124. super.updateMatrixWorld( force );
  9125. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  9126. }
  9127. updateWorldMatrix( updateParents, updateChildren ) {
  9128. super.updateWorldMatrix( updateParents, updateChildren );
  9129. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  9130. }
  9131. clone() {
  9132. return new this.constructor().copy( this );
  9133. }
  9134. }
  9135. const _v3$1 = /*@__PURE__*/ new Vector3();
  9136. const _minTarget = /*@__PURE__*/ new Vector2();
  9137. const _maxTarget = /*@__PURE__*/ new Vector2();
  9138. class PerspectiveCamera extends Camera {
  9139. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  9140. super();
  9141. this.isPerspectiveCamera = true;
  9142. this.type = 'PerspectiveCamera';
  9143. this.fov = fov;
  9144. this.zoom = 1;
  9145. this.near = near;
  9146. this.far = far;
  9147. this.focus = 10;
  9148. this.aspect = aspect;
  9149. this.view = null;
  9150. this.filmGauge = 35; // width of the film (default in millimeters)
  9151. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  9152. this.updateProjectionMatrix();
  9153. }
  9154. copy( source, recursive ) {
  9155. super.copy( source, recursive );
  9156. this.fov = source.fov;
  9157. this.zoom = source.zoom;
  9158. this.near = source.near;
  9159. this.far = source.far;
  9160. this.focus = source.focus;
  9161. this.aspect = source.aspect;
  9162. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9163. this.filmGauge = source.filmGauge;
  9164. this.filmOffset = source.filmOffset;
  9165. return this;
  9166. }
  9167. /**
  9168. * Sets the FOV by focal length in respect to the current .filmGauge.
  9169. *
  9170. * The default film gauge is 35, so that the focal length can be specified for
  9171. * a 35mm (full frame) camera.
  9172. *
  9173. * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
  9174. */
  9175. setFocalLength( focalLength ) {
  9176. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  9177. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  9178. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  9179. this.updateProjectionMatrix();
  9180. }
  9181. /**
  9182. * Calculates the focal length from the current .fov and .filmGauge.
  9183. *
  9184. * @returns {number}
  9185. */
  9186. getFocalLength() {
  9187. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  9188. return 0.5 * this.getFilmHeight() / vExtentSlope;
  9189. }
  9190. getEffectiveFOV() {
  9191. return RAD2DEG * 2 * Math.atan(
  9192. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  9193. }
  9194. getFilmWidth() {
  9195. // film not completely covered in portrait format (aspect < 1)
  9196. return this.filmGauge * Math.min( this.aspect, 1 );
  9197. }
  9198. getFilmHeight() {
  9199. // film not completely covered in landscape format (aspect > 1)
  9200. return this.filmGauge / Math.max( this.aspect, 1 );
  9201. }
  9202. /**
  9203. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  9204. * Sets minTarget and maxTarget to the coordinates of the lower-left and upper-right corners of the view rectangle.
  9205. *
  9206. * @param {number} distance
  9207. * @param {Vector2} minTarget
  9208. * @param {Vector2} maxTarget
  9209. */
  9210. getViewBounds( distance, minTarget, maxTarget ) {
  9211. _v3$1.set( -1, -1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  9212. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  9213. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  9214. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  9215. }
  9216. /**
  9217. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  9218. *
  9219. * @param {number} distance
  9220. * @param {Vector2} target - Vector2 target used to store result where x is width and y is height.
  9221. * @returns {Vector2}
  9222. */
  9223. getViewSize( distance, target ) {
  9224. this.getViewBounds( distance, _minTarget, _maxTarget );
  9225. return target.subVectors( _maxTarget, _minTarget );
  9226. }
  9227. /**
  9228. * Sets an offset in a larger frustum. This is useful for multi-window or
  9229. * multi-monitor/multi-machine setups.
  9230. *
  9231. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  9232. * the monitors are in grid like this
  9233. *
  9234. * +---+---+---+
  9235. * | A | B | C |
  9236. * +---+---+---+
  9237. * | D | E | F |
  9238. * +---+---+---+
  9239. *
  9240. * then for each monitor you would call it like this
  9241. *
  9242. * const w = 1920;
  9243. * const h = 1080;
  9244. * const fullWidth = w * 3;
  9245. * const fullHeight = h * 2;
  9246. *
  9247. * --A--
  9248. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  9249. * --B--
  9250. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  9251. * --C--
  9252. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  9253. * --D--
  9254. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  9255. * --E--
  9256. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  9257. * --F--
  9258. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  9259. *
  9260. * Note there is no reason monitors have to be the same size or in a grid.
  9261. *
  9262. * @param {number} fullWidth
  9263. * @param {number} fullHeight
  9264. * @param {number} x
  9265. * @param {number} y
  9266. * @param {number} width
  9267. * @param {number} height
  9268. */
  9269. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  9270. this.aspect = fullWidth / fullHeight;
  9271. if ( this.view === null ) {
  9272. this.view = {
  9273. enabled: true,
  9274. fullWidth: 1,
  9275. fullHeight: 1,
  9276. offsetX: 0,
  9277. offsetY: 0,
  9278. width: 1,
  9279. height: 1
  9280. };
  9281. }
  9282. this.view.enabled = true;
  9283. this.view.fullWidth = fullWidth;
  9284. this.view.fullHeight = fullHeight;
  9285. this.view.offsetX = x;
  9286. this.view.offsetY = y;
  9287. this.view.width = width;
  9288. this.view.height = height;
  9289. this.updateProjectionMatrix();
  9290. }
  9291. clearViewOffset() {
  9292. if ( this.view !== null ) {
  9293. this.view.enabled = false;
  9294. }
  9295. this.updateProjectionMatrix();
  9296. }
  9297. updateProjectionMatrix() {
  9298. const near = this.near;
  9299. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  9300. let height = 2 * top;
  9301. let width = this.aspect * height;
  9302. let left = -0.5 * width;
  9303. const view = this.view;
  9304. if ( this.view !== null && this.view.enabled ) {
  9305. const fullWidth = view.fullWidth,
  9306. fullHeight = view.fullHeight;
  9307. left += view.offsetX * width / fullWidth;
  9308. top -= view.offsetY * height / fullHeight;
  9309. width *= view.width / fullWidth;
  9310. height *= view.height / fullHeight;
  9311. }
  9312. const skew = this.filmOffset;
  9313. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  9314. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem );
  9315. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  9316. }
  9317. toJSON( meta ) {
  9318. const data = super.toJSON( meta );
  9319. data.object.fov = this.fov;
  9320. data.object.zoom = this.zoom;
  9321. data.object.near = this.near;
  9322. data.object.far = this.far;
  9323. data.object.focus = this.focus;
  9324. data.object.aspect = this.aspect;
  9325. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9326. data.object.filmGauge = this.filmGauge;
  9327. data.object.filmOffset = this.filmOffset;
  9328. return data;
  9329. }
  9330. }
  9331. const fov = -90; // negative fov is not an error
  9332. const aspect = 1;
  9333. class CubeCamera extends Object3D {
  9334. constructor( near, far, renderTarget ) {
  9335. super();
  9336. this.type = 'CubeCamera';
  9337. this.renderTarget = renderTarget;
  9338. this.coordinateSystem = null;
  9339. this.activeMipmapLevel = 0;
  9340. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  9341. cameraPX.layers = this.layers;
  9342. this.add( cameraPX );
  9343. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  9344. cameraNX.layers = this.layers;
  9345. this.add( cameraNX );
  9346. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  9347. cameraPY.layers = this.layers;
  9348. this.add( cameraPY );
  9349. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  9350. cameraNY.layers = this.layers;
  9351. this.add( cameraNY );
  9352. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  9353. cameraPZ.layers = this.layers;
  9354. this.add( cameraPZ );
  9355. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  9356. cameraNZ.layers = this.layers;
  9357. this.add( cameraNZ );
  9358. }
  9359. updateCoordinateSystem() {
  9360. const coordinateSystem = this.coordinateSystem;
  9361. const cameras = this.children.concat();
  9362. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  9363. for ( const camera of cameras ) this.remove( camera );
  9364. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9365. cameraPX.up.set( 0, 1, 0 );
  9366. cameraPX.lookAt( 1, 0, 0 );
  9367. cameraNX.up.set( 0, 1, 0 );
  9368. cameraNX.lookAt( -1, 0, 0 );
  9369. cameraPY.up.set( 0, 0, -1 );
  9370. cameraPY.lookAt( 0, 1, 0 );
  9371. cameraNY.up.set( 0, 0, 1 );
  9372. cameraNY.lookAt( 0, -1, 0 );
  9373. cameraPZ.up.set( 0, 1, 0 );
  9374. cameraPZ.lookAt( 0, 0, 1 );
  9375. cameraNZ.up.set( 0, 1, 0 );
  9376. cameraNZ.lookAt( 0, 0, -1 );
  9377. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9378. cameraPX.up.set( 0, -1, 0 );
  9379. cameraPX.lookAt( -1, 0, 0 );
  9380. cameraNX.up.set( 0, -1, 0 );
  9381. cameraNX.lookAt( 1, 0, 0 );
  9382. cameraPY.up.set( 0, 0, 1 );
  9383. cameraPY.lookAt( 0, 1, 0 );
  9384. cameraNY.up.set( 0, 0, -1 );
  9385. cameraNY.lookAt( 0, -1, 0 );
  9386. cameraPZ.up.set( 0, -1, 0 );
  9387. cameraPZ.lookAt( 0, 0, 1 );
  9388. cameraNZ.up.set( 0, -1, 0 );
  9389. cameraNZ.lookAt( 0, 0, -1 );
  9390. } else {
  9391. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  9392. }
  9393. for ( const camera of cameras ) {
  9394. this.add( camera );
  9395. camera.updateMatrixWorld();
  9396. }
  9397. }
  9398. update( renderer, scene ) {
  9399. if ( this.parent === null ) this.updateMatrixWorld();
  9400. const { renderTarget, activeMipmapLevel } = this;
  9401. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  9402. this.coordinateSystem = renderer.coordinateSystem;
  9403. this.updateCoordinateSystem();
  9404. }
  9405. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  9406. const currentRenderTarget = renderer.getRenderTarget();
  9407. const currentActiveCubeFace = renderer.getActiveCubeFace();
  9408. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  9409. const currentXrEnabled = renderer.xr.enabled;
  9410. renderer.xr.enabled = false;
  9411. const generateMipmaps = renderTarget.texture.generateMipmaps;
  9412. renderTarget.texture.generateMipmaps = false;
  9413. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  9414. renderer.render( scene, cameraPX );
  9415. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  9416. renderer.render( scene, cameraNX );
  9417. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  9418. renderer.render( scene, cameraPY );
  9419. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  9420. renderer.render( scene, cameraNY );
  9421. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  9422. renderer.render( scene, cameraPZ );
  9423. // mipmaps are generated during the last call of render()
  9424. // at this point, all sides of the cube render target are defined
  9425. renderTarget.texture.generateMipmaps = generateMipmaps;
  9426. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  9427. renderer.render( scene, cameraNZ );
  9428. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  9429. renderer.xr.enabled = currentXrEnabled;
  9430. renderTarget.texture.needsPMREMUpdate = true;
  9431. }
  9432. }
  9433. class CubeTexture extends Texture {
  9434. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  9435. images = images !== undefined ? images : [];
  9436. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  9437. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  9438. this.isCubeTexture = true;
  9439. this.flipY = false;
  9440. }
  9441. get images() {
  9442. return this.image;
  9443. }
  9444. set images( value ) {
  9445. this.image = value;
  9446. }
  9447. }
  9448. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  9449. constructor( size = 1, options = {} ) {
  9450. super( size, size, options );
  9451. this.isWebGLCubeRenderTarget = true;
  9452. const image = { width: size, height: size, depth: 1 };
  9453. const images = [ image, image, image, image, image, image ];
  9454. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  9455. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  9456. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  9457. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  9458. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  9459. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  9460. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  9461. this.texture.isRenderTargetTexture = true;
  9462. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  9463. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  9464. }
  9465. fromEquirectangularTexture( renderer, texture ) {
  9466. this.texture.type = texture.type;
  9467. this.texture.colorSpace = texture.colorSpace;
  9468. this.texture.generateMipmaps = texture.generateMipmaps;
  9469. this.texture.minFilter = texture.minFilter;
  9470. this.texture.magFilter = texture.magFilter;
  9471. const shader = {
  9472. uniforms: {
  9473. tEquirect: { value: null },
  9474. },
  9475. vertexShader: /* glsl */`
  9476. varying vec3 vWorldDirection;
  9477. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  9478. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  9479. }
  9480. void main() {
  9481. vWorldDirection = transformDirection( position, modelMatrix );
  9482. #include <begin_vertex>
  9483. #include <project_vertex>
  9484. }
  9485. `,
  9486. fragmentShader: /* glsl */`
  9487. uniform sampler2D tEquirect;
  9488. varying vec3 vWorldDirection;
  9489. #include <common>
  9490. void main() {
  9491. vec3 direction = normalize( vWorldDirection );
  9492. vec2 sampleUV = equirectUv( direction );
  9493. gl_FragColor = texture2D( tEquirect, sampleUV );
  9494. }
  9495. `
  9496. };
  9497. const geometry = new BoxGeometry( 5, 5, 5 );
  9498. const material = new ShaderMaterial( {
  9499. name: 'CubemapFromEquirect',
  9500. uniforms: cloneUniforms( shader.uniforms ),
  9501. vertexShader: shader.vertexShader,
  9502. fragmentShader: shader.fragmentShader,
  9503. side: BackSide,
  9504. blending: NoBlending
  9505. } );
  9506. material.uniforms.tEquirect.value = texture;
  9507. const mesh = new Mesh( geometry, material );
  9508. const currentMinFilter = texture.minFilter;
  9509. // Avoid blurred poles
  9510. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  9511. const camera = new CubeCamera( 1, 10, this );
  9512. camera.update( renderer, mesh );
  9513. texture.minFilter = currentMinFilter;
  9514. mesh.geometry.dispose();
  9515. mesh.material.dispose();
  9516. return this;
  9517. }
  9518. clear( renderer, color, depth, stencil ) {
  9519. const currentRenderTarget = renderer.getRenderTarget();
  9520. for ( let i = 0; i < 6; i ++ ) {
  9521. renderer.setRenderTarget( this, i );
  9522. renderer.clear( color, depth, stencil );
  9523. }
  9524. renderer.setRenderTarget( currentRenderTarget );
  9525. }
  9526. }
  9527. class Group extends Object3D {
  9528. constructor() {
  9529. super();
  9530. this.isGroup = true;
  9531. this.type = 'Group';
  9532. }
  9533. }
  9534. const _moveEvent = { type: 'move' };
  9535. class WebXRController {
  9536. constructor() {
  9537. this._targetRay = null;
  9538. this._grip = null;
  9539. this._hand = null;
  9540. }
  9541. getHandSpace() {
  9542. if ( this._hand === null ) {
  9543. this._hand = new Group();
  9544. this._hand.matrixAutoUpdate = false;
  9545. this._hand.visible = false;
  9546. this._hand.joints = {};
  9547. this._hand.inputState = { pinching: false };
  9548. }
  9549. return this._hand;
  9550. }
  9551. getTargetRaySpace() {
  9552. if ( this._targetRay === null ) {
  9553. this._targetRay = new Group();
  9554. this._targetRay.matrixAutoUpdate = false;
  9555. this._targetRay.visible = false;
  9556. this._targetRay.hasLinearVelocity = false;
  9557. this._targetRay.linearVelocity = new Vector3();
  9558. this._targetRay.hasAngularVelocity = false;
  9559. this._targetRay.angularVelocity = new Vector3();
  9560. }
  9561. return this._targetRay;
  9562. }
  9563. getGripSpace() {
  9564. if ( this._grip === null ) {
  9565. this._grip = new Group();
  9566. this._grip.matrixAutoUpdate = false;
  9567. this._grip.visible = false;
  9568. this._grip.hasLinearVelocity = false;
  9569. this._grip.linearVelocity = new Vector3();
  9570. this._grip.hasAngularVelocity = false;
  9571. this._grip.angularVelocity = new Vector3();
  9572. }
  9573. return this._grip;
  9574. }
  9575. dispatchEvent( event ) {
  9576. if ( this._targetRay !== null ) {
  9577. this._targetRay.dispatchEvent( event );
  9578. }
  9579. if ( this._grip !== null ) {
  9580. this._grip.dispatchEvent( event );
  9581. }
  9582. if ( this._hand !== null ) {
  9583. this._hand.dispatchEvent( event );
  9584. }
  9585. return this;
  9586. }
  9587. connect( inputSource ) {
  9588. if ( inputSource && inputSource.hand ) {
  9589. const hand = this._hand;
  9590. if ( hand ) {
  9591. for ( const inputjoint of inputSource.hand.values() ) {
  9592. // Initialize hand with joints when connected
  9593. this._getHandJoint( hand, inputjoint );
  9594. }
  9595. }
  9596. }
  9597. this.dispatchEvent( { type: 'connected', data: inputSource } );
  9598. return this;
  9599. }
  9600. disconnect( inputSource ) {
  9601. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  9602. if ( this._targetRay !== null ) {
  9603. this._targetRay.visible = false;
  9604. }
  9605. if ( this._grip !== null ) {
  9606. this._grip.visible = false;
  9607. }
  9608. if ( this._hand !== null ) {
  9609. this._hand.visible = false;
  9610. }
  9611. return this;
  9612. }
  9613. update( inputSource, frame, referenceSpace ) {
  9614. let inputPose = null;
  9615. let gripPose = null;
  9616. let handPose = null;
  9617. const targetRay = this._targetRay;
  9618. const grip = this._grip;
  9619. const hand = this._hand;
  9620. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  9621. if ( hand && inputSource.hand ) {
  9622. handPose = true;
  9623. for ( const inputjoint of inputSource.hand.values() ) {
  9624. // Update the joints groups with the XRJoint poses
  9625. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  9626. // The transform of this joint will be updated with the joint pose on each frame
  9627. const joint = this._getHandJoint( hand, inputjoint );
  9628. if ( jointPose !== null ) {
  9629. joint.matrix.fromArray( jointPose.transform.matrix );
  9630. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  9631. joint.matrixWorldNeedsUpdate = true;
  9632. joint.jointRadius = jointPose.radius;
  9633. }
  9634. joint.visible = jointPose !== null;
  9635. }
  9636. // Custom events
  9637. // Check pinchz
  9638. const indexTip = hand.joints[ 'index-finger-tip' ];
  9639. const thumbTip = hand.joints[ 'thumb-tip' ];
  9640. const distance = indexTip.position.distanceTo( thumbTip.position );
  9641. const distanceToPinch = 0.02;
  9642. const threshold = 0.005;
  9643. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  9644. hand.inputState.pinching = false;
  9645. this.dispatchEvent( {
  9646. type: 'pinchend',
  9647. handedness: inputSource.handedness,
  9648. target: this
  9649. } );
  9650. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  9651. hand.inputState.pinching = true;
  9652. this.dispatchEvent( {
  9653. type: 'pinchstart',
  9654. handedness: inputSource.handedness,
  9655. target: this
  9656. } );
  9657. }
  9658. } else {
  9659. if ( grip !== null && inputSource.gripSpace ) {
  9660. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  9661. if ( gripPose !== null ) {
  9662. grip.matrix.fromArray( gripPose.transform.matrix );
  9663. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  9664. grip.matrixWorldNeedsUpdate = true;
  9665. if ( gripPose.linearVelocity ) {
  9666. grip.hasLinearVelocity = true;
  9667. grip.linearVelocity.copy( gripPose.linearVelocity );
  9668. } else {
  9669. grip.hasLinearVelocity = false;
  9670. }
  9671. if ( gripPose.angularVelocity ) {
  9672. grip.hasAngularVelocity = true;
  9673. grip.angularVelocity.copy( gripPose.angularVelocity );
  9674. } else {
  9675. grip.hasAngularVelocity = false;
  9676. }
  9677. }
  9678. }
  9679. }
  9680. if ( targetRay !== null ) {
  9681. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  9682. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  9683. if ( inputPose === null && gripPose !== null ) {
  9684. inputPose = gripPose;
  9685. }
  9686. if ( inputPose !== null ) {
  9687. targetRay.matrix.fromArray( inputPose.transform.matrix );
  9688. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  9689. targetRay.matrixWorldNeedsUpdate = true;
  9690. if ( inputPose.linearVelocity ) {
  9691. targetRay.hasLinearVelocity = true;
  9692. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  9693. } else {
  9694. targetRay.hasLinearVelocity = false;
  9695. }
  9696. if ( inputPose.angularVelocity ) {
  9697. targetRay.hasAngularVelocity = true;
  9698. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  9699. } else {
  9700. targetRay.hasAngularVelocity = false;
  9701. }
  9702. this.dispatchEvent( _moveEvent );
  9703. }
  9704. }
  9705. }
  9706. if ( targetRay !== null ) {
  9707. targetRay.visible = ( inputPose !== null );
  9708. }
  9709. if ( grip !== null ) {
  9710. grip.visible = ( gripPose !== null );
  9711. }
  9712. if ( hand !== null ) {
  9713. hand.visible = ( handPose !== null );
  9714. }
  9715. return this;
  9716. }
  9717. // private method
  9718. _getHandJoint( hand, inputjoint ) {
  9719. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  9720. const joint = new Group();
  9721. joint.matrixAutoUpdate = false;
  9722. joint.visible = false;
  9723. hand.joints[ inputjoint.jointName ] = joint;
  9724. hand.add( joint );
  9725. }
  9726. return hand.joints[ inputjoint.jointName ];
  9727. }
  9728. }
  9729. class FogExp2 {
  9730. constructor( color, density = 0.00025 ) {
  9731. this.isFogExp2 = true;
  9732. this.name = '';
  9733. this.color = new Color( color );
  9734. this.density = density;
  9735. }
  9736. clone() {
  9737. return new FogExp2( this.color, this.density );
  9738. }
  9739. toJSON( /* meta */ ) {
  9740. return {
  9741. type: 'FogExp2',
  9742. name: this.name,
  9743. color: this.color.getHex(),
  9744. density: this.density
  9745. };
  9746. }
  9747. }
  9748. class Fog {
  9749. constructor( color, near = 1, far = 1000 ) {
  9750. this.isFog = true;
  9751. this.name = '';
  9752. this.color = new Color( color );
  9753. this.near = near;
  9754. this.far = far;
  9755. }
  9756. clone() {
  9757. return new Fog( this.color, this.near, this.far );
  9758. }
  9759. toJSON( /* meta */ ) {
  9760. return {
  9761. type: 'Fog',
  9762. name: this.name,
  9763. color: this.color.getHex(),
  9764. near: this.near,
  9765. far: this.far
  9766. };
  9767. }
  9768. }
  9769. class Scene extends Object3D {
  9770. constructor() {
  9771. super();
  9772. this.isScene = true;
  9773. this.type = 'Scene';
  9774. this.background = null;
  9775. this.environment = null;
  9776. this.fog = null;
  9777. this.backgroundBlurriness = 0;
  9778. this.backgroundIntensity = 1;
  9779. this.backgroundRotation = new Euler();
  9780. this.environmentIntensity = 1;
  9781. this.environmentRotation = new Euler();
  9782. this.overrideMaterial = null;
  9783. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  9784. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  9785. }
  9786. }
  9787. copy( source, recursive ) {
  9788. super.copy( source, recursive );
  9789. if ( source.background !== null ) this.background = source.background.clone();
  9790. if ( source.environment !== null ) this.environment = source.environment.clone();
  9791. if ( source.fog !== null ) this.fog = source.fog.clone();
  9792. this.backgroundBlurriness = source.backgroundBlurriness;
  9793. this.backgroundIntensity = source.backgroundIntensity;
  9794. this.backgroundRotation.copy( source.backgroundRotation );
  9795. this.environmentIntensity = source.environmentIntensity;
  9796. this.environmentRotation.copy( source.environmentRotation );
  9797. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  9798. this.matrixAutoUpdate = source.matrixAutoUpdate;
  9799. return this;
  9800. }
  9801. toJSON( meta ) {
  9802. const data = super.toJSON( meta );
  9803. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  9804. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  9805. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  9806. data.object.backgroundRotation = this.backgroundRotation.toArray();
  9807. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  9808. data.object.environmentRotation = this.environmentRotation.toArray();
  9809. return data;
  9810. }
  9811. }
  9812. class InterleavedBuffer {
  9813. constructor( array, stride ) {
  9814. this.isInterleavedBuffer = true;
  9815. this.array = array;
  9816. this.stride = stride;
  9817. this.count = array !== undefined ? array.length / stride : 0;
  9818. this.usage = StaticDrawUsage;
  9819. this.updateRanges = [];
  9820. this.version = 0;
  9821. this.uuid = generateUUID();
  9822. }
  9823. onUploadCallback() {}
  9824. set needsUpdate( value ) {
  9825. if ( value === true ) this.version ++;
  9826. }
  9827. setUsage( value ) {
  9828. this.usage = value;
  9829. return this;
  9830. }
  9831. addUpdateRange( start, count ) {
  9832. this.updateRanges.push( { start, count } );
  9833. }
  9834. clearUpdateRanges() {
  9835. this.updateRanges.length = 0;
  9836. }
  9837. copy( source ) {
  9838. this.array = new source.array.constructor( source.array );
  9839. this.count = source.count;
  9840. this.stride = source.stride;
  9841. this.usage = source.usage;
  9842. return this;
  9843. }
  9844. copyAt( index1, attribute, index2 ) {
  9845. index1 *= this.stride;
  9846. index2 *= attribute.stride;
  9847. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  9848. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  9849. }
  9850. return this;
  9851. }
  9852. set( value, offset = 0 ) {
  9853. this.array.set( value, offset );
  9854. return this;
  9855. }
  9856. clone( data ) {
  9857. if ( data.arrayBuffers === undefined ) {
  9858. data.arrayBuffers = {};
  9859. }
  9860. if ( this.array.buffer._uuid === undefined ) {
  9861. this.array.buffer._uuid = generateUUID();
  9862. }
  9863. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  9864. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  9865. }
  9866. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  9867. const ib = new this.constructor( array, this.stride );
  9868. ib.setUsage( this.usage );
  9869. return ib;
  9870. }
  9871. onUpload( callback ) {
  9872. this.onUploadCallback = callback;
  9873. return this;
  9874. }
  9875. toJSON( data ) {
  9876. if ( data.arrayBuffers === undefined ) {
  9877. data.arrayBuffers = {};
  9878. }
  9879. // generate UUID for array buffer if necessary
  9880. if ( this.array.buffer._uuid === undefined ) {
  9881. this.array.buffer._uuid = generateUUID();
  9882. }
  9883. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  9884. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  9885. }
  9886. //
  9887. return {
  9888. uuid: this.uuid,
  9889. buffer: this.array.buffer._uuid,
  9890. type: this.array.constructor.name,
  9891. stride: this.stride
  9892. };
  9893. }
  9894. }
  9895. const _vector$7 = /*@__PURE__*/ new Vector3();
  9896. class InterleavedBufferAttribute {
  9897. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  9898. this.isInterleavedBufferAttribute = true;
  9899. this.name = '';
  9900. this.data = interleavedBuffer;
  9901. this.itemSize = itemSize;
  9902. this.offset = offset;
  9903. this.normalized = normalized;
  9904. }
  9905. get count() {
  9906. return this.data.count;
  9907. }
  9908. get array() {
  9909. return this.data.array;
  9910. }
  9911. set needsUpdate( value ) {
  9912. this.data.needsUpdate = value;
  9913. }
  9914. applyMatrix4( m ) {
  9915. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  9916. _vector$7.fromBufferAttribute( this, i );
  9917. _vector$7.applyMatrix4( m );
  9918. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  9919. }
  9920. return this;
  9921. }
  9922. applyNormalMatrix( m ) {
  9923. for ( let i = 0, l = this.count; i < l; i ++ ) {
  9924. _vector$7.fromBufferAttribute( this, i );
  9925. _vector$7.applyNormalMatrix( m );
  9926. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  9927. }
  9928. return this;
  9929. }
  9930. transformDirection( m ) {
  9931. for ( let i = 0, l = this.count; i < l; i ++ ) {
  9932. _vector$7.fromBufferAttribute( this, i );
  9933. _vector$7.transformDirection( m );
  9934. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  9935. }
  9936. return this;
  9937. }
  9938. getComponent( index, component ) {
  9939. let value = this.array[ index * this.data.stride + this.offset + component ];
  9940. if ( this.normalized ) value = denormalize( value, this.array );
  9941. return value;
  9942. }
  9943. setComponent( index, component, value ) {
  9944. if ( this.normalized ) value = normalize( value, this.array );
  9945. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  9946. return this;
  9947. }
  9948. setX( index, x ) {
  9949. if ( this.normalized ) x = normalize( x, this.array );
  9950. this.data.array[ index * this.data.stride + this.offset ] = x;
  9951. return this;
  9952. }
  9953. setY( index, y ) {
  9954. if ( this.normalized ) y = normalize( y, this.array );
  9955. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  9956. return this;
  9957. }
  9958. setZ( index, z ) {
  9959. if ( this.normalized ) z = normalize( z, this.array );
  9960. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  9961. return this;
  9962. }
  9963. setW( index, w ) {
  9964. if ( this.normalized ) w = normalize( w, this.array );
  9965. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  9966. return this;
  9967. }
  9968. getX( index ) {
  9969. let x = this.data.array[ index * this.data.stride + this.offset ];
  9970. if ( this.normalized ) x = denormalize( x, this.array );
  9971. return x;
  9972. }
  9973. getY( index ) {
  9974. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  9975. if ( this.normalized ) y = denormalize( y, this.array );
  9976. return y;
  9977. }
  9978. getZ( index ) {
  9979. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  9980. if ( this.normalized ) z = denormalize( z, this.array );
  9981. return z;
  9982. }
  9983. getW( index ) {
  9984. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  9985. if ( this.normalized ) w = denormalize( w, this.array );
  9986. return w;
  9987. }
  9988. setXY( index, x, y ) {
  9989. index = index * this.data.stride + this.offset;
  9990. if ( this.normalized ) {
  9991. x = normalize( x, this.array );
  9992. y = normalize( y, this.array );
  9993. }
  9994. this.data.array[ index + 0 ] = x;
  9995. this.data.array[ index + 1 ] = y;
  9996. return this;
  9997. }
  9998. setXYZ( index, x, y, z ) {
  9999. index = index * this.data.stride + this.offset;
  10000. if ( this.normalized ) {
  10001. x = normalize( x, this.array );
  10002. y = normalize( y, this.array );
  10003. z = normalize( z, this.array );
  10004. }
  10005. this.data.array[ index + 0 ] = x;
  10006. this.data.array[ index + 1 ] = y;
  10007. this.data.array[ index + 2 ] = z;
  10008. return this;
  10009. }
  10010. setXYZW( index, x, y, z, w ) {
  10011. index = index * this.data.stride + this.offset;
  10012. if ( this.normalized ) {
  10013. x = normalize( x, this.array );
  10014. y = normalize( y, this.array );
  10015. z = normalize( z, this.array );
  10016. w = normalize( w, this.array );
  10017. }
  10018. this.data.array[ index + 0 ] = x;
  10019. this.data.array[ index + 1 ] = y;
  10020. this.data.array[ index + 2 ] = z;
  10021. this.data.array[ index + 3 ] = w;
  10022. return this;
  10023. }
  10024. clone( data ) {
  10025. if ( data === undefined ) {
  10026. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  10027. const array = [];
  10028. for ( let i = 0; i < this.count; i ++ ) {
  10029. const index = i * this.data.stride + this.offset;
  10030. for ( let j = 0; j < this.itemSize; j ++ ) {
  10031. array.push( this.data.array[ index + j ] );
  10032. }
  10033. }
  10034. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  10035. } else {
  10036. if ( data.interleavedBuffers === undefined ) {
  10037. data.interleavedBuffers = {};
  10038. }
  10039. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  10040. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  10041. }
  10042. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  10043. }
  10044. }
  10045. toJSON( data ) {
  10046. if ( data === undefined ) {
  10047. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  10048. const array = [];
  10049. for ( let i = 0; i < this.count; i ++ ) {
  10050. const index = i * this.data.stride + this.offset;
  10051. for ( let j = 0; j < this.itemSize; j ++ ) {
  10052. array.push( this.data.array[ index + j ] );
  10053. }
  10054. }
  10055. // de-interleave data and save it as an ordinary buffer attribute for now
  10056. return {
  10057. itemSize: this.itemSize,
  10058. type: this.array.constructor.name,
  10059. array: array,
  10060. normalized: this.normalized
  10061. };
  10062. } else {
  10063. // save as true interleaved attribute
  10064. if ( data.interleavedBuffers === undefined ) {
  10065. data.interleavedBuffers = {};
  10066. }
  10067. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  10068. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  10069. }
  10070. return {
  10071. isInterleavedBufferAttribute: true,
  10072. itemSize: this.itemSize,
  10073. data: this.data.uuid,
  10074. offset: this.offset,
  10075. normalized: this.normalized
  10076. };
  10077. }
  10078. }
  10079. }
  10080. class SpriteMaterial extends Material {
  10081. constructor( parameters ) {
  10082. super();
  10083. this.isSpriteMaterial = true;
  10084. this.type = 'SpriteMaterial';
  10085. this.color = new Color( 0xffffff );
  10086. this.map = null;
  10087. this.alphaMap = null;
  10088. this.rotation = 0;
  10089. this.sizeAttenuation = true;
  10090. this.transparent = true;
  10091. this.fog = true;
  10092. this.setValues( parameters );
  10093. }
  10094. copy( source ) {
  10095. super.copy( source );
  10096. this.color.copy( source.color );
  10097. this.map = source.map;
  10098. this.alphaMap = source.alphaMap;
  10099. this.rotation = source.rotation;
  10100. this.sizeAttenuation = source.sizeAttenuation;
  10101. this.fog = source.fog;
  10102. return this;
  10103. }
  10104. }
  10105. let _geometry;
  10106. const _intersectPoint = /*@__PURE__*/ new Vector3();
  10107. const _worldScale = /*@__PURE__*/ new Vector3();
  10108. const _mvPosition = /*@__PURE__*/ new Vector3();
  10109. const _alignedPosition = /*@__PURE__*/ new Vector2();
  10110. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  10111. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  10112. const _vA = /*@__PURE__*/ new Vector3();
  10113. const _vB = /*@__PURE__*/ new Vector3();
  10114. const _vC = /*@__PURE__*/ new Vector3();
  10115. const _uvA = /*@__PURE__*/ new Vector2();
  10116. const _uvB = /*@__PURE__*/ new Vector2();
  10117. const _uvC = /*@__PURE__*/ new Vector2();
  10118. class Sprite extends Object3D {
  10119. constructor( material = new SpriteMaterial() ) {
  10120. super();
  10121. this.isSprite = true;
  10122. this.type = 'Sprite';
  10123. if ( _geometry === undefined ) {
  10124. _geometry = new BufferGeometry();
  10125. const float32Array = new Float32Array( [
  10126. -0.5, -0.5, 0, 0, 0,
  10127. 0.5, -0.5, 0, 1, 0,
  10128. 0.5, 0.5, 0, 1, 1,
  10129. -0.5, 0.5, 0, 0, 1
  10130. ] );
  10131. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  10132. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  10133. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  10134. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  10135. }
  10136. this.geometry = _geometry;
  10137. this.material = material;
  10138. this.center = new Vector2( 0.5, 0.5 );
  10139. }
  10140. raycast( raycaster, intersects ) {
  10141. if ( raycaster.camera === null ) {
  10142. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  10143. }
  10144. _worldScale.setFromMatrixScale( this.matrixWorld );
  10145. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  10146. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  10147. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  10148. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  10149. _worldScale.multiplyScalar( - _mvPosition.z );
  10150. }
  10151. const rotation = this.material.rotation;
  10152. let sin, cos;
  10153. if ( rotation !== 0 ) {
  10154. cos = Math.cos( rotation );
  10155. sin = Math.sin( rotation );
  10156. }
  10157. const center = this.center;
  10158. transformVertex( _vA.set( -0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  10159. transformVertex( _vB.set( 0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  10160. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  10161. _uvA.set( 0, 0 );
  10162. _uvB.set( 1, 0 );
  10163. _uvC.set( 1, 1 );
  10164. // check first triangle
  10165. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  10166. if ( intersect === null ) {
  10167. // check second triangle
  10168. transformVertex( _vB.set( -0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  10169. _uvB.set( 0, 1 );
  10170. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  10171. if ( intersect === null ) {
  10172. return;
  10173. }
  10174. }
  10175. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  10176. if ( distance < raycaster.near || distance > raycaster.far ) return;
  10177. intersects.push( {
  10178. distance: distance,
  10179. point: _intersectPoint.clone(),
  10180. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  10181. face: null,
  10182. object: this
  10183. } );
  10184. }
  10185. copy( source, recursive ) {
  10186. super.copy( source, recursive );
  10187. if ( source.center !== undefined ) this.center.copy( source.center );
  10188. this.material = source.material;
  10189. return this;
  10190. }
  10191. }
  10192. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  10193. // compute position in camera space
  10194. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  10195. // to check if rotation is not zero
  10196. if ( sin !== undefined ) {
  10197. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  10198. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  10199. } else {
  10200. _rotatedPosition.copy( _alignedPosition );
  10201. }
  10202. vertexPosition.copy( mvPosition );
  10203. vertexPosition.x += _rotatedPosition.x;
  10204. vertexPosition.y += _rotatedPosition.y;
  10205. // transform to world space
  10206. vertexPosition.applyMatrix4( _viewWorldMatrix );
  10207. }
  10208. const _v1$2 = /*@__PURE__*/ new Vector3();
  10209. const _v2$1 = /*@__PURE__*/ new Vector3();
  10210. class LOD extends Object3D {
  10211. constructor() {
  10212. super();
  10213. this._currentLevel = 0;
  10214. this.type = 'LOD';
  10215. Object.defineProperties( this, {
  10216. levels: {
  10217. enumerable: true,
  10218. value: []
  10219. },
  10220. isLOD: {
  10221. value: true,
  10222. }
  10223. } );
  10224. this.autoUpdate = true;
  10225. }
  10226. copy( source ) {
  10227. super.copy( source, false );
  10228. const levels = source.levels;
  10229. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  10230. const level = levels[ i ];
  10231. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  10232. }
  10233. this.autoUpdate = source.autoUpdate;
  10234. return this;
  10235. }
  10236. addLevel( object, distance = 0, hysteresis = 0 ) {
  10237. distance = Math.abs( distance );
  10238. const levels = this.levels;
  10239. let l;
  10240. for ( l = 0; l < levels.length; l ++ ) {
  10241. if ( distance < levels[ l ].distance ) {
  10242. break;
  10243. }
  10244. }
  10245. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  10246. this.add( object );
  10247. return this;
  10248. }
  10249. removeLevel( distance ) {
  10250. const levels = this.levels;
  10251. for ( let i = 0; i < levels.length; i ++ ) {
  10252. if ( levels[ i ].distance === distance ) {
  10253. const removedElements = levels.splice( i, 1 );
  10254. this.remove( removedElements[ 0 ].object );
  10255. return true;
  10256. }
  10257. }
  10258. return false;
  10259. }
  10260. getCurrentLevel() {
  10261. return this._currentLevel;
  10262. }
  10263. getObjectForDistance( distance ) {
  10264. const levels = this.levels;
  10265. if ( levels.length > 0 ) {
  10266. let i, l;
  10267. for ( i = 1, l = levels.length; i < l; i ++ ) {
  10268. let levelDistance = levels[ i ].distance;
  10269. if ( levels[ i ].object.visible ) {
  10270. levelDistance -= levelDistance * levels[ i ].hysteresis;
  10271. }
  10272. if ( distance < levelDistance ) {
  10273. break;
  10274. }
  10275. }
  10276. return levels[ i - 1 ].object;
  10277. }
  10278. return null;
  10279. }
  10280. raycast( raycaster, intersects ) {
  10281. const levels = this.levels;
  10282. if ( levels.length > 0 ) {
  10283. _v1$2.setFromMatrixPosition( this.matrixWorld );
  10284. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  10285. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  10286. }
  10287. }
  10288. update( camera ) {
  10289. const levels = this.levels;
  10290. if ( levels.length > 1 ) {
  10291. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  10292. _v2$1.setFromMatrixPosition( this.matrixWorld );
  10293. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  10294. levels[ 0 ].object.visible = true;
  10295. let i, l;
  10296. for ( i = 1, l = levels.length; i < l; i ++ ) {
  10297. let levelDistance = levels[ i ].distance;
  10298. if ( levels[ i ].object.visible ) {
  10299. levelDistance -= levelDistance * levels[ i ].hysteresis;
  10300. }
  10301. if ( distance >= levelDistance ) {
  10302. levels[ i - 1 ].object.visible = false;
  10303. levels[ i ].object.visible = true;
  10304. } else {
  10305. break;
  10306. }
  10307. }
  10308. this._currentLevel = i - 1;
  10309. for ( ; i < l; i ++ ) {
  10310. levels[ i ].object.visible = false;
  10311. }
  10312. }
  10313. }
  10314. toJSON( meta ) {
  10315. const data = super.toJSON( meta );
  10316. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  10317. data.object.levels = [];
  10318. const levels = this.levels;
  10319. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  10320. const level = levels[ i ];
  10321. data.object.levels.push( {
  10322. object: level.object.uuid,
  10323. distance: level.distance,
  10324. hysteresis: level.hysteresis
  10325. } );
  10326. }
  10327. return data;
  10328. }
  10329. }
  10330. const _basePosition = /*@__PURE__*/ new Vector3();
  10331. const _skinIndex = /*@__PURE__*/ new Vector4();
  10332. const _skinWeight = /*@__PURE__*/ new Vector4();
  10333. const _vector3 = /*@__PURE__*/ new Vector3();
  10334. const _matrix4 = /*@__PURE__*/ new Matrix4();
  10335. const _vertex = /*@__PURE__*/ new Vector3();
  10336. const _sphere$5 = /*@__PURE__*/ new Sphere();
  10337. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  10338. const _ray$2 = /*@__PURE__*/ new Ray();
  10339. class SkinnedMesh extends Mesh {
  10340. constructor( geometry, material ) {
  10341. super( geometry, material );
  10342. this.isSkinnedMesh = true;
  10343. this.type = 'SkinnedMesh';
  10344. this.bindMode = AttachedBindMode;
  10345. this.bindMatrix = new Matrix4();
  10346. this.bindMatrixInverse = new Matrix4();
  10347. this.boundingBox = null;
  10348. this.boundingSphere = null;
  10349. }
  10350. computeBoundingBox() {
  10351. const geometry = this.geometry;
  10352. if ( this.boundingBox === null ) {
  10353. this.boundingBox = new Box3();
  10354. }
  10355. this.boundingBox.makeEmpty();
  10356. const positionAttribute = geometry.getAttribute( 'position' );
  10357. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  10358. this.getVertexPosition( i, _vertex );
  10359. this.boundingBox.expandByPoint( _vertex );
  10360. }
  10361. }
  10362. computeBoundingSphere() {
  10363. const geometry = this.geometry;
  10364. if ( this.boundingSphere === null ) {
  10365. this.boundingSphere = new Sphere();
  10366. }
  10367. this.boundingSphere.makeEmpty();
  10368. const positionAttribute = geometry.getAttribute( 'position' );
  10369. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  10370. this.getVertexPosition( i, _vertex );
  10371. this.boundingSphere.expandByPoint( _vertex );
  10372. }
  10373. }
  10374. copy( source, recursive ) {
  10375. super.copy( source, recursive );
  10376. this.bindMode = source.bindMode;
  10377. this.bindMatrix.copy( source.bindMatrix );
  10378. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  10379. this.skeleton = source.skeleton;
  10380. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  10381. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  10382. return this;
  10383. }
  10384. raycast( raycaster, intersects ) {
  10385. const material = this.material;
  10386. const matrixWorld = this.matrixWorld;
  10387. if ( material === undefined ) return;
  10388. // test with bounding sphere in world space
  10389. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  10390. _sphere$5.copy( this.boundingSphere );
  10391. _sphere$5.applyMatrix4( matrixWorld );
  10392. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  10393. // convert ray to local space of skinned mesh
  10394. _inverseMatrix$2.copy( matrixWorld ).invert();
  10395. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  10396. // test with bounding box in local space
  10397. if ( this.boundingBox !== null ) {
  10398. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  10399. }
  10400. // test for intersections with geometry
  10401. this._computeIntersections( raycaster, intersects, _ray$2 );
  10402. }
  10403. getVertexPosition( index, target ) {
  10404. super.getVertexPosition( index, target );
  10405. this.applyBoneTransform( index, target );
  10406. return target;
  10407. }
  10408. bind( skeleton, bindMatrix ) {
  10409. this.skeleton = skeleton;
  10410. if ( bindMatrix === undefined ) {
  10411. this.updateMatrixWorld( true );
  10412. this.skeleton.calculateInverses();
  10413. bindMatrix = this.matrixWorld;
  10414. }
  10415. this.bindMatrix.copy( bindMatrix );
  10416. this.bindMatrixInverse.copy( bindMatrix ).invert();
  10417. }
  10418. pose() {
  10419. this.skeleton.pose();
  10420. }
  10421. normalizeSkinWeights() {
  10422. const vector = new Vector4();
  10423. const skinWeight = this.geometry.attributes.skinWeight;
  10424. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  10425. vector.fromBufferAttribute( skinWeight, i );
  10426. const scale = 1.0 / vector.manhattanLength();
  10427. if ( scale !== Infinity ) {
  10428. vector.multiplyScalar( scale );
  10429. } else {
  10430. vector.set( 1, 0, 0, 0 ); // do something reasonable
  10431. }
  10432. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  10433. }
  10434. }
  10435. updateMatrixWorld( force ) {
  10436. super.updateMatrixWorld( force );
  10437. if ( this.bindMode === AttachedBindMode ) {
  10438. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  10439. } else if ( this.bindMode === DetachedBindMode ) {
  10440. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  10441. } else {
  10442. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  10443. }
  10444. }
  10445. applyBoneTransform( index, vector ) {
  10446. const skeleton = this.skeleton;
  10447. const geometry = this.geometry;
  10448. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  10449. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  10450. _basePosition.copy( vector ).applyMatrix4( this.bindMatrix );
  10451. vector.set( 0, 0, 0 );
  10452. for ( let i = 0; i < 4; i ++ ) {
  10453. const weight = _skinWeight.getComponent( i );
  10454. if ( weight !== 0 ) {
  10455. const boneIndex = _skinIndex.getComponent( i );
  10456. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  10457. vector.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  10458. }
  10459. }
  10460. return vector.applyMatrix4( this.bindMatrixInverse );
  10461. }
  10462. }
  10463. class Bone extends Object3D {
  10464. constructor() {
  10465. super();
  10466. this.isBone = true;
  10467. this.type = 'Bone';
  10468. }
  10469. }
  10470. class DataTexture extends Texture {
  10471. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  10472. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  10473. this.isDataTexture = true;
  10474. this.image = { data: data, width: width, height: height };
  10475. this.generateMipmaps = false;
  10476. this.flipY = false;
  10477. this.unpackAlignment = 1;
  10478. }
  10479. }
  10480. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  10481. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  10482. class Skeleton {
  10483. constructor( bones = [], boneInverses = [] ) {
  10484. this.uuid = generateUUID();
  10485. this.bones = bones.slice( 0 );
  10486. this.boneInverses = boneInverses;
  10487. this.boneMatrices = null;
  10488. this.boneTexture = null;
  10489. this.init();
  10490. }
  10491. init() {
  10492. const bones = this.bones;
  10493. const boneInverses = this.boneInverses;
  10494. this.boneMatrices = new Float32Array( bones.length * 16 );
  10495. // calculate inverse bone matrices if necessary
  10496. if ( boneInverses.length === 0 ) {
  10497. this.calculateInverses();
  10498. } else {
  10499. // handle special case
  10500. if ( bones.length !== boneInverses.length ) {
  10501. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  10502. this.boneInverses = [];
  10503. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  10504. this.boneInverses.push( new Matrix4() );
  10505. }
  10506. }
  10507. }
  10508. }
  10509. calculateInverses() {
  10510. this.boneInverses.length = 0;
  10511. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  10512. const inverse = new Matrix4();
  10513. if ( this.bones[ i ] ) {
  10514. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  10515. }
  10516. this.boneInverses.push( inverse );
  10517. }
  10518. }
  10519. pose() {
  10520. // recover the bind-time world matrices
  10521. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  10522. const bone = this.bones[ i ];
  10523. if ( bone ) {
  10524. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  10525. }
  10526. }
  10527. // compute the local matrices, positions, rotations and scales
  10528. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  10529. const bone = this.bones[ i ];
  10530. if ( bone ) {
  10531. if ( bone.parent && bone.parent.isBone ) {
  10532. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  10533. bone.matrix.multiply( bone.matrixWorld );
  10534. } else {
  10535. bone.matrix.copy( bone.matrixWorld );
  10536. }
  10537. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  10538. }
  10539. }
  10540. }
  10541. update() {
  10542. const bones = this.bones;
  10543. const boneInverses = this.boneInverses;
  10544. const boneMatrices = this.boneMatrices;
  10545. const boneTexture = this.boneTexture;
  10546. // flatten bone matrices to array
  10547. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  10548. // compute the offset between the current and the original transform
  10549. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  10550. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  10551. _offsetMatrix.toArray( boneMatrices, i * 16 );
  10552. }
  10553. if ( boneTexture !== null ) {
  10554. boneTexture.needsUpdate = true;
  10555. }
  10556. }
  10557. clone() {
  10558. return new Skeleton( this.bones, this.boneInverses );
  10559. }
  10560. computeBoneTexture() {
  10561. // layout (1 matrix = 4 pixels)
  10562. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  10563. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  10564. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  10565. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  10566. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  10567. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  10568. size = Math.ceil( size / 4 ) * 4;
  10569. size = Math.max( size, 4 );
  10570. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  10571. boneMatrices.set( this.boneMatrices ); // copy current values
  10572. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  10573. boneTexture.needsUpdate = true;
  10574. this.boneMatrices = boneMatrices;
  10575. this.boneTexture = boneTexture;
  10576. return this;
  10577. }
  10578. getBoneByName( name ) {
  10579. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  10580. const bone = this.bones[ i ];
  10581. if ( bone.name === name ) {
  10582. return bone;
  10583. }
  10584. }
  10585. return undefined;
  10586. }
  10587. dispose( ) {
  10588. if ( this.boneTexture !== null ) {
  10589. this.boneTexture.dispose();
  10590. this.boneTexture = null;
  10591. }
  10592. }
  10593. fromJSON( json, bones ) {
  10594. this.uuid = json.uuid;
  10595. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  10596. const uuid = json.bones[ i ];
  10597. let bone = bones[ uuid ];
  10598. if ( bone === undefined ) {
  10599. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  10600. bone = new Bone();
  10601. }
  10602. this.bones.push( bone );
  10603. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  10604. }
  10605. this.init();
  10606. return this;
  10607. }
  10608. toJSON() {
  10609. const data = {
  10610. metadata: {
  10611. version: 4.6,
  10612. type: 'Skeleton',
  10613. generator: 'Skeleton.toJSON'
  10614. },
  10615. bones: [],
  10616. boneInverses: []
  10617. };
  10618. data.uuid = this.uuid;
  10619. const bones = this.bones;
  10620. const boneInverses = this.boneInverses;
  10621. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  10622. const bone = bones[ i ];
  10623. data.bones.push( bone.uuid );
  10624. const boneInverse = boneInverses[ i ];
  10625. data.boneInverses.push( boneInverse.toArray() );
  10626. }
  10627. return data;
  10628. }
  10629. }
  10630. class InstancedBufferAttribute extends BufferAttribute {
  10631. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  10632. super( array, itemSize, normalized );
  10633. this.isInstancedBufferAttribute = true;
  10634. this.meshPerAttribute = meshPerAttribute;
  10635. }
  10636. copy( source ) {
  10637. super.copy( source );
  10638. this.meshPerAttribute = source.meshPerAttribute;
  10639. return this;
  10640. }
  10641. toJSON() {
  10642. const data = super.toJSON();
  10643. data.meshPerAttribute = this.meshPerAttribute;
  10644. data.isInstancedBufferAttribute = true;
  10645. return data;
  10646. }
  10647. }
  10648. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  10649. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  10650. const _instanceIntersects = [];
  10651. const _box3 = /*@__PURE__*/ new Box3();
  10652. const _identity = /*@__PURE__*/ new Matrix4();
  10653. const _mesh$1 = /*@__PURE__*/ new Mesh();
  10654. const _sphere$4 = /*@__PURE__*/ new Sphere();
  10655. class InstancedMesh extends Mesh {
  10656. constructor( geometry, material, count ) {
  10657. super( geometry, material );
  10658. this.isInstancedMesh = true;
  10659. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  10660. this.instanceColor = null;
  10661. this.morphTexture = null;
  10662. this.count = count;
  10663. this.boundingBox = null;
  10664. this.boundingSphere = null;
  10665. for ( let i = 0; i < count; i ++ ) {
  10666. this.setMatrixAt( i, _identity );
  10667. }
  10668. }
  10669. computeBoundingBox() {
  10670. const geometry = this.geometry;
  10671. const count = this.count;
  10672. if ( this.boundingBox === null ) {
  10673. this.boundingBox = new Box3();
  10674. }
  10675. if ( geometry.boundingBox === null ) {
  10676. geometry.computeBoundingBox();
  10677. }
  10678. this.boundingBox.makeEmpty();
  10679. for ( let i = 0; i < count; i ++ ) {
  10680. this.getMatrixAt( i, _instanceLocalMatrix );
  10681. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  10682. this.boundingBox.union( _box3 );
  10683. }
  10684. }
  10685. computeBoundingSphere() {
  10686. const geometry = this.geometry;
  10687. const count = this.count;
  10688. if ( this.boundingSphere === null ) {
  10689. this.boundingSphere = new Sphere();
  10690. }
  10691. if ( geometry.boundingSphere === null ) {
  10692. geometry.computeBoundingSphere();
  10693. }
  10694. this.boundingSphere.makeEmpty();
  10695. for ( let i = 0; i < count; i ++ ) {
  10696. this.getMatrixAt( i, _instanceLocalMatrix );
  10697. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  10698. this.boundingSphere.union( _sphere$4 );
  10699. }
  10700. }
  10701. copy( source, recursive ) {
  10702. super.copy( source, recursive );
  10703. this.instanceMatrix.copy( source.instanceMatrix );
  10704. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  10705. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  10706. this.count = source.count;
  10707. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  10708. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  10709. return this;
  10710. }
  10711. getColorAt( index, color ) {
  10712. color.fromArray( this.instanceColor.array, index * 3 );
  10713. }
  10714. getMatrixAt( index, matrix ) {
  10715. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  10716. }
  10717. getMorphAt( index, object ) {
  10718. const objectInfluences = object.morphTargetInfluences;
  10719. const array = this.morphTexture.source.data.data;
  10720. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  10721. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  10722. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  10723. objectInfluences[ i ] = array[ dataIndex + i ];
  10724. }
  10725. }
  10726. raycast( raycaster, intersects ) {
  10727. const matrixWorld = this.matrixWorld;
  10728. const raycastTimes = this.count;
  10729. _mesh$1.geometry = this.geometry;
  10730. _mesh$1.material = this.material;
  10731. if ( _mesh$1.material === undefined ) return;
  10732. // test with bounding sphere first
  10733. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  10734. _sphere$4.copy( this.boundingSphere );
  10735. _sphere$4.applyMatrix4( matrixWorld );
  10736. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  10737. // now test each instance
  10738. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  10739. // calculate the world matrix for each instance
  10740. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  10741. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  10742. // the mesh represents this single instance
  10743. _mesh$1.matrixWorld = _instanceWorldMatrix;
  10744. _mesh$1.raycast( raycaster, _instanceIntersects );
  10745. // process the result of raycast
  10746. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  10747. const intersect = _instanceIntersects[ i ];
  10748. intersect.instanceId = instanceId;
  10749. intersect.object = this;
  10750. intersects.push( intersect );
  10751. }
  10752. _instanceIntersects.length = 0;
  10753. }
  10754. }
  10755. setColorAt( index, color ) {
  10756. if ( this.instanceColor === null ) {
  10757. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  10758. }
  10759. color.toArray( this.instanceColor.array, index * 3 );
  10760. }
  10761. setMatrixAt( index, matrix ) {
  10762. matrix.toArray( this.instanceMatrix.array, index * 16 );
  10763. }
  10764. setMorphAt( index, object ) {
  10765. const objectInfluences = object.morphTargetInfluences;
  10766. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  10767. if ( this.morphTexture === null ) {
  10768. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  10769. }
  10770. const array = this.morphTexture.source.data.data;
  10771. let morphInfluencesSum = 0;
  10772. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  10773. morphInfluencesSum += objectInfluences[ i ];
  10774. }
  10775. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10776. const dataIndex = len * index;
  10777. array[ dataIndex ] = morphBaseInfluence;
  10778. array.set( objectInfluences, dataIndex + 1 );
  10779. }
  10780. updateMorphTargets() {
  10781. }
  10782. dispose() {
  10783. this.dispatchEvent( { type: 'dispose' } );
  10784. if ( this.morphTexture !== null ) {
  10785. this.morphTexture.dispose();
  10786. this.morphTexture = null;
  10787. }
  10788. return this;
  10789. }
  10790. }
  10791. const _vector1 = /*@__PURE__*/ new Vector3();
  10792. const _vector2 = /*@__PURE__*/ new Vector3();
  10793. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  10794. class Plane {
  10795. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  10796. this.isPlane = true;
  10797. // normal is assumed to be normalized
  10798. this.normal = normal;
  10799. this.constant = constant;
  10800. }
  10801. set( normal, constant ) {
  10802. this.normal.copy( normal );
  10803. this.constant = constant;
  10804. return this;
  10805. }
  10806. setComponents( x, y, z, w ) {
  10807. this.normal.set( x, y, z );
  10808. this.constant = w;
  10809. return this;
  10810. }
  10811. setFromNormalAndCoplanarPoint( normal, point ) {
  10812. this.normal.copy( normal );
  10813. this.constant = - point.dot( this.normal );
  10814. return this;
  10815. }
  10816. setFromCoplanarPoints( a, b, c ) {
  10817. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  10818. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  10819. this.setFromNormalAndCoplanarPoint( normal, a );
  10820. return this;
  10821. }
  10822. copy( plane ) {
  10823. this.normal.copy( plane.normal );
  10824. this.constant = plane.constant;
  10825. return this;
  10826. }
  10827. normalize() {
  10828. // Note: will lead to a divide by zero if the plane is invalid.
  10829. const inverseNormalLength = 1.0 / this.normal.length();
  10830. this.normal.multiplyScalar( inverseNormalLength );
  10831. this.constant *= inverseNormalLength;
  10832. return this;
  10833. }
  10834. negate() {
  10835. this.constant *= -1;
  10836. this.normal.negate();
  10837. return this;
  10838. }
  10839. distanceToPoint( point ) {
  10840. return this.normal.dot( point ) + this.constant;
  10841. }
  10842. distanceToSphere( sphere ) {
  10843. return this.distanceToPoint( sphere.center ) - sphere.radius;
  10844. }
  10845. projectPoint( point, target ) {
  10846. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  10847. }
  10848. intersectLine( line, target ) {
  10849. const direction = line.delta( _vector1 );
  10850. const denominator = this.normal.dot( direction );
  10851. if ( denominator === 0 ) {
  10852. // line is coplanar, return origin
  10853. if ( this.distanceToPoint( line.start ) === 0 ) {
  10854. return target.copy( line.start );
  10855. }
  10856. // Unsure if this is the correct method to handle this case.
  10857. return null;
  10858. }
  10859. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  10860. if ( t < 0 || t > 1 ) {
  10861. return null;
  10862. }
  10863. return target.copy( line.start ).addScaledVector( direction, t );
  10864. }
  10865. intersectsLine( line ) {
  10866. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  10867. const startSign = this.distanceToPoint( line.start );
  10868. const endSign = this.distanceToPoint( line.end );
  10869. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  10870. }
  10871. intersectsBox( box ) {
  10872. return box.intersectsPlane( this );
  10873. }
  10874. intersectsSphere( sphere ) {
  10875. return sphere.intersectsPlane( this );
  10876. }
  10877. coplanarPoint( target ) {
  10878. return target.copy( this.normal ).multiplyScalar( - this.constant );
  10879. }
  10880. applyMatrix4( matrix, optionalNormalMatrix ) {
  10881. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  10882. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  10883. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  10884. this.constant = - referencePoint.dot( normal );
  10885. return this;
  10886. }
  10887. translate( offset ) {
  10888. this.constant -= offset.dot( this.normal );
  10889. return this;
  10890. }
  10891. equals( plane ) {
  10892. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  10893. }
  10894. clone() {
  10895. return new this.constructor().copy( this );
  10896. }
  10897. }
  10898. const _sphere$3 = /*@__PURE__*/ new Sphere();
  10899. const _vector$6 = /*@__PURE__*/ new Vector3();
  10900. class Frustum {
  10901. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  10902. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  10903. }
  10904. set( p0, p1, p2, p3, p4, p5 ) {
  10905. const planes = this.planes;
  10906. planes[ 0 ].copy( p0 );
  10907. planes[ 1 ].copy( p1 );
  10908. planes[ 2 ].copy( p2 );
  10909. planes[ 3 ].copy( p3 );
  10910. planes[ 4 ].copy( p4 );
  10911. planes[ 5 ].copy( p5 );
  10912. return this;
  10913. }
  10914. copy( frustum ) {
  10915. const planes = this.planes;
  10916. for ( let i = 0; i < 6; i ++ ) {
  10917. planes[ i ].copy( frustum.planes[ i ] );
  10918. }
  10919. return this;
  10920. }
  10921. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  10922. const planes = this.planes;
  10923. const me = m.elements;
  10924. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  10925. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  10926. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  10927. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  10928. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  10929. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  10930. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  10931. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  10932. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  10933. if ( coordinateSystem === WebGLCoordinateSystem ) {
  10934. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  10935. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  10936. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  10937. } else {
  10938. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  10939. }
  10940. return this;
  10941. }
  10942. intersectsObject( object ) {
  10943. if ( object.boundingSphere !== undefined ) {
  10944. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  10945. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  10946. } else {
  10947. const geometry = object.geometry;
  10948. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  10949. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  10950. }
  10951. return this.intersectsSphere( _sphere$3 );
  10952. }
  10953. intersectsSprite( sprite ) {
  10954. _sphere$3.center.set( 0, 0, 0 );
  10955. _sphere$3.radius = 0.7071067811865476;
  10956. _sphere$3.applyMatrix4( sprite.matrixWorld );
  10957. return this.intersectsSphere( _sphere$3 );
  10958. }
  10959. intersectsSphere( sphere ) {
  10960. const planes = this.planes;
  10961. const center = sphere.center;
  10962. const negRadius = - sphere.radius;
  10963. for ( let i = 0; i < 6; i ++ ) {
  10964. const distance = planes[ i ].distanceToPoint( center );
  10965. if ( distance < negRadius ) {
  10966. return false;
  10967. }
  10968. }
  10969. return true;
  10970. }
  10971. intersectsBox( box ) {
  10972. const planes = this.planes;
  10973. for ( let i = 0; i < 6; i ++ ) {
  10974. const plane = planes[ i ];
  10975. // corner at max distance
  10976. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  10977. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  10978. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  10979. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  10980. return false;
  10981. }
  10982. }
  10983. return true;
  10984. }
  10985. containsPoint( point ) {
  10986. const planes = this.planes;
  10987. for ( let i = 0; i < 6; i ++ ) {
  10988. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  10989. return false;
  10990. }
  10991. }
  10992. return true;
  10993. }
  10994. clone() {
  10995. return new this.constructor().copy( this );
  10996. }
  10997. }
  10998. function ascIdSort( a, b ) {
  10999. return a - b;
  11000. }
  11001. function sortOpaque( a, b ) {
  11002. return a.z - b.z;
  11003. }
  11004. function sortTransparent( a, b ) {
  11005. return b.z - a.z;
  11006. }
  11007. class MultiDrawRenderList {
  11008. constructor() {
  11009. this.index = 0;
  11010. this.pool = [];
  11011. this.list = [];
  11012. }
  11013. push( start, count, z, index ) {
  11014. const pool = this.pool;
  11015. const list = this.list;
  11016. if ( this.index >= pool.length ) {
  11017. pool.push( {
  11018. start: -1,
  11019. count: -1,
  11020. z: -1,
  11021. index: -1,
  11022. } );
  11023. }
  11024. const item = pool[ this.index ];
  11025. list.push( item );
  11026. this.index ++;
  11027. item.start = start;
  11028. item.count = count;
  11029. item.z = z;
  11030. item.index = index;
  11031. }
  11032. reset() {
  11033. this.list.length = 0;
  11034. this.index = 0;
  11035. }
  11036. }
  11037. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  11038. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  11039. const _frustum = /*@__PURE__*/ new Frustum();
  11040. const _box$1 = /*@__PURE__*/ new Box3();
  11041. const _sphere$2 = /*@__PURE__*/ new Sphere();
  11042. const _vector$5 = /*@__PURE__*/ new Vector3();
  11043. const _forward = /*@__PURE__*/ new Vector3();
  11044. const _temp = /*@__PURE__*/ new Vector3();
  11045. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  11046. const _mesh = /*@__PURE__*/ new Mesh();
  11047. const _batchIntersects = [];
  11048. // copies data from attribute "src" into "target" starting at "targetOffset"
  11049. function copyAttributeData( src, target, targetOffset = 0 ) {
  11050. const itemSize = target.itemSize;
  11051. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  11052. // use the component getters and setters if the array data cannot
  11053. // be copied directly
  11054. const vertexCount = src.count;
  11055. for ( let i = 0; i < vertexCount; i ++ ) {
  11056. for ( let c = 0; c < itemSize; c ++ ) {
  11057. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  11058. }
  11059. }
  11060. } else {
  11061. // faster copy approach using typed array set function
  11062. target.array.set( src.array, targetOffset * itemSize );
  11063. }
  11064. target.needsUpdate = true;
  11065. }
  11066. // safely copies array contents to a potentially smaller array
  11067. function copyArrayContents( src, target ) {
  11068. if ( src.constructor !== target.constructor ) {
  11069. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  11070. const len = Math.min( src.length, target.length );
  11071. for ( let i = 0; i < len; i ++ ) {
  11072. target[ i ] = src[ i ];
  11073. }
  11074. } else {
  11075. // if the arrays use the same data layout we can use a fast block copy
  11076. const len = Math.min( src.length, target.length );
  11077. target.set( new src.constructor( src.buffer, 0, len ) );
  11078. }
  11079. }
  11080. class BatchedMesh extends Mesh {
  11081. get maxInstanceCount() {
  11082. return this._maxInstanceCount;
  11083. }
  11084. get instanceCount() {
  11085. return this._instanceInfo.length - this._availableInstanceIds.length;
  11086. }
  11087. get unusedVertexCount() {
  11088. return this._maxVertexCount - this._nextVertexStart;
  11089. }
  11090. get unusedIndexCount() {
  11091. return this._maxIndexCount - this._nextIndexStart;
  11092. }
  11093. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  11094. super( new BufferGeometry(), material );
  11095. this.isBatchedMesh = true;
  11096. this.perObjectFrustumCulled = true;
  11097. this.sortObjects = true;
  11098. this.boundingBox = null;
  11099. this.boundingSphere = null;
  11100. this.customSort = null;
  11101. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  11102. this._instanceInfo = [];
  11103. this._geometryInfo = [];
  11104. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  11105. this._availableInstanceIds = [];
  11106. this._availableGeometryIds = [];
  11107. // used to track where the next point is that geometry should be inserted
  11108. this._nextIndexStart = 0;
  11109. this._nextVertexStart = 0;
  11110. this._geometryCount = 0;
  11111. // flags
  11112. this._visibilityChanged = true;
  11113. this._geometryInitialized = false;
  11114. // cached user options
  11115. this._maxInstanceCount = maxInstanceCount;
  11116. this._maxVertexCount = maxVertexCount;
  11117. this._maxIndexCount = maxIndexCount;
  11118. // buffers for multi draw
  11119. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  11120. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  11121. this._multiDrawCount = 0;
  11122. this._multiDrawInstances = null;
  11123. // Local matrix per geometry by using data texture
  11124. this._matricesTexture = null;
  11125. this._indirectTexture = null;
  11126. this._colorsTexture = null;
  11127. this._initMatricesTexture();
  11128. this._initIndirectTexture();
  11129. }
  11130. _initMatricesTexture() {
  11131. // layout (1 matrix = 4 pixels)
  11132. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  11133. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  11134. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  11135. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  11136. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  11137. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  11138. size = Math.ceil( size / 4 ) * 4;
  11139. size = Math.max( size, 4 );
  11140. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  11141. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  11142. this._matricesTexture = matricesTexture;
  11143. }
  11144. _initIndirectTexture() {
  11145. let size = Math.sqrt( this._maxInstanceCount );
  11146. size = Math.ceil( size );
  11147. const indirectArray = new Uint32Array( size * size );
  11148. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  11149. this._indirectTexture = indirectTexture;
  11150. }
  11151. _initColorsTexture() {
  11152. let size = Math.sqrt( this._maxInstanceCount );
  11153. size = Math.ceil( size );
  11154. // 4 floats per RGBA pixel initialized to white
  11155. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  11156. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  11157. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  11158. this._colorsTexture = colorsTexture;
  11159. }
  11160. _initializeGeometry( reference ) {
  11161. const geometry = this.geometry;
  11162. const maxVertexCount = this._maxVertexCount;
  11163. const maxIndexCount = this._maxIndexCount;
  11164. if ( this._geometryInitialized === false ) {
  11165. for ( const attributeName in reference.attributes ) {
  11166. const srcAttribute = reference.getAttribute( attributeName );
  11167. const { array, itemSize, normalized } = srcAttribute;
  11168. const dstArray = new array.constructor( maxVertexCount * itemSize );
  11169. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  11170. geometry.setAttribute( attributeName, dstAttribute );
  11171. }
  11172. if ( reference.getIndex() !== null ) {
  11173. // Reserve last u16 index for primitive restart.
  11174. const indexArray = maxVertexCount > 65535
  11175. ? new Uint32Array( maxIndexCount )
  11176. : new Uint16Array( maxIndexCount );
  11177. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  11178. }
  11179. this._geometryInitialized = true;
  11180. }
  11181. }
  11182. // Make sure the geometry is compatible with the existing combined geometry attributes
  11183. _validateGeometry( geometry ) {
  11184. // check to ensure the geometries are using consistent attributes and indices
  11185. const batchGeometry = this.geometry;
  11186. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  11187. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  11188. }
  11189. for ( const attributeName in batchGeometry.attributes ) {
  11190. if ( ! geometry.hasAttribute( attributeName ) ) {
  11191. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  11192. }
  11193. const srcAttribute = geometry.getAttribute( attributeName );
  11194. const dstAttribute = batchGeometry.getAttribute( attributeName );
  11195. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  11196. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  11197. }
  11198. }
  11199. }
  11200. validateInstanceId( instanceId ) {
  11201. const instanceInfo = this._instanceInfo;
  11202. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  11203. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  11204. }
  11205. }
  11206. validateGeometryId( geometryId ) {
  11207. const geometryInfoList = this._geometryInfo;
  11208. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  11209. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  11210. }
  11211. }
  11212. setCustomSort( func ) {
  11213. this.customSort = func;
  11214. return this;
  11215. }
  11216. computeBoundingBox() {
  11217. if ( this.boundingBox === null ) {
  11218. this.boundingBox = new Box3();
  11219. }
  11220. const boundingBox = this.boundingBox;
  11221. const instanceInfo = this._instanceInfo;
  11222. boundingBox.makeEmpty();
  11223. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  11224. if ( instanceInfo[ i ].active === false ) continue;
  11225. const geometryId = instanceInfo[ i ].geometryIndex;
  11226. this.getMatrixAt( i, _matrix$1 );
  11227. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  11228. boundingBox.union( _box$1 );
  11229. }
  11230. }
  11231. computeBoundingSphere() {
  11232. if ( this.boundingSphere === null ) {
  11233. this.boundingSphere = new Sphere();
  11234. }
  11235. const boundingSphere = this.boundingSphere;
  11236. const instanceInfo = this._instanceInfo;
  11237. boundingSphere.makeEmpty();
  11238. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  11239. if ( instanceInfo[ i ].active === false ) continue;
  11240. const geometryId = instanceInfo[ i ].geometryIndex;
  11241. this.getMatrixAt( i, _matrix$1 );
  11242. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  11243. boundingSphere.union( _sphere$2 );
  11244. }
  11245. }
  11246. addInstance( geometryId ) {
  11247. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  11248. // ensure we're not over geometry
  11249. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  11250. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  11251. }
  11252. const instanceInfo = {
  11253. visible: true,
  11254. active: true,
  11255. geometryIndex: geometryId,
  11256. };
  11257. let drawId = null;
  11258. // Prioritize using previously freed instance ids
  11259. if ( this._availableInstanceIds.length > 0 ) {
  11260. this._availableInstanceIds.sort( ascIdSort );
  11261. drawId = this._availableInstanceIds.shift();
  11262. this._instanceInfo[ drawId ] = instanceInfo;
  11263. } else {
  11264. drawId = this._instanceInfo.length;
  11265. this._instanceInfo.push( instanceInfo );
  11266. }
  11267. const matricesTexture = this._matricesTexture;
  11268. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  11269. matricesTexture.needsUpdate = true;
  11270. const colorsTexture = this._colorsTexture;
  11271. if ( colorsTexture ) {
  11272. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  11273. colorsTexture.needsUpdate = true;
  11274. }
  11275. this._visibilityChanged = true;
  11276. return drawId;
  11277. }
  11278. addGeometry( geometry, reservedVertexCount = -1, reservedIndexCount = -1 ) {
  11279. this._initializeGeometry( geometry );
  11280. this._validateGeometry( geometry );
  11281. const geometryInfo = {
  11282. // geometry information
  11283. vertexStart: -1,
  11284. vertexCount: -1,
  11285. reservedVertexCount: -1,
  11286. indexStart: -1,
  11287. indexCount: -1,
  11288. reservedIndexCount: -1,
  11289. // draw range information
  11290. start: -1,
  11291. count: -1,
  11292. // state
  11293. boundingBox: null,
  11294. boundingSphere: null,
  11295. active: true,
  11296. };
  11297. const geometryInfoList = this._geometryInfo;
  11298. geometryInfo.vertexStart = this._nextVertexStart;
  11299. geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  11300. const index = geometry.getIndex();
  11301. const hasIndex = index !== null;
  11302. if ( hasIndex ) {
  11303. geometryInfo.indexStart = this._nextIndexStart;
  11304. geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount;
  11305. }
  11306. if (
  11307. geometryInfo.indexStart !== -1 &&
  11308. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  11309. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  11310. ) {
  11311. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  11312. }
  11313. // update id
  11314. let geometryId;
  11315. if ( this._availableGeometryIds.length > 0 ) {
  11316. this._availableGeometryIds.sort( ascIdSort );
  11317. geometryId = this._availableGeometryIds.shift();
  11318. geometryInfoList[ geometryId ] = geometryInfo;
  11319. } else {
  11320. geometryId = this._geometryCount;
  11321. this._geometryCount ++;
  11322. geometryInfoList.push( geometryInfo );
  11323. }
  11324. // update the geometry
  11325. this.setGeometryAt( geometryId, geometry );
  11326. // increment the next geometry position
  11327. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  11328. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  11329. return geometryId;
  11330. }
  11331. setGeometryAt( geometryId, geometry ) {
  11332. if ( geometryId >= this._geometryCount ) {
  11333. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  11334. }
  11335. this._validateGeometry( geometry );
  11336. const batchGeometry = this.geometry;
  11337. const hasIndex = batchGeometry.getIndex() !== null;
  11338. const dstIndex = batchGeometry.getIndex();
  11339. const srcIndex = geometry.getIndex();
  11340. const geometryInfo = this._geometryInfo[ geometryId ];
  11341. if (
  11342. hasIndex &&
  11343. srcIndex.count > geometryInfo.reservedIndexCount ||
  11344. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  11345. ) {
  11346. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  11347. }
  11348. // copy geometry buffer data over
  11349. const vertexStart = geometryInfo.vertexStart;
  11350. const reservedVertexCount = geometryInfo.reservedVertexCount;
  11351. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  11352. for ( const attributeName in batchGeometry.attributes ) {
  11353. // copy attribute data
  11354. const srcAttribute = geometry.getAttribute( attributeName );
  11355. const dstAttribute = batchGeometry.getAttribute( attributeName );
  11356. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  11357. // fill the rest in with zeroes
  11358. const itemSize = srcAttribute.itemSize;
  11359. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  11360. const index = vertexStart + i;
  11361. for ( let c = 0; c < itemSize; c ++ ) {
  11362. dstAttribute.setComponent( index, c, 0 );
  11363. }
  11364. }
  11365. dstAttribute.needsUpdate = true;
  11366. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  11367. }
  11368. // copy index
  11369. if ( hasIndex ) {
  11370. const indexStart = geometryInfo.indexStart;
  11371. const reservedIndexCount = geometryInfo.reservedIndexCount;
  11372. geometryInfo.indexCount = geometry.getIndex().count;
  11373. // copy index data over
  11374. for ( let i = 0; i < srcIndex.count; i ++ ) {
  11375. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  11376. }
  11377. // fill the rest in with zeroes
  11378. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  11379. dstIndex.setX( indexStart + i, vertexStart );
  11380. }
  11381. dstIndex.needsUpdate = true;
  11382. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  11383. }
  11384. // update the draw range
  11385. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  11386. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  11387. // store the bounding boxes
  11388. geometryInfo.boundingBox = null;
  11389. if ( geometry.boundingBox !== null ) {
  11390. geometryInfo.boundingBox = geometry.boundingBox.clone();
  11391. }
  11392. geometryInfo.boundingSphere = null;
  11393. if ( geometry.boundingSphere !== null ) {
  11394. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  11395. }
  11396. this._visibilityChanged = true;
  11397. return geometryId;
  11398. }
  11399. deleteGeometry( geometryId ) {
  11400. const geometryInfoList = this._geometryInfo;
  11401. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  11402. return this;
  11403. }
  11404. // delete any instances associated with this geometry
  11405. const instanceInfo = this._instanceInfo;
  11406. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  11407. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  11408. this.deleteInstance( i );
  11409. }
  11410. }
  11411. geometryInfoList[ geometryId ].active = false;
  11412. this._availableGeometryIds.push( geometryId );
  11413. this._visibilityChanged = true;
  11414. return this;
  11415. }
  11416. deleteInstance( instanceId ) {
  11417. this.validateInstanceId( instanceId );
  11418. this._instanceInfo[ instanceId ].active = false;
  11419. this._availableInstanceIds.push( instanceId );
  11420. this._visibilityChanged = true;
  11421. return this;
  11422. }
  11423. optimize() {
  11424. // track the next indices to copy data to
  11425. let nextVertexStart = 0;
  11426. let nextIndexStart = 0;
  11427. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  11428. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  11429. const geometryInfoList = this._geometryInfo;
  11430. const indices = geometryInfoList
  11431. .map( ( e, i ) => i )
  11432. .sort( ( a, b ) => {
  11433. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  11434. } );
  11435. const geometry = this.geometry;
  11436. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  11437. // if a geometry range is inactive then don't copy anything
  11438. const index = indices[ i ];
  11439. const geometryInfo = geometryInfoList[ index ];
  11440. if ( geometryInfo.active === false ) {
  11441. continue;
  11442. }
  11443. // if a geometry contains an index buffer then shift it, as well
  11444. if ( geometry.index !== null ) {
  11445. if ( geometryInfo.indexStart !== nextIndexStart ) {
  11446. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  11447. const index = geometry.index;
  11448. const array = index.array;
  11449. // shift the index pointers based on how the vertex data will shift
  11450. // adjusting the index must happen first so the original vertex start value is available
  11451. const elementDelta = nextVertexStart - vertexStart;
  11452. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  11453. array[ j ] = array[ j ] + elementDelta;
  11454. }
  11455. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  11456. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  11457. geometryInfo.indexStart = nextIndexStart;
  11458. }
  11459. nextIndexStart += geometryInfo.reservedIndexCount;
  11460. }
  11461. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  11462. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  11463. const { vertexStart, reservedVertexCount } = geometryInfo;
  11464. const attributes = geometry.attributes;
  11465. for ( const key in attributes ) {
  11466. const attribute = attributes[ key ];
  11467. const { array, itemSize } = attribute;
  11468. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  11469. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  11470. }
  11471. geometryInfo.vertexStart = nextVertexStart;
  11472. }
  11473. nextVertexStart += geometryInfo.reservedVertexCount;
  11474. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  11475. // step the next geometry points to the shifted position
  11476. this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0;
  11477. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  11478. }
  11479. return this;
  11480. }
  11481. // get bounding box and compute it if it doesn't exist
  11482. getBoundingBoxAt( geometryId, target ) {
  11483. if ( geometryId >= this._geometryCount ) {
  11484. return null;
  11485. }
  11486. // compute bounding box
  11487. const geometry = this.geometry;
  11488. const geometryInfo = this._geometryInfo[ geometryId ];
  11489. if ( geometryInfo.boundingBox === null ) {
  11490. const box = new Box3();
  11491. const index = geometry.index;
  11492. const position = geometry.attributes.position;
  11493. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  11494. let iv = i;
  11495. if ( index ) {
  11496. iv = index.getX( iv );
  11497. }
  11498. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  11499. }
  11500. geometryInfo.boundingBox = box;
  11501. }
  11502. target.copy( geometryInfo.boundingBox );
  11503. return target;
  11504. }
  11505. // get bounding sphere and compute it if it doesn't exist
  11506. getBoundingSphereAt( geometryId, target ) {
  11507. if ( geometryId >= this._geometryCount ) {
  11508. return null;
  11509. }
  11510. // compute bounding sphere
  11511. const geometry = this.geometry;
  11512. const geometryInfo = this._geometryInfo[ geometryId ];
  11513. if ( geometryInfo.boundingSphere === null ) {
  11514. const sphere = new Sphere();
  11515. this.getBoundingBoxAt( geometryId, _box$1 );
  11516. _box$1.getCenter( sphere.center );
  11517. const index = geometry.index;
  11518. const position = geometry.attributes.position;
  11519. let maxRadiusSq = 0;
  11520. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  11521. let iv = i;
  11522. if ( index ) {
  11523. iv = index.getX( iv );
  11524. }
  11525. _vector$5.fromBufferAttribute( position, iv );
  11526. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  11527. }
  11528. sphere.radius = Math.sqrt( maxRadiusSq );
  11529. geometryInfo.boundingSphere = sphere;
  11530. }
  11531. target.copy( geometryInfo.boundingSphere );
  11532. return target;
  11533. }
  11534. setMatrixAt( instanceId, matrix ) {
  11535. this.validateInstanceId( instanceId );
  11536. const matricesTexture = this._matricesTexture;
  11537. const matricesArray = this._matricesTexture.image.data;
  11538. matrix.toArray( matricesArray, instanceId * 16 );
  11539. matricesTexture.needsUpdate = true;
  11540. return this;
  11541. }
  11542. getMatrixAt( instanceId, matrix ) {
  11543. this.validateInstanceId( instanceId );
  11544. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  11545. }
  11546. setColorAt( instanceId, color ) {
  11547. this.validateInstanceId( instanceId );
  11548. if ( this._colorsTexture === null ) {
  11549. this._initColorsTexture();
  11550. }
  11551. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  11552. this._colorsTexture.needsUpdate = true;
  11553. return this;
  11554. }
  11555. getColorAt( instanceId, color ) {
  11556. this.validateInstanceId( instanceId );
  11557. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  11558. }
  11559. setVisibleAt( instanceId, value ) {
  11560. this.validateInstanceId( instanceId );
  11561. if ( this._instanceInfo[ instanceId ].visible === value ) {
  11562. return this;
  11563. }
  11564. this._instanceInfo[ instanceId ].visible = value;
  11565. this._visibilityChanged = true;
  11566. return this;
  11567. }
  11568. getVisibleAt( instanceId ) {
  11569. this.validateInstanceId( instanceId );
  11570. return this._instanceInfo[ instanceId ].visible;
  11571. }
  11572. setGeometryIdAt( instanceId, geometryId ) {
  11573. this.validateInstanceId( instanceId );
  11574. this.validateGeometryId( geometryId );
  11575. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  11576. return this;
  11577. }
  11578. getGeometryIdAt( instanceId ) {
  11579. this.validateInstanceId( instanceId );
  11580. return this._instanceInfo[ instanceId ].geometryIndex;
  11581. }
  11582. getGeometryRangeAt( geometryId, target = {} ) {
  11583. this.validateGeometryId( geometryId );
  11584. const geometryInfo = this._geometryInfo[ geometryId ];
  11585. target.vertexStart = geometryInfo.vertexStart;
  11586. target.vertexCount = geometryInfo.vertexCount;
  11587. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  11588. target.indexStart = geometryInfo.indexStart;
  11589. target.indexCount = geometryInfo.indexCount;
  11590. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  11591. target.start = geometryInfo.start;
  11592. target.count = geometryInfo.count;
  11593. return target;
  11594. }
  11595. setInstanceCount( maxInstanceCount ) {
  11596. // shrink the available instances as much as possible
  11597. const availableInstanceIds = this._availableInstanceIds;
  11598. const instanceInfo = this._instanceInfo;
  11599. availableInstanceIds.sort( ascIdSort );
  11600. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length ) {
  11601. instanceInfo.pop();
  11602. availableInstanceIds.pop();
  11603. }
  11604. // throw an error if it can't be shrunk to the desired size
  11605. if ( maxInstanceCount < instanceInfo.length ) {
  11606. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  11607. }
  11608. // copy the multi draw counts
  11609. const multiDrawCounts = new Int32Array( maxInstanceCount );
  11610. const multiDrawStarts = new Int32Array( maxInstanceCount );
  11611. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  11612. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  11613. this._multiDrawCounts = multiDrawCounts;
  11614. this._multiDrawStarts = multiDrawStarts;
  11615. this._maxInstanceCount = maxInstanceCount;
  11616. // update texture data for instance sampling
  11617. const indirectTexture = this._indirectTexture;
  11618. const matricesTexture = this._matricesTexture;
  11619. const colorsTexture = this._colorsTexture;
  11620. indirectTexture.dispose();
  11621. this._initIndirectTexture();
  11622. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  11623. matricesTexture.dispose();
  11624. this._initMatricesTexture();
  11625. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  11626. if ( colorsTexture ) {
  11627. colorsTexture.dispose();
  11628. this._initColorsTexture();
  11629. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  11630. }
  11631. }
  11632. setGeometrySize( maxVertexCount, maxIndexCount ) {
  11633. // Check if we can shrink to the requested vertex attribute size
  11634. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  11635. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  11636. if ( requiredVertexLength > maxVertexCount ) {
  11637. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  11638. }
  11639. // Check if we can shrink to the requested index attribute size
  11640. if ( this.geometry.index ) {
  11641. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  11642. if ( requiredIndexLength > maxIndexCount ) {
  11643. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  11644. }
  11645. }
  11646. //
  11647. // dispose of the previous geometry
  11648. const oldGeometry = this.geometry;
  11649. oldGeometry.dispose();
  11650. // recreate the geometry needed based on the previous variant
  11651. this._maxVertexCount = maxVertexCount;
  11652. this._maxIndexCount = maxIndexCount;
  11653. if ( this._geometryInitialized ) {
  11654. this._geometryInitialized = false;
  11655. this.geometry = new BufferGeometry();
  11656. this._initializeGeometry( oldGeometry );
  11657. }
  11658. // copy data from the previous geometry
  11659. const geometry = this.geometry;
  11660. if ( oldGeometry.index ) {
  11661. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  11662. }
  11663. for ( const key in oldGeometry.attributes ) {
  11664. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  11665. }
  11666. }
  11667. raycast( raycaster, intersects ) {
  11668. const instanceInfo = this._instanceInfo;
  11669. const geometryInfoList = this._geometryInfo;
  11670. const matrixWorld = this.matrixWorld;
  11671. const batchGeometry = this.geometry;
  11672. // iterate over each geometry
  11673. _mesh.material = this.material;
  11674. _mesh.geometry.index = batchGeometry.index;
  11675. _mesh.geometry.attributes = batchGeometry.attributes;
  11676. if ( _mesh.geometry.boundingBox === null ) {
  11677. _mesh.geometry.boundingBox = new Box3();
  11678. }
  11679. if ( _mesh.geometry.boundingSphere === null ) {
  11680. _mesh.geometry.boundingSphere = new Sphere();
  11681. }
  11682. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  11683. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  11684. continue;
  11685. }
  11686. const geometryId = instanceInfo[ i ].geometryIndex;
  11687. const geometryInfo = geometryInfoList[ geometryId ];
  11688. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  11689. // get the intersects
  11690. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  11691. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  11692. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  11693. _mesh.raycast( raycaster, _batchIntersects );
  11694. // add batch id to the intersects
  11695. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  11696. const intersect = _batchIntersects[ j ];
  11697. intersect.object = this;
  11698. intersect.batchId = i;
  11699. intersects.push( intersect );
  11700. }
  11701. _batchIntersects.length = 0;
  11702. }
  11703. _mesh.material = null;
  11704. _mesh.geometry.index = null;
  11705. _mesh.geometry.attributes = {};
  11706. _mesh.geometry.setDrawRange( 0, Infinity );
  11707. }
  11708. copy( source ) {
  11709. super.copy( source );
  11710. this.geometry = source.geometry.clone();
  11711. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  11712. this.sortObjects = source.sortObjects;
  11713. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  11714. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  11715. this._geometryInfo = source._geometryInfo.map( info => ( {
  11716. ...info,
  11717. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  11718. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  11719. } ) );
  11720. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  11721. this._maxInstanceCount = source._maxInstanceCount;
  11722. this._maxVertexCount = source._maxVertexCount;
  11723. this._maxIndexCount = source._maxIndexCount;
  11724. this._geometryInitialized = source._geometryInitialized;
  11725. this._geometryCount = source._geometryCount;
  11726. this._multiDrawCounts = source._multiDrawCounts.slice();
  11727. this._multiDrawStarts = source._multiDrawStarts.slice();
  11728. this._matricesTexture = source._matricesTexture.clone();
  11729. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  11730. if ( this._colorsTexture !== null ) {
  11731. this._colorsTexture = source._colorsTexture.clone();
  11732. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  11733. }
  11734. return this;
  11735. }
  11736. dispose() {
  11737. // Assuming the geometry is not shared with other meshes
  11738. this.geometry.dispose();
  11739. this._matricesTexture.dispose();
  11740. this._matricesTexture = null;
  11741. this._indirectTexture.dispose();
  11742. this._indirectTexture = null;
  11743. if ( this._colorsTexture !== null ) {
  11744. this._colorsTexture.dispose();
  11745. this._colorsTexture = null;
  11746. }
  11747. return this;
  11748. }
  11749. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  11750. // if visibility has not changed and frustum culling and object sorting is not required
  11751. // then skip iterating over all items
  11752. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  11753. return;
  11754. }
  11755. // the indexed version of the multi draw function requires specifying the start
  11756. // offset in bytes.
  11757. const index = geometry.getIndex();
  11758. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  11759. const instanceInfo = this._instanceInfo;
  11760. const multiDrawStarts = this._multiDrawStarts;
  11761. const multiDrawCounts = this._multiDrawCounts;
  11762. const geometryInfoList = this._geometryInfo;
  11763. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  11764. const indirectTexture = this._indirectTexture;
  11765. const indirectArray = indirectTexture.image.data;
  11766. // prepare the frustum in the local frame
  11767. if ( perObjectFrustumCulled ) {
  11768. _matrix$1
  11769. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  11770. .multiply( this.matrixWorld );
  11771. _frustum.setFromProjectionMatrix(
  11772. _matrix$1,
  11773. renderer.coordinateSystem
  11774. );
  11775. }
  11776. let multiDrawCount = 0;
  11777. if ( this.sortObjects ) {
  11778. // get the camera position in the local frame
  11779. _matrix$1.copy( this.matrixWorld ).invert();
  11780. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  11781. _forward.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  11782. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  11783. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  11784. const geometryId = instanceInfo[ i ].geometryIndex;
  11785. // get the bounds in world space
  11786. this.getMatrixAt( i, _matrix$1 );
  11787. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  11788. // determine whether the batched geometry is within the frustum
  11789. let culled = false;
  11790. if ( perObjectFrustumCulled ) {
  11791. culled = ! _frustum.intersectsSphere( _sphere$2 );
  11792. }
  11793. if ( ! culled ) {
  11794. // get the distance from camera used for sorting
  11795. const geometryInfo = geometryInfoList[ geometryId ];
  11796. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward );
  11797. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  11798. }
  11799. }
  11800. }
  11801. // Sort the draw ranges and prep for rendering
  11802. const list = _renderList.list;
  11803. const customSort = this.customSort;
  11804. if ( customSort === null ) {
  11805. list.sort( material.transparent ? sortTransparent : sortOpaque );
  11806. } else {
  11807. customSort.call( this, list, camera );
  11808. }
  11809. for ( let i = 0, l = list.length; i < l; i ++ ) {
  11810. const item = list[ i ];
  11811. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement;
  11812. multiDrawCounts[ multiDrawCount ] = item.count;
  11813. indirectArray[ multiDrawCount ] = item.index;
  11814. multiDrawCount ++;
  11815. }
  11816. _renderList.reset();
  11817. } else {
  11818. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  11819. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  11820. const geometryId = instanceInfo[ i ].geometryIndex;
  11821. // determine whether the batched geometry is within the frustum
  11822. let culled = false;
  11823. if ( perObjectFrustumCulled ) {
  11824. // get the bounds in world space
  11825. this.getMatrixAt( i, _matrix$1 );
  11826. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  11827. culled = ! _frustum.intersectsSphere( _sphere$2 );
  11828. }
  11829. if ( ! culled ) {
  11830. const geometryInfo = geometryInfoList[ geometryId ];
  11831. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement;
  11832. multiDrawCounts[ multiDrawCount ] = geometryInfo.count;
  11833. indirectArray[ multiDrawCount ] = i;
  11834. multiDrawCount ++;
  11835. }
  11836. }
  11837. }
  11838. }
  11839. indirectTexture.needsUpdate = true;
  11840. this._multiDrawCount = multiDrawCount;
  11841. this._visibilityChanged = false;
  11842. }
  11843. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  11844. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  11845. }
  11846. }
  11847. class LineBasicMaterial extends Material {
  11848. constructor( parameters ) {
  11849. super();
  11850. this.isLineBasicMaterial = true;
  11851. this.type = 'LineBasicMaterial';
  11852. this.color = new Color( 0xffffff );
  11853. this.map = null;
  11854. this.linewidth = 1;
  11855. this.linecap = 'round';
  11856. this.linejoin = 'round';
  11857. this.fog = true;
  11858. this.setValues( parameters );
  11859. }
  11860. copy( source ) {
  11861. super.copy( source );
  11862. this.color.copy( source.color );
  11863. this.map = source.map;
  11864. this.linewidth = source.linewidth;
  11865. this.linecap = source.linecap;
  11866. this.linejoin = source.linejoin;
  11867. this.fog = source.fog;
  11868. return this;
  11869. }
  11870. }
  11871. const _vStart = /*@__PURE__*/ new Vector3();
  11872. const _vEnd = /*@__PURE__*/ new Vector3();
  11873. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  11874. const _ray$1 = /*@__PURE__*/ new Ray();
  11875. const _sphere$1 = /*@__PURE__*/ new Sphere();
  11876. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  11877. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  11878. class Line extends Object3D {
  11879. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  11880. super();
  11881. this.isLine = true;
  11882. this.type = 'Line';
  11883. this.geometry = geometry;
  11884. this.material = material;
  11885. this.updateMorphTargets();
  11886. }
  11887. copy( source, recursive ) {
  11888. super.copy( source, recursive );
  11889. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  11890. this.geometry = source.geometry;
  11891. return this;
  11892. }
  11893. computeLineDistances() {
  11894. const geometry = this.geometry;
  11895. // we assume non-indexed geometry
  11896. if ( geometry.index === null ) {
  11897. const positionAttribute = geometry.attributes.position;
  11898. const lineDistances = [ 0 ];
  11899. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  11900. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  11901. _vEnd.fromBufferAttribute( positionAttribute, i );
  11902. lineDistances[ i ] = lineDistances[ i - 1 ];
  11903. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  11904. }
  11905. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  11906. } else {
  11907. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  11908. }
  11909. return this;
  11910. }
  11911. raycast( raycaster, intersects ) {
  11912. const geometry = this.geometry;
  11913. const matrixWorld = this.matrixWorld;
  11914. const threshold = raycaster.params.Line.threshold;
  11915. const drawRange = geometry.drawRange;
  11916. // Checking boundingSphere distance to ray
  11917. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  11918. _sphere$1.copy( geometry.boundingSphere );
  11919. _sphere$1.applyMatrix4( matrixWorld );
  11920. _sphere$1.radius += threshold;
  11921. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  11922. //
  11923. _inverseMatrix$1.copy( matrixWorld ).invert();
  11924. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  11925. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  11926. const localThresholdSq = localThreshold * localThreshold;
  11927. const step = this.isLineSegments ? 2 : 1;
  11928. const index = geometry.index;
  11929. const attributes = geometry.attributes;
  11930. const positionAttribute = attributes.position;
  11931. if ( index !== null ) {
  11932. const start = Math.max( 0, drawRange.start );
  11933. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  11934. for ( let i = start, l = end - 1; i < l; i += step ) {
  11935. const a = index.getX( i );
  11936. const b = index.getX( i + 1 );
  11937. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i );
  11938. if ( intersect ) {
  11939. intersects.push( intersect );
  11940. }
  11941. }
  11942. if ( this.isLineLoop ) {
  11943. const a = index.getX( end - 1 );
  11944. const b = index.getX( start );
  11945. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 );
  11946. if ( intersect ) {
  11947. intersects.push( intersect );
  11948. }
  11949. }
  11950. } else {
  11951. const start = Math.max( 0, drawRange.start );
  11952. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  11953. for ( let i = start, l = end - 1; i < l; i += step ) {
  11954. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i );
  11955. if ( intersect ) {
  11956. intersects.push( intersect );
  11957. }
  11958. }
  11959. if ( this.isLineLoop ) {
  11960. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 );
  11961. if ( intersect ) {
  11962. intersects.push( intersect );
  11963. }
  11964. }
  11965. }
  11966. }
  11967. updateMorphTargets() {
  11968. const geometry = this.geometry;
  11969. const morphAttributes = geometry.morphAttributes;
  11970. const keys = Object.keys( morphAttributes );
  11971. if ( keys.length > 0 ) {
  11972. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  11973. if ( morphAttribute !== undefined ) {
  11974. this.morphTargetInfluences = [];
  11975. this.morphTargetDictionary = {};
  11976. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  11977. const name = morphAttribute[ m ].name || String( m );
  11978. this.morphTargetInfluences.push( 0 );
  11979. this.morphTargetDictionary[ name ] = m;
  11980. }
  11981. }
  11982. }
  11983. }
  11984. }
  11985. function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) {
  11986. const positionAttribute = object.geometry.attributes.position;
  11987. _vStart.fromBufferAttribute( positionAttribute, a );
  11988. _vEnd.fromBufferAttribute( positionAttribute, b );
  11989. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  11990. if ( distSq > thresholdSq ) return;
  11991. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  11992. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  11993. if ( distance < raycaster.near || distance > raycaster.far ) return;
  11994. return {
  11995. distance: distance,
  11996. // What do we want? intersection point on the ray or on the segment??
  11997. // point: raycaster.ray.at( distance ),
  11998. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  11999. index: i,
  12000. face: null,
  12001. faceIndex: null,
  12002. barycoord: null,
  12003. object: object
  12004. };
  12005. }
  12006. const _start = /*@__PURE__*/ new Vector3();
  12007. const _end = /*@__PURE__*/ new Vector3();
  12008. class LineSegments extends Line {
  12009. constructor( geometry, material ) {
  12010. super( geometry, material );
  12011. this.isLineSegments = true;
  12012. this.type = 'LineSegments';
  12013. }
  12014. computeLineDistances() {
  12015. const geometry = this.geometry;
  12016. // we assume non-indexed geometry
  12017. if ( geometry.index === null ) {
  12018. const positionAttribute = geometry.attributes.position;
  12019. const lineDistances = [];
  12020. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  12021. _start.fromBufferAttribute( positionAttribute, i );
  12022. _end.fromBufferAttribute( positionAttribute, i + 1 );
  12023. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  12024. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  12025. }
  12026. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  12027. } else {
  12028. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  12029. }
  12030. return this;
  12031. }
  12032. }
  12033. class LineLoop extends Line {
  12034. constructor( geometry, material ) {
  12035. super( geometry, material );
  12036. this.isLineLoop = true;
  12037. this.type = 'LineLoop';
  12038. }
  12039. }
  12040. class PointsMaterial extends Material {
  12041. constructor( parameters ) {
  12042. super();
  12043. this.isPointsMaterial = true;
  12044. this.type = 'PointsMaterial';
  12045. this.color = new Color( 0xffffff );
  12046. this.map = null;
  12047. this.alphaMap = null;
  12048. this.size = 1;
  12049. this.sizeAttenuation = true;
  12050. this.fog = true;
  12051. this.setValues( parameters );
  12052. }
  12053. copy( source ) {
  12054. super.copy( source );
  12055. this.color.copy( source.color );
  12056. this.map = source.map;
  12057. this.alphaMap = source.alphaMap;
  12058. this.size = source.size;
  12059. this.sizeAttenuation = source.sizeAttenuation;
  12060. this.fog = source.fog;
  12061. return this;
  12062. }
  12063. }
  12064. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  12065. const _ray = /*@__PURE__*/ new Ray();
  12066. const _sphere = /*@__PURE__*/ new Sphere();
  12067. const _position$2 = /*@__PURE__*/ new Vector3();
  12068. class Points extends Object3D {
  12069. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  12070. super();
  12071. this.isPoints = true;
  12072. this.type = 'Points';
  12073. this.geometry = geometry;
  12074. this.material = material;
  12075. this.updateMorphTargets();
  12076. }
  12077. copy( source, recursive ) {
  12078. super.copy( source, recursive );
  12079. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  12080. this.geometry = source.geometry;
  12081. return this;
  12082. }
  12083. raycast( raycaster, intersects ) {
  12084. const geometry = this.geometry;
  12085. const matrixWorld = this.matrixWorld;
  12086. const threshold = raycaster.params.Points.threshold;
  12087. const drawRange = geometry.drawRange;
  12088. // Checking boundingSphere distance to ray
  12089. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  12090. _sphere.copy( geometry.boundingSphere );
  12091. _sphere.applyMatrix4( matrixWorld );
  12092. _sphere.radius += threshold;
  12093. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  12094. //
  12095. _inverseMatrix.copy( matrixWorld ).invert();
  12096. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  12097. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  12098. const localThresholdSq = localThreshold * localThreshold;
  12099. const index = geometry.index;
  12100. const attributes = geometry.attributes;
  12101. const positionAttribute = attributes.position;
  12102. if ( index !== null ) {
  12103. const start = Math.max( 0, drawRange.start );
  12104. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  12105. for ( let i = start, il = end; i < il; i ++ ) {
  12106. const a = index.getX( i );
  12107. _position$2.fromBufferAttribute( positionAttribute, a );
  12108. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  12109. }
  12110. } else {
  12111. const start = Math.max( 0, drawRange.start );
  12112. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  12113. for ( let i = start, l = end; i < l; i ++ ) {
  12114. _position$2.fromBufferAttribute( positionAttribute, i );
  12115. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  12116. }
  12117. }
  12118. }
  12119. updateMorphTargets() {
  12120. const geometry = this.geometry;
  12121. const morphAttributes = geometry.morphAttributes;
  12122. const keys = Object.keys( morphAttributes );
  12123. if ( keys.length > 0 ) {
  12124. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  12125. if ( morphAttribute !== undefined ) {
  12126. this.morphTargetInfluences = [];
  12127. this.morphTargetDictionary = {};
  12128. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  12129. const name = morphAttribute[ m ].name || String( m );
  12130. this.morphTargetInfluences.push( 0 );
  12131. this.morphTargetDictionary[ name ] = m;
  12132. }
  12133. }
  12134. }
  12135. }
  12136. }
  12137. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  12138. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  12139. if ( rayPointDistanceSq < localThresholdSq ) {
  12140. const intersectPoint = new Vector3();
  12141. _ray.closestPointToPoint( point, intersectPoint );
  12142. intersectPoint.applyMatrix4( matrixWorld );
  12143. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  12144. if ( distance < raycaster.near || distance > raycaster.far ) return;
  12145. intersects.push( {
  12146. distance: distance,
  12147. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  12148. point: intersectPoint,
  12149. index: index,
  12150. face: null,
  12151. faceIndex: null,
  12152. barycoord: null,
  12153. object: object
  12154. } );
  12155. }
  12156. }
  12157. class VideoTexture extends Texture {
  12158. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  12159. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  12160. this.isVideoTexture = true;
  12161. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  12162. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  12163. this.generateMipmaps = false;
  12164. const scope = this;
  12165. function updateVideo() {
  12166. scope.needsUpdate = true;
  12167. video.requestVideoFrameCallback( updateVideo );
  12168. }
  12169. if ( 'requestVideoFrameCallback' in video ) {
  12170. video.requestVideoFrameCallback( updateVideo );
  12171. }
  12172. }
  12173. clone() {
  12174. return new this.constructor( this.image ).copy( this );
  12175. }
  12176. update() {
  12177. const video = this.image;
  12178. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  12179. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  12180. this.needsUpdate = true;
  12181. }
  12182. }
  12183. }
  12184. class VideoFrameTexture extends VideoTexture {
  12185. constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  12186. super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  12187. this.isVideoFrameTexture = true;
  12188. }
  12189. update() {
  12190. // overwrites `VideoTexture.update()` with an empty method since
  12191. // this type of texture is updated via `setFrame()`.
  12192. }
  12193. clone() {
  12194. return new this.constructor().copy( this ); // restoring Texture.clone()
  12195. }
  12196. setFrame( frame ) {
  12197. this.image = frame;
  12198. this.needsUpdate = true;
  12199. }
  12200. }
  12201. class FramebufferTexture extends Texture {
  12202. constructor( width, height ) {
  12203. super( { width, height } );
  12204. this.isFramebufferTexture = true;
  12205. this.magFilter = NearestFilter;
  12206. this.minFilter = NearestFilter;
  12207. this.generateMipmaps = false;
  12208. this.needsUpdate = true;
  12209. }
  12210. }
  12211. class CompressedTexture extends Texture {
  12212. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  12213. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  12214. this.isCompressedTexture = true;
  12215. this.image = { width: width, height: height };
  12216. this.mipmaps = mipmaps;
  12217. // no flipping for cube textures
  12218. // (also flipping doesn't work for compressed textures )
  12219. this.flipY = false;
  12220. // can't generate mipmaps for compressed textures
  12221. // mips must be embedded in DDS files
  12222. this.generateMipmaps = false;
  12223. }
  12224. }
  12225. class CompressedArrayTexture extends CompressedTexture {
  12226. constructor( mipmaps, width, height, depth, format, type ) {
  12227. super( mipmaps, width, height, format, type );
  12228. this.isCompressedArrayTexture = true;
  12229. this.image.depth = depth;
  12230. this.wrapR = ClampToEdgeWrapping;
  12231. this.layerUpdates = new Set();
  12232. }
  12233. addLayerUpdate( layerIndex ) {
  12234. this.layerUpdates.add( layerIndex );
  12235. }
  12236. clearLayerUpdates() {
  12237. this.layerUpdates.clear();
  12238. }
  12239. }
  12240. class CompressedCubeTexture extends CompressedTexture {
  12241. constructor( images, format, type ) {
  12242. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  12243. this.isCompressedCubeTexture = true;
  12244. this.isCubeTexture = true;
  12245. this.image = images;
  12246. }
  12247. }
  12248. class CanvasTexture extends Texture {
  12249. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  12250. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  12251. this.isCanvasTexture = true;
  12252. this.needsUpdate = true;
  12253. }
  12254. }
  12255. class DepthTexture extends Texture {
  12256. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format = DepthFormat ) {
  12257. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  12258. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  12259. }
  12260. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  12261. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  12262. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  12263. this.isDepthTexture = true;
  12264. this.image = { width: width, height: height };
  12265. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  12266. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  12267. this.flipY = false;
  12268. this.generateMipmaps = false;
  12269. this.compareFunction = null;
  12270. }
  12271. copy( source ) {
  12272. super.copy( source );
  12273. this.compareFunction = source.compareFunction;
  12274. return this;
  12275. }
  12276. toJSON( meta ) {
  12277. const data = super.toJSON( meta );
  12278. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  12279. return data;
  12280. }
  12281. }
  12282. /**
  12283. * Extensible curve object.
  12284. *
  12285. * Some common of curve methods:
  12286. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  12287. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  12288. * .getPoints(), .getSpacedPoints()
  12289. * .getLength()
  12290. * .updateArcLengths()
  12291. *
  12292. * This following curves inherit from THREE.Curve:
  12293. *
  12294. * -- 2D curves --
  12295. * THREE.ArcCurve
  12296. * THREE.CubicBezierCurve
  12297. * THREE.EllipseCurve
  12298. * THREE.LineCurve
  12299. * THREE.QuadraticBezierCurve
  12300. * THREE.SplineCurve
  12301. *
  12302. * -- 3D curves --
  12303. * THREE.CatmullRomCurve3
  12304. * THREE.CubicBezierCurve3
  12305. * THREE.LineCurve3
  12306. * THREE.QuadraticBezierCurve3
  12307. *
  12308. * A series of curves can be represented as a THREE.CurvePath.
  12309. *
  12310. **/
  12311. class Curve {
  12312. constructor() {
  12313. this.type = 'Curve';
  12314. this.arcLengthDivisions = 200;
  12315. }
  12316. // Virtual base class method to overwrite and implement in subclasses
  12317. // - t [0 .. 1]
  12318. getPoint( /* t, optionalTarget */ ) {
  12319. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  12320. return null;
  12321. }
  12322. // Get point at relative position in curve according to arc length
  12323. // - u [0 .. 1]
  12324. getPointAt( u, optionalTarget ) {
  12325. const t = this.getUtoTmapping( u );
  12326. return this.getPoint( t, optionalTarget );
  12327. }
  12328. // Get sequence of points using getPoint( t )
  12329. getPoints( divisions = 5 ) {
  12330. const points = [];
  12331. for ( let d = 0; d <= divisions; d ++ ) {
  12332. points.push( this.getPoint( d / divisions ) );
  12333. }
  12334. return points;
  12335. }
  12336. // Get sequence of points using getPointAt( u )
  12337. getSpacedPoints( divisions = 5 ) {
  12338. const points = [];
  12339. for ( let d = 0; d <= divisions; d ++ ) {
  12340. points.push( this.getPointAt( d / divisions ) );
  12341. }
  12342. return points;
  12343. }
  12344. // Get total curve arc length
  12345. getLength() {
  12346. const lengths = this.getLengths();
  12347. return lengths[ lengths.length - 1 ];
  12348. }
  12349. // Get list of cumulative segment lengths
  12350. getLengths( divisions = this.arcLengthDivisions ) {
  12351. if ( this.cacheArcLengths &&
  12352. ( this.cacheArcLengths.length === divisions + 1 ) &&
  12353. ! this.needsUpdate ) {
  12354. return this.cacheArcLengths;
  12355. }
  12356. this.needsUpdate = false;
  12357. const cache = [];
  12358. let current, last = this.getPoint( 0 );
  12359. let sum = 0;
  12360. cache.push( 0 );
  12361. for ( let p = 1; p <= divisions; p ++ ) {
  12362. current = this.getPoint( p / divisions );
  12363. sum += current.distanceTo( last );
  12364. cache.push( sum );
  12365. last = current;
  12366. }
  12367. this.cacheArcLengths = cache;
  12368. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  12369. }
  12370. updateArcLengths() {
  12371. this.needsUpdate = true;
  12372. this.getLengths();
  12373. }
  12374. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  12375. getUtoTmapping( u, distance ) {
  12376. const arcLengths = this.getLengths();
  12377. let i = 0;
  12378. const il = arcLengths.length;
  12379. let targetArcLength; // The targeted u distance value to get
  12380. if ( distance ) {
  12381. targetArcLength = distance;
  12382. } else {
  12383. targetArcLength = u * arcLengths[ il - 1 ];
  12384. }
  12385. // binary search for the index with largest value smaller than target u distance
  12386. let low = 0, high = il - 1, comparison;
  12387. while ( low <= high ) {
  12388. 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
  12389. comparison = arcLengths[ i ] - targetArcLength;
  12390. if ( comparison < 0 ) {
  12391. low = i + 1;
  12392. } else if ( comparison > 0 ) {
  12393. high = i - 1;
  12394. } else {
  12395. high = i;
  12396. break;
  12397. // DONE
  12398. }
  12399. }
  12400. i = high;
  12401. if ( arcLengths[ i ] === targetArcLength ) {
  12402. return i / ( il - 1 );
  12403. }
  12404. // we could get finer grain at lengths, or use simple interpolation between two points
  12405. const lengthBefore = arcLengths[ i ];
  12406. const lengthAfter = arcLengths[ i + 1 ];
  12407. const segmentLength = lengthAfter - lengthBefore;
  12408. // determine where we are between the 'before' and 'after' points
  12409. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  12410. // add that fractional amount to t
  12411. const t = ( i + segmentFraction ) / ( il - 1 );
  12412. return t;
  12413. }
  12414. // Returns a unit vector tangent at t
  12415. // In case any sub curve does not implement its tangent derivation,
  12416. // 2 points a small delta apart will be used to find its gradient
  12417. // which seems to give a reasonable approximation
  12418. getTangent( t, optionalTarget ) {
  12419. const delta = 0.0001;
  12420. let t1 = t - delta;
  12421. let t2 = t + delta;
  12422. // Capping in case of danger
  12423. if ( t1 < 0 ) t1 = 0;
  12424. if ( t2 > 1 ) t2 = 1;
  12425. const pt1 = this.getPoint( t1 );
  12426. const pt2 = this.getPoint( t2 );
  12427. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  12428. tangent.copy( pt2 ).sub( pt1 ).normalize();
  12429. return tangent;
  12430. }
  12431. getTangentAt( u, optionalTarget ) {
  12432. const t = this.getUtoTmapping( u );
  12433. return this.getTangent( t, optionalTarget );
  12434. }
  12435. computeFrenetFrames( segments, closed ) {
  12436. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  12437. const normal = new Vector3();
  12438. const tangents = [];
  12439. const normals = [];
  12440. const binormals = [];
  12441. const vec = new Vector3();
  12442. const mat = new Matrix4();
  12443. // compute the tangent vectors for each segment on the curve
  12444. for ( let i = 0; i <= segments; i ++ ) {
  12445. const u = i / segments;
  12446. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  12447. }
  12448. // select an initial normal vector perpendicular to the first tangent vector,
  12449. // and in the direction of the minimum tangent xyz component
  12450. normals[ 0 ] = new Vector3();
  12451. binormals[ 0 ] = new Vector3();
  12452. let min = Number.MAX_VALUE;
  12453. const tx = Math.abs( tangents[ 0 ].x );
  12454. const ty = Math.abs( tangents[ 0 ].y );
  12455. const tz = Math.abs( tangents[ 0 ].z );
  12456. if ( tx <= min ) {
  12457. min = tx;
  12458. normal.set( 1, 0, 0 );
  12459. }
  12460. if ( ty <= min ) {
  12461. min = ty;
  12462. normal.set( 0, 1, 0 );
  12463. }
  12464. if ( tz <= min ) {
  12465. normal.set( 0, 0, 1 );
  12466. }
  12467. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  12468. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  12469. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  12470. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  12471. for ( let i = 1; i <= segments; i ++ ) {
  12472. normals[ i ] = normals[ i - 1 ].clone();
  12473. binormals[ i ] = binormals[ i - 1 ].clone();
  12474. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  12475. if ( vec.length() > Number.EPSILON ) {
  12476. vec.normalize();
  12477. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  12478. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  12479. }
  12480. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  12481. }
  12482. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  12483. if ( closed === true ) {
  12484. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), -1, 1 ) );
  12485. theta /= segments;
  12486. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  12487. theta = - theta;
  12488. }
  12489. for ( let i = 1; i <= segments; i ++ ) {
  12490. // twist a little...
  12491. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  12492. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  12493. }
  12494. }
  12495. return {
  12496. tangents: tangents,
  12497. normals: normals,
  12498. binormals: binormals
  12499. };
  12500. }
  12501. clone() {
  12502. return new this.constructor().copy( this );
  12503. }
  12504. copy( source ) {
  12505. this.arcLengthDivisions = source.arcLengthDivisions;
  12506. return this;
  12507. }
  12508. toJSON() {
  12509. const data = {
  12510. metadata: {
  12511. version: 4.6,
  12512. type: 'Curve',
  12513. generator: 'Curve.toJSON'
  12514. }
  12515. };
  12516. data.arcLengthDivisions = this.arcLengthDivisions;
  12517. data.type = this.type;
  12518. return data;
  12519. }
  12520. fromJSON( json ) {
  12521. this.arcLengthDivisions = json.arcLengthDivisions;
  12522. return this;
  12523. }
  12524. }
  12525. class EllipseCurve extends Curve {
  12526. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  12527. super();
  12528. this.isEllipseCurve = true;
  12529. this.type = 'EllipseCurve';
  12530. this.aX = aX;
  12531. this.aY = aY;
  12532. this.xRadius = xRadius;
  12533. this.yRadius = yRadius;
  12534. this.aStartAngle = aStartAngle;
  12535. this.aEndAngle = aEndAngle;
  12536. this.aClockwise = aClockwise;
  12537. this.aRotation = aRotation;
  12538. }
  12539. getPoint( t, optionalTarget = new Vector2() ) {
  12540. const point = optionalTarget;
  12541. const twoPi = Math.PI * 2;
  12542. let deltaAngle = this.aEndAngle - this.aStartAngle;
  12543. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  12544. // ensures that deltaAngle is 0 .. 2 PI
  12545. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  12546. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  12547. if ( deltaAngle < Number.EPSILON ) {
  12548. if ( samePoints ) {
  12549. deltaAngle = 0;
  12550. } else {
  12551. deltaAngle = twoPi;
  12552. }
  12553. }
  12554. if ( this.aClockwise === true && ! samePoints ) {
  12555. if ( deltaAngle === twoPi ) {
  12556. deltaAngle = - twoPi;
  12557. } else {
  12558. deltaAngle = deltaAngle - twoPi;
  12559. }
  12560. }
  12561. const angle = this.aStartAngle + t * deltaAngle;
  12562. let x = this.aX + this.xRadius * Math.cos( angle );
  12563. let y = this.aY + this.yRadius * Math.sin( angle );
  12564. if ( this.aRotation !== 0 ) {
  12565. const cos = Math.cos( this.aRotation );
  12566. const sin = Math.sin( this.aRotation );
  12567. const tx = x - this.aX;
  12568. const ty = y - this.aY;
  12569. // Rotate the point about the center of the ellipse.
  12570. x = tx * cos - ty * sin + this.aX;
  12571. y = tx * sin + ty * cos + this.aY;
  12572. }
  12573. return point.set( x, y );
  12574. }
  12575. copy( source ) {
  12576. super.copy( source );
  12577. this.aX = source.aX;
  12578. this.aY = source.aY;
  12579. this.xRadius = source.xRadius;
  12580. this.yRadius = source.yRadius;
  12581. this.aStartAngle = source.aStartAngle;
  12582. this.aEndAngle = source.aEndAngle;
  12583. this.aClockwise = source.aClockwise;
  12584. this.aRotation = source.aRotation;
  12585. return this;
  12586. }
  12587. toJSON() {
  12588. const data = super.toJSON();
  12589. data.aX = this.aX;
  12590. data.aY = this.aY;
  12591. data.xRadius = this.xRadius;
  12592. data.yRadius = this.yRadius;
  12593. data.aStartAngle = this.aStartAngle;
  12594. data.aEndAngle = this.aEndAngle;
  12595. data.aClockwise = this.aClockwise;
  12596. data.aRotation = this.aRotation;
  12597. return data;
  12598. }
  12599. fromJSON( json ) {
  12600. super.fromJSON( json );
  12601. this.aX = json.aX;
  12602. this.aY = json.aY;
  12603. this.xRadius = json.xRadius;
  12604. this.yRadius = json.yRadius;
  12605. this.aStartAngle = json.aStartAngle;
  12606. this.aEndAngle = json.aEndAngle;
  12607. this.aClockwise = json.aClockwise;
  12608. this.aRotation = json.aRotation;
  12609. return this;
  12610. }
  12611. }
  12612. class ArcCurve extends EllipseCurve {
  12613. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  12614. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  12615. this.isArcCurve = true;
  12616. this.type = 'ArcCurve';
  12617. }
  12618. }
  12619. /**
  12620. * Centripetal CatmullRom Curve - which is useful for avoiding
  12621. * cusps and self-intersections in non-uniform catmull rom curves.
  12622. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  12623. *
  12624. * curve.type accepts centripetal(default), chordal and catmullrom
  12625. * curve.tension is used for catmullrom which defaults to 0.5
  12626. */
  12627. /*
  12628. Based on an optimized c++ solution in
  12629. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  12630. - http://ideone.com/NoEbVM
  12631. This CubicPoly class could be used for reusing some variables and calculations,
  12632. but for three.js curve use, it could be possible inlined and flatten into a single function call
  12633. which can be placed in CurveUtils.
  12634. */
  12635. function CubicPoly() {
  12636. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  12637. /*
  12638. * Compute coefficients for a cubic polynomial
  12639. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  12640. * such that
  12641. * p(0) = x0, p(1) = x1
  12642. * and
  12643. * p'(0) = t0, p'(1) = t1.
  12644. */
  12645. function init( x0, x1, t0, t1 ) {
  12646. c0 = x0;
  12647. c1 = t0;
  12648. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  12649. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  12650. }
  12651. return {
  12652. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  12653. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  12654. },
  12655. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  12656. // compute tangents when parameterized in [t1,t2]
  12657. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  12658. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  12659. // rescale tangents for parametrization in [0,1]
  12660. t1 *= dt1;
  12661. t2 *= dt1;
  12662. init( x1, x2, t1, t2 );
  12663. },
  12664. calc: function ( t ) {
  12665. const t2 = t * t;
  12666. const t3 = t2 * t;
  12667. return c0 + c1 * t + c2 * t2 + c3 * t3;
  12668. }
  12669. };
  12670. }
  12671. //
  12672. const tmp = /*@__PURE__*/ new Vector3();
  12673. const px = /*@__PURE__*/ new CubicPoly();
  12674. const py = /*@__PURE__*/ new CubicPoly();
  12675. const pz = /*@__PURE__*/ new CubicPoly();
  12676. class CatmullRomCurve3 extends Curve {
  12677. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  12678. super();
  12679. this.isCatmullRomCurve3 = true;
  12680. this.type = 'CatmullRomCurve3';
  12681. this.points = points;
  12682. this.closed = closed;
  12683. this.curveType = curveType;
  12684. this.tension = tension;
  12685. }
  12686. getPoint( t, optionalTarget = new Vector3() ) {
  12687. const point = optionalTarget;
  12688. const points = this.points;
  12689. const l = points.length;
  12690. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  12691. let intPoint = Math.floor( p );
  12692. let weight = p - intPoint;
  12693. if ( this.closed ) {
  12694. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  12695. } else if ( weight === 0 && intPoint === l - 1 ) {
  12696. intPoint = l - 2;
  12697. weight = 1;
  12698. }
  12699. let p0, p3; // 4 points (p1 & p2 defined below)
  12700. if ( this.closed || intPoint > 0 ) {
  12701. p0 = points[ ( intPoint - 1 ) % l ];
  12702. } else {
  12703. // extrapolate first point
  12704. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  12705. p0 = tmp;
  12706. }
  12707. const p1 = points[ intPoint % l ];
  12708. const p2 = points[ ( intPoint + 1 ) % l ];
  12709. if ( this.closed || intPoint + 2 < l ) {
  12710. p3 = points[ ( intPoint + 2 ) % l ];
  12711. } else {
  12712. // extrapolate last point
  12713. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  12714. p3 = tmp;
  12715. }
  12716. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  12717. // init Centripetal / Chordal Catmull-Rom
  12718. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  12719. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  12720. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  12721. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  12722. // safety check for repeated points
  12723. if ( dt1 < 1e-4 ) dt1 = 1.0;
  12724. if ( dt0 < 1e-4 ) dt0 = dt1;
  12725. if ( dt2 < 1e-4 ) dt2 = dt1;
  12726. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  12727. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  12728. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  12729. } else if ( this.curveType === 'catmullrom' ) {
  12730. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  12731. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  12732. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  12733. }
  12734. point.set(
  12735. px.calc( weight ),
  12736. py.calc( weight ),
  12737. pz.calc( weight )
  12738. );
  12739. return point;
  12740. }
  12741. copy( source ) {
  12742. super.copy( source );
  12743. this.points = [];
  12744. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  12745. const point = source.points[ i ];
  12746. this.points.push( point.clone() );
  12747. }
  12748. this.closed = source.closed;
  12749. this.curveType = source.curveType;
  12750. this.tension = source.tension;
  12751. return this;
  12752. }
  12753. toJSON() {
  12754. const data = super.toJSON();
  12755. data.points = [];
  12756. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  12757. const point = this.points[ i ];
  12758. data.points.push( point.toArray() );
  12759. }
  12760. data.closed = this.closed;
  12761. data.curveType = this.curveType;
  12762. data.tension = this.tension;
  12763. return data;
  12764. }
  12765. fromJSON( json ) {
  12766. super.fromJSON( json );
  12767. this.points = [];
  12768. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  12769. const point = json.points[ i ];
  12770. this.points.push( new Vector3().fromArray( point ) );
  12771. }
  12772. this.closed = json.closed;
  12773. this.curveType = json.curveType;
  12774. this.tension = json.tension;
  12775. return this;
  12776. }
  12777. }
  12778. /**
  12779. * Bezier Curves formulas obtained from
  12780. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  12781. */
  12782. function CatmullRom( t, p0, p1, p2, p3 ) {
  12783. const v0 = ( p2 - p0 ) * 0.5;
  12784. const v1 = ( p3 - p1 ) * 0.5;
  12785. const t2 = t * t;
  12786. const t3 = t * t2;
  12787. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( -3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  12788. }
  12789. //
  12790. function QuadraticBezierP0( t, p ) {
  12791. const k = 1 - t;
  12792. return k * k * p;
  12793. }
  12794. function QuadraticBezierP1( t, p ) {
  12795. return 2 * ( 1 - t ) * t * p;
  12796. }
  12797. function QuadraticBezierP2( t, p ) {
  12798. return t * t * p;
  12799. }
  12800. function QuadraticBezier( t, p0, p1, p2 ) {
  12801. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  12802. QuadraticBezierP2( t, p2 );
  12803. }
  12804. //
  12805. function CubicBezierP0( t, p ) {
  12806. const k = 1 - t;
  12807. return k * k * k * p;
  12808. }
  12809. function CubicBezierP1( t, p ) {
  12810. const k = 1 - t;
  12811. return 3 * k * k * t * p;
  12812. }
  12813. function CubicBezierP2( t, p ) {
  12814. return 3 * ( 1 - t ) * t * t * p;
  12815. }
  12816. function CubicBezierP3( t, p ) {
  12817. return t * t * t * p;
  12818. }
  12819. function CubicBezier( t, p0, p1, p2, p3 ) {
  12820. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  12821. CubicBezierP3( t, p3 );
  12822. }
  12823. class CubicBezierCurve extends Curve {
  12824. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  12825. super();
  12826. this.isCubicBezierCurve = true;
  12827. this.type = 'CubicBezierCurve';
  12828. this.v0 = v0;
  12829. this.v1 = v1;
  12830. this.v2 = v2;
  12831. this.v3 = v3;
  12832. }
  12833. getPoint( t, optionalTarget = new Vector2() ) {
  12834. const point = optionalTarget;
  12835. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  12836. point.set(
  12837. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  12838. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  12839. );
  12840. return point;
  12841. }
  12842. copy( source ) {
  12843. super.copy( source );
  12844. this.v0.copy( source.v0 );
  12845. this.v1.copy( source.v1 );
  12846. this.v2.copy( source.v2 );
  12847. this.v3.copy( source.v3 );
  12848. return this;
  12849. }
  12850. toJSON() {
  12851. const data = super.toJSON();
  12852. data.v0 = this.v0.toArray();
  12853. data.v1 = this.v1.toArray();
  12854. data.v2 = this.v2.toArray();
  12855. data.v3 = this.v3.toArray();
  12856. return data;
  12857. }
  12858. fromJSON( json ) {
  12859. super.fromJSON( json );
  12860. this.v0.fromArray( json.v0 );
  12861. this.v1.fromArray( json.v1 );
  12862. this.v2.fromArray( json.v2 );
  12863. this.v3.fromArray( json.v3 );
  12864. return this;
  12865. }
  12866. }
  12867. class CubicBezierCurve3 extends Curve {
  12868. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  12869. super();
  12870. this.isCubicBezierCurve3 = true;
  12871. this.type = 'CubicBezierCurve3';
  12872. this.v0 = v0;
  12873. this.v1 = v1;
  12874. this.v2 = v2;
  12875. this.v3 = v3;
  12876. }
  12877. getPoint( t, optionalTarget = new Vector3() ) {
  12878. const point = optionalTarget;
  12879. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  12880. point.set(
  12881. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  12882. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  12883. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  12884. );
  12885. return point;
  12886. }
  12887. copy( source ) {
  12888. super.copy( source );
  12889. this.v0.copy( source.v0 );
  12890. this.v1.copy( source.v1 );
  12891. this.v2.copy( source.v2 );
  12892. this.v3.copy( source.v3 );
  12893. return this;
  12894. }
  12895. toJSON() {
  12896. const data = super.toJSON();
  12897. data.v0 = this.v0.toArray();
  12898. data.v1 = this.v1.toArray();
  12899. data.v2 = this.v2.toArray();
  12900. data.v3 = this.v3.toArray();
  12901. return data;
  12902. }
  12903. fromJSON( json ) {
  12904. super.fromJSON( json );
  12905. this.v0.fromArray( json.v0 );
  12906. this.v1.fromArray( json.v1 );
  12907. this.v2.fromArray( json.v2 );
  12908. this.v3.fromArray( json.v3 );
  12909. return this;
  12910. }
  12911. }
  12912. class LineCurve extends Curve {
  12913. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  12914. super();
  12915. this.isLineCurve = true;
  12916. this.type = 'LineCurve';
  12917. this.v1 = v1;
  12918. this.v2 = v2;
  12919. }
  12920. getPoint( t, optionalTarget = new Vector2() ) {
  12921. const point = optionalTarget;
  12922. if ( t === 1 ) {
  12923. point.copy( this.v2 );
  12924. } else {
  12925. point.copy( this.v2 ).sub( this.v1 );
  12926. point.multiplyScalar( t ).add( this.v1 );
  12927. }
  12928. return point;
  12929. }
  12930. // Line curve is linear, so we can overwrite default getPointAt
  12931. getPointAt( u, optionalTarget ) {
  12932. return this.getPoint( u, optionalTarget );
  12933. }
  12934. getTangent( t, optionalTarget = new Vector2() ) {
  12935. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  12936. }
  12937. getTangentAt( u, optionalTarget ) {
  12938. return this.getTangent( u, optionalTarget );
  12939. }
  12940. copy( source ) {
  12941. super.copy( source );
  12942. this.v1.copy( source.v1 );
  12943. this.v2.copy( source.v2 );
  12944. return this;
  12945. }
  12946. toJSON() {
  12947. const data = super.toJSON();
  12948. data.v1 = this.v1.toArray();
  12949. data.v2 = this.v2.toArray();
  12950. return data;
  12951. }
  12952. fromJSON( json ) {
  12953. super.fromJSON( json );
  12954. this.v1.fromArray( json.v1 );
  12955. this.v2.fromArray( json.v2 );
  12956. return this;
  12957. }
  12958. }
  12959. class LineCurve3 extends Curve {
  12960. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  12961. super();
  12962. this.isLineCurve3 = true;
  12963. this.type = 'LineCurve3';
  12964. this.v1 = v1;
  12965. this.v2 = v2;
  12966. }
  12967. getPoint( t, optionalTarget = new Vector3() ) {
  12968. const point = optionalTarget;
  12969. if ( t === 1 ) {
  12970. point.copy( this.v2 );
  12971. } else {
  12972. point.copy( this.v2 ).sub( this.v1 );
  12973. point.multiplyScalar( t ).add( this.v1 );
  12974. }
  12975. return point;
  12976. }
  12977. // Line curve is linear, so we can overwrite default getPointAt
  12978. getPointAt( u, optionalTarget ) {
  12979. return this.getPoint( u, optionalTarget );
  12980. }
  12981. getTangent( t, optionalTarget = new Vector3() ) {
  12982. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  12983. }
  12984. getTangentAt( u, optionalTarget ) {
  12985. return this.getTangent( u, optionalTarget );
  12986. }
  12987. copy( source ) {
  12988. super.copy( source );
  12989. this.v1.copy( source.v1 );
  12990. this.v2.copy( source.v2 );
  12991. return this;
  12992. }
  12993. toJSON() {
  12994. const data = super.toJSON();
  12995. data.v1 = this.v1.toArray();
  12996. data.v2 = this.v2.toArray();
  12997. return data;
  12998. }
  12999. fromJSON( json ) {
  13000. super.fromJSON( json );
  13001. this.v1.fromArray( json.v1 );
  13002. this.v2.fromArray( json.v2 );
  13003. return this;
  13004. }
  13005. }
  13006. class QuadraticBezierCurve extends Curve {
  13007. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  13008. super();
  13009. this.isQuadraticBezierCurve = true;
  13010. this.type = 'QuadraticBezierCurve';
  13011. this.v0 = v0;
  13012. this.v1 = v1;
  13013. this.v2 = v2;
  13014. }
  13015. getPoint( t, optionalTarget = new Vector2() ) {
  13016. const point = optionalTarget;
  13017. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  13018. point.set(
  13019. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  13020. QuadraticBezier( t, v0.y, v1.y, v2.y )
  13021. );
  13022. return point;
  13023. }
  13024. copy( source ) {
  13025. super.copy( source );
  13026. this.v0.copy( source.v0 );
  13027. this.v1.copy( source.v1 );
  13028. this.v2.copy( source.v2 );
  13029. return this;
  13030. }
  13031. toJSON() {
  13032. const data = super.toJSON();
  13033. data.v0 = this.v0.toArray();
  13034. data.v1 = this.v1.toArray();
  13035. data.v2 = this.v2.toArray();
  13036. return data;
  13037. }
  13038. fromJSON( json ) {
  13039. super.fromJSON( json );
  13040. this.v0.fromArray( json.v0 );
  13041. this.v1.fromArray( json.v1 );
  13042. this.v2.fromArray( json.v2 );
  13043. return this;
  13044. }
  13045. }
  13046. class QuadraticBezierCurve3 extends Curve {
  13047. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  13048. super();
  13049. this.isQuadraticBezierCurve3 = true;
  13050. this.type = 'QuadraticBezierCurve3';
  13051. this.v0 = v0;
  13052. this.v1 = v1;
  13053. this.v2 = v2;
  13054. }
  13055. getPoint( t, optionalTarget = new Vector3() ) {
  13056. const point = optionalTarget;
  13057. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  13058. point.set(
  13059. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  13060. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  13061. QuadraticBezier( t, v0.z, v1.z, v2.z )
  13062. );
  13063. return point;
  13064. }
  13065. copy( source ) {
  13066. super.copy( source );
  13067. this.v0.copy( source.v0 );
  13068. this.v1.copy( source.v1 );
  13069. this.v2.copy( source.v2 );
  13070. return this;
  13071. }
  13072. toJSON() {
  13073. const data = super.toJSON();
  13074. data.v0 = this.v0.toArray();
  13075. data.v1 = this.v1.toArray();
  13076. data.v2 = this.v2.toArray();
  13077. return data;
  13078. }
  13079. fromJSON( json ) {
  13080. super.fromJSON( json );
  13081. this.v0.fromArray( json.v0 );
  13082. this.v1.fromArray( json.v1 );
  13083. this.v2.fromArray( json.v2 );
  13084. return this;
  13085. }
  13086. }
  13087. class SplineCurve extends Curve {
  13088. constructor( points = [] ) {
  13089. super();
  13090. this.isSplineCurve = true;
  13091. this.type = 'SplineCurve';
  13092. this.points = points;
  13093. }
  13094. getPoint( t, optionalTarget = new Vector2() ) {
  13095. const point = optionalTarget;
  13096. const points = this.points;
  13097. const p = ( points.length - 1 ) * t;
  13098. const intPoint = Math.floor( p );
  13099. const weight = p - intPoint;
  13100. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  13101. const p1 = points[ intPoint ];
  13102. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  13103. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  13104. point.set(
  13105. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  13106. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  13107. );
  13108. return point;
  13109. }
  13110. copy( source ) {
  13111. super.copy( source );
  13112. this.points = [];
  13113. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  13114. const point = source.points[ i ];
  13115. this.points.push( point.clone() );
  13116. }
  13117. return this;
  13118. }
  13119. toJSON() {
  13120. const data = super.toJSON();
  13121. data.points = [];
  13122. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  13123. const point = this.points[ i ];
  13124. data.points.push( point.toArray() );
  13125. }
  13126. return data;
  13127. }
  13128. fromJSON( json ) {
  13129. super.fromJSON( json );
  13130. this.points = [];
  13131. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  13132. const point = json.points[ i ];
  13133. this.points.push( new Vector2().fromArray( point ) );
  13134. }
  13135. return this;
  13136. }
  13137. }
  13138. var Curves = /*#__PURE__*/Object.freeze({
  13139. __proto__: null,
  13140. ArcCurve: ArcCurve,
  13141. CatmullRomCurve3: CatmullRomCurve3,
  13142. CubicBezierCurve: CubicBezierCurve,
  13143. CubicBezierCurve3: CubicBezierCurve3,
  13144. EllipseCurve: EllipseCurve,
  13145. LineCurve: LineCurve,
  13146. LineCurve3: LineCurve3,
  13147. QuadraticBezierCurve: QuadraticBezierCurve,
  13148. QuadraticBezierCurve3: QuadraticBezierCurve3,
  13149. SplineCurve: SplineCurve
  13150. });
  13151. /**************************************************************
  13152. * Curved Path - a curve path is simply a array of connected
  13153. * curves, but retains the api of a curve
  13154. **************************************************************/
  13155. class CurvePath extends Curve {
  13156. constructor() {
  13157. super();
  13158. this.type = 'CurvePath';
  13159. this.curves = [];
  13160. this.autoClose = false; // Automatically closes the path
  13161. }
  13162. add( curve ) {
  13163. this.curves.push( curve );
  13164. }
  13165. closePath() {
  13166. // Add a line curve if start and end of lines are not connected
  13167. const startPoint = this.curves[ 0 ].getPoint( 0 );
  13168. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  13169. if ( ! startPoint.equals( endPoint ) ) {
  13170. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  13171. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  13172. }
  13173. return this;
  13174. }
  13175. // To get accurate point with reference to
  13176. // entire path distance at time t,
  13177. // following has to be done:
  13178. // 1. Length of each sub path have to be known
  13179. // 2. Locate and identify type of curve
  13180. // 3. Get t for the curve
  13181. // 4. Return curve.getPointAt(t')
  13182. getPoint( t, optionalTarget ) {
  13183. const d = t * this.getLength();
  13184. const curveLengths = this.getCurveLengths();
  13185. let i = 0;
  13186. // To think about boundaries points.
  13187. while ( i < curveLengths.length ) {
  13188. if ( curveLengths[ i ] >= d ) {
  13189. const diff = curveLengths[ i ] - d;
  13190. const curve = this.curves[ i ];
  13191. const segmentLength = curve.getLength();
  13192. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  13193. return curve.getPointAt( u, optionalTarget );
  13194. }
  13195. i ++;
  13196. }
  13197. return null;
  13198. // loop where sum != 0, sum > d , sum+1 <d
  13199. }
  13200. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  13201. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  13202. // getPoint() depends on getLength
  13203. getLength() {
  13204. const lens = this.getCurveLengths();
  13205. return lens[ lens.length - 1 ];
  13206. }
  13207. // cacheLengths must be recalculated.
  13208. updateArcLengths() {
  13209. this.needsUpdate = true;
  13210. this.cacheLengths = null;
  13211. this.getCurveLengths();
  13212. }
  13213. // Compute lengths and cache them
  13214. // We cannot overwrite getLengths() because UtoT mapping uses it.
  13215. getCurveLengths() {
  13216. // We use cache values if curves and cache array are same length
  13217. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  13218. return this.cacheLengths;
  13219. }
  13220. // Get length of sub-curve
  13221. // Push sums into cached array
  13222. const lengths = [];
  13223. let sums = 0;
  13224. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  13225. sums += this.curves[ i ].getLength();
  13226. lengths.push( sums );
  13227. }
  13228. this.cacheLengths = lengths;
  13229. return lengths;
  13230. }
  13231. getSpacedPoints( divisions = 40 ) {
  13232. const points = [];
  13233. for ( let i = 0; i <= divisions; i ++ ) {
  13234. points.push( this.getPoint( i / divisions ) );
  13235. }
  13236. if ( this.autoClose ) {
  13237. points.push( points[ 0 ] );
  13238. }
  13239. return points;
  13240. }
  13241. getPoints( divisions = 12 ) {
  13242. const points = [];
  13243. let last;
  13244. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  13245. const curve = curves[ i ];
  13246. const resolution = curve.isEllipseCurve ? divisions * 2
  13247. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  13248. : curve.isSplineCurve ? divisions * curve.points.length
  13249. : divisions;
  13250. const pts = curve.getPoints( resolution );
  13251. for ( let j = 0; j < pts.length; j ++ ) {
  13252. const point = pts[ j ];
  13253. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  13254. points.push( point );
  13255. last = point;
  13256. }
  13257. }
  13258. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  13259. points.push( points[ 0 ] );
  13260. }
  13261. return points;
  13262. }
  13263. copy( source ) {
  13264. super.copy( source );
  13265. this.curves = [];
  13266. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  13267. const curve = source.curves[ i ];
  13268. this.curves.push( curve.clone() );
  13269. }
  13270. this.autoClose = source.autoClose;
  13271. return this;
  13272. }
  13273. toJSON() {
  13274. const data = super.toJSON();
  13275. data.autoClose = this.autoClose;
  13276. data.curves = [];
  13277. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  13278. const curve = this.curves[ i ];
  13279. data.curves.push( curve.toJSON() );
  13280. }
  13281. return data;
  13282. }
  13283. fromJSON( json ) {
  13284. super.fromJSON( json );
  13285. this.autoClose = json.autoClose;
  13286. this.curves = [];
  13287. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  13288. const curve = json.curves[ i ];
  13289. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  13290. }
  13291. return this;
  13292. }
  13293. }
  13294. class Path extends CurvePath {
  13295. constructor( points ) {
  13296. super();
  13297. this.type = 'Path';
  13298. this.currentPoint = new Vector2();
  13299. if ( points ) {
  13300. this.setFromPoints( points );
  13301. }
  13302. }
  13303. setFromPoints( points ) {
  13304. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  13305. for ( let i = 1, l = points.length; i < l; i ++ ) {
  13306. this.lineTo( points[ i ].x, points[ i ].y );
  13307. }
  13308. return this;
  13309. }
  13310. moveTo( x, y ) {
  13311. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  13312. return this;
  13313. }
  13314. lineTo( x, y ) {
  13315. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  13316. this.curves.push( curve );
  13317. this.currentPoint.set( x, y );
  13318. return this;
  13319. }
  13320. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  13321. const curve = new QuadraticBezierCurve(
  13322. this.currentPoint.clone(),
  13323. new Vector2( aCPx, aCPy ),
  13324. new Vector2( aX, aY )
  13325. );
  13326. this.curves.push( curve );
  13327. this.currentPoint.set( aX, aY );
  13328. return this;
  13329. }
  13330. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  13331. const curve = new CubicBezierCurve(
  13332. this.currentPoint.clone(),
  13333. new Vector2( aCP1x, aCP1y ),
  13334. new Vector2( aCP2x, aCP2y ),
  13335. new Vector2( aX, aY )
  13336. );
  13337. this.curves.push( curve );
  13338. this.currentPoint.set( aX, aY );
  13339. return this;
  13340. }
  13341. splineThru( pts /*Array of Vector*/ ) {
  13342. const npts = [ this.currentPoint.clone() ].concat( pts );
  13343. const curve = new SplineCurve( npts );
  13344. this.curves.push( curve );
  13345. this.currentPoint.copy( pts[ pts.length - 1 ] );
  13346. return this;
  13347. }
  13348. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  13349. const x0 = this.currentPoint.x;
  13350. const y0 = this.currentPoint.y;
  13351. this.absarc( aX + x0, aY + y0, aRadius,
  13352. aStartAngle, aEndAngle, aClockwise );
  13353. return this;
  13354. }
  13355. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  13356. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  13357. return this;
  13358. }
  13359. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  13360. const x0 = this.currentPoint.x;
  13361. const y0 = this.currentPoint.y;
  13362. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  13363. return this;
  13364. }
  13365. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  13366. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  13367. if ( this.curves.length > 0 ) {
  13368. // if a previous curve is present, attempt to join
  13369. const firstPoint = curve.getPoint( 0 );
  13370. if ( ! firstPoint.equals( this.currentPoint ) ) {
  13371. this.lineTo( firstPoint.x, firstPoint.y );
  13372. }
  13373. }
  13374. this.curves.push( curve );
  13375. const lastPoint = curve.getPoint( 1 );
  13376. this.currentPoint.copy( lastPoint );
  13377. return this;
  13378. }
  13379. copy( source ) {
  13380. super.copy( source );
  13381. this.currentPoint.copy( source.currentPoint );
  13382. return this;
  13383. }
  13384. toJSON() {
  13385. const data = super.toJSON();
  13386. data.currentPoint = this.currentPoint.toArray();
  13387. return data;
  13388. }
  13389. fromJSON( json ) {
  13390. super.fromJSON( json );
  13391. this.currentPoint.fromArray( json.currentPoint );
  13392. return this;
  13393. }
  13394. }
  13395. class LatheGeometry extends BufferGeometry {
  13396. constructor( points = [ new Vector2( 0, -0.5 ), new Vector2( 0.5, 0 ), new Vector2( 0, 0.5 ) ], segments = 12, phiStart = 0, phiLength = Math.PI * 2 ) {
  13397. super();
  13398. this.type = 'LatheGeometry';
  13399. this.parameters = {
  13400. points: points,
  13401. segments: segments,
  13402. phiStart: phiStart,
  13403. phiLength: phiLength
  13404. };
  13405. segments = Math.floor( segments );
  13406. // clamp phiLength so it's in range of [ 0, 2PI ]
  13407. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  13408. // buffers
  13409. const indices = [];
  13410. const vertices = [];
  13411. const uvs = [];
  13412. const initNormals = [];
  13413. const normals = [];
  13414. // helper variables
  13415. const inverseSegments = 1.0 / segments;
  13416. const vertex = new Vector3();
  13417. const uv = new Vector2();
  13418. const normal = new Vector3();
  13419. const curNormal = new Vector3();
  13420. const prevNormal = new Vector3();
  13421. let dx = 0;
  13422. let dy = 0;
  13423. // pre-compute normals for initial "meridian"
  13424. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  13425. switch ( j ) {
  13426. case 0: // special handling for 1st vertex on path
  13427. dx = points[ j + 1 ].x - points[ j ].x;
  13428. dy = points[ j + 1 ].y - points[ j ].y;
  13429. normal.x = dy * 1.0;
  13430. normal.y = - dx;
  13431. normal.z = dy * 0.0;
  13432. prevNormal.copy( normal );
  13433. normal.normalize();
  13434. initNormals.push( normal.x, normal.y, normal.z );
  13435. break;
  13436. case ( points.length - 1 ): // special handling for last Vertex on path
  13437. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  13438. break;
  13439. default: // default handling for all vertices in between
  13440. dx = points[ j + 1 ].x - points[ j ].x;
  13441. dy = points[ j + 1 ].y - points[ j ].y;
  13442. normal.x = dy * 1.0;
  13443. normal.y = - dx;
  13444. normal.z = dy * 0.0;
  13445. curNormal.copy( normal );
  13446. normal.x += prevNormal.x;
  13447. normal.y += prevNormal.y;
  13448. normal.z += prevNormal.z;
  13449. normal.normalize();
  13450. initNormals.push( normal.x, normal.y, normal.z );
  13451. prevNormal.copy( curNormal );
  13452. }
  13453. }
  13454. // generate vertices, uvs and normals
  13455. for ( let i = 0; i <= segments; i ++ ) {
  13456. const phi = phiStart + i * inverseSegments * phiLength;
  13457. const sin = Math.sin( phi );
  13458. const cos = Math.cos( phi );
  13459. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  13460. // vertex
  13461. vertex.x = points[ j ].x * sin;
  13462. vertex.y = points[ j ].y;
  13463. vertex.z = points[ j ].x * cos;
  13464. vertices.push( vertex.x, vertex.y, vertex.z );
  13465. // uv
  13466. uv.x = i / segments;
  13467. uv.y = j / ( points.length - 1 );
  13468. uvs.push( uv.x, uv.y );
  13469. // normal
  13470. const x = initNormals[ 3 * j + 0 ] * sin;
  13471. const y = initNormals[ 3 * j + 1 ];
  13472. const z = initNormals[ 3 * j + 0 ] * cos;
  13473. normals.push( x, y, z );
  13474. }
  13475. }
  13476. // indices
  13477. for ( let i = 0; i < segments; i ++ ) {
  13478. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  13479. const base = j + i * points.length;
  13480. const a = base;
  13481. const b = base + points.length;
  13482. const c = base + points.length + 1;
  13483. const d = base + 1;
  13484. // faces
  13485. indices.push( a, b, d );
  13486. indices.push( c, d, b );
  13487. }
  13488. }
  13489. // build geometry
  13490. this.setIndex( indices );
  13491. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13492. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13493. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13494. }
  13495. copy( source ) {
  13496. super.copy( source );
  13497. this.parameters = Object.assign( {}, source.parameters );
  13498. return this;
  13499. }
  13500. static fromJSON( data ) {
  13501. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  13502. }
  13503. }
  13504. class CapsuleGeometry extends LatheGeometry {
  13505. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  13506. const path = new Path();
  13507. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  13508. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  13509. super( path.getPoints( capSegments ), radialSegments );
  13510. this.type = 'CapsuleGeometry';
  13511. this.parameters = {
  13512. radius: radius,
  13513. length: length,
  13514. capSegments: capSegments,
  13515. radialSegments: radialSegments,
  13516. };
  13517. }
  13518. static fromJSON( data ) {
  13519. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  13520. }
  13521. }
  13522. class CircleGeometry extends BufferGeometry {
  13523. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  13524. super();
  13525. this.type = 'CircleGeometry';
  13526. this.parameters = {
  13527. radius: radius,
  13528. segments: segments,
  13529. thetaStart: thetaStart,
  13530. thetaLength: thetaLength
  13531. };
  13532. segments = Math.max( 3, segments );
  13533. // buffers
  13534. const indices = [];
  13535. const vertices = [];
  13536. const normals = [];
  13537. const uvs = [];
  13538. // helper variables
  13539. const vertex = new Vector3();
  13540. const uv = new Vector2();
  13541. // center point
  13542. vertices.push( 0, 0, 0 );
  13543. normals.push( 0, 0, 1 );
  13544. uvs.push( 0.5, 0.5 );
  13545. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  13546. const segment = thetaStart + s / segments * thetaLength;
  13547. // vertex
  13548. vertex.x = radius * Math.cos( segment );
  13549. vertex.y = radius * Math.sin( segment );
  13550. vertices.push( vertex.x, vertex.y, vertex.z );
  13551. // normal
  13552. normals.push( 0, 0, 1 );
  13553. // uvs
  13554. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  13555. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  13556. uvs.push( uv.x, uv.y );
  13557. }
  13558. // indices
  13559. for ( let i = 1; i <= segments; i ++ ) {
  13560. indices.push( i, i + 1, 0 );
  13561. }
  13562. // build geometry
  13563. this.setIndex( indices );
  13564. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13565. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13566. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13567. }
  13568. copy( source ) {
  13569. super.copy( source );
  13570. this.parameters = Object.assign( {}, source.parameters );
  13571. return this;
  13572. }
  13573. static fromJSON( data ) {
  13574. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  13575. }
  13576. }
  13577. class CylinderGeometry extends BufferGeometry {
  13578. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  13579. super();
  13580. this.type = 'CylinderGeometry';
  13581. this.parameters = {
  13582. radiusTop: radiusTop,
  13583. radiusBottom: radiusBottom,
  13584. height: height,
  13585. radialSegments: radialSegments,
  13586. heightSegments: heightSegments,
  13587. openEnded: openEnded,
  13588. thetaStart: thetaStart,
  13589. thetaLength: thetaLength
  13590. };
  13591. const scope = this;
  13592. radialSegments = Math.floor( radialSegments );
  13593. heightSegments = Math.floor( heightSegments );
  13594. // buffers
  13595. const indices = [];
  13596. const vertices = [];
  13597. const normals = [];
  13598. const uvs = [];
  13599. // helper variables
  13600. let index = 0;
  13601. const indexArray = [];
  13602. const halfHeight = height / 2;
  13603. let groupStart = 0;
  13604. // generate geometry
  13605. generateTorso();
  13606. if ( openEnded === false ) {
  13607. if ( radiusTop > 0 ) generateCap( true );
  13608. if ( radiusBottom > 0 ) generateCap( false );
  13609. }
  13610. // build geometry
  13611. this.setIndex( indices );
  13612. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13613. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13614. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13615. function generateTorso() {
  13616. const normal = new Vector3();
  13617. const vertex = new Vector3();
  13618. let groupCount = 0;
  13619. // this will be used to calculate the normal
  13620. const slope = ( radiusBottom - radiusTop ) / height;
  13621. // generate vertices, normals and uvs
  13622. for ( let y = 0; y <= heightSegments; y ++ ) {
  13623. const indexRow = [];
  13624. const v = y / heightSegments;
  13625. // calculate the radius of the current row
  13626. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  13627. for ( let x = 0; x <= radialSegments; x ++ ) {
  13628. const u = x / radialSegments;
  13629. const theta = u * thetaLength + thetaStart;
  13630. const sinTheta = Math.sin( theta );
  13631. const cosTheta = Math.cos( theta );
  13632. // vertex
  13633. vertex.x = radius * sinTheta;
  13634. vertex.y = - v * height + halfHeight;
  13635. vertex.z = radius * cosTheta;
  13636. vertices.push( vertex.x, vertex.y, vertex.z );
  13637. // normal
  13638. normal.set( sinTheta, slope, cosTheta ).normalize();
  13639. normals.push( normal.x, normal.y, normal.z );
  13640. // uv
  13641. uvs.push( u, 1 - v );
  13642. // save index of vertex in respective row
  13643. indexRow.push( index ++ );
  13644. }
  13645. // now save vertices of the row in our index array
  13646. indexArray.push( indexRow );
  13647. }
  13648. // generate indices
  13649. for ( let x = 0; x < radialSegments; x ++ ) {
  13650. for ( let y = 0; y < heightSegments; y ++ ) {
  13651. // we use the index array to access the correct indices
  13652. const a = indexArray[ y ][ x ];
  13653. const b = indexArray[ y + 1 ][ x ];
  13654. const c = indexArray[ y + 1 ][ x + 1 ];
  13655. const d = indexArray[ y ][ x + 1 ];
  13656. // faces
  13657. if ( radiusTop > 0 || y !== 0 ) {
  13658. indices.push( a, b, d );
  13659. groupCount += 3;
  13660. }
  13661. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  13662. indices.push( b, c, d );
  13663. groupCount += 3;
  13664. }
  13665. }
  13666. }
  13667. // add a group to the geometry. this will ensure multi material support
  13668. scope.addGroup( groupStart, groupCount, 0 );
  13669. // calculate new start value for groups
  13670. groupStart += groupCount;
  13671. }
  13672. function generateCap( top ) {
  13673. // save the index of the first center vertex
  13674. const centerIndexStart = index;
  13675. const uv = new Vector2();
  13676. const vertex = new Vector3();
  13677. let groupCount = 0;
  13678. const radius = ( top === true ) ? radiusTop : radiusBottom;
  13679. const sign = ( top === true ) ? 1 : -1;
  13680. // first we generate the center vertex data of the cap.
  13681. // because the geometry needs one set of uvs per face,
  13682. // we must generate a center vertex per face/segment
  13683. for ( let x = 1; x <= radialSegments; x ++ ) {
  13684. // vertex
  13685. vertices.push( 0, halfHeight * sign, 0 );
  13686. // normal
  13687. normals.push( 0, sign, 0 );
  13688. // uv
  13689. uvs.push( 0.5, 0.5 );
  13690. // increase index
  13691. index ++;
  13692. }
  13693. // save the index of the last center vertex
  13694. const centerIndexEnd = index;
  13695. // now we generate the surrounding vertices, normals and uvs
  13696. for ( let x = 0; x <= radialSegments; x ++ ) {
  13697. const u = x / radialSegments;
  13698. const theta = u * thetaLength + thetaStart;
  13699. const cosTheta = Math.cos( theta );
  13700. const sinTheta = Math.sin( theta );
  13701. // vertex
  13702. vertex.x = radius * sinTheta;
  13703. vertex.y = halfHeight * sign;
  13704. vertex.z = radius * cosTheta;
  13705. vertices.push( vertex.x, vertex.y, vertex.z );
  13706. // normal
  13707. normals.push( 0, sign, 0 );
  13708. // uv
  13709. uv.x = ( cosTheta * 0.5 ) + 0.5;
  13710. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  13711. uvs.push( uv.x, uv.y );
  13712. // increase index
  13713. index ++;
  13714. }
  13715. // generate indices
  13716. for ( let x = 0; x < radialSegments; x ++ ) {
  13717. const c = centerIndexStart + x;
  13718. const i = centerIndexEnd + x;
  13719. if ( top === true ) {
  13720. // face top
  13721. indices.push( i, i + 1, c );
  13722. } else {
  13723. // face bottom
  13724. indices.push( i + 1, i, c );
  13725. }
  13726. groupCount += 3;
  13727. }
  13728. // add a group to the geometry. this will ensure multi material support
  13729. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  13730. // calculate new start value for groups
  13731. groupStart += groupCount;
  13732. }
  13733. }
  13734. copy( source ) {
  13735. super.copy( source );
  13736. this.parameters = Object.assign( {}, source.parameters );
  13737. return this;
  13738. }
  13739. static fromJSON( data ) {
  13740. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  13741. }
  13742. }
  13743. class ConeGeometry extends CylinderGeometry {
  13744. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  13745. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  13746. this.type = 'ConeGeometry';
  13747. this.parameters = {
  13748. radius: radius,
  13749. height: height,
  13750. radialSegments: radialSegments,
  13751. heightSegments: heightSegments,
  13752. openEnded: openEnded,
  13753. thetaStart: thetaStart,
  13754. thetaLength: thetaLength
  13755. };
  13756. }
  13757. static fromJSON( data ) {
  13758. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  13759. }
  13760. }
  13761. class PolyhedronGeometry extends BufferGeometry {
  13762. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  13763. super();
  13764. this.type = 'PolyhedronGeometry';
  13765. this.parameters = {
  13766. vertices: vertices,
  13767. indices: indices,
  13768. radius: radius,
  13769. detail: detail
  13770. };
  13771. // default buffer data
  13772. const vertexBuffer = [];
  13773. const uvBuffer = [];
  13774. // the subdivision creates the vertex buffer data
  13775. subdivide( detail );
  13776. // all vertices should lie on a conceptual sphere with a given radius
  13777. applyRadius( radius );
  13778. // finally, create the uv data
  13779. generateUVs();
  13780. // build non-indexed geometry
  13781. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  13782. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  13783. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  13784. if ( detail === 0 ) {
  13785. this.computeVertexNormals(); // flat normals
  13786. } else {
  13787. this.normalizeNormals(); // smooth normals
  13788. }
  13789. // helper functions
  13790. function subdivide( detail ) {
  13791. const a = new Vector3();
  13792. const b = new Vector3();
  13793. const c = new Vector3();
  13794. // iterate over all faces and apply a subdivision with the given detail value
  13795. for ( let i = 0; i < indices.length; i += 3 ) {
  13796. // get the vertices of the face
  13797. getVertexByIndex( indices[ i + 0 ], a );
  13798. getVertexByIndex( indices[ i + 1 ], b );
  13799. getVertexByIndex( indices[ i + 2 ], c );
  13800. // perform subdivision
  13801. subdivideFace( a, b, c, detail );
  13802. }
  13803. }
  13804. function subdivideFace( a, b, c, detail ) {
  13805. const cols = detail + 1;
  13806. // we use this multidimensional array as a data structure for creating the subdivision
  13807. const v = [];
  13808. // construct all of the vertices for this subdivision
  13809. for ( let i = 0; i <= cols; i ++ ) {
  13810. v[ i ] = [];
  13811. const aj = a.clone().lerp( c, i / cols );
  13812. const bj = b.clone().lerp( c, i / cols );
  13813. const rows = cols - i;
  13814. for ( let j = 0; j <= rows; j ++ ) {
  13815. if ( j === 0 && i === cols ) {
  13816. v[ i ][ j ] = aj;
  13817. } else {
  13818. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  13819. }
  13820. }
  13821. }
  13822. // construct all of the faces
  13823. for ( let i = 0; i < cols; i ++ ) {
  13824. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  13825. const k = Math.floor( j / 2 );
  13826. if ( j % 2 === 0 ) {
  13827. pushVertex( v[ i ][ k + 1 ] );
  13828. pushVertex( v[ i + 1 ][ k ] );
  13829. pushVertex( v[ i ][ k ] );
  13830. } else {
  13831. pushVertex( v[ i ][ k + 1 ] );
  13832. pushVertex( v[ i + 1 ][ k + 1 ] );
  13833. pushVertex( v[ i + 1 ][ k ] );
  13834. }
  13835. }
  13836. }
  13837. }
  13838. function applyRadius( radius ) {
  13839. const vertex = new Vector3();
  13840. // iterate over the entire buffer and apply the radius to each vertex
  13841. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  13842. vertex.x = vertexBuffer[ i + 0 ];
  13843. vertex.y = vertexBuffer[ i + 1 ];
  13844. vertex.z = vertexBuffer[ i + 2 ];
  13845. vertex.normalize().multiplyScalar( radius );
  13846. vertexBuffer[ i + 0 ] = vertex.x;
  13847. vertexBuffer[ i + 1 ] = vertex.y;
  13848. vertexBuffer[ i + 2 ] = vertex.z;
  13849. }
  13850. }
  13851. function generateUVs() {
  13852. const vertex = new Vector3();
  13853. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  13854. vertex.x = vertexBuffer[ i + 0 ];
  13855. vertex.y = vertexBuffer[ i + 1 ];
  13856. vertex.z = vertexBuffer[ i + 2 ];
  13857. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  13858. const v = inclination( vertex ) / Math.PI + 0.5;
  13859. uvBuffer.push( u, 1 - v );
  13860. }
  13861. correctUVs();
  13862. correctSeam();
  13863. }
  13864. function correctSeam() {
  13865. // handle case when face straddles the seam, see #3269
  13866. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  13867. // uv data of a single face
  13868. const x0 = uvBuffer[ i + 0 ];
  13869. const x1 = uvBuffer[ i + 2 ];
  13870. const x2 = uvBuffer[ i + 4 ];
  13871. const max = Math.max( x0, x1, x2 );
  13872. const min = Math.min( x0, x1, x2 );
  13873. // 0.9 is somewhat arbitrary
  13874. if ( max > 0.9 && min < 0.1 ) {
  13875. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  13876. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  13877. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  13878. }
  13879. }
  13880. }
  13881. function pushVertex( vertex ) {
  13882. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  13883. }
  13884. function getVertexByIndex( index, vertex ) {
  13885. const stride = index * 3;
  13886. vertex.x = vertices[ stride + 0 ];
  13887. vertex.y = vertices[ stride + 1 ];
  13888. vertex.z = vertices[ stride + 2 ];
  13889. }
  13890. function correctUVs() {
  13891. const a = new Vector3();
  13892. const b = new Vector3();
  13893. const c = new Vector3();
  13894. const centroid = new Vector3();
  13895. const uvA = new Vector2();
  13896. const uvB = new Vector2();
  13897. const uvC = new Vector2();
  13898. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  13899. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  13900. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  13901. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  13902. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  13903. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  13904. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  13905. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  13906. const azi = azimuth( centroid );
  13907. correctUV( uvA, j + 0, a, azi );
  13908. correctUV( uvB, j + 2, b, azi );
  13909. correctUV( uvC, j + 4, c, azi );
  13910. }
  13911. }
  13912. function correctUV( uv, stride, vector, azimuth ) {
  13913. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  13914. uvBuffer[ stride ] = uv.x - 1;
  13915. }
  13916. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  13917. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  13918. }
  13919. }
  13920. // Angle around the Y axis, counter-clockwise when looking from above.
  13921. function azimuth( vector ) {
  13922. return Math.atan2( vector.z, - vector.x );
  13923. }
  13924. // Angle above the XZ plane.
  13925. function inclination( vector ) {
  13926. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  13927. }
  13928. }
  13929. copy( source ) {
  13930. super.copy( source );
  13931. this.parameters = Object.assign( {}, source.parameters );
  13932. return this;
  13933. }
  13934. static fromJSON( data ) {
  13935. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  13936. }
  13937. }
  13938. class DodecahedronGeometry extends PolyhedronGeometry {
  13939. constructor( radius = 1, detail = 0 ) {
  13940. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  13941. const r = 1 / t;
  13942. const vertices = [
  13943. // (±1, ±1, ±1)
  13944. -1, -1, -1, -1, -1, 1,
  13945. -1, 1, -1, -1, 1, 1,
  13946. 1, -1, -1, 1, -1, 1,
  13947. 1, 1, -1, 1, 1, 1,
  13948. // (0, ±1/φ, ±φ)
  13949. 0, - r, - t, 0, - r, t,
  13950. 0, r, - t, 0, r, t,
  13951. // (±1/φ, ±φ, 0)
  13952. - r, - t, 0, - r, t, 0,
  13953. r, - t, 0, r, t, 0,
  13954. // (±φ, 0, ±1/φ)
  13955. - t, 0, - r, t, 0, - r,
  13956. - t, 0, r, t, 0, r
  13957. ];
  13958. const indices = [
  13959. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  13960. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  13961. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  13962. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  13963. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  13964. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  13965. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  13966. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  13967. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  13968. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  13969. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  13970. 1, 12, 14, 1, 14, 5, 1, 5, 9
  13971. ];
  13972. super( vertices, indices, radius, detail );
  13973. this.type = 'DodecahedronGeometry';
  13974. this.parameters = {
  13975. radius: radius,
  13976. detail: detail
  13977. };
  13978. }
  13979. static fromJSON( data ) {
  13980. return new DodecahedronGeometry( data.radius, data.detail );
  13981. }
  13982. }
  13983. const _v0 = /*@__PURE__*/ new Vector3();
  13984. const _v1$1 = /*@__PURE__*/ new Vector3();
  13985. const _normal = /*@__PURE__*/ new Vector3();
  13986. const _triangle = /*@__PURE__*/ new Triangle();
  13987. class EdgesGeometry extends BufferGeometry {
  13988. constructor( geometry = null, thresholdAngle = 1 ) {
  13989. super();
  13990. this.type = 'EdgesGeometry';
  13991. this.parameters = {
  13992. geometry: geometry,
  13993. thresholdAngle: thresholdAngle
  13994. };
  13995. if ( geometry !== null ) {
  13996. const precisionPoints = 4;
  13997. const precision = Math.pow( 10, precisionPoints );
  13998. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  13999. const indexAttr = geometry.getIndex();
  14000. const positionAttr = geometry.getAttribute( 'position' );
  14001. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  14002. const indexArr = [ 0, 0, 0 ];
  14003. const vertKeys = [ 'a', 'b', 'c' ];
  14004. const hashes = new Array( 3 );
  14005. const edgeData = {};
  14006. const vertices = [];
  14007. for ( let i = 0; i < indexCount; i += 3 ) {
  14008. if ( indexAttr ) {
  14009. indexArr[ 0 ] = indexAttr.getX( i );
  14010. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  14011. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  14012. } else {
  14013. indexArr[ 0 ] = i;
  14014. indexArr[ 1 ] = i + 1;
  14015. indexArr[ 2 ] = i + 2;
  14016. }
  14017. const { a, b, c } = _triangle;
  14018. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  14019. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  14020. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  14021. _triangle.getNormal( _normal );
  14022. // create hashes for the edge from the vertices
  14023. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  14024. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  14025. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  14026. // skip degenerate triangles
  14027. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  14028. continue;
  14029. }
  14030. // iterate over every edge
  14031. for ( let j = 0; j < 3; j ++ ) {
  14032. // get the first and next vertex making up the edge
  14033. const jNext = ( j + 1 ) % 3;
  14034. const vecHash0 = hashes[ j ];
  14035. const vecHash1 = hashes[ jNext ];
  14036. const v0 = _triangle[ vertKeys[ j ] ];
  14037. const v1 = _triangle[ vertKeys[ jNext ] ];
  14038. const hash = `${ vecHash0 }_${ vecHash1 }`;
  14039. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  14040. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  14041. // if we found a sibling edge add it into the vertex array if
  14042. // it meets the angle threshold and delete the edge from the map.
  14043. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  14044. vertices.push( v0.x, v0.y, v0.z );
  14045. vertices.push( v1.x, v1.y, v1.z );
  14046. }
  14047. edgeData[ reverseHash ] = null;
  14048. } else if ( ! ( hash in edgeData ) ) {
  14049. // if we've already got an edge here then skip adding a new one
  14050. edgeData[ hash ] = {
  14051. index0: indexArr[ j ],
  14052. index1: indexArr[ jNext ],
  14053. normal: _normal.clone(),
  14054. };
  14055. }
  14056. }
  14057. }
  14058. // iterate over all remaining, unmatched edges and add them to the vertex array
  14059. for ( const key in edgeData ) {
  14060. if ( edgeData[ key ] ) {
  14061. const { index0, index1 } = edgeData[ key ];
  14062. _v0.fromBufferAttribute( positionAttr, index0 );
  14063. _v1$1.fromBufferAttribute( positionAttr, index1 );
  14064. vertices.push( _v0.x, _v0.y, _v0.z );
  14065. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  14066. }
  14067. }
  14068. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  14069. }
  14070. }
  14071. copy( source ) {
  14072. super.copy( source );
  14073. this.parameters = Object.assign( {}, source.parameters );
  14074. return this;
  14075. }
  14076. }
  14077. class Shape extends Path {
  14078. constructor( points ) {
  14079. super( points );
  14080. this.uuid = generateUUID();
  14081. this.type = 'Shape';
  14082. this.holes = [];
  14083. }
  14084. getPointsHoles( divisions ) {
  14085. const holesPts = [];
  14086. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  14087. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  14088. }
  14089. return holesPts;
  14090. }
  14091. // get points of shape and holes (keypoints based on segments parameter)
  14092. extractPoints( divisions ) {
  14093. return {
  14094. shape: this.getPoints( divisions ),
  14095. holes: this.getPointsHoles( divisions )
  14096. };
  14097. }
  14098. copy( source ) {
  14099. super.copy( source );
  14100. this.holes = [];
  14101. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  14102. const hole = source.holes[ i ];
  14103. this.holes.push( hole.clone() );
  14104. }
  14105. return this;
  14106. }
  14107. toJSON() {
  14108. const data = super.toJSON();
  14109. data.uuid = this.uuid;
  14110. data.holes = [];
  14111. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  14112. const hole = this.holes[ i ];
  14113. data.holes.push( hole.toJSON() );
  14114. }
  14115. return data;
  14116. }
  14117. fromJSON( json ) {
  14118. super.fromJSON( json );
  14119. this.uuid = json.uuid;
  14120. this.holes = [];
  14121. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  14122. const hole = json.holes[ i ];
  14123. this.holes.push( new Path().fromJSON( hole ) );
  14124. }
  14125. return this;
  14126. }
  14127. }
  14128. /**
  14129. * Port from https://github.com/mapbox/earcut (v2.2.4)
  14130. */
  14131. const Earcut = {
  14132. triangulate: function ( data, holeIndices, dim = 2 ) {
  14133. const hasHoles = holeIndices && holeIndices.length;
  14134. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  14135. let outerNode = linkedList( data, 0, outerLen, dim, true );
  14136. const triangles = [];
  14137. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  14138. let minX, minY, maxX, maxY, x, y, invSize;
  14139. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  14140. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  14141. if ( data.length > 80 * dim ) {
  14142. minX = maxX = data[ 0 ];
  14143. minY = maxY = data[ 1 ];
  14144. for ( let i = dim; i < outerLen; i += dim ) {
  14145. x = data[ i ];
  14146. y = data[ i + 1 ];
  14147. if ( x < minX ) minX = x;
  14148. if ( y < minY ) minY = y;
  14149. if ( x > maxX ) maxX = x;
  14150. if ( y > maxY ) maxY = y;
  14151. }
  14152. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  14153. invSize = Math.max( maxX - minX, maxY - minY );
  14154. invSize = invSize !== 0 ? 32767 / invSize : 0;
  14155. }
  14156. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  14157. return triangles;
  14158. }
  14159. };
  14160. // create a circular doubly linked list from polygon points in the specified winding order
  14161. function linkedList( data, start, end, dim, clockwise ) {
  14162. let i, last;
  14163. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  14164. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  14165. } else {
  14166. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  14167. }
  14168. if ( last && equals( last, last.next ) ) {
  14169. removeNode( last );
  14170. last = last.next;
  14171. }
  14172. return last;
  14173. }
  14174. // eliminate colinear or duplicate points
  14175. function filterPoints( start, end ) {
  14176. if ( ! start ) return start;
  14177. if ( ! end ) end = start;
  14178. let p = start,
  14179. again;
  14180. do {
  14181. again = false;
  14182. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  14183. removeNode( p );
  14184. p = end = p.prev;
  14185. if ( p === p.next ) break;
  14186. again = true;
  14187. } else {
  14188. p = p.next;
  14189. }
  14190. } while ( again || p !== end );
  14191. return end;
  14192. }
  14193. // main ear slicing loop which triangulates a polygon (given as a linked list)
  14194. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  14195. if ( ! ear ) return;
  14196. // interlink polygon nodes in z-order
  14197. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  14198. let stop = ear,
  14199. prev, next;
  14200. // iterate through ears, slicing them one by one
  14201. while ( ear.prev !== ear.next ) {
  14202. prev = ear.prev;
  14203. next = ear.next;
  14204. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  14205. // cut off the triangle
  14206. triangles.push( prev.i / dim | 0 );
  14207. triangles.push( ear.i / dim | 0 );
  14208. triangles.push( next.i / dim | 0 );
  14209. removeNode( ear );
  14210. // skipping the next vertex leads to less sliver triangles
  14211. ear = next.next;
  14212. stop = next.next;
  14213. continue;
  14214. }
  14215. ear = next;
  14216. // if we looped through the whole remaining polygon and can't find any more ears
  14217. if ( ear === stop ) {
  14218. // try filtering points and slicing again
  14219. if ( ! pass ) {
  14220. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  14221. // if this didn't work, try curing all small self-intersections locally
  14222. } else if ( pass === 1 ) {
  14223. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  14224. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  14225. // as a last resort, try splitting the remaining polygon into two
  14226. } else if ( pass === 2 ) {
  14227. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  14228. }
  14229. break;
  14230. }
  14231. }
  14232. }
  14233. // check whether a polygon node forms a valid ear with adjacent nodes
  14234. function isEar( ear ) {
  14235. const a = ear.prev,
  14236. b = ear,
  14237. c = ear.next;
  14238. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  14239. // now make sure we don't have other points inside the potential ear
  14240. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  14241. // triangle bbox; min & max are calculated like this for speed
  14242. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  14243. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  14244. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  14245. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  14246. let p = c.next;
  14247. while ( p !== a ) {
  14248. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  14249. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  14250. area( p.prev, p, p.next ) >= 0 ) return false;
  14251. p = p.next;
  14252. }
  14253. return true;
  14254. }
  14255. function isEarHashed( ear, minX, minY, invSize ) {
  14256. const a = ear.prev,
  14257. b = ear,
  14258. c = ear.next;
  14259. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  14260. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  14261. // triangle bbox; min & max are calculated like this for speed
  14262. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  14263. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  14264. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  14265. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  14266. // z-order range for the current triangle bbox;
  14267. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  14268. maxZ = zOrder( x1, y1, minX, minY, invSize );
  14269. let p = ear.prevZ,
  14270. n = ear.nextZ;
  14271. // look for points inside the triangle in both directions
  14272. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  14273. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  14274. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  14275. p = p.prevZ;
  14276. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  14277. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  14278. n = n.nextZ;
  14279. }
  14280. // look for remaining points in decreasing z-order
  14281. while ( p && p.z >= minZ ) {
  14282. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  14283. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  14284. p = p.prevZ;
  14285. }
  14286. // look for remaining points in increasing z-order
  14287. while ( n && n.z <= maxZ ) {
  14288. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  14289. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  14290. n = n.nextZ;
  14291. }
  14292. return true;
  14293. }
  14294. // go through all polygon nodes and cure small local self-intersections
  14295. function cureLocalIntersections( start, triangles, dim ) {
  14296. let p = start;
  14297. do {
  14298. const a = p.prev,
  14299. b = p.next.next;
  14300. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  14301. triangles.push( a.i / dim | 0 );
  14302. triangles.push( p.i / dim | 0 );
  14303. triangles.push( b.i / dim | 0 );
  14304. // remove two nodes involved
  14305. removeNode( p );
  14306. removeNode( p.next );
  14307. p = start = b;
  14308. }
  14309. p = p.next;
  14310. } while ( p !== start );
  14311. return filterPoints( p );
  14312. }
  14313. // try splitting polygon into two and triangulate them independently
  14314. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  14315. // look for a valid diagonal that divides the polygon into two
  14316. let a = start;
  14317. do {
  14318. let b = a.next.next;
  14319. while ( b !== a.prev ) {
  14320. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  14321. // split the polygon in two by the diagonal
  14322. let c = splitPolygon( a, b );
  14323. // filter colinear points around the cuts
  14324. a = filterPoints( a, a.next );
  14325. c = filterPoints( c, c.next );
  14326. // run earcut on each half
  14327. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  14328. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  14329. return;
  14330. }
  14331. b = b.next;
  14332. }
  14333. a = a.next;
  14334. } while ( a !== start );
  14335. }
  14336. // link every hole into the outer loop, producing a single-ring polygon without holes
  14337. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  14338. const queue = [];
  14339. let i, len, start, end, list;
  14340. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  14341. start = holeIndices[ i ] * dim;
  14342. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  14343. list = linkedList( data, start, end, dim, false );
  14344. if ( list === list.next ) list.steiner = true;
  14345. queue.push( getLeftmost( list ) );
  14346. }
  14347. queue.sort( compareX );
  14348. // process holes from left to right
  14349. for ( i = 0; i < queue.length; i ++ ) {
  14350. outerNode = eliminateHole( queue[ i ], outerNode );
  14351. }
  14352. return outerNode;
  14353. }
  14354. function compareX( a, b ) {
  14355. return a.x - b.x;
  14356. }
  14357. // find a bridge between vertices that connects hole with an outer ring and link it
  14358. function eliminateHole( hole, outerNode ) {
  14359. const bridge = findHoleBridge( hole, outerNode );
  14360. if ( ! bridge ) {
  14361. return outerNode;
  14362. }
  14363. const bridgeReverse = splitPolygon( bridge, hole );
  14364. // filter collinear points around the cuts
  14365. filterPoints( bridgeReverse, bridgeReverse.next );
  14366. return filterPoints( bridge, bridge.next );
  14367. }
  14368. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  14369. function findHoleBridge( hole, outerNode ) {
  14370. let p = outerNode,
  14371. qx = - Infinity,
  14372. m;
  14373. const hx = hole.x, hy = hole.y;
  14374. // find a segment intersected by a ray from the hole's leftmost point to the left;
  14375. // segment's endpoint with lesser x will be potential connection point
  14376. do {
  14377. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  14378. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  14379. if ( x <= hx && x > qx ) {
  14380. qx = x;
  14381. m = p.x < p.next.x ? p : p.next;
  14382. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  14383. }
  14384. }
  14385. p = p.next;
  14386. } while ( p !== outerNode );
  14387. if ( ! m ) return null;
  14388. // look for points inside the triangle of hole point, segment intersection and endpoint;
  14389. // if there are no points found, we have a valid connection;
  14390. // otherwise choose the point of the minimum angle with the ray as connection point
  14391. const stop = m,
  14392. mx = m.x,
  14393. my = m.y;
  14394. let tanMin = Infinity, tan;
  14395. p = m;
  14396. do {
  14397. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  14398. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  14399. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  14400. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  14401. m = p;
  14402. tanMin = tan;
  14403. }
  14404. }
  14405. p = p.next;
  14406. } while ( p !== stop );
  14407. return m;
  14408. }
  14409. // whether sector in vertex m contains sector in vertex p in the same coordinates
  14410. function sectorContainsSector( m, p ) {
  14411. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  14412. }
  14413. // interlink polygon nodes in z-order
  14414. function indexCurve( start, minX, minY, invSize ) {
  14415. let p = start;
  14416. do {
  14417. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  14418. p.prevZ = p.prev;
  14419. p.nextZ = p.next;
  14420. p = p.next;
  14421. } while ( p !== start );
  14422. p.prevZ.nextZ = null;
  14423. p.prevZ = null;
  14424. sortLinked( p );
  14425. }
  14426. // Simon Tatham's linked list merge sort algorithm
  14427. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  14428. function sortLinked( list ) {
  14429. let i, p, q, e, tail, numMerges, pSize, qSize,
  14430. inSize = 1;
  14431. do {
  14432. p = list;
  14433. list = null;
  14434. tail = null;
  14435. numMerges = 0;
  14436. while ( p ) {
  14437. numMerges ++;
  14438. q = p;
  14439. pSize = 0;
  14440. for ( i = 0; i < inSize; i ++ ) {
  14441. pSize ++;
  14442. q = q.nextZ;
  14443. if ( ! q ) break;
  14444. }
  14445. qSize = inSize;
  14446. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  14447. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  14448. e = p;
  14449. p = p.nextZ;
  14450. pSize --;
  14451. } else {
  14452. e = q;
  14453. q = q.nextZ;
  14454. qSize --;
  14455. }
  14456. if ( tail ) tail.nextZ = e;
  14457. else list = e;
  14458. e.prevZ = tail;
  14459. tail = e;
  14460. }
  14461. p = q;
  14462. }
  14463. tail.nextZ = null;
  14464. inSize *= 2;
  14465. } while ( numMerges > 1 );
  14466. return list;
  14467. }
  14468. // z-order of a point given coords and inverse of the longer side of data bbox
  14469. function zOrder( x, y, minX, minY, invSize ) {
  14470. // coords are transformed into non-negative 15-bit integer range
  14471. x = ( x - minX ) * invSize | 0;
  14472. y = ( y - minY ) * invSize | 0;
  14473. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  14474. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  14475. x = ( x | ( x << 2 ) ) & 0x33333333;
  14476. x = ( x | ( x << 1 ) ) & 0x55555555;
  14477. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  14478. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  14479. y = ( y | ( y << 2 ) ) & 0x33333333;
  14480. y = ( y | ( y << 1 ) ) & 0x55555555;
  14481. return x | ( y << 1 );
  14482. }
  14483. // find the leftmost node of a polygon ring
  14484. function getLeftmost( start ) {
  14485. let p = start,
  14486. leftmost = start;
  14487. do {
  14488. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  14489. p = p.next;
  14490. } while ( p !== start );
  14491. return leftmost;
  14492. }
  14493. // check if a point lies within a convex triangle
  14494. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  14495. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  14496. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  14497. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  14498. }
  14499. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  14500. function isValidDiagonal( a, b ) {
  14501. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // doesn't intersect other edges
  14502. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  14503. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  14504. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  14505. }
  14506. // signed area of a triangle
  14507. function area( p, q, r ) {
  14508. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  14509. }
  14510. // check if two points are equal
  14511. function equals( p1, p2 ) {
  14512. return p1.x === p2.x && p1.y === p2.y;
  14513. }
  14514. // check if two segments intersect
  14515. function intersects( p1, q1, p2, q2 ) {
  14516. const o1 = sign( area( p1, q1, p2 ) );
  14517. const o2 = sign( area( p1, q1, q2 ) );
  14518. const o3 = sign( area( p2, q2, p1 ) );
  14519. const o4 = sign( area( p2, q2, q1 ) );
  14520. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  14521. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  14522. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  14523. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  14524. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  14525. return false;
  14526. }
  14527. // for collinear points p, q, r, check if point q lies on segment pr
  14528. function onSegment( p, q, r ) {
  14529. 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 );
  14530. }
  14531. function sign( num ) {
  14532. return num > 0 ? 1 : num < 0 ? -1 : 0;
  14533. }
  14534. // check if a polygon diagonal intersects any polygon segments
  14535. function intersectsPolygon( a, b ) {
  14536. let p = a;
  14537. do {
  14538. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  14539. intersects( p, p.next, a, b ) ) return true;
  14540. p = p.next;
  14541. } while ( p !== a );
  14542. return false;
  14543. }
  14544. // check if a polygon diagonal is locally inside the polygon
  14545. function locallyInside( a, b ) {
  14546. return area( a.prev, a, a.next ) < 0 ?
  14547. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  14548. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  14549. }
  14550. // check if the middle point of a polygon diagonal is inside the polygon
  14551. function middleInside( a, b ) {
  14552. let p = a,
  14553. inside = false;
  14554. const px = ( a.x + b.x ) / 2,
  14555. py = ( a.y + b.y ) / 2;
  14556. do {
  14557. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  14558. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  14559. inside = ! inside;
  14560. p = p.next;
  14561. } while ( p !== a );
  14562. return inside;
  14563. }
  14564. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  14565. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  14566. function splitPolygon( a, b ) {
  14567. const a2 = new Node( a.i, a.x, a.y ),
  14568. b2 = new Node( b.i, b.x, b.y ),
  14569. an = a.next,
  14570. bp = b.prev;
  14571. a.next = b;
  14572. b.prev = a;
  14573. a2.next = an;
  14574. an.prev = a2;
  14575. b2.next = a2;
  14576. a2.prev = b2;
  14577. bp.next = b2;
  14578. b2.prev = bp;
  14579. return b2;
  14580. }
  14581. // create a node and optionally link it with previous one (in a circular doubly linked list)
  14582. function insertNode( i, x, y, last ) {
  14583. const p = new Node( i, x, y );
  14584. if ( ! last ) {
  14585. p.prev = p;
  14586. p.next = p;
  14587. } else {
  14588. p.next = last.next;
  14589. p.prev = last;
  14590. last.next.prev = p;
  14591. last.next = p;
  14592. }
  14593. return p;
  14594. }
  14595. function removeNode( p ) {
  14596. p.next.prev = p.prev;
  14597. p.prev.next = p.next;
  14598. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  14599. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  14600. }
  14601. function Node( i, x, y ) {
  14602. // vertex index in coordinates array
  14603. this.i = i;
  14604. // vertex coordinates
  14605. this.x = x;
  14606. this.y = y;
  14607. // previous and next vertex nodes in a polygon ring
  14608. this.prev = null;
  14609. this.next = null;
  14610. // z-order curve value
  14611. this.z = 0;
  14612. // previous and next nodes in z-order
  14613. this.prevZ = null;
  14614. this.nextZ = null;
  14615. // indicates whether this is a steiner point
  14616. this.steiner = false;
  14617. }
  14618. function signedArea( data, start, end, dim ) {
  14619. let sum = 0;
  14620. for ( let i = start, j = end - dim; i < end; i += dim ) {
  14621. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  14622. j = i;
  14623. }
  14624. return sum;
  14625. }
  14626. class ShapeUtils {
  14627. // calculate area of the contour polygon
  14628. static area( contour ) {
  14629. const n = contour.length;
  14630. let a = 0.0;
  14631. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  14632. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  14633. }
  14634. return a * 0.5;
  14635. }
  14636. static isClockWise( pts ) {
  14637. return ShapeUtils.area( pts ) < 0;
  14638. }
  14639. static triangulateShape( contour, holes ) {
  14640. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  14641. const holeIndices = []; // array of hole indices
  14642. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  14643. removeDupEndPts( contour );
  14644. addContour( vertices, contour );
  14645. //
  14646. let holeIndex = contour.length;
  14647. holes.forEach( removeDupEndPts );
  14648. for ( let i = 0; i < holes.length; i ++ ) {
  14649. holeIndices.push( holeIndex );
  14650. holeIndex += holes[ i ].length;
  14651. addContour( vertices, holes[ i ] );
  14652. }
  14653. //
  14654. const triangles = Earcut.triangulate( vertices, holeIndices );
  14655. //
  14656. for ( let i = 0; i < triangles.length; i += 3 ) {
  14657. faces.push( triangles.slice( i, i + 3 ) );
  14658. }
  14659. return faces;
  14660. }
  14661. }
  14662. function removeDupEndPts( points ) {
  14663. const l = points.length;
  14664. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  14665. points.pop();
  14666. }
  14667. }
  14668. function addContour( vertices, contour ) {
  14669. for ( let i = 0; i < contour.length; i ++ ) {
  14670. vertices.push( contour[ i ].x );
  14671. vertices.push( contour[ i ].y );
  14672. }
  14673. }
  14674. /**
  14675. * Creates extruded geometry from a path shape.
  14676. *
  14677. * parameters = {
  14678. *
  14679. * curveSegments: <int>, // number of points on the curves
  14680. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  14681. * depth: <float>, // Depth to extrude the shape
  14682. *
  14683. * bevelEnabled: <bool>, // turn on bevel
  14684. * bevelThickness: <float>, // how deep into the original shape bevel goes
  14685. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  14686. * bevelOffset: <float>, // how far from shape outline does bevel start
  14687. * bevelSegments: <int>, // number of bevel layers
  14688. *
  14689. * extrudePath: <THREE.Curve> // curve to extrude shape along
  14690. *
  14691. * UVGenerator: <Object> // object that provides UV generator functions
  14692. *
  14693. * }
  14694. */
  14695. class ExtrudeGeometry extends BufferGeometry {
  14696. constructor( shapes = new Shape( [ new Vector2( 0.5, 0.5 ), new Vector2( -0.5, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), options = {} ) {
  14697. super();
  14698. this.type = 'ExtrudeGeometry';
  14699. this.parameters = {
  14700. shapes: shapes,
  14701. options: options
  14702. };
  14703. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  14704. const scope = this;
  14705. const verticesArray = [];
  14706. const uvArray = [];
  14707. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  14708. const shape = shapes[ i ];
  14709. addShape( shape );
  14710. }
  14711. // build geometry
  14712. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  14713. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  14714. this.computeVertexNormals();
  14715. // functions
  14716. function addShape( shape ) {
  14717. const placeholder = [];
  14718. // options
  14719. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  14720. const steps = options.steps !== undefined ? options.steps : 1;
  14721. const depth = options.depth !== undefined ? options.depth : 1;
  14722. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  14723. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  14724. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  14725. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  14726. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  14727. const extrudePath = options.extrudePath;
  14728. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  14729. //
  14730. let extrudePts, extrudeByPath = false;
  14731. let splineTube, binormal, normal, position2;
  14732. if ( extrudePath ) {
  14733. extrudePts = extrudePath.getSpacedPoints( steps );
  14734. extrudeByPath = true;
  14735. bevelEnabled = false; // bevels not supported for path extrusion
  14736. // SETUP TNB variables
  14737. // TODO1 - have a .isClosed in spline?
  14738. splineTube = extrudePath.computeFrenetFrames( steps, false );
  14739. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  14740. binormal = new Vector3();
  14741. normal = new Vector3();
  14742. position2 = new Vector3();
  14743. }
  14744. // Safeguards if bevels are not enabled
  14745. if ( ! bevelEnabled ) {
  14746. bevelSegments = 0;
  14747. bevelThickness = 0;
  14748. bevelSize = 0;
  14749. bevelOffset = 0;
  14750. }
  14751. // Variables initialization
  14752. const shapePoints = shape.extractPoints( curveSegments );
  14753. let vertices = shapePoints.shape;
  14754. const holes = shapePoints.holes;
  14755. const reverse = ! ShapeUtils.isClockWise( vertices );
  14756. if ( reverse ) {
  14757. vertices = vertices.reverse();
  14758. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  14759. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  14760. const ahole = holes[ h ];
  14761. if ( ShapeUtils.isClockWise( ahole ) ) {
  14762. holes[ h ] = ahole.reverse();
  14763. }
  14764. }
  14765. }
  14766. const faces = ShapeUtils.triangulateShape( vertices, holes );
  14767. /* Vertices */
  14768. const contour = vertices; // vertices has all points but contour has only points of circumference
  14769. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  14770. const ahole = holes[ h ];
  14771. vertices = vertices.concat( ahole );
  14772. }
  14773. function scalePt2( pt, vec, size ) {
  14774. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  14775. return pt.clone().addScaledVector( vec, size );
  14776. }
  14777. const vlen = vertices.length, flen = faces.length;
  14778. // Find directions for point movement
  14779. function getBevelVec( inPt, inPrev, inNext ) {
  14780. // computes for inPt the corresponding point inPt' on a new contour
  14781. // shifted by 1 unit (length of normalized vector) to the left
  14782. // if we walk along contour clockwise, this new contour is outside the old one
  14783. //
  14784. // inPt' is the intersection of the two lines parallel to the two
  14785. // adjacent edges of inPt at a distance of 1 unit on the left side.
  14786. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  14787. // good reading for geometry algorithms (here: line-line intersection)
  14788. // http://geomalgorithms.com/a05-_intersect-1.html
  14789. const v_prev_x = inPt.x - inPrev.x,
  14790. v_prev_y = inPt.y - inPrev.y;
  14791. const v_next_x = inNext.x - inPt.x,
  14792. v_next_y = inNext.y - inPt.y;
  14793. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  14794. // check for collinear edges
  14795. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  14796. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  14797. // not collinear
  14798. // length of vectors for normalizing
  14799. const v_prev_len = Math.sqrt( v_prev_lensq );
  14800. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  14801. // shift adjacent points by unit vectors to the left
  14802. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  14803. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  14804. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  14805. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  14806. // scaling factor for v_prev to intersection point
  14807. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  14808. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  14809. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  14810. // vector from inPt to intersection point
  14811. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  14812. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  14813. // Don't normalize!, otherwise sharp corners become ugly
  14814. // but prevent crazy spikes
  14815. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  14816. if ( v_trans_lensq <= 2 ) {
  14817. return new Vector2( v_trans_x, v_trans_y );
  14818. } else {
  14819. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  14820. }
  14821. } else {
  14822. // handle special case of collinear edges
  14823. let direction_eq = false; // assumes: opposite
  14824. if ( v_prev_x > Number.EPSILON ) {
  14825. if ( v_next_x > Number.EPSILON ) {
  14826. direction_eq = true;
  14827. }
  14828. } else {
  14829. if ( v_prev_x < - Number.EPSILON ) {
  14830. if ( v_next_x < - Number.EPSILON ) {
  14831. direction_eq = true;
  14832. }
  14833. } else {
  14834. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  14835. direction_eq = true;
  14836. }
  14837. }
  14838. }
  14839. if ( direction_eq ) {
  14840. // console.log("Warning: lines are a straight sequence");
  14841. v_trans_x = - v_prev_y;
  14842. v_trans_y = v_prev_x;
  14843. shrink_by = Math.sqrt( v_prev_lensq );
  14844. } else {
  14845. // console.log("Warning: lines are a straight spike");
  14846. v_trans_x = v_prev_x;
  14847. v_trans_y = v_prev_y;
  14848. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  14849. }
  14850. }
  14851. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  14852. }
  14853. const contourMovements = [];
  14854. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  14855. if ( j === il ) j = 0;
  14856. if ( k === il ) k = 0;
  14857. // (j)---(i)---(k)
  14858. // console.log('i,j,k', i, j , k)
  14859. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  14860. }
  14861. const holesMovements = [];
  14862. let oneHoleMovements, verticesMovements = contourMovements.concat();
  14863. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  14864. const ahole = holes[ h ];
  14865. oneHoleMovements = [];
  14866. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  14867. if ( j === il ) j = 0;
  14868. if ( k === il ) k = 0;
  14869. // (j)---(i)---(k)
  14870. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  14871. }
  14872. holesMovements.push( oneHoleMovements );
  14873. verticesMovements = verticesMovements.concat( oneHoleMovements );
  14874. }
  14875. // Loop bevelSegments, 1 for the front, 1 for the back
  14876. for ( let b = 0; b < bevelSegments; b ++ ) {
  14877. //for ( b = bevelSegments; b > 0; b -- ) {
  14878. const t = b / bevelSegments;
  14879. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  14880. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  14881. // contract shape
  14882. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  14883. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  14884. v( vert.x, vert.y, - z );
  14885. }
  14886. // expand holes
  14887. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  14888. const ahole = holes[ h ];
  14889. oneHoleMovements = holesMovements[ h ];
  14890. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  14891. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  14892. v( vert.x, vert.y, - z );
  14893. }
  14894. }
  14895. }
  14896. const bs = bevelSize + bevelOffset;
  14897. // Back facing vertices
  14898. for ( let i = 0; i < vlen; i ++ ) {
  14899. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  14900. if ( ! extrudeByPath ) {
  14901. v( vert.x, vert.y, 0 );
  14902. } else {
  14903. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  14904. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  14905. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  14906. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  14907. v( position2.x, position2.y, position2.z );
  14908. }
  14909. }
  14910. // Add stepped vertices...
  14911. // Including front facing vertices
  14912. for ( let s = 1; s <= steps; s ++ ) {
  14913. for ( let i = 0; i < vlen; i ++ ) {
  14914. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  14915. if ( ! extrudeByPath ) {
  14916. v( vert.x, vert.y, depth / steps * s );
  14917. } else {
  14918. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  14919. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  14920. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  14921. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  14922. v( position2.x, position2.y, position2.z );
  14923. }
  14924. }
  14925. }
  14926. // Add bevel segments planes
  14927. //for ( b = 1; b <= bevelSegments; b ++ ) {
  14928. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  14929. const t = b / bevelSegments;
  14930. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  14931. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  14932. // contract shape
  14933. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  14934. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  14935. v( vert.x, vert.y, depth + z );
  14936. }
  14937. // expand holes
  14938. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  14939. const ahole = holes[ h ];
  14940. oneHoleMovements = holesMovements[ h ];
  14941. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  14942. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  14943. if ( ! extrudeByPath ) {
  14944. v( vert.x, vert.y, depth + z );
  14945. } else {
  14946. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  14947. }
  14948. }
  14949. }
  14950. }
  14951. /* Faces */
  14952. // Top and bottom faces
  14953. buildLidFaces();
  14954. // Sides faces
  14955. buildSideFaces();
  14956. ///// Internal functions
  14957. function buildLidFaces() {
  14958. const start = verticesArray.length / 3;
  14959. if ( bevelEnabled ) {
  14960. let layer = 0; // steps + 1
  14961. let offset = vlen * layer;
  14962. // Bottom faces
  14963. for ( let i = 0; i < flen; i ++ ) {
  14964. const face = faces[ i ];
  14965. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  14966. }
  14967. layer = steps + bevelSegments * 2;
  14968. offset = vlen * layer;
  14969. // Top faces
  14970. for ( let i = 0; i < flen; i ++ ) {
  14971. const face = faces[ i ];
  14972. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  14973. }
  14974. } else {
  14975. // Bottom faces
  14976. for ( let i = 0; i < flen; i ++ ) {
  14977. const face = faces[ i ];
  14978. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  14979. }
  14980. // Top faces
  14981. for ( let i = 0; i < flen; i ++ ) {
  14982. const face = faces[ i ];
  14983. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  14984. }
  14985. }
  14986. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  14987. }
  14988. // Create faces for the z-sides of the shape
  14989. function buildSideFaces() {
  14990. const start = verticesArray.length / 3;
  14991. let layeroffset = 0;
  14992. sidewalls( contour, layeroffset );
  14993. layeroffset += contour.length;
  14994. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  14995. const ahole = holes[ h ];
  14996. sidewalls( ahole, layeroffset );
  14997. //, true
  14998. layeroffset += ahole.length;
  14999. }
  15000. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  15001. }
  15002. function sidewalls( contour, layeroffset ) {
  15003. let i = contour.length;
  15004. while ( -- i >= 0 ) {
  15005. const j = i;
  15006. let k = i - 1;
  15007. if ( k < 0 ) k = contour.length - 1;
  15008. //console.log('b', i,j, i-1, k,vertices.length);
  15009. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  15010. const slen1 = vlen * s;
  15011. const slen2 = vlen * ( s + 1 );
  15012. const a = layeroffset + j + slen1,
  15013. b = layeroffset + k + slen1,
  15014. c = layeroffset + k + slen2,
  15015. d = layeroffset + j + slen2;
  15016. f4( a, b, c, d );
  15017. }
  15018. }
  15019. }
  15020. function v( x, y, z ) {
  15021. placeholder.push( x );
  15022. placeholder.push( y );
  15023. placeholder.push( z );
  15024. }
  15025. function f3( a, b, c ) {
  15026. addVertex( a );
  15027. addVertex( b );
  15028. addVertex( c );
  15029. const nextIndex = verticesArray.length / 3;
  15030. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  15031. addUV( uvs[ 0 ] );
  15032. addUV( uvs[ 1 ] );
  15033. addUV( uvs[ 2 ] );
  15034. }
  15035. function f4( a, b, c, d ) {
  15036. addVertex( a );
  15037. addVertex( b );
  15038. addVertex( d );
  15039. addVertex( b );
  15040. addVertex( c );
  15041. addVertex( d );
  15042. const nextIndex = verticesArray.length / 3;
  15043. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  15044. addUV( uvs[ 0 ] );
  15045. addUV( uvs[ 1 ] );
  15046. addUV( uvs[ 3 ] );
  15047. addUV( uvs[ 1 ] );
  15048. addUV( uvs[ 2 ] );
  15049. addUV( uvs[ 3 ] );
  15050. }
  15051. function addVertex( index ) {
  15052. verticesArray.push( placeholder[ index * 3 + 0 ] );
  15053. verticesArray.push( placeholder[ index * 3 + 1 ] );
  15054. verticesArray.push( placeholder[ index * 3 + 2 ] );
  15055. }
  15056. function addUV( vector2 ) {
  15057. uvArray.push( vector2.x );
  15058. uvArray.push( vector2.y );
  15059. }
  15060. }
  15061. }
  15062. copy( source ) {
  15063. super.copy( source );
  15064. this.parameters = Object.assign( {}, source.parameters );
  15065. return this;
  15066. }
  15067. toJSON() {
  15068. const data = super.toJSON();
  15069. const shapes = this.parameters.shapes;
  15070. const options = this.parameters.options;
  15071. return toJSON$1( shapes, options, data );
  15072. }
  15073. static fromJSON( data, shapes ) {
  15074. const geometryShapes = [];
  15075. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  15076. const shape = shapes[ data.shapes[ j ] ];
  15077. geometryShapes.push( shape );
  15078. }
  15079. const extrudePath = data.options.extrudePath;
  15080. if ( extrudePath !== undefined ) {
  15081. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  15082. }
  15083. return new ExtrudeGeometry( geometryShapes, data.options );
  15084. }
  15085. }
  15086. const WorldUVGenerator = {
  15087. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  15088. const a_x = vertices[ indexA * 3 ];
  15089. const a_y = vertices[ indexA * 3 + 1 ];
  15090. const b_x = vertices[ indexB * 3 ];
  15091. const b_y = vertices[ indexB * 3 + 1 ];
  15092. const c_x = vertices[ indexC * 3 ];
  15093. const c_y = vertices[ indexC * 3 + 1 ];
  15094. return [
  15095. new Vector2( a_x, a_y ),
  15096. new Vector2( b_x, b_y ),
  15097. new Vector2( c_x, c_y )
  15098. ];
  15099. },
  15100. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  15101. const a_x = vertices[ indexA * 3 ];
  15102. const a_y = vertices[ indexA * 3 + 1 ];
  15103. const a_z = vertices[ indexA * 3 + 2 ];
  15104. const b_x = vertices[ indexB * 3 ];
  15105. const b_y = vertices[ indexB * 3 + 1 ];
  15106. const b_z = vertices[ indexB * 3 + 2 ];
  15107. const c_x = vertices[ indexC * 3 ];
  15108. const c_y = vertices[ indexC * 3 + 1 ];
  15109. const c_z = vertices[ indexC * 3 + 2 ];
  15110. const d_x = vertices[ indexD * 3 ];
  15111. const d_y = vertices[ indexD * 3 + 1 ];
  15112. const d_z = vertices[ indexD * 3 + 2 ];
  15113. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  15114. return [
  15115. new Vector2( a_x, 1 - a_z ),
  15116. new Vector2( b_x, 1 - b_z ),
  15117. new Vector2( c_x, 1 - c_z ),
  15118. new Vector2( d_x, 1 - d_z )
  15119. ];
  15120. } else {
  15121. return [
  15122. new Vector2( a_y, 1 - a_z ),
  15123. new Vector2( b_y, 1 - b_z ),
  15124. new Vector2( c_y, 1 - c_z ),
  15125. new Vector2( d_y, 1 - d_z )
  15126. ];
  15127. }
  15128. }
  15129. };
  15130. function toJSON$1( shapes, options, data ) {
  15131. data.shapes = [];
  15132. if ( Array.isArray( shapes ) ) {
  15133. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  15134. const shape = shapes[ i ];
  15135. data.shapes.push( shape.uuid );
  15136. }
  15137. } else {
  15138. data.shapes.push( shapes.uuid );
  15139. }
  15140. data.options = Object.assign( {}, options );
  15141. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  15142. return data;
  15143. }
  15144. class IcosahedronGeometry extends PolyhedronGeometry {
  15145. constructor( radius = 1, detail = 0 ) {
  15146. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  15147. const vertices = [
  15148. -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, 0,
  15149. 0, -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t,
  15150. t, 0, -1, t, 0, 1, - t, 0, -1, - t, 0, 1
  15151. ];
  15152. const indices = [
  15153. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  15154. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  15155. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  15156. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  15157. ];
  15158. super( vertices, indices, radius, detail );
  15159. this.type = 'IcosahedronGeometry';
  15160. this.parameters = {
  15161. radius: radius,
  15162. detail: detail
  15163. };
  15164. }
  15165. static fromJSON( data ) {
  15166. return new IcosahedronGeometry( data.radius, data.detail );
  15167. }
  15168. }
  15169. class OctahedronGeometry extends PolyhedronGeometry {
  15170. constructor( radius = 1, detail = 0 ) {
  15171. const vertices = [
  15172. 1, 0, 0, -1, 0, 0, 0, 1, 0,
  15173. 0, -1, 0, 0, 0, 1, 0, 0, -1
  15174. ];
  15175. const indices = [
  15176. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  15177. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  15178. 1, 3, 4, 1, 4, 2
  15179. ];
  15180. super( vertices, indices, radius, detail );
  15181. this.type = 'OctahedronGeometry';
  15182. this.parameters = {
  15183. radius: radius,
  15184. detail: detail
  15185. };
  15186. }
  15187. static fromJSON( data ) {
  15188. return new OctahedronGeometry( data.radius, data.detail );
  15189. }
  15190. }
  15191. class PlaneGeometry extends BufferGeometry {
  15192. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  15193. super();
  15194. this.type = 'PlaneGeometry';
  15195. this.parameters = {
  15196. width: width,
  15197. height: height,
  15198. widthSegments: widthSegments,
  15199. heightSegments: heightSegments
  15200. };
  15201. const width_half = width / 2;
  15202. const height_half = height / 2;
  15203. const gridX = Math.floor( widthSegments );
  15204. const gridY = Math.floor( heightSegments );
  15205. const gridX1 = gridX + 1;
  15206. const gridY1 = gridY + 1;
  15207. const segment_width = width / gridX;
  15208. const segment_height = height / gridY;
  15209. //
  15210. const indices = [];
  15211. const vertices = [];
  15212. const normals = [];
  15213. const uvs = [];
  15214. for ( let iy = 0; iy < gridY1; iy ++ ) {
  15215. const y = iy * segment_height - height_half;
  15216. for ( let ix = 0; ix < gridX1; ix ++ ) {
  15217. const x = ix * segment_width - width_half;
  15218. vertices.push( x, - y, 0 );
  15219. normals.push( 0, 0, 1 );
  15220. uvs.push( ix / gridX );
  15221. uvs.push( 1 - ( iy / gridY ) );
  15222. }
  15223. }
  15224. for ( let iy = 0; iy < gridY; iy ++ ) {
  15225. for ( let ix = 0; ix < gridX; ix ++ ) {
  15226. const a = ix + gridX1 * iy;
  15227. const b = ix + gridX1 * ( iy + 1 );
  15228. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  15229. const d = ( ix + 1 ) + gridX1 * iy;
  15230. indices.push( a, b, d );
  15231. indices.push( b, c, d );
  15232. }
  15233. }
  15234. this.setIndex( indices );
  15235. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15236. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15237. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15238. }
  15239. copy( source ) {
  15240. super.copy( source );
  15241. this.parameters = Object.assign( {}, source.parameters );
  15242. return this;
  15243. }
  15244. static fromJSON( data ) {
  15245. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  15246. }
  15247. }
  15248. class RingGeometry extends BufferGeometry {
  15249. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  15250. super();
  15251. this.type = 'RingGeometry';
  15252. this.parameters = {
  15253. innerRadius: innerRadius,
  15254. outerRadius: outerRadius,
  15255. thetaSegments: thetaSegments,
  15256. phiSegments: phiSegments,
  15257. thetaStart: thetaStart,
  15258. thetaLength: thetaLength
  15259. };
  15260. thetaSegments = Math.max( 3, thetaSegments );
  15261. phiSegments = Math.max( 1, phiSegments );
  15262. // buffers
  15263. const indices = [];
  15264. const vertices = [];
  15265. const normals = [];
  15266. const uvs = [];
  15267. // some helper variables
  15268. let radius = innerRadius;
  15269. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  15270. const vertex = new Vector3();
  15271. const uv = new Vector2();
  15272. // generate vertices, normals and uvs
  15273. for ( let j = 0; j <= phiSegments; j ++ ) {
  15274. for ( let i = 0; i <= thetaSegments; i ++ ) {
  15275. // values are generate from the inside of the ring to the outside
  15276. const segment = thetaStart + i / thetaSegments * thetaLength;
  15277. // vertex
  15278. vertex.x = radius * Math.cos( segment );
  15279. vertex.y = radius * Math.sin( segment );
  15280. vertices.push( vertex.x, vertex.y, vertex.z );
  15281. // normal
  15282. normals.push( 0, 0, 1 );
  15283. // uv
  15284. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  15285. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  15286. uvs.push( uv.x, uv.y );
  15287. }
  15288. // increase the radius for next row of vertices
  15289. radius += radiusStep;
  15290. }
  15291. // indices
  15292. for ( let j = 0; j < phiSegments; j ++ ) {
  15293. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  15294. for ( let i = 0; i < thetaSegments; i ++ ) {
  15295. const segment = i + thetaSegmentLevel;
  15296. const a = segment;
  15297. const b = segment + thetaSegments + 1;
  15298. const c = segment + thetaSegments + 2;
  15299. const d = segment + 1;
  15300. // faces
  15301. indices.push( a, b, d );
  15302. indices.push( b, c, d );
  15303. }
  15304. }
  15305. // build geometry
  15306. this.setIndex( indices );
  15307. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15308. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15309. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15310. }
  15311. copy( source ) {
  15312. super.copy( source );
  15313. this.parameters = Object.assign( {}, source.parameters );
  15314. return this;
  15315. }
  15316. static fromJSON( data ) {
  15317. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  15318. }
  15319. }
  15320. class ShapeGeometry extends BufferGeometry {
  15321. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), curveSegments = 12 ) {
  15322. super();
  15323. this.type = 'ShapeGeometry';
  15324. this.parameters = {
  15325. shapes: shapes,
  15326. curveSegments: curveSegments
  15327. };
  15328. // buffers
  15329. const indices = [];
  15330. const vertices = [];
  15331. const normals = [];
  15332. const uvs = [];
  15333. // helper variables
  15334. let groupStart = 0;
  15335. let groupCount = 0;
  15336. // allow single and array values for "shapes" parameter
  15337. if ( Array.isArray( shapes ) === false ) {
  15338. addShape( shapes );
  15339. } else {
  15340. for ( let i = 0; i < shapes.length; i ++ ) {
  15341. addShape( shapes[ i ] );
  15342. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  15343. groupStart += groupCount;
  15344. groupCount = 0;
  15345. }
  15346. }
  15347. // build geometry
  15348. this.setIndex( indices );
  15349. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15350. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15351. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15352. // helper functions
  15353. function addShape( shape ) {
  15354. const indexOffset = vertices.length / 3;
  15355. const points = shape.extractPoints( curveSegments );
  15356. let shapeVertices = points.shape;
  15357. const shapeHoles = points.holes;
  15358. // check direction of vertices
  15359. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  15360. shapeVertices = shapeVertices.reverse();
  15361. }
  15362. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  15363. const shapeHole = shapeHoles[ i ];
  15364. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  15365. shapeHoles[ i ] = shapeHole.reverse();
  15366. }
  15367. }
  15368. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  15369. // join vertices of inner and outer paths to a single array
  15370. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  15371. const shapeHole = shapeHoles[ i ];
  15372. shapeVertices = shapeVertices.concat( shapeHole );
  15373. }
  15374. // vertices, normals, uvs
  15375. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  15376. const vertex = shapeVertices[ i ];
  15377. vertices.push( vertex.x, vertex.y, 0 );
  15378. normals.push( 0, 0, 1 );
  15379. uvs.push( vertex.x, vertex.y ); // world uvs
  15380. }
  15381. // indices
  15382. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  15383. const face = faces[ i ];
  15384. const a = face[ 0 ] + indexOffset;
  15385. const b = face[ 1 ] + indexOffset;
  15386. const c = face[ 2 ] + indexOffset;
  15387. indices.push( a, b, c );
  15388. groupCount += 3;
  15389. }
  15390. }
  15391. }
  15392. copy( source ) {
  15393. super.copy( source );
  15394. this.parameters = Object.assign( {}, source.parameters );
  15395. return this;
  15396. }
  15397. toJSON() {
  15398. const data = super.toJSON();
  15399. const shapes = this.parameters.shapes;
  15400. return toJSON( shapes, data );
  15401. }
  15402. static fromJSON( data, shapes ) {
  15403. const geometryShapes = [];
  15404. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  15405. const shape = shapes[ data.shapes[ j ] ];
  15406. geometryShapes.push( shape );
  15407. }
  15408. return new ShapeGeometry( geometryShapes, data.curveSegments );
  15409. }
  15410. }
  15411. function toJSON( shapes, data ) {
  15412. data.shapes = [];
  15413. if ( Array.isArray( shapes ) ) {
  15414. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  15415. const shape = shapes[ i ];
  15416. data.shapes.push( shape.uuid );
  15417. }
  15418. } else {
  15419. data.shapes.push( shapes.uuid );
  15420. }
  15421. return data;
  15422. }
  15423. class SphereGeometry extends BufferGeometry {
  15424. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  15425. super();
  15426. this.type = 'SphereGeometry';
  15427. this.parameters = {
  15428. radius: radius,
  15429. widthSegments: widthSegments,
  15430. heightSegments: heightSegments,
  15431. phiStart: phiStart,
  15432. phiLength: phiLength,
  15433. thetaStart: thetaStart,
  15434. thetaLength: thetaLength
  15435. };
  15436. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  15437. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  15438. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  15439. let index = 0;
  15440. const grid = [];
  15441. const vertex = new Vector3();
  15442. const normal = new Vector3();
  15443. // buffers
  15444. const indices = [];
  15445. const vertices = [];
  15446. const normals = [];
  15447. const uvs = [];
  15448. // generate vertices, normals and uvs
  15449. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  15450. const verticesRow = [];
  15451. const v = iy / heightSegments;
  15452. // special case for the poles
  15453. let uOffset = 0;
  15454. if ( iy === 0 && thetaStart === 0 ) {
  15455. uOffset = 0.5 / widthSegments;
  15456. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  15457. uOffset = -0.5 / widthSegments;
  15458. }
  15459. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  15460. const u = ix / widthSegments;
  15461. // vertex
  15462. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  15463. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  15464. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  15465. vertices.push( vertex.x, vertex.y, vertex.z );
  15466. // normal
  15467. normal.copy( vertex ).normalize();
  15468. normals.push( normal.x, normal.y, normal.z );
  15469. // uv
  15470. uvs.push( u + uOffset, 1 - v );
  15471. verticesRow.push( index ++ );
  15472. }
  15473. grid.push( verticesRow );
  15474. }
  15475. // indices
  15476. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  15477. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  15478. const a = grid[ iy ][ ix + 1 ];
  15479. const b = grid[ iy ][ ix ];
  15480. const c = grid[ iy + 1 ][ ix ];
  15481. const d = grid[ iy + 1 ][ ix + 1 ];
  15482. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  15483. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  15484. }
  15485. }
  15486. // build geometry
  15487. this.setIndex( indices );
  15488. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15489. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15490. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15491. }
  15492. copy( source ) {
  15493. super.copy( source );
  15494. this.parameters = Object.assign( {}, source.parameters );
  15495. return this;
  15496. }
  15497. static fromJSON( data ) {
  15498. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  15499. }
  15500. }
  15501. class TetrahedronGeometry extends PolyhedronGeometry {
  15502. constructor( radius = 1, detail = 0 ) {
  15503. const vertices = [
  15504. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  15505. ];
  15506. const indices = [
  15507. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  15508. ];
  15509. super( vertices, indices, radius, detail );
  15510. this.type = 'TetrahedronGeometry';
  15511. this.parameters = {
  15512. radius: radius,
  15513. detail: detail
  15514. };
  15515. }
  15516. static fromJSON( data ) {
  15517. return new TetrahedronGeometry( data.radius, data.detail );
  15518. }
  15519. }
  15520. class TorusGeometry extends BufferGeometry {
  15521. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  15522. super();
  15523. this.type = 'TorusGeometry';
  15524. this.parameters = {
  15525. radius: radius,
  15526. tube: tube,
  15527. radialSegments: radialSegments,
  15528. tubularSegments: tubularSegments,
  15529. arc: arc
  15530. };
  15531. radialSegments = Math.floor( radialSegments );
  15532. tubularSegments = Math.floor( tubularSegments );
  15533. // buffers
  15534. const indices = [];
  15535. const vertices = [];
  15536. const normals = [];
  15537. const uvs = [];
  15538. // helper variables
  15539. const center = new Vector3();
  15540. const vertex = new Vector3();
  15541. const normal = new Vector3();
  15542. // generate vertices, normals and uvs
  15543. for ( let j = 0; j <= radialSegments; j ++ ) {
  15544. for ( let i = 0; i <= tubularSegments; i ++ ) {
  15545. const u = i / tubularSegments * arc;
  15546. const v = j / radialSegments * Math.PI * 2;
  15547. // vertex
  15548. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  15549. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  15550. vertex.z = tube * Math.sin( v );
  15551. vertices.push( vertex.x, vertex.y, vertex.z );
  15552. // normal
  15553. center.x = radius * Math.cos( u );
  15554. center.y = radius * Math.sin( u );
  15555. normal.subVectors( vertex, center ).normalize();
  15556. normals.push( normal.x, normal.y, normal.z );
  15557. // uv
  15558. uvs.push( i / tubularSegments );
  15559. uvs.push( j / radialSegments );
  15560. }
  15561. }
  15562. // generate indices
  15563. for ( let j = 1; j <= radialSegments; j ++ ) {
  15564. for ( let i = 1; i <= tubularSegments; i ++ ) {
  15565. // indices
  15566. const a = ( tubularSegments + 1 ) * j + i - 1;
  15567. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  15568. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  15569. const d = ( tubularSegments + 1 ) * j + i;
  15570. // faces
  15571. indices.push( a, b, d );
  15572. indices.push( b, c, d );
  15573. }
  15574. }
  15575. // build geometry
  15576. this.setIndex( indices );
  15577. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15578. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15579. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15580. }
  15581. copy( source ) {
  15582. super.copy( source );
  15583. this.parameters = Object.assign( {}, source.parameters );
  15584. return this;
  15585. }
  15586. static fromJSON( data ) {
  15587. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  15588. }
  15589. }
  15590. class TorusKnotGeometry extends BufferGeometry {
  15591. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  15592. super();
  15593. this.type = 'TorusKnotGeometry';
  15594. this.parameters = {
  15595. radius: radius,
  15596. tube: tube,
  15597. tubularSegments: tubularSegments,
  15598. radialSegments: radialSegments,
  15599. p: p,
  15600. q: q
  15601. };
  15602. tubularSegments = Math.floor( tubularSegments );
  15603. radialSegments = Math.floor( radialSegments );
  15604. // buffers
  15605. const indices = [];
  15606. const vertices = [];
  15607. const normals = [];
  15608. const uvs = [];
  15609. // helper variables
  15610. const vertex = new Vector3();
  15611. const normal = new Vector3();
  15612. const P1 = new Vector3();
  15613. const P2 = new Vector3();
  15614. const B = new Vector3();
  15615. const T = new Vector3();
  15616. const N = new Vector3();
  15617. // generate vertices, normals and uvs
  15618. for ( let i = 0; i <= tubularSegments; ++ i ) {
  15619. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  15620. const u = i / tubularSegments * p * Math.PI * 2;
  15621. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  15622. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  15623. calculatePositionOnCurve( u, p, q, radius, P1 );
  15624. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  15625. // calculate orthonormal basis
  15626. T.subVectors( P2, P1 );
  15627. N.addVectors( P2, P1 );
  15628. B.crossVectors( T, N );
  15629. N.crossVectors( B, T );
  15630. // normalize B, N. T can be ignored, we don't use it
  15631. B.normalize();
  15632. N.normalize();
  15633. for ( let j = 0; j <= radialSegments; ++ j ) {
  15634. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  15635. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  15636. const v = j / radialSegments * Math.PI * 2;
  15637. const cx = - tube * Math.cos( v );
  15638. const cy = tube * Math.sin( v );
  15639. // now calculate the final vertex position.
  15640. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  15641. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  15642. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  15643. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  15644. vertices.push( vertex.x, vertex.y, vertex.z );
  15645. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  15646. normal.subVectors( vertex, P1 ).normalize();
  15647. normals.push( normal.x, normal.y, normal.z );
  15648. // uv
  15649. uvs.push( i / tubularSegments );
  15650. uvs.push( j / radialSegments );
  15651. }
  15652. }
  15653. // generate indices
  15654. for ( let j = 1; j <= tubularSegments; j ++ ) {
  15655. for ( let i = 1; i <= radialSegments; i ++ ) {
  15656. // indices
  15657. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  15658. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  15659. const c = ( radialSegments + 1 ) * j + i;
  15660. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  15661. // faces
  15662. indices.push( a, b, d );
  15663. indices.push( b, c, d );
  15664. }
  15665. }
  15666. // build geometry
  15667. this.setIndex( indices );
  15668. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15669. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15670. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15671. // this function calculates the current position on the torus curve
  15672. function calculatePositionOnCurve( u, p, q, radius, position ) {
  15673. const cu = Math.cos( u );
  15674. const su = Math.sin( u );
  15675. const quOverP = q / p * u;
  15676. const cs = Math.cos( quOverP );
  15677. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  15678. position.y = radius * ( 2 + cs ) * su * 0.5;
  15679. position.z = radius * Math.sin( quOverP ) * 0.5;
  15680. }
  15681. }
  15682. copy( source ) {
  15683. super.copy( source );
  15684. this.parameters = Object.assign( {}, source.parameters );
  15685. return this;
  15686. }
  15687. static fromJSON( data ) {
  15688. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  15689. }
  15690. }
  15691. class TubeGeometry extends BufferGeometry {
  15692. constructor( path = new QuadraticBezierCurve3( new Vector3( -1, -1, 0 ), new Vector3( -1, 1, 0 ), new Vector3( 1, 1, 0 ) ), tubularSegments = 64, radius = 1, radialSegments = 8, closed = false ) {
  15693. super();
  15694. this.type = 'TubeGeometry';
  15695. this.parameters = {
  15696. path: path,
  15697. tubularSegments: tubularSegments,
  15698. radius: radius,
  15699. radialSegments: radialSegments,
  15700. closed: closed
  15701. };
  15702. const frames = path.computeFrenetFrames( tubularSegments, closed );
  15703. // expose internals
  15704. this.tangents = frames.tangents;
  15705. this.normals = frames.normals;
  15706. this.binormals = frames.binormals;
  15707. // helper variables
  15708. const vertex = new Vector3();
  15709. const normal = new Vector3();
  15710. const uv = new Vector2();
  15711. let P = new Vector3();
  15712. // buffer
  15713. const vertices = [];
  15714. const normals = [];
  15715. const uvs = [];
  15716. const indices = [];
  15717. // create buffer data
  15718. generateBufferData();
  15719. // build geometry
  15720. this.setIndex( indices );
  15721. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15722. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15723. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15724. // functions
  15725. function generateBufferData() {
  15726. for ( let i = 0; i < tubularSegments; i ++ ) {
  15727. generateSegment( i );
  15728. }
  15729. // if the geometry is not closed, generate the last row of vertices and normals
  15730. // at the regular position on the given path
  15731. //
  15732. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  15733. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  15734. // uvs are generated in a separate function.
  15735. // this makes it easy compute correct values for closed geometries
  15736. generateUVs();
  15737. // finally create faces
  15738. generateIndices();
  15739. }
  15740. function generateSegment( i ) {
  15741. // we use getPointAt to sample evenly distributed points from the given path
  15742. P = path.getPointAt( i / tubularSegments, P );
  15743. // retrieve corresponding normal and binormal
  15744. const N = frames.normals[ i ];
  15745. const B = frames.binormals[ i ];
  15746. // generate normals and vertices for the current segment
  15747. for ( let j = 0; j <= radialSegments; j ++ ) {
  15748. const v = j / radialSegments * Math.PI * 2;
  15749. const sin = Math.sin( v );
  15750. const cos = - Math.cos( v );
  15751. // normal
  15752. normal.x = ( cos * N.x + sin * B.x );
  15753. normal.y = ( cos * N.y + sin * B.y );
  15754. normal.z = ( cos * N.z + sin * B.z );
  15755. normal.normalize();
  15756. normals.push( normal.x, normal.y, normal.z );
  15757. // vertex
  15758. vertex.x = P.x + radius * normal.x;
  15759. vertex.y = P.y + radius * normal.y;
  15760. vertex.z = P.z + radius * normal.z;
  15761. vertices.push( vertex.x, vertex.y, vertex.z );
  15762. }
  15763. }
  15764. function generateIndices() {
  15765. for ( let j = 1; j <= tubularSegments; j ++ ) {
  15766. for ( let i = 1; i <= radialSegments; i ++ ) {
  15767. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  15768. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  15769. const c = ( radialSegments + 1 ) * j + i;
  15770. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  15771. // faces
  15772. indices.push( a, b, d );
  15773. indices.push( b, c, d );
  15774. }
  15775. }
  15776. }
  15777. function generateUVs() {
  15778. for ( let i = 0; i <= tubularSegments; i ++ ) {
  15779. for ( let j = 0; j <= radialSegments; j ++ ) {
  15780. uv.x = i / tubularSegments;
  15781. uv.y = j / radialSegments;
  15782. uvs.push( uv.x, uv.y );
  15783. }
  15784. }
  15785. }
  15786. }
  15787. copy( source ) {
  15788. super.copy( source );
  15789. this.parameters = Object.assign( {}, source.parameters );
  15790. return this;
  15791. }
  15792. toJSON() {
  15793. const data = super.toJSON();
  15794. data.path = this.parameters.path.toJSON();
  15795. return data;
  15796. }
  15797. static fromJSON( data ) {
  15798. // This only works for built-in curves (e.g. CatmullRomCurve3).
  15799. // User defined curves or instances of CurvePath will not be deserialized.
  15800. return new TubeGeometry(
  15801. new Curves[ data.path.type ]().fromJSON( data.path ),
  15802. data.tubularSegments,
  15803. data.radius,
  15804. data.radialSegments,
  15805. data.closed
  15806. );
  15807. }
  15808. }
  15809. class WireframeGeometry extends BufferGeometry {
  15810. constructor( geometry = null ) {
  15811. super();
  15812. this.type = 'WireframeGeometry';
  15813. this.parameters = {
  15814. geometry: geometry
  15815. };
  15816. if ( geometry !== null ) {
  15817. // buffer
  15818. const vertices = [];
  15819. const edges = new Set();
  15820. // helper variables
  15821. const start = new Vector3();
  15822. const end = new Vector3();
  15823. if ( geometry.index !== null ) {
  15824. // indexed BufferGeometry
  15825. const position = geometry.attributes.position;
  15826. const indices = geometry.index;
  15827. let groups = geometry.groups;
  15828. if ( groups.length === 0 ) {
  15829. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  15830. }
  15831. // create a data structure that contains all edges without duplicates
  15832. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  15833. const group = groups[ o ];
  15834. const groupStart = group.start;
  15835. const groupCount = group.count;
  15836. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  15837. for ( let j = 0; j < 3; j ++ ) {
  15838. const index1 = indices.getX( i + j );
  15839. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  15840. start.fromBufferAttribute( position, index1 );
  15841. end.fromBufferAttribute( position, index2 );
  15842. if ( isUniqueEdge( start, end, edges ) === true ) {
  15843. vertices.push( start.x, start.y, start.z );
  15844. vertices.push( end.x, end.y, end.z );
  15845. }
  15846. }
  15847. }
  15848. }
  15849. } else {
  15850. // non-indexed BufferGeometry
  15851. const position = geometry.attributes.position;
  15852. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  15853. for ( let j = 0; j < 3; j ++ ) {
  15854. // three edges per triangle, an edge is represented as (index1, index2)
  15855. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  15856. const index1 = 3 * i + j;
  15857. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  15858. start.fromBufferAttribute( position, index1 );
  15859. end.fromBufferAttribute( position, index2 );
  15860. if ( isUniqueEdge( start, end, edges ) === true ) {
  15861. vertices.push( start.x, start.y, start.z );
  15862. vertices.push( end.x, end.y, end.z );
  15863. }
  15864. }
  15865. }
  15866. }
  15867. // build geometry
  15868. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15869. }
  15870. }
  15871. copy( source ) {
  15872. super.copy( source );
  15873. this.parameters = Object.assign( {}, source.parameters );
  15874. return this;
  15875. }
  15876. }
  15877. function isUniqueEdge( start, end, edges ) {
  15878. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  15879. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  15880. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  15881. return false;
  15882. } else {
  15883. edges.add( hash1 );
  15884. edges.add( hash2 );
  15885. return true;
  15886. }
  15887. }
  15888. var Geometries = /*#__PURE__*/Object.freeze({
  15889. __proto__: null,
  15890. BoxGeometry: BoxGeometry,
  15891. CapsuleGeometry: CapsuleGeometry,
  15892. CircleGeometry: CircleGeometry,
  15893. ConeGeometry: ConeGeometry,
  15894. CylinderGeometry: CylinderGeometry,
  15895. DodecahedronGeometry: DodecahedronGeometry,
  15896. EdgesGeometry: EdgesGeometry,
  15897. ExtrudeGeometry: ExtrudeGeometry,
  15898. IcosahedronGeometry: IcosahedronGeometry,
  15899. LatheGeometry: LatheGeometry,
  15900. OctahedronGeometry: OctahedronGeometry,
  15901. PlaneGeometry: PlaneGeometry,
  15902. PolyhedronGeometry: PolyhedronGeometry,
  15903. RingGeometry: RingGeometry,
  15904. ShapeGeometry: ShapeGeometry,
  15905. SphereGeometry: SphereGeometry,
  15906. TetrahedronGeometry: TetrahedronGeometry,
  15907. TorusGeometry: TorusGeometry,
  15908. TorusKnotGeometry: TorusKnotGeometry,
  15909. TubeGeometry: TubeGeometry,
  15910. WireframeGeometry: WireframeGeometry
  15911. });
  15912. class ShadowMaterial extends Material {
  15913. constructor( parameters ) {
  15914. super();
  15915. this.isShadowMaterial = true;
  15916. this.type = 'ShadowMaterial';
  15917. this.color = new Color( 0x000000 );
  15918. this.transparent = true;
  15919. this.fog = true;
  15920. this.setValues( parameters );
  15921. }
  15922. copy( source ) {
  15923. super.copy( source );
  15924. this.color.copy( source.color );
  15925. this.fog = source.fog;
  15926. return this;
  15927. }
  15928. }
  15929. class RawShaderMaterial extends ShaderMaterial {
  15930. constructor( parameters ) {
  15931. super( parameters );
  15932. this.isRawShaderMaterial = true;
  15933. this.type = 'RawShaderMaterial';
  15934. }
  15935. }
  15936. class MeshStandardMaterial extends Material {
  15937. constructor( parameters ) {
  15938. super();
  15939. this.isMeshStandardMaterial = true;
  15940. this.type = 'MeshStandardMaterial';
  15941. this.defines = { 'STANDARD': '' };
  15942. this.color = new Color( 0xffffff ); // diffuse
  15943. this.roughness = 1.0;
  15944. this.metalness = 0.0;
  15945. this.map = null;
  15946. this.lightMap = null;
  15947. this.lightMapIntensity = 1.0;
  15948. this.aoMap = null;
  15949. this.aoMapIntensity = 1.0;
  15950. this.emissive = new Color( 0x000000 );
  15951. this.emissiveIntensity = 1.0;
  15952. this.emissiveMap = null;
  15953. this.bumpMap = null;
  15954. this.bumpScale = 1;
  15955. this.normalMap = null;
  15956. this.normalMapType = TangentSpaceNormalMap;
  15957. this.normalScale = new Vector2( 1, 1 );
  15958. this.displacementMap = null;
  15959. this.displacementScale = 1;
  15960. this.displacementBias = 0;
  15961. this.roughnessMap = null;
  15962. this.metalnessMap = null;
  15963. this.alphaMap = null;
  15964. this.envMap = null;
  15965. this.envMapRotation = new Euler();
  15966. this.envMapIntensity = 1.0;
  15967. this.wireframe = false;
  15968. this.wireframeLinewidth = 1;
  15969. this.wireframeLinecap = 'round';
  15970. this.wireframeLinejoin = 'round';
  15971. this.flatShading = false;
  15972. this.fog = true;
  15973. this.setValues( parameters );
  15974. }
  15975. copy( source ) {
  15976. super.copy( source );
  15977. this.defines = { 'STANDARD': '' };
  15978. this.color.copy( source.color );
  15979. this.roughness = source.roughness;
  15980. this.metalness = source.metalness;
  15981. this.map = source.map;
  15982. this.lightMap = source.lightMap;
  15983. this.lightMapIntensity = source.lightMapIntensity;
  15984. this.aoMap = source.aoMap;
  15985. this.aoMapIntensity = source.aoMapIntensity;
  15986. this.emissive.copy( source.emissive );
  15987. this.emissiveMap = source.emissiveMap;
  15988. this.emissiveIntensity = source.emissiveIntensity;
  15989. this.bumpMap = source.bumpMap;
  15990. this.bumpScale = source.bumpScale;
  15991. this.normalMap = source.normalMap;
  15992. this.normalMapType = source.normalMapType;
  15993. this.normalScale.copy( source.normalScale );
  15994. this.displacementMap = source.displacementMap;
  15995. this.displacementScale = source.displacementScale;
  15996. this.displacementBias = source.displacementBias;
  15997. this.roughnessMap = source.roughnessMap;
  15998. this.metalnessMap = source.metalnessMap;
  15999. this.alphaMap = source.alphaMap;
  16000. this.envMap = source.envMap;
  16001. this.envMapRotation.copy( source.envMapRotation );
  16002. this.envMapIntensity = source.envMapIntensity;
  16003. this.wireframe = source.wireframe;
  16004. this.wireframeLinewidth = source.wireframeLinewidth;
  16005. this.wireframeLinecap = source.wireframeLinecap;
  16006. this.wireframeLinejoin = source.wireframeLinejoin;
  16007. this.flatShading = source.flatShading;
  16008. this.fog = source.fog;
  16009. return this;
  16010. }
  16011. }
  16012. class MeshPhysicalMaterial extends MeshStandardMaterial {
  16013. constructor( parameters ) {
  16014. super();
  16015. this.isMeshPhysicalMaterial = true;
  16016. this.defines = {
  16017. 'STANDARD': '',
  16018. 'PHYSICAL': ''
  16019. };
  16020. this.type = 'MeshPhysicalMaterial';
  16021. this.anisotropyRotation = 0;
  16022. this.anisotropyMap = null;
  16023. this.clearcoatMap = null;
  16024. this.clearcoatRoughness = 0.0;
  16025. this.clearcoatRoughnessMap = null;
  16026. this.clearcoatNormalScale = new Vector2( 1, 1 );
  16027. this.clearcoatNormalMap = null;
  16028. this.ior = 1.5;
  16029. Object.defineProperty( this, 'reflectivity', {
  16030. get: function () {
  16031. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  16032. },
  16033. set: function ( reflectivity ) {
  16034. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  16035. }
  16036. } );
  16037. this.iridescenceMap = null;
  16038. this.iridescenceIOR = 1.3;
  16039. this.iridescenceThicknessRange = [ 100, 400 ];
  16040. this.iridescenceThicknessMap = null;
  16041. this.sheenColor = new Color( 0x000000 );
  16042. this.sheenColorMap = null;
  16043. this.sheenRoughness = 1.0;
  16044. this.sheenRoughnessMap = null;
  16045. this.transmissionMap = null;
  16046. this.thickness = 0;
  16047. this.thicknessMap = null;
  16048. this.attenuationDistance = Infinity;
  16049. this.attenuationColor = new Color( 1, 1, 1 );
  16050. this.specularIntensity = 1.0;
  16051. this.specularIntensityMap = null;
  16052. this.specularColor = new Color( 1, 1, 1 );
  16053. this.specularColorMap = null;
  16054. this._anisotropy = 0;
  16055. this._clearcoat = 0;
  16056. this._dispersion = 0;
  16057. this._iridescence = 0;
  16058. this._sheen = 0.0;
  16059. this._transmission = 0;
  16060. this.setValues( parameters );
  16061. }
  16062. get anisotropy() {
  16063. return this._anisotropy;
  16064. }
  16065. set anisotropy( value ) {
  16066. if ( this._anisotropy > 0 !== value > 0 ) {
  16067. this.version ++;
  16068. }
  16069. this._anisotropy = value;
  16070. }
  16071. get clearcoat() {
  16072. return this._clearcoat;
  16073. }
  16074. set clearcoat( value ) {
  16075. if ( this._clearcoat > 0 !== value > 0 ) {
  16076. this.version ++;
  16077. }
  16078. this._clearcoat = value;
  16079. }
  16080. get iridescence() {
  16081. return this._iridescence;
  16082. }
  16083. set iridescence( value ) {
  16084. if ( this._iridescence > 0 !== value > 0 ) {
  16085. this.version ++;
  16086. }
  16087. this._iridescence = value;
  16088. }
  16089. get dispersion() {
  16090. return this._dispersion;
  16091. }
  16092. set dispersion( value ) {
  16093. if ( this._dispersion > 0 !== value > 0 ) {
  16094. this.version ++;
  16095. }
  16096. this._dispersion = value;
  16097. }
  16098. get sheen() {
  16099. return this._sheen;
  16100. }
  16101. set sheen( value ) {
  16102. if ( this._sheen > 0 !== value > 0 ) {
  16103. this.version ++;
  16104. }
  16105. this._sheen = value;
  16106. }
  16107. get transmission() {
  16108. return this._transmission;
  16109. }
  16110. set transmission( value ) {
  16111. if ( this._transmission > 0 !== value > 0 ) {
  16112. this.version ++;
  16113. }
  16114. this._transmission = value;
  16115. }
  16116. copy( source ) {
  16117. super.copy( source );
  16118. this.defines = {
  16119. 'STANDARD': '',
  16120. 'PHYSICAL': ''
  16121. };
  16122. this.anisotropy = source.anisotropy;
  16123. this.anisotropyRotation = source.anisotropyRotation;
  16124. this.anisotropyMap = source.anisotropyMap;
  16125. this.clearcoat = source.clearcoat;
  16126. this.clearcoatMap = source.clearcoatMap;
  16127. this.clearcoatRoughness = source.clearcoatRoughness;
  16128. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  16129. this.clearcoatNormalMap = source.clearcoatNormalMap;
  16130. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  16131. this.dispersion = source.dispersion;
  16132. this.ior = source.ior;
  16133. this.iridescence = source.iridescence;
  16134. this.iridescenceMap = source.iridescenceMap;
  16135. this.iridescenceIOR = source.iridescenceIOR;
  16136. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  16137. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  16138. this.sheen = source.sheen;
  16139. this.sheenColor.copy( source.sheenColor );
  16140. this.sheenColorMap = source.sheenColorMap;
  16141. this.sheenRoughness = source.sheenRoughness;
  16142. this.sheenRoughnessMap = source.sheenRoughnessMap;
  16143. this.transmission = source.transmission;
  16144. this.transmissionMap = source.transmissionMap;
  16145. this.thickness = source.thickness;
  16146. this.thicknessMap = source.thicknessMap;
  16147. this.attenuationDistance = source.attenuationDistance;
  16148. this.attenuationColor.copy( source.attenuationColor );
  16149. this.specularIntensity = source.specularIntensity;
  16150. this.specularIntensityMap = source.specularIntensityMap;
  16151. this.specularColor.copy( source.specularColor );
  16152. this.specularColorMap = source.specularColorMap;
  16153. return this;
  16154. }
  16155. }
  16156. class MeshPhongMaterial extends Material {
  16157. constructor( parameters ) {
  16158. super();
  16159. this.isMeshPhongMaterial = true;
  16160. this.type = 'MeshPhongMaterial';
  16161. this.color = new Color( 0xffffff ); // diffuse
  16162. this.specular = new Color( 0x111111 );
  16163. this.shininess = 30;
  16164. this.map = null;
  16165. this.lightMap = null;
  16166. this.lightMapIntensity = 1.0;
  16167. this.aoMap = null;
  16168. this.aoMapIntensity = 1.0;
  16169. this.emissive = new Color( 0x000000 );
  16170. this.emissiveIntensity = 1.0;
  16171. this.emissiveMap = null;
  16172. this.bumpMap = null;
  16173. this.bumpScale = 1;
  16174. this.normalMap = null;
  16175. this.normalMapType = TangentSpaceNormalMap;
  16176. this.normalScale = new Vector2( 1, 1 );
  16177. this.displacementMap = null;
  16178. this.displacementScale = 1;
  16179. this.displacementBias = 0;
  16180. this.specularMap = null;
  16181. this.alphaMap = null;
  16182. this.envMap = null;
  16183. this.envMapRotation = new Euler();
  16184. this.combine = MultiplyOperation;
  16185. this.reflectivity = 1;
  16186. this.refractionRatio = 0.98;
  16187. this.wireframe = false;
  16188. this.wireframeLinewidth = 1;
  16189. this.wireframeLinecap = 'round';
  16190. this.wireframeLinejoin = 'round';
  16191. this.flatShading = false;
  16192. this.fog = true;
  16193. this.setValues( parameters );
  16194. }
  16195. copy( source ) {
  16196. super.copy( source );
  16197. this.color.copy( source.color );
  16198. this.specular.copy( source.specular );
  16199. this.shininess = source.shininess;
  16200. this.map = source.map;
  16201. this.lightMap = source.lightMap;
  16202. this.lightMapIntensity = source.lightMapIntensity;
  16203. this.aoMap = source.aoMap;
  16204. this.aoMapIntensity = source.aoMapIntensity;
  16205. this.emissive.copy( source.emissive );
  16206. this.emissiveMap = source.emissiveMap;
  16207. this.emissiveIntensity = source.emissiveIntensity;
  16208. this.bumpMap = source.bumpMap;
  16209. this.bumpScale = source.bumpScale;
  16210. this.normalMap = source.normalMap;
  16211. this.normalMapType = source.normalMapType;
  16212. this.normalScale.copy( source.normalScale );
  16213. this.displacementMap = source.displacementMap;
  16214. this.displacementScale = source.displacementScale;
  16215. this.displacementBias = source.displacementBias;
  16216. this.specularMap = source.specularMap;
  16217. this.alphaMap = source.alphaMap;
  16218. this.envMap = source.envMap;
  16219. this.envMapRotation.copy( source.envMapRotation );
  16220. this.combine = source.combine;
  16221. this.reflectivity = source.reflectivity;
  16222. this.refractionRatio = source.refractionRatio;
  16223. this.wireframe = source.wireframe;
  16224. this.wireframeLinewidth = source.wireframeLinewidth;
  16225. this.wireframeLinecap = source.wireframeLinecap;
  16226. this.wireframeLinejoin = source.wireframeLinejoin;
  16227. this.flatShading = source.flatShading;
  16228. this.fog = source.fog;
  16229. return this;
  16230. }
  16231. }
  16232. class MeshToonMaterial extends Material {
  16233. constructor( parameters ) {
  16234. super();
  16235. this.isMeshToonMaterial = true;
  16236. this.defines = { 'TOON': '' };
  16237. this.type = 'MeshToonMaterial';
  16238. this.color = new Color( 0xffffff );
  16239. this.map = null;
  16240. this.gradientMap = null;
  16241. this.lightMap = null;
  16242. this.lightMapIntensity = 1.0;
  16243. this.aoMap = null;
  16244. this.aoMapIntensity = 1.0;
  16245. this.emissive = new Color( 0x000000 );
  16246. this.emissiveIntensity = 1.0;
  16247. this.emissiveMap = null;
  16248. this.bumpMap = null;
  16249. this.bumpScale = 1;
  16250. this.normalMap = null;
  16251. this.normalMapType = TangentSpaceNormalMap;
  16252. this.normalScale = new Vector2( 1, 1 );
  16253. this.displacementMap = null;
  16254. this.displacementScale = 1;
  16255. this.displacementBias = 0;
  16256. this.alphaMap = null;
  16257. this.wireframe = false;
  16258. this.wireframeLinewidth = 1;
  16259. this.wireframeLinecap = 'round';
  16260. this.wireframeLinejoin = 'round';
  16261. this.fog = true;
  16262. this.setValues( parameters );
  16263. }
  16264. copy( source ) {
  16265. super.copy( source );
  16266. this.color.copy( source.color );
  16267. this.map = source.map;
  16268. this.gradientMap = source.gradientMap;
  16269. this.lightMap = source.lightMap;
  16270. this.lightMapIntensity = source.lightMapIntensity;
  16271. this.aoMap = source.aoMap;
  16272. this.aoMapIntensity = source.aoMapIntensity;
  16273. this.emissive.copy( source.emissive );
  16274. this.emissiveMap = source.emissiveMap;
  16275. this.emissiveIntensity = source.emissiveIntensity;
  16276. this.bumpMap = source.bumpMap;
  16277. this.bumpScale = source.bumpScale;
  16278. this.normalMap = source.normalMap;
  16279. this.normalMapType = source.normalMapType;
  16280. this.normalScale.copy( source.normalScale );
  16281. this.displacementMap = source.displacementMap;
  16282. this.displacementScale = source.displacementScale;
  16283. this.displacementBias = source.displacementBias;
  16284. this.alphaMap = source.alphaMap;
  16285. this.wireframe = source.wireframe;
  16286. this.wireframeLinewidth = source.wireframeLinewidth;
  16287. this.wireframeLinecap = source.wireframeLinecap;
  16288. this.wireframeLinejoin = source.wireframeLinejoin;
  16289. this.fog = source.fog;
  16290. return this;
  16291. }
  16292. }
  16293. class MeshNormalMaterial extends Material {
  16294. constructor( parameters ) {
  16295. super();
  16296. this.isMeshNormalMaterial = true;
  16297. this.type = 'MeshNormalMaterial';
  16298. this.bumpMap = null;
  16299. this.bumpScale = 1;
  16300. this.normalMap = null;
  16301. this.normalMapType = TangentSpaceNormalMap;
  16302. this.normalScale = new Vector2( 1, 1 );
  16303. this.displacementMap = null;
  16304. this.displacementScale = 1;
  16305. this.displacementBias = 0;
  16306. this.wireframe = false;
  16307. this.wireframeLinewidth = 1;
  16308. this.flatShading = false;
  16309. this.setValues( parameters );
  16310. }
  16311. copy( source ) {
  16312. super.copy( source );
  16313. this.bumpMap = source.bumpMap;
  16314. this.bumpScale = source.bumpScale;
  16315. this.normalMap = source.normalMap;
  16316. this.normalMapType = source.normalMapType;
  16317. this.normalScale.copy( source.normalScale );
  16318. this.displacementMap = source.displacementMap;
  16319. this.displacementScale = source.displacementScale;
  16320. this.displacementBias = source.displacementBias;
  16321. this.wireframe = source.wireframe;
  16322. this.wireframeLinewidth = source.wireframeLinewidth;
  16323. this.flatShading = source.flatShading;
  16324. return this;
  16325. }
  16326. }
  16327. class MeshLambertMaterial extends Material {
  16328. constructor( parameters ) {
  16329. super();
  16330. this.isMeshLambertMaterial = true;
  16331. this.type = 'MeshLambertMaterial';
  16332. this.color = new Color( 0xffffff ); // diffuse
  16333. this.map = null;
  16334. this.lightMap = null;
  16335. this.lightMapIntensity = 1.0;
  16336. this.aoMap = null;
  16337. this.aoMapIntensity = 1.0;
  16338. this.emissive = new Color( 0x000000 );
  16339. this.emissiveIntensity = 1.0;
  16340. this.emissiveMap = null;
  16341. this.bumpMap = null;
  16342. this.bumpScale = 1;
  16343. this.normalMap = null;
  16344. this.normalMapType = TangentSpaceNormalMap;
  16345. this.normalScale = new Vector2( 1, 1 );
  16346. this.displacementMap = null;
  16347. this.displacementScale = 1;
  16348. this.displacementBias = 0;
  16349. this.specularMap = null;
  16350. this.alphaMap = null;
  16351. this.envMap = null;
  16352. this.envMapRotation = new Euler();
  16353. this.combine = MultiplyOperation;
  16354. this.reflectivity = 1;
  16355. this.refractionRatio = 0.98;
  16356. this.wireframe = false;
  16357. this.wireframeLinewidth = 1;
  16358. this.wireframeLinecap = 'round';
  16359. this.wireframeLinejoin = 'round';
  16360. this.flatShading = false;
  16361. this.fog = true;
  16362. this.setValues( parameters );
  16363. }
  16364. copy( source ) {
  16365. super.copy( source );
  16366. this.color.copy( source.color );
  16367. this.map = source.map;
  16368. this.lightMap = source.lightMap;
  16369. this.lightMapIntensity = source.lightMapIntensity;
  16370. this.aoMap = source.aoMap;
  16371. this.aoMapIntensity = source.aoMapIntensity;
  16372. this.emissive.copy( source.emissive );
  16373. this.emissiveMap = source.emissiveMap;
  16374. this.emissiveIntensity = source.emissiveIntensity;
  16375. this.bumpMap = source.bumpMap;
  16376. this.bumpScale = source.bumpScale;
  16377. this.normalMap = source.normalMap;
  16378. this.normalMapType = source.normalMapType;
  16379. this.normalScale.copy( source.normalScale );
  16380. this.displacementMap = source.displacementMap;
  16381. this.displacementScale = source.displacementScale;
  16382. this.displacementBias = source.displacementBias;
  16383. this.specularMap = source.specularMap;
  16384. this.alphaMap = source.alphaMap;
  16385. this.envMap = source.envMap;
  16386. this.envMapRotation.copy( source.envMapRotation );
  16387. this.combine = source.combine;
  16388. this.reflectivity = source.reflectivity;
  16389. this.refractionRatio = source.refractionRatio;
  16390. this.wireframe = source.wireframe;
  16391. this.wireframeLinewidth = source.wireframeLinewidth;
  16392. this.wireframeLinecap = source.wireframeLinecap;
  16393. this.wireframeLinejoin = source.wireframeLinejoin;
  16394. this.flatShading = source.flatShading;
  16395. this.fog = source.fog;
  16396. return this;
  16397. }
  16398. }
  16399. class MeshDepthMaterial extends Material {
  16400. constructor( parameters ) {
  16401. super();
  16402. this.isMeshDepthMaterial = true;
  16403. this.type = 'MeshDepthMaterial';
  16404. this.depthPacking = BasicDepthPacking;
  16405. this.map = null;
  16406. this.alphaMap = null;
  16407. this.displacementMap = null;
  16408. this.displacementScale = 1;
  16409. this.displacementBias = 0;
  16410. this.wireframe = false;
  16411. this.wireframeLinewidth = 1;
  16412. this.setValues( parameters );
  16413. }
  16414. copy( source ) {
  16415. super.copy( source );
  16416. this.depthPacking = source.depthPacking;
  16417. this.map = source.map;
  16418. this.alphaMap = source.alphaMap;
  16419. this.displacementMap = source.displacementMap;
  16420. this.displacementScale = source.displacementScale;
  16421. this.displacementBias = source.displacementBias;
  16422. this.wireframe = source.wireframe;
  16423. this.wireframeLinewidth = source.wireframeLinewidth;
  16424. return this;
  16425. }
  16426. }
  16427. class MeshDistanceMaterial extends Material {
  16428. constructor( parameters ) {
  16429. super();
  16430. this.isMeshDistanceMaterial = true;
  16431. this.type = 'MeshDistanceMaterial';
  16432. this.map = null;
  16433. this.alphaMap = null;
  16434. this.displacementMap = null;
  16435. this.displacementScale = 1;
  16436. this.displacementBias = 0;
  16437. this.setValues( parameters );
  16438. }
  16439. copy( source ) {
  16440. super.copy( source );
  16441. this.map = source.map;
  16442. this.alphaMap = source.alphaMap;
  16443. this.displacementMap = source.displacementMap;
  16444. this.displacementScale = source.displacementScale;
  16445. this.displacementBias = source.displacementBias;
  16446. return this;
  16447. }
  16448. }
  16449. class MeshMatcapMaterial extends Material {
  16450. constructor( parameters ) {
  16451. super();
  16452. this.isMeshMatcapMaterial = true;
  16453. this.defines = { 'MATCAP': '' };
  16454. this.type = 'MeshMatcapMaterial';
  16455. this.color = new Color( 0xffffff ); // diffuse
  16456. this.matcap = null;
  16457. this.map = null;
  16458. this.bumpMap = null;
  16459. this.bumpScale = 1;
  16460. this.normalMap = null;
  16461. this.normalMapType = TangentSpaceNormalMap;
  16462. this.normalScale = new Vector2( 1, 1 );
  16463. this.displacementMap = null;
  16464. this.displacementScale = 1;
  16465. this.displacementBias = 0;
  16466. this.alphaMap = null;
  16467. this.flatShading = false;
  16468. this.fog = true;
  16469. this.setValues( parameters );
  16470. }
  16471. copy( source ) {
  16472. super.copy( source );
  16473. this.defines = { 'MATCAP': '' };
  16474. this.color.copy( source.color );
  16475. this.matcap = source.matcap;
  16476. this.map = source.map;
  16477. this.bumpMap = source.bumpMap;
  16478. this.bumpScale = source.bumpScale;
  16479. this.normalMap = source.normalMap;
  16480. this.normalMapType = source.normalMapType;
  16481. this.normalScale.copy( source.normalScale );
  16482. this.displacementMap = source.displacementMap;
  16483. this.displacementScale = source.displacementScale;
  16484. this.displacementBias = source.displacementBias;
  16485. this.alphaMap = source.alphaMap;
  16486. this.flatShading = source.flatShading;
  16487. this.fog = source.fog;
  16488. return this;
  16489. }
  16490. }
  16491. class LineDashedMaterial extends LineBasicMaterial {
  16492. constructor( parameters ) {
  16493. super();
  16494. this.isLineDashedMaterial = true;
  16495. this.type = 'LineDashedMaterial';
  16496. this.scale = 1;
  16497. this.dashSize = 3;
  16498. this.gapSize = 1;
  16499. this.setValues( parameters );
  16500. }
  16501. copy( source ) {
  16502. super.copy( source );
  16503. this.scale = source.scale;
  16504. this.dashSize = source.dashSize;
  16505. this.gapSize = source.gapSize;
  16506. return this;
  16507. }
  16508. }
  16509. // converts an array to a specific type
  16510. function convertArray( array, type, forceClone ) {
  16511. if ( ! array || // let 'undefined' and 'null' pass
  16512. ! forceClone && array.constructor === type ) return array;
  16513. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  16514. return new type( array ); // create typed array
  16515. }
  16516. return Array.prototype.slice.call( array ); // create Array
  16517. }
  16518. function isTypedArray( object ) {
  16519. return ArrayBuffer.isView( object ) &&
  16520. ! ( object instanceof DataView );
  16521. }
  16522. // returns an array by which times and values can be sorted
  16523. function getKeyframeOrder( times ) {
  16524. function compareTime( i, j ) {
  16525. return times[ i ] - times[ j ];
  16526. }
  16527. const n = times.length;
  16528. const result = new Array( n );
  16529. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  16530. result.sort( compareTime );
  16531. return result;
  16532. }
  16533. // uses the array previously returned by 'getKeyframeOrder' to sort data
  16534. function sortedArray( values, stride, order ) {
  16535. const nValues = values.length;
  16536. const result = new values.constructor( nValues );
  16537. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  16538. const srcOffset = order[ i ] * stride;
  16539. for ( let j = 0; j !== stride; ++ j ) {
  16540. result[ dstOffset ++ ] = values[ srcOffset + j ];
  16541. }
  16542. }
  16543. return result;
  16544. }
  16545. // function for parsing AOS keyframe formats
  16546. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  16547. let i = 1, key = jsonKeys[ 0 ];
  16548. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  16549. key = jsonKeys[ i ++ ];
  16550. }
  16551. if ( key === undefined ) return; // no data
  16552. let value = key[ valuePropertyName ];
  16553. if ( value === undefined ) return; // no data
  16554. if ( Array.isArray( value ) ) {
  16555. do {
  16556. value = key[ valuePropertyName ];
  16557. if ( value !== undefined ) {
  16558. times.push( key.time );
  16559. values.push( ...value ); // push all elements
  16560. }
  16561. key = jsonKeys[ i ++ ];
  16562. } while ( key !== undefined );
  16563. } else if ( value.toArray !== undefined ) {
  16564. // ...assume THREE.Math-ish
  16565. do {
  16566. value = key[ valuePropertyName ];
  16567. if ( value !== undefined ) {
  16568. times.push( key.time );
  16569. value.toArray( values, values.length );
  16570. }
  16571. key = jsonKeys[ i ++ ];
  16572. } while ( key !== undefined );
  16573. } else {
  16574. // otherwise push as-is
  16575. do {
  16576. value = key[ valuePropertyName ];
  16577. if ( value !== undefined ) {
  16578. times.push( key.time );
  16579. values.push( value );
  16580. }
  16581. key = jsonKeys[ i ++ ];
  16582. } while ( key !== undefined );
  16583. }
  16584. }
  16585. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  16586. const clip = sourceClip.clone();
  16587. clip.name = name;
  16588. const tracks = [];
  16589. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  16590. const track = clip.tracks[ i ];
  16591. const valueSize = track.getValueSize();
  16592. const times = [];
  16593. const values = [];
  16594. for ( let j = 0; j < track.times.length; ++ j ) {
  16595. const frame = track.times[ j ] * fps;
  16596. if ( frame < startFrame || frame >= endFrame ) continue;
  16597. times.push( track.times[ j ] );
  16598. for ( let k = 0; k < valueSize; ++ k ) {
  16599. values.push( track.values[ j * valueSize + k ] );
  16600. }
  16601. }
  16602. if ( times.length === 0 ) continue;
  16603. track.times = convertArray( times, track.times.constructor );
  16604. track.values = convertArray( values, track.values.constructor );
  16605. tracks.push( track );
  16606. }
  16607. clip.tracks = tracks;
  16608. // find minimum .times value across all tracks in the trimmed clip
  16609. let minStartTime = Infinity;
  16610. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  16611. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  16612. minStartTime = clip.tracks[ i ].times[ 0 ];
  16613. }
  16614. }
  16615. // shift all tracks such that clip begins at t=0
  16616. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  16617. clip.tracks[ i ].shift( -1 * minStartTime );
  16618. }
  16619. clip.resetDuration();
  16620. return clip;
  16621. }
  16622. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  16623. if ( fps <= 0 ) fps = 30;
  16624. const numTracks = referenceClip.tracks.length;
  16625. const referenceTime = referenceFrame / fps;
  16626. // Make each track's values relative to the values at the reference frame
  16627. for ( let i = 0; i < numTracks; ++ i ) {
  16628. const referenceTrack = referenceClip.tracks[ i ];
  16629. const referenceTrackType = referenceTrack.ValueTypeName;
  16630. // Skip this track if it's non-numeric
  16631. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  16632. // Find the track in the target clip whose name and type matches the reference track
  16633. const targetTrack = targetClip.tracks.find( function ( track ) {
  16634. return track.name === referenceTrack.name
  16635. && track.ValueTypeName === referenceTrackType;
  16636. } );
  16637. if ( targetTrack === undefined ) continue;
  16638. let referenceOffset = 0;
  16639. const referenceValueSize = referenceTrack.getValueSize();
  16640. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  16641. referenceOffset = referenceValueSize / 3;
  16642. }
  16643. let targetOffset = 0;
  16644. const targetValueSize = targetTrack.getValueSize();
  16645. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  16646. targetOffset = targetValueSize / 3;
  16647. }
  16648. const lastIndex = referenceTrack.times.length - 1;
  16649. let referenceValue;
  16650. // Find the value to subtract out of the track
  16651. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  16652. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  16653. const startIndex = referenceOffset;
  16654. const endIndex = referenceValueSize - referenceOffset;
  16655. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  16656. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  16657. // Reference frame is after the last keyframe, so just use the last keyframe
  16658. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  16659. const endIndex = startIndex + referenceValueSize - referenceOffset;
  16660. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  16661. } else {
  16662. // Interpolate to the reference value
  16663. const interpolant = referenceTrack.createInterpolant();
  16664. const startIndex = referenceOffset;
  16665. const endIndex = referenceValueSize - referenceOffset;
  16666. interpolant.evaluate( referenceTime );
  16667. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  16668. }
  16669. // Conjugate the quaternion
  16670. if ( referenceTrackType === 'quaternion' ) {
  16671. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  16672. referenceQuat.toArray( referenceValue );
  16673. }
  16674. // Subtract the reference value from all of the track values
  16675. const numTimes = targetTrack.times.length;
  16676. for ( let j = 0; j < numTimes; ++ j ) {
  16677. const valueStart = j * targetValueSize + targetOffset;
  16678. if ( referenceTrackType === 'quaternion' ) {
  16679. // Multiply the conjugate for quaternion track types
  16680. Quaternion.multiplyQuaternionsFlat(
  16681. targetTrack.values,
  16682. valueStart,
  16683. referenceValue,
  16684. 0,
  16685. targetTrack.values,
  16686. valueStart
  16687. );
  16688. } else {
  16689. const valueEnd = targetValueSize - targetOffset * 2;
  16690. // Subtract each value for all other numeric track types
  16691. for ( let k = 0; k < valueEnd; ++ k ) {
  16692. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  16693. }
  16694. }
  16695. }
  16696. }
  16697. targetClip.blendMode = AdditiveAnimationBlendMode;
  16698. return targetClip;
  16699. }
  16700. const AnimationUtils = {
  16701. convertArray: convertArray,
  16702. isTypedArray: isTypedArray,
  16703. getKeyframeOrder: getKeyframeOrder,
  16704. sortedArray: sortedArray,
  16705. flattenJSON: flattenJSON,
  16706. subclip: subclip,
  16707. makeClipAdditive: makeClipAdditive
  16708. };
  16709. /**
  16710. * Abstract base class of interpolants over parametric samples.
  16711. *
  16712. * The parameter domain is one dimensional, typically the time or a path
  16713. * along a curve defined by the data.
  16714. *
  16715. * The sample values can have any dimensionality and derived classes may
  16716. * apply special interpretations to the data.
  16717. *
  16718. * This class provides the interval seek in a Template Method, deferring
  16719. * the actual interpolation to derived classes.
  16720. *
  16721. * Time complexity is O(1) for linear access crossing at most two points
  16722. * and O(log N) for random access, where N is the number of positions.
  16723. *
  16724. * References:
  16725. *
  16726. * http://www.oodesign.com/template-method-pattern.html
  16727. *
  16728. */
  16729. class Interpolant {
  16730. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  16731. this.parameterPositions = parameterPositions;
  16732. this._cachedIndex = 0;
  16733. this.resultBuffer = resultBuffer !== undefined ?
  16734. resultBuffer : new sampleValues.constructor( sampleSize );
  16735. this.sampleValues = sampleValues;
  16736. this.valueSize = sampleSize;
  16737. this.settings = null;
  16738. this.DefaultSettings_ = {};
  16739. }
  16740. evaluate( t ) {
  16741. const pp = this.parameterPositions;
  16742. let i1 = this._cachedIndex,
  16743. t1 = pp[ i1 ],
  16744. t0 = pp[ i1 - 1 ];
  16745. validate_interval: {
  16746. seek: {
  16747. let right;
  16748. linear_scan: {
  16749. //- See http://jsperf.com/comparison-to-undefined/3
  16750. //- slower code:
  16751. //-
  16752. //- if ( t >= t1 || t1 === undefined ) {
  16753. forward_scan: if ( ! ( t < t1 ) ) {
  16754. for ( let giveUpAt = i1 + 2; ; ) {
  16755. if ( t1 === undefined ) {
  16756. if ( t < t0 ) break forward_scan;
  16757. // after end
  16758. i1 = pp.length;
  16759. this._cachedIndex = i1;
  16760. return this.copySampleValue_( i1 - 1 );
  16761. }
  16762. if ( i1 === giveUpAt ) break; // this loop
  16763. t0 = t1;
  16764. t1 = pp[ ++ i1 ];
  16765. if ( t < t1 ) {
  16766. // we have arrived at the sought interval
  16767. break seek;
  16768. }
  16769. }
  16770. // prepare binary search on the right side of the index
  16771. right = pp.length;
  16772. break linear_scan;
  16773. }
  16774. //- slower code:
  16775. //- if ( t < t0 || t0 === undefined ) {
  16776. if ( ! ( t >= t0 ) ) {
  16777. // looping?
  16778. const t1global = pp[ 1 ];
  16779. if ( t < t1global ) {
  16780. i1 = 2; // + 1, using the scan for the details
  16781. t0 = t1global;
  16782. }
  16783. // linear reverse scan
  16784. for ( let giveUpAt = i1 - 2; ; ) {
  16785. if ( t0 === undefined ) {
  16786. // before start
  16787. this._cachedIndex = 0;
  16788. return this.copySampleValue_( 0 );
  16789. }
  16790. if ( i1 === giveUpAt ) break; // this loop
  16791. t1 = t0;
  16792. t0 = pp[ -- i1 - 1 ];
  16793. if ( t >= t0 ) {
  16794. // we have arrived at the sought interval
  16795. break seek;
  16796. }
  16797. }
  16798. // prepare binary search on the left side of the index
  16799. right = i1;
  16800. i1 = 0;
  16801. break linear_scan;
  16802. }
  16803. // the interval is valid
  16804. break validate_interval;
  16805. } // linear scan
  16806. // binary search
  16807. while ( i1 < right ) {
  16808. const mid = ( i1 + right ) >>> 1;
  16809. if ( t < pp[ mid ] ) {
  16810. right = mid;
  16811. } else {
  16812. i1 = mid + 1;
  16813. }
  16814. }
  16815. t1 = pp[ i1 ];
  16816. t0 = pp[ i1 - 1 ];
  16817. // check boundary cases, again
  16818. if ( t0 === undefined ) {
  16819. this._cachedIndex = 0;
  16820. return this.copySampleValue_( 0 );
  16821. }
  16822. if ( t1 === undefined ) {
  16823. i1 = pp.length;
  16824. this._cachedIndex = i1;
  16825. return this.copySampleValue_( i1 - 1 );
  16826. }
  16827. } // seek
  16828. this._cachedIndex = i1;
  16829. this.intervalChanged_( i1, t0, t1 );
  16830. } // validate_interval
  16831. return this.interpolate_( i1, t0, t, t1 );
  16832. }
  16833. getSettings_() {
  16834. return this.settings || this.DefaultSettings_;
  16835. }
  16836. copySampleValue_( index ) {
  16837. // copies a sample value to the result buffer
  16838. const result = this.resultBuffer,
  16839. values = this.sampleValues,
  16840. stride = this.valueSize,
  16841. offset = index * stride;
  16842. for ( let i = 0; i !== stride; ++ i ) {
  16843. result[ i ] = values[ offset + i ];
  16844. }
  16845. return result;
  16846. }
  16847. // Template methods for derived classes:
  16848. interpolate_( /* i1, t0, t, t1 */ ) {
  16849. throw new Error( 'call to abstract method' );
  16850. // implementations shall return this.resultBuffer
  16851. }
  16852. intervalChanged_( /* i1, t0, t1 */ ) {
  16853. // empty
  16854. }
  16855. }
  16856. /**
  16857. * Fast and simple cubic spline interpolant.
  16858. *
  16859. * It was derived from a Hermitian construction setting the first derivative
  16860. * at each sample position to the linear slope between neighboring positions
  16861. * over their parameter interval.
  16862. */
  16863. class CubicInterpolant extends Interpolant {
  16864. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  16865. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  16866. this._weightPrev = -0;
  16867. this._offsetPrev = -0;
  16868. this._weightNext = -0;
  16869. this._offsetNext = -0;
  16870. this.DefaultSettings_ = {
  16871. endingStart: ZeroCurvatureEnding,
  16872. endingEnd: ZeroCurvatureEnding
  16873. };
  16874. }
  16875. intervalChanged_( i1, t0, t1 ) {
  16876. const pp = this.parameterPositions;
  16877. let iPrev = i1 - 2,
  16878. iNext = i1 + 1,
  16879. tPrev = pp[ iPrev ],
  16880. tNext = pp[ iNext ];
  16881. if ( tPrev === undefined ) {
  16882. switch ( this.getSettings_().endingStart ) {
  16883. case ZeroSlopeEnding:
  16884. // f'(t0) = 0
  16885. iPrev = i1;
  16886. tPrev = 2 * t0 - t1;
  16887. break;
  16888. case WrapAroundEnding:
  16889. // use the other end of the curve
  16890. iPrev = pp.length - 2;
  16891. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  16892. break;
  16893. default: // ZeroCurvatureEnding
  16894. // f''(t0) = 0 a.k.a. Natural Spline
  16895. iPrev = i1;
  16896. tPrev = t1;
  16897. }
  16898. }
  16899. if ( tNext === undefined ) {
  16900. switch ( this.getSettings_().endingEnd ) {
  16901. case ZeroSlopeEnding:
  16902. // f'(tN) = 0
  16903. iNext = i1;
  16904. tNext = 2 * t1 - t0;
  16905. break;
  16906. case WrapAroundEnding:
  16907. // use the other end of the curve
  16908. iNext = 1;
  16909. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  16910. break;
  16911. default: // ZeroCurvatureEnding
  16912. // f''(tN) = 0, a.k.a. Natural Spline
  16913. iNext = i1 - 1;
  16914. tNext = t0;
  16915. }
  16916. }
  16917. const halfDt = ( t1 - t0 ) * 0.5,
  16918. stride = this.valueSize;
  16919. this._weightPrev = halfDt / ( t0 - tPrev );
  16920. this._weightNext = halfDt / ( tNext - t1 );
  16921. this._offsetPrev = iPrev * stride;
  16922. this._offsetNext = iNext * stride;
  16923. }
  16924. interpolate_( i1, t0, t, t1 ) {
  16925. const result = this.resultBuffer,
  16926. values = this.sampleValues,
  16927. stride = this.valueSize,
  16928. o1 = i1 * stride, o0 = o1 - stride,
  16929. oP = this._offsetPrev, oN = this._offsetNext,
  16930. wP = this._weightPrev, wN = this._weightNext,
  16931. p = ( t - t0 ) / ( t1 - t0 ),
  16932. pp = p * p,
  16933. ppp = pp * p;
  16934. // evaluate polynomials
  16935. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  16936. const s0 = ( 1 + wP ) * ppp + ( -1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  16937. const s1 = ( -1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  16938. const sN = wN * ppp - wN * pp;
  16939. // combine data linearly
  16940. for ( let i = 0; i !== stride; ++ i ) {
  16941. result[ i ] =
  16942. sP * values[ oP + i ] +
  16943. s0 * values[ o0 + i ] +
  16944. s1 * values[ o1 + i ] +
  16945. sN * values[ oN + i ];
  16946. }
  16947. return result;
  16948. }
  16949. }
  16950. class LinearInterpolant extends Interpolant {
  16951. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  16952. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  16953. }
  16954. interpolate_( i1, t0, t, t1 ) {
  16955. const result = this.resultBuffer,
  16956. values = this.sampleValues,
  16957. stride = this.valueSize,
  16958. offset1 = i1 * stride,
  16959. offset0 = offset1 - stride,
  16960. weight1 = ( t - t0 ) / ( t1 - t0 ),
  16961. weight0 = 1 - weight1;
  16962. for ( let i = 0; i !== stride; ++ i ) {
  16963. result[ i ] =
  16964. values[ offset0 + i ] * weight0 +
  16965. values[ offset1 + i ] * weight1;
  16966. }
  16967. return result;
  16968. }
  16969. }
  16970. /**
  16971. *
  16972. * Interpolant that evaluates to the sample value at the position preceding
  16973. * the parameter.
  16974. */
  16975. class DiscreteInterpolant extends Interpolant {
  16976. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  16977. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  16978. }
  16979. interpolate_( i1 /*, t0, t, t1 */ ) {
  16980. return this.copySampleValue_( i1 - 1 );
  16981. }
  16982. }
  16983. class KeyframeTrack {
  16984. constructor( name, times, values, interpolation ) {
  16985. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  16986. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  16987. this.name = name;
  16988. this.times = convertArray( times, this.TimeBufferType );
  16989. this.values = convertArray( values, this.ValueBufferType );
  16990. this.setInterpolation( interpolation || this.DefaultInterpolation );
  16991. }
  16992. // Serialization (in static context, because of constructor invocation
  16993. // and automatic invocation of .toJSON):
  16994. static toJSON( track ) {
  16995. const trackType = track.constructor;
  16996. let json;
  16997. // derived classes can define a static toJSON method
  16998. if ( trackType.toJSON !== this.toJSON ) {
  16999. json = trackType.toJSON( track );
  17000. } else {
  17001. // by default, we assume the data can be serialized as-is
  17002. json = {
  17003. 'name': track.name,
  17004. 'times': convertArray( track.times, Array ),
  17005. 'values': convertArray( track.values, Array )
  17006. };
  17007. const interpolation = track.getInterpolation();
  17008. if ( interpolation !== track.DefaultInterpolation ) {
  17009. json.interpolation = interpolation;
  17010. }
  17011. }
  17012. json.type = track.ValueTypeName; // mandatory
  17013. return json;
  17014. }
  17015. InterpolantFactoryMethodDiscrete( result ) {
  17016. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  17017. }
  17018. InterpolantFactoryMethodLinear( result ) {
  17019. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  17020. }
  17021. InterpolantFactoryMethodSmooth( result ) {
  17022. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  17023. }
  17024. setInterpolation( interpolation ) {
  17025. let factoryMethod;
  17026. switch ( interpolation ) {
  17027. case InterpolateDiscrete:
  17028. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  17029. break;
  17030. case InterpolateLinear:
  17031. factoryMethod = this.InterpolantFactoryMethodLinear;
  17032. break;
  17033. case InterpolateSmooth:
  17034. factoryMethod = this.InterpolantFactoryMethodSmooth;
  17035. break;
  17036. }
  17037. if ( factoryMethod === undefined ) {
  17038. const message = 'unsupported interpolation for ' +
  17039. this.ValueTypeName + ' keyframe track named ' + this.name;
  17040. if ( this.createInterpolant === undefined ) {
  17041. // fall back to default, unless the default itself is messed up
  17042. if ( interpolation !== this.DefaultInterpolation ) {
  17043. this.setInterpolation( this.DefaultInterpolation );
  17044. } else {
  17045. throw new Error( message ); // fatal, in this case
  17046. }
  17047. }
  17048. console.warn( 'THREE.KeyframeTrack:', message );
  17049. return this;
  17050. }
  17051. this.createInterpolant = factoryMethod;
  17052. return this;
  17053. }
  17054. getInterpolation() {
  17055. switch ( this.createInterpolant ) {
  17056. case this.InterpolantFactoryMethodDiscrete:
  17057. return InterpolateDiscrete;
  17058. case this.InterpolantFactoryMethodLinear:
  17059. return InterpolateLinear;
  17060. case this.InterpolantFactoryMethodSmooth:
  17061. return InterpolateSmooth;
  17062. }
  17063. }
  17064. getValueSize() {
  17065. return this.values.length / this.times.length;
  17066. }
  17067. // move all keyframes either forwards or backwards in time
  17068. shift( timeOffset ) {
  17069. if ( timeOffset !== 0.0 ) {
  17070. const times = this.times;
  17071. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  17072. times[ i ] += timeOffset;
  17073. }
  17074. }
  17075. return this;
  17076. }
  17077. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  17078. scale( timeScale ) {
  17079. if ( timeScale !== 1.0 ) {
  17080. const times = this.times;
  17081. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  17082. times[ i ] *= timeScale;
  17083. }
  17084. }
  17085. return this;
  17086. }
  17087. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  17088. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  17089. trim( startTime, endTime ) {
  17090. const times = this.times,
  17091. nKeys = times.length;
  17092. let from = 0,
  17093. to = nKeys - 1;
  17094. while ( from !== nKeys && times[ from ] < startTime ) {
  17095. ++ from;
  17096. }
  17097. while ( to !== -1 && times[ to ] > endTime ) {
  17098. -- to;
  17099. }
  17100. ++ to; // inclusive -> exclusive bound
  17101. if ( from !== 0 || to !== nKeys ) {
  17102. // empty tracks are forbidden, so keep at least one keyframe
  17103. if ( from >= to ) {
  17104. to = Math.max( to, 1 );
  17105. from = to - 1;
  17106. }
  17107. const stride = this.getValueSize();
  17108. this.times = times.slice( from, to );
  17109. this.values = this.values.slice( from * stride, to * stride );
  17110. }
  17111. return this;
  17112. }
  17113. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  17114. validate() {
  17115. let valid = true;
  17116. const valueSize = this.getValueSize();
  17117. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  17118. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  17119. valid = false;
  17120. }
  17121. const times = this.times,
  17122. values = this.values,
  17123. nKeys = times.length;
  17124. if ( nKeys === 0 ) {
  17125. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  17126. valid = false;
  17127. }
  17128. let prevTime = null;
  17129. for ( let i = 0; i !== nKeys; i ++ ) {
  17130. const currTime = times[ i ];
  17131. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  17132. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  17133. valid = false;
  17134. break;
  17135. }
  17136. if ( prevTime !== null && prevTime > currTime ) {
  17137. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  17138. valid = false;
  17139. break;
  17140. }
  17141. prevTime = currTime;
  17142. }
  17143. if ( values !== undefined ) {
  17144. if ( isTypedArray( values ) ) {
  17145. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  17146. const value = values[ i ];
  17147. if ( isNaN( value ) ) {
  17148. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  17149. valid = false;
  17150. break;
  17151. }
  17152. }
  17153. }
  17154. }
  17155. return valid;
  17156. }
  17157. // removes equivalent sequential keys as common in morph target sequences
  17158. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  17159. optimize() {
  17160. // times or values may be shared with other tracks, so overwriting is unsafe
  17161. const times = this.times.slice(),
  17162. values = this.values.slice(),
  17163. stride = this.getValueSize(),
  17164. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  17165. lastIndex = times.length - 1;
  17166. let writeIndex = 1;
  17167. for ( let i = 1; i < lastIndex; ++ i ) {
  17168. let keep = false;
  17169. const time = times[ i ];
  17170. const timeNext = times[ i + 1 ];
  17171. // remove adjacent keyframes scheduled at the same time
  17172. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  17173. if ( ! smoothInterpolation ) {
  17174. // remove unnecessary keyframes same as their neighbors
  17175. const offset = i * stride,
  17176. offsetP = offset - stride,
  17177. offsetN = offset + stride;
  17178. for ( let j = 0; j !== stride; ++ j ) {
  17179. const value = values[ offset + j ];
  17180. if ( value !== values[ offsetP + j ] ||
  17181. value !== values[ offsetN + j ] ) {
  17182. keep = true;
  17183. break;
  17184. }
  17185. }
  17186. } else {
  17187. keep = true;
  17188. }
  17189. }
  17190. // in-place compaction
  17191. if ( keep ) {
  17192. if ( i !== writeIndex ) {
  17193. times[ writeIndex ] = times[ i ];
  17194. const readOffset = i * stride,
  17195. writeOffset = writeIndex * stride;
  17196. for ( let j = 0; j !== stride; ++ j ) {
  17197. values[ writeOffset + j ] = values[ readOffset + j ];
  17198. }
  17199. }
  17200. ++ writeIndex;
  17201. }
  17202. }
  17203. // flush last keyframe (compaction looks ahead)
  17204. if ( lastIndex > 0 ) {
  17205. times[ writeIndex ] = times[ lastIndex ];
  17206. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  17207. values[ writeOffset + j ] = values[ readOffset + j ];
  17208. }
  17209. ++ writeIndex;
  17210. }
  17211. if ( writeIndex !== times.length ) {
  17212. this.times = times.slice( 0, writeIndex );
  17213. this.values = values.slice( 0, writeIndex * stride );
  17214. } else {
  17215. this.times = times;
  17216. this.values = values;
  17217. }
  17218. return this;
  17219. }
  17220. clone() {
  17221. const times = this.times.slice();
  17222. const values = this.values.slice();
  17223. const TypedKeyframeTrack = this.constructor;
  17224. const track = new TypedKeyframeTrack( this.name, times, values );
  17225. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  17226. track.createInterpolant = this.createInterpolant;
  17227. return track;
  17228. }
  17229. }
  17230. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  17231. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  17232. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  17233. /**
  17234. * A Track of Boolean keyframe values.
  17235. */
  17236. class BooleanKeyframeTrack extends KeyframeTrack {
  17237. // No interpolation parameter because only InterpolateDiscrete is valid.
  17238. constructor( name, times, values ) {
  17239. super( name, times, values );
  17240. }
  17241. }
  17242. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  17243. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  17244. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  17245. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  17246. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  17247. /**
  17248. * A Track of keyframe values that represent color.
  17249. */
  17250. class ColorKeyframeTrack extends KeyframeTrack {}
  17251. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  17252. /**
  17253. * A Track of numeric keyframe values.
  17254. */
  17255. class NumberKeyframeTrack extends KeyframeTrack {}
  17256. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  17257. /**
  17258. * Spherical linear unit quaternion interpolant.
  17259. */
  17260. class QuaternionLinearInterpolant extends Interpolant {
  17261. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  17262. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  17263. }
  17264. interpolate_( i1, t0, t, t1 ) {
  17265. const result = this.resultBuffer,
  17266. values = this.sampleValues,
  17267. stride = this.valueSize,
  17268. alpha = ( t - t0 ) / ( t1 - t0 );
  17269. let offset = i1 * stride;
  17270. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  17271. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  17272. }
  17273. return result;
  17274. }
  17275. }
  17276. /**
  17277. * A Track of quaternion keyframe values.
  17278. */
  17279. class QuaternionKeyframeTrack extends KeyframeTrack {
  17280. InterpolantFactoryMethodLinear( result ) {
  17281. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  17282. }
  17283. }
  17284. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  17285. // ValueBufferType is inherited
  17286. // DefaultInterpolation is inherited;
  17287. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  17288. /**
  17289. * A Track that interpolates Strings
  17290. */
  17291. class StringKeyframeTrack extends KeyframeTrack {
  17292. // No interpolation parameter because only InterpolateDiscrete is valid.
  17293. constructor( name, times, values ) {
  17294. super( name, times, values );
  17295. }
  17296. }
  17297. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  17298. StringKeyframeTrack.prototype.ValueBufferType = Array;
  17299. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  17300. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  17301. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  17302. /**
  17303. * A Track of vectored keyframe values.
  17304. */
  17305. class VectorKeyframeTrack extends KeyframeTrack {}
  17306. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  17307. class AnimationClip {
  17308. constructor( name = '', duration = -1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  17309. this.name = name;
  17310. this.tracks = tracks;
  17311. this.duration = duration;
  17312. this.blendMode = blendMode;
  17313. this.uuid = generateUUID();
  17314. // this means it should figure out its duration by scanning the tracks
  17315. if ( this.duration < 0 ) {
  17316. this.resetDuration();
  17317. }
  17318. }
  17319. static parse( json ) {
  17320. const tracks = [],
  17321. jsonTracks = json.tracks,
  17322. frameTime = 1.0 / ( json.fps || 1.0 );
  17323. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  17324. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  17325. }
  17326. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  17327. clip.uuid = json.uuid;
  17328. return clip;
  17329. }
  17330. static toJSON( clip ) {
  17331. const tracks = [],
  17332. clipTracks = clip.tracks;
  17333. const json = {
  17334. 'name': clip.name,
  17335. 'duration': clip.duration,
  17336. 'tracks': tracks,
  17337. 'uuid': clip.uuid,
  17338. 'blendMode': clip.blendMode
  17339. };
  17340. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  17341. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  17342. }
  17343. return json;
  17344. }
  17345. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  17346. const numMorphTargets = morphTargetSequence.length;
  17347. const tracks = [];
  17348. for ( let i = 0; i < numMorphTargets; i ++ ) {
  17349. let times = [];
  17350. let values = [];
  17351. times.push(
  17352. ( i + numMorphTargets - 1 ) % numMorphTargets,
  17353. i,
  17354. ( i + 1 ) % numMorphTargets );
  17355. values.push( 0, 1, 0 );
  17356. const order = getKeyframeOrder( times );
  17357. times = sortedArray( times, 1, order );
  17358. values = sortedArray( values, 1, order );
  17359. // if there is a key at the first frame, duplicate it as the
  17360. // last frame as well for perfect loop.
  17361. if ( ! noLoop && times[ 0 ] === 0 ) {
  17362. times.push( numMorphTargets );
  17363. values.push( values[ 0 ] );
  17364. }
  17365. tracks.push(
  17366. new NumberKeyframeTrack(
  17367. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  17368. times, values
  17369. ).scale( 1.0 / fps ) );
  17370. }
  17371. return new this( name, -1, tracks );
  17372. }
  17373. static findByName( objectOrClipArray, name ) {
  17374. let clipArray = objectOrClipArray;
  17375. if ( ! Array.isArray( objectOrClipArray ) ) {
  17376. const o = objectOrClipArray;
  17377. clipArray = o.geometry && o.geometry.animations || o.animations;
  17378. }
  17379. for ( let i = 0; i < clipArray.length; i ++ ) {
  17380. if ( clipArray[ i ].name === name ) {
  17381. return clipArray[ i ];
  17382. }
  17383. }
  17384. return null;
  17385. }
  17386. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  17387. const animationToMorphTargets = {};
  17388. // tested with https://regex101.com/ on trick sequences
  17389. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  17390. const pattern = /^([\w-]*?)([\d]+)$/;
  17391. // sort morph target names into animation groups based
  17392. // patterns like Walk_001, Walk_002, Run_001, Run_002
  17393. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  17394. const morphTarget = morphTargets[ i ];
  17395. const parts = morphTarget.name.match( pattern );
  17396. if ( parts && parts.length > 1 ) {
  17397. const name = parts[ 1 ];
  17398. let animationMorphTargets = animationToMorphTargets[ name ];
  17399. if ( ! animationMorphTargets ) {
  17400. animationToMorphTargets[ name ] = animationMorphTargets = [];
  17401. }
  17402. animationMorphTargets.push( morphTarget );
  17403. }
  17404. }
  17405. const clips = [];
  17406. for ( const name in animationToMorphTargets ) {
  17407. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  17408. }
  17409. return clips;
  17410. }
  17411. // parse the animation.hierarchy format
  17412. static parseAnimation( animation, bones ) {
  17413. if ( ! animation ) {
  17414. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  17415. return null;
  17416. }
  17417. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  17418. // only return track if there are actually keys.
  17419. if ( animationKeys.length !== 0 ) {
  17420. const times = [];
  17421. const values = [];
  17422. flattenJSON( animationKeys, times, values, propertyName );
  17423. // empty keys are filtered out, so check again
  17424. if ( times.length !== 0 ) {
  17425. destTracks.push( new trackType( trackName, times, values ) );
  17426. }
  17427. }
  17428. };
  17429. const tracks = [];
  17430. const clipName = animation.name || 'default';
  17431. const fps = animation.fps || 30;
  17432. const blendMode = animation.blendMode;
  17433. // automatic length determination in AnimationClip.
  17434. let duration = animation.length || -1;
  17435. const hierarchyTracks = animation.hierarchy || [];
  17436. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  17437. const animationKeys = hierarchyTracks[ h ].keys;
  17438. // skip empty tracks
  17439. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  17440. // process morph targets
  17441. if ( animationKeys[ 0 ].morphTargets ) {
  17442. // figure out all morph targets used in this track
  17443. const morphTargetNames = {};
  17444. let k;
  17445. for ( k = 0; k < animationKeys.length; k ++ ) {
  17446. if ( animationKeys[ k ].morphTargets ) {
  17447. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  17448. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = -1;
  17449. }
  17450. }
  17451. }
  17452. // create a track for each morph target with all zero
  17453. // morphTargetInfluences except for the keys in which
  17454. // the morphTarget is named.
  17455. for ( const morphTargetName in morphTargetNames ) {
  17456. const times = [];
  17457. const values = [];
  17458. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  17459. const animationKey = animationKeys[ k ];
  17460. times.push( animationKey.time );
  17461. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  17462. }
  17463. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  17464. }
  17465. duration = morphTargetNames.length * fps;
  17466. } else {
  17467. // ...assume skeletal animation
  17468. const boneName = '.bones[' + bones[ h ].name + ']';
  17469. addNonemptyTrack(
  17470. VectorKeyframeTrack, boneName + '.position',
  17471. animationKeys, 'pos', tracks );
  17472. addNonemptyTrack(
  17473. QuaternionKeyframeTrack, boneName + '.quaternion',
  17474. animationKeys, 'rot', tracks );
  17475. addNonemptyTrack(
  17476. VectorKeyframeTrack, boneName + '.scale',
  17477. animationKeys, 'scl', tracks );
  17478. }
  17479. }
  17480. if ( tracks.length === 0 ) {
  17481. return null;
  17482. }
  17483. const clip = new this( clipName, duration, tracks, blendMode );
  17484. return clip;
  17485. }
  17486. resetDuration() {
  17487. const tracks = this.tracks;
  17488. let duration = 0;
  17489. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  17490. const track = this.tracks[ i ];
  17491. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  17492. }
  17493. this.duration = duration;
  17494. return this;
  17495. }
  17496. trim() {
  17497. for ( let i = 0; i < this.tracks.length; i ++ ) {
  17498. this.tracks[ i ].trim( 0, this.duration );
  17499. }
  17500. return this;
  17501. }
  17502. validate() {
  17503. let valid = true;
  17504. for ( let i = 0; i < this.tracks.length; i ++ ) {
  17505. valid = valid && this.tracks[ i ].validate();
  17506. }
  17507. return valid;
  17508. }
  17509. optimize() {
  17510. for ( let i = 0; i < this.tracks.length; i ++ ) {
  17511. this.tracks[ i ].optimize();
  17512. }
  17513. return this;
  17514. }
  17515. clone() {
  17516. const tracks = [];
  17517. for ( let i = 0; i < this.tracks.length; i ++ ) {
  17518. tracks.push( this.tracks[ i ].clone() );
  17519. }
  17520. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  17521. }
  17522. toJSON() {
  17523. return this.constructor.toJSON( this );
  17524. }
  17525. }
  17526. function getTrackTypeForValueTypeName( typeName ) {
  17527. switch ( typeName.toLowerCase() ) {
  17528. case 'scalar':
  17529. case 'double':
  17530. case 'float':
  17531. case 'number':
  17532. case 'integer':
  17533. return NumberKeyframeTrack;
  17534. case 'vector':
  17535. case 'vector2':
  17536. case 'vector3':
  17537. case 'vector4':
  17538. return VectorKeyframeTrack;
  17539. case 'color':
  17540. return ColorKeyframeTrack;
  17541. case 'quaternion':
  17542. return QuaternionKeyframeTrack;
  17543. case 'bool':
  17544. case 'boolean':
  17545. return BooleanKeyframeTrack;
  17546. case 'string':
  17547. return StringKeyframeTrack;
  17548. }
  17549. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  17550. }
  17551. function parseKeyframeTrack( json ) {
  17552. if ( json.type === undefined ) {
  17553. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  17554. }
  17555. const trackType = getTrackTypeForValueTypeName( json.type );
  17556. if ( json.times === undefined ) {
  17557. const times = [], values = [];
  17558. flattenJSON( json.keys, times, values, 'value' );
  17559. json.times = times;
  17560. json.values = values;
  17561. }
  17562. // derived classes can define a static parse method
  17563. if ( trackType.parse !== undefined ) {
  17564. return trackType.parse( json );
  17565. } else {
  17566. // by default, we assume a constructor compatible with the base
  17567. return new trackType( json.name, json.times, json.values, json.interpolation );
  17568. }
  17569. }
  17570. const Cache = {
  17571. enabled: false,
  17572. files: {},
  17573. add: function ( key, file ) {
  17574. if ( this.enabled === false ) return;
  17575. // console.log( 'THREE.Cache', 'Adding key:', key );
  17576. this.files[ key ] = file;
  17577. },
  17578. get: function ( key ) {
  17579. if ( this.enabled === false ) return;
  17580. // console.log( 'THREE.Cache', 'Checking key:', key );
  17581. return this.files[ key ];
  17582. },
  17583. remove: function ( key ) {
  17584. delete this.files[ key ];
  17585. },
  17586. clear: function () {
  17587. this.files = {};
  17588. }
  17589. };
  17590. class LoadingManager {
  17591. constructor( onLoad, onProgress, onError ) {
  17592. const scope = this;
  17593. let isLoading = false;
  17594. let itemsLoaded = 0;
  17595. let itemsTotal = 0;
  17596. let urlModifier = undefined;
  17597. const handlers = [];
  17598. // Refer to #5689 for the reason why we don't set .onStart
  17599. // in the constructor
  17600. this.onStart = undefined;
  17601. this.onLoad = onLoad;
  17602. this.onProgress = onProgress;
  17603. this.onError = onError;
  17604. this.itemStart = function ( url ) {
  17605. itemsTotal ++;
  17606. if ( isLoading === false ) {
  17607. if ( scope.onStart !== undefined ) {
  17608. scope.onStart( url, itemsLoaded, itemsTotal );
  17609. }
  17610. }
  17611. isLoading = true;
  17612. };
  17613. this.itemEnd = function ( url ) {
  17614. itemsLoaded ++;
  17615. if ( scope.onProgress !== undefined ) {
  17616. scope.onProgress( url, itemsLoaded, itemsTotal );
  17617. }
  17618. if ( itemsLoaded === itemsTotal ) {
  17619. isLoading = false;
  17620. if ( scope.onLoad !== undefined ) {
  17621. scope.onLoad();
  17622. }
  17623. }
  17624. };
  17625. this.itemError = function ( url ) {
  17626. if ( scope.onError !== undefined ) {
  17627. scope.onError( url );
  17628. }
  17629. };
  17630. this.resolveURL = function ( url ) {
  17631. if ( urlModifier ) {
  17632. return urlModifier( url );
  17633. }
  17634. return url;
  17635. };
  17636. this.setURLModifier = function ( transform ) {
  17637. urlModifier = transform;
  17638. return this;
  17639. };
  17640. this.addHandler = function ( regex, loader ) {
  17641. handlers.push( regex, loader );
  17642. return this;
  17643. };
  17644. this.removeHandler = function ( regex ) {
  17645. const index = handlers.indexOf( regex );
  17646. if ( index !== -1 ) {
  17647. handlers.splice( index, 2 );
  17648. }
  17649. return this;
  17650. };
  17651. this.getHandler = function ( file ) {
  17652. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  17653. const regex = handlers[ i ];
  17654. const loader = handlers[ i + 1 ];
  17655. if ( regex.global ) regex.lastIndex = 0; // see #17920
  17656. if ( regex.test( file ) ) {
  17657. return loader;
  17658. }
  17659. }
  17660. return null;
  17661. };
  17662. }
  17663. }
  17664. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  17665. class Loader {
  17666. constructor( manager ) {
  17667. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17668. this.crossOrigin = 'anonymous';
  17669. this.withCredentials = false;
  17670. this.path = '';
  17671. this.resourcePath = '';
  17672. this.requestHeader = {};
  17673. }
  17674. load( /* url, onLoad, onProgress, onError */ ) {}
  17675. loadAsync( url, onProgress ) {
  17676. const scope = this;
  17677. return new Promise( function ( resolve, reject ) {
  17678. scope.load( url, resolve, onProgress, reject );
  17679. } );
  17680. }
  17681. parse( /* data */ ) {}
  17682. setCrossOrigin( crossOrigin ) {
  17683. this.crossOrigin = crossOrigin;
  17684. return this;
  17685. }
  17686. setWithCredentials( value ) {
  17687. this.withCredentials = value;
  17688. return this;
  17689. }
  17690. setPath( path ) {
  17691. this.path = path;
  17692. return this;
  17693. }
  17694. setResourcePath( resourcePath ) {
  17695. this.resourcePath = resourcePath;
  17696. return this;
  17697. }
  17698. setRequestHeader( requestHeader ) {
  17699. this.requestHeader = requestHeader;
  17700. return this;
  17701. }
  17702. }
  17703. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  17704. const loading = {};
  17705. class HttpError extends Error {
  17706. constructor( message, response ) {
  17707. super( message );
  17708. this.response = response;
  17709. }
  17710. }
  17711. class FileLoader extends Loader {
  17712. constructor( manager ) {
  17713. super( manager );
  17714. }
  17715. load( url, onLoad, onProgress, onError ) {
  17716. if ( url === undefined ) url = '';
  17717. if ( this.path !== undefined ) url = this.path + url;
  17718. url = this.manager.resolveURL( url );
  17719. const cached = Cache.get( url );
  17720. if ( cached !== undefined ) {
  17721. this.manager.itemStart( url );
  17722. setTimeout( () => {
  17723. if ( onLoad ) onLoad( cached );
  17724. this.manager.itemEnd( url );
  17725. }, 0 );
  17726. return cached;
  17727. }
  17728. // Check if request is duplicate
  17729. if ( loading[ url ] !== undefined ) {
  17730. loading[ url ].push( {
  17731. onLoad: onLoad,
  17732. onProgress: onProgress,
  17733. onError: onError
  17734. } );
  17735. return;
  17736. }
  17737. // Initialise array for duplicate requests
  17738. loading[ url ] = [];
  17739. loading[ url ].push( {
  17740. onLoad: onLoad,
  17741. onProgress: onProgress,
  17742. onError: onError,
  17743. } );
  17744. // create request
  17745. const req = new Request( url, {
  17746. headers: new Headers( this.requestHeader ),
  17747. credentials: this.withCredentials ? 'include' : 'same-origin',
  17748. // An abort controller could be added within a future PR
  17749. } );
  17750. // record states ( avoid data race )
  17751. const mimeType = this.mimeType;
  17752. const responseType = this.responseType;
  17753. // start the fetch
  17754. fetch( req )
  17755. .then( response => {
  17756. if ( response.status === 200 || response.status === 0 ) {
  17757. // Some browsers return HTTP Status 0 when using non-http protocol
  17758. // e.g. 'file://' or 'data://'. Handle as success.
  17759. if ( response.status === 0 ) {
  17760. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  17761. }
  17762. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  17763. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  17764. return response;
  17765. }
  17766. const callbacks = loading[ url ];
  17767. const reader = response.body.getReader();
  17768. // Nginx needs X-File-Size check
  17769. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  17770. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  17771. const total = contentLength ? parseInt( contentLength ) : 0;
  17772. const lengthComputable = total !== 0;
  17773. let loaded = 0;
  17774. // periodically read data into the new stream tracking while download progress
  17775. const stream = new ReadableStream( {
  17776. start( controller ) {
  17777. readData();
  17778. function readData() {
  17779. reader.read().then( ( { done, value } ) => {
  17780. if ( done ) {
  17781. controller.close();
  17782. } else {
  17783. loaded += value.byteLength;
  17784. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  17785. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  17786. const callback = callbacks[ i ];
  17787. if ( callback.onProgress ) callback.onProgress( event );
  17788. }
  17789. controller.enqueue( value );
  17790. readData();
  17791. }
  17792. }, ( e ) => {
  17793. controller.error( e );
  17794. } );
  17795. }
  17796. }
  17797. } );
  17798. return new Response( stream );
  17799. } else {
  17800. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  17801. }
  17802. } )
  17803. .then( response => {
  17804. switch ( responseType ) {
  17805. case 'arraybuffer':
  17806. return response.arrayBuffer();
  17807. case 'blob':
  17808. return response.blob();
  17809. case 'document':
  17810. return response.text()
  17811. .then( text => {
  17812. const parser = new DOMParser();
  17813. return parser.parseFromString( text, mimeType );
  17814. } );
  17815. case 'json':
  17816. return response.json();
  17817. default:
  17818. if ( mimeType === undefined ) {
  17819. return response.text();
  17820. } else {
  17821. // sniff encoding
  17822. const re = /charset="?([^;"\s]*)"?/i;
  17823. const exec = re.exec( mimeType );
  17824. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  17825. const decoder = new TextDecoder( label );
  17826. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  17827. }
  17828. }
  17829. } )
  17830. .then( data => {
  17831. // Add to cache only on HTTP success, so that we do not cache
  17832. // error response bodies as proper responses to requests.
  17833. Cache.add( url, data );
  17834. const callbacks = loading[ url ];
  17835. delete loading[ url ];
  17836. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  17837. const callback = callbacks[ i ];
  17838. if ( callback.onLoad ) callback.onLoad( data );
  17839. }
  17840. } )
  17841. .catch( err => {
  17842. // Abort errors and other errors are handled the same
  17843. const callbacks = loading[ url ];
  17844. if ( callbacks === undefined ) {
  17845. // When onLoad was called and url was deleted in `loading`
  17846. this.manager.itemError( url );
  17847. throw err;
  17848. }
  17849. delete loading[ url ];
  17850. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  17851. const callback = callbacks[ i ];
  17852. if ( callback.onError ) callback.onError( err );
  17853. }
  17854. this.manager.itemError( url );
  17855. } )
  17856. .finally( () => {
  17857. this.manager.itemEnd( url );
  17858. } );
  17859. this.manager.itemStart( url );
  17860. }
  17861. setResponseType( value ) {
  17862. this.responseType = value;
  17863. return this;
  17864. }
  17865. setMimeType( value ) {
  17866. this.mimeType = value;
  17867. return this;
  17868. }
  17869. }
  17870. class AnimationLoader extends Loader {
  17871. constructor( manager ) {
  17872. super( manager );
  17873. }
  17874. load( url, onLoad, onProgress, onError ) {
  17875. const scope = this;
  17876. const loader = new FileLoader( this.manager );
  17877. loader.setPath( this.path );
  17878. loader.setRequestHeader( this.requestHeader );
  17879. loader.setWithCredentials( this.withCredentials );
  17880. loader.load( url, function ( text ) {
  17881. try {
  17882. onLoad( scope.parse( JSON.parse( text ) ) );
  17883. } catch ( e ) {
  17884. if ( onError ) {
  17885. onError( e );
  17886. } else {
  17887. console.error( e );
  17888. }
  17889. scope.manager.itemError( url );
  17890. }
  17891. }, onProgress, onError );
  17892. }
  17893. parse( json ) {
  17894. const animations = [];
  17895. for ( let i = 0; i < json.length; i ++ ) {
  17896. const clip = AnimationClip.parse( json[ i ] );
  17897. animations.push( clip );
  17898. }
  17899. return animations;
  17900. }
  17901. }
  17902. /**
  17903. * Abstract Base class to block based textures loader (dds, pvr, ...)
  17904. *
  17905. * Sub classes have to implement the parse() method which will be used in load().
  17906. */
  17907. class CompressedTextureLoader extends Loader {
  17908. constructor( manager ) {
  17909. super( manager );
  17910. }
  17911. load( url, onLoad, onProgress, onError ) {
  17912. const scope = this;
  17913. const images = [];
  17914. const texture = new CompressedTexture();
  17915. const loader = new FileLoader( this.manager );
  17916. loader.setPath( this.path );
  17917. loader.setResponseType( 'arraybuffer' );
  17918. loader.setRequestHeader( this.requestHeader );
  17919. loader.setWithCredentials( scope.withCredentials );
  17920. let loaded = 0;
  17921. function loadTexture( i ) {
  17922. loader.load( url[ i ], function ( buffer ) {
  17923. const texDatas = scope.parse( buffer, true );
  17924. images[ i ] = {
  17925. width: texDatas.width,
  17926. height: texDatas.height,
  17927. format: texDatas.format,
  17928. mipmaps: texDatas.mipmaps
  17929. };
  17930. loaded += 1;
  17931. if ( loaded === 6 ) {
  17932. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  17933. texture.image = images;
  17934. texture.format = texDatas.format;
  17935. texture.needsUpdate = true;
  17936. if ( onLoad ) onLoad( texture );
  17937. }
  17938. }, onProgress, onError );
  17939. }
  17940. if ( Array.isArray( url ) ) {
  17941. for ( let i = 0, il = url.length; i < il; ++ i ) {
  17942. loadTexture( i );
  17943. }
  17944. } else {
  17945. // compressed cubemap texture stored in a single DDS file
  17946. loader.load( url, function ( buffer ) {
  17947. const texDatas = scope.parse( buffer, true );
  17948. if ( texDatas.isCubemap ) {
  17949. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  17950. for ( let f = 0; f < faces; f ++ ) {
  17951. images[ f ] = { mipmaps: [] };
  17952. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  17953. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  17954. images[ f ].format = texDatas.format;
  17955. images[ f ].width = texDatas.width;
  17956. images[ f ].height = texDatas.height;
  17957. }
  17958. }
  17959. texture.image = images;
  17960. } else {
  17961. texture.image.width = texDatas.width;
  17962. texture.image.height = texDatas.height;
  17963. texture.mipmaps = texDatas.mipmaps;
  17964. }
  17965. if ( texDatas.mipmapCount === 1 ) {
  17966. texture.minFilter = LinearFilter;
  17967. }
  17968. texture.format = texDatas.format;
  17969. texture.needsUpdate = true;
  17970. if ( onLoad ) onLoad( texture );
  17971. }, onProgress, onError );
  17972. }
  17973. return texture;
  17974. }
  17975. }
  17976. class ImageLoader extends Loader {
  17977. constructor( manager ) {
  17978. super( manager );
  17979. }
  17980. load( url, onLoad, onProgress, onError ) {
  17981. if ( this.path !== undefined ) url = this.path + url;
  17982. url = this.manager.resolveURL( url );
  17983. const scope = this;
  17984. const cached = Cache.get( url );
  17985. if ( cached !== undefined ) {
  17986. scope.manager.itemStart( url );
  17987. setTimeout( function () {
  17988. if ( onLoad ) onLoad( cached );
  17989. scope.manager.itemEnd( url );
  17990. }, 0 );
  17991. return cached;
  17992. }
  17993. const image = createElementNS( 'img' );
  17994. function onImageLoad() {
  17995. removeEventListeners();
  17996. Cache.add( url, this );
  17997. if ( onLoad ) onLoad( this );
  17998. scope.manager.itemEnd( url );
  17999. }
  18000. function onImageError( event ) {
  18001. removeEventListeners();
  18002. if ( onError ) onError( event );
  18003. scope.manager.itemError( url );
  18004. scope.manager.itemEnd( url );
  18005. }
  18006. function removeEventListeners() {
  18007. image.removeEventListener( 'load', onImageLoad, false );
  18008. image.removeEventListener( 'error', onImageError, false );
  18009. }
  18010. image.addEventListener( 'load', onImageLoad, false );
  18011. image.addEventListener( 'error', onImageError, false );
  18012. if ( url.slice( 0, 5 ) !== 'data:' ) {
  18013. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  18014. }
  18015. scope.manager.itemStart( url );
  18016. image.src = url;
  18017. return image;
  18018. }
  18019. }
  18020. class CubeTextureLoader extends Loader {
  18021. constructor( manager ) {
  18022. super( manager );
  18023. }
  18024. load( urls, onLoad, onProgress, onError ) {
  18025. const texture = new CubeTexture();
  18026. texture.colorSpace = SRGBColorSpace;
  18027. const loader = new ImageLoader( this.manager );
  18028. loader.setCrossOrigin( this.crossOrigin );
  18029. loader.setPath( this.path );
  18030. let loaded = 0;
  18031. function loadTexture( i ) {
  18032. loader.load( urls[ i ], function ( image ) {
  18033. texture.images[ i ] = image;
  18034. loaded ++;
  18035. if ( loaded === 6 ) {
  18036. texture.needsUpdate = true;
  18037. if ( onLoad ) onLoad( texture );
  18038. }
  18039. }, undefined, onError );
  18040. }
  18041. for ( let i = 0; i < urls.length; ++ i ) {
  18042. loadTexture( i );
  18043. }
  18044. return texture;
  18045. }
  18046. }
  18047. /**
  18048. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  18049. *
  18050. * Sub classes have to implement the parse() method which will be used in load().
  18051. */
  18052. class DataTextureLoader extends Loader {
  18053. constructor( manager ) {
  18054. super( manager );
  18055. }
  18056. load( url, onLoad, onProgress, onError ) {
  18057. const scope = this;
  18058. const texture = new DataTexture();
  18059. const loader = new FileLoader( this.manager );
  18060. loader.setResponseType( 'arraybuffer' );
  18061. loader.setRequestHeader( this.requestHeader );
  18062. loader.setPath( this.path );
  18063. loader.setWithCredentials( scope.withCredentials );
  18064. loader.load( url, function ( buffer ) {
  18065. let texData;
  18066. try {
  18067. texData = scope.parse( buffer );
  18068. } catch ( error ) {
  18069. if ( onError !== undefined ) {
  18070. onError( error );
  18071. } else {
  18072. console.error( error );
  18073. return;
  18074. }
  18075. }
  18076. if ( texData.image !== undefined ) {
  18077. texture.image = texData.image;
  18078. } else if ( texData.data !== undefined ) {
  18079. texture.image.width = texData.width;
  18080. texture.image.height = texData.height;
  18081. texture.image.data = texData.data;
  18082. }
  18083. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  18084. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  18085. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  18086. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  18087. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  18088. if ( texData.colorSpace !== undefined ) {
  18089. texture.colorSpace = texData.colorSpace;
  18090. }
  18091. if ( texData.flipY !== undefined ) {
  18092. texture.flipY = texData.flipY;
  18093. }
  18094. if ( texData.format !== undefined ) {
  18095. texture.format = texData.format;
  18096. }
  18097. if ( texData.type !== undefined ) {
  18098. texture.type = texData.type;
  18099. }
  18100. if ( texData.mipmaps !== undefined ) {
  18101. texture.mipmaps = texData.mipmaps;
  18102. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  18103. }
  18104. if ( texData.mipmapCount === 1 ) {
  18105. texture.minFilter = LinearFilter;
  18106. }
  18107. if ( texData.generateMipmaps !== undefined ) {
  18108. texture.generateMipmaps = texData.generateMipmaps;
  18109. }
  18110. texture.needsUpdate = true;
  18111. if ( onLoad ) onLoad( texture, texData );
  18112. }, onProgress, onError );
  18113. return texture;
  18114. }
  18115. }
  18116. class TextureLoader extends Loader {
  18117. constructor( manager ) {
  18118. super( manager );
  18119. }
  18120. load( url, onLoad, onProgress, onError ) {
  18121. const texture = new Texture();
  18122. const loader = new ImageLoader( this.manager );
  18123. loader.setCrossOrigin( this.crossOrigin );
  18124. loader.setPath( this.path );
  18125. loader.load( url, function ( image ) {
  18126. texture.image = image;
  18127. texture.needsUpdate = true;
  18128. if ( onLoad !== undefined ) {
  18129. onLoad( texture );
  18130. }
  18131. }, onProgress, onError );
  18132. return texture;
  18133. }
  18134. }
  18135. class Light extends Object3D {
  18136. constructor( color, intensity = 1 ) {
  18137. super();
  18138. this.isLight = true;
  18139. this.type = 'Light';
  18140. this.color = new Color( color );
  18141. this.intensity = intensity;
  18142. }
  18143. dispose() {
  18144. // Empty here in base class; some subclasses override.
  18145. }
  18146. copy( source, recursive ) {
  18147. super.copy( source, recursive );
  18148. this.color.copy( source.color );
  18149. this.intensity = source.intensity;
  18150. return this;
  18151. }
  18152. toJSON( meta ) {
  18153. const data = super.toJSON( meta );
  18154. data.object.color = this.color.getHex();
  18155. data.object.intensity = this.intensity;
  18156. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  18157. if ( this.distance !== undefined ) data.object.distance = this.distance;
  18158. if ( this.angle !== undefined ) data.object.angle = this.angle;
  18159. if ( this.decay !== undefined ) data.object.decay = this.decay;
  18160. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  18161. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  18162. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  18163. return data;
  18164. }
  18165. }
  18166. class HemisphereLight extends Light {
  18167. constructor( skyColor, groundColor, intensity ) {
  18168. super( skyColor, intensity );
  18169. this.isHemisphereLight = true;
  18170. this.type = 'HemisphereLight';
  18171. this.position.copy( Object3D.DEFAULT_UP );
  18172. this.updateMatrix();
  18173. this.groundColor = new Color( groundColor );
  18174. }
  18175. copy( source, recursive ) {
  18176. super.copy( source, recursive );
  18177. this.groundColor.copy( source.groundColor );
  18178. return this;
  18179. }
  18180. }
  18181. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  18182. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  18183. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  18184. class LightShadow {
  18185. constructor( camera ) {
  18186. this.camera = camera;
  18187. this.intensity = 1;
  18188. this.bias = 0;
  18189. this.normalBias = 0;
  18190. this.radius = 1;
  18191. this.blurSamples = 8;
  18192. this.mapSize = new Vector2( 512, 512 );
  18193. this.map = null;
  18194. this.mapPass = null;
  18195. this.matrix = new Matrix4();
  18196. this.autoUpdate = true;
  18197. this.needsUpdate = false;
  18198. this._frustum = new Frustum();
  18199. this._frameExtents = new Vector2( 1, 1 );
  18200. this._viewportCount = 1;
  18201. this._viewports = [
  18202. new Vector4( 0, 0, 1, 1 )
  18203. ];
  18204. }
  18205. getViewportCount() {
  18206. return this._viewportCount;
  18207. }
  18208. getFrustum() {
  18209. return this._frustum;
  18210. }
  18211. updateMatrices( light ) {
  18212. const shadowCamera = this.camera;
  18213. const shadowMatrix = this.matrix;
  18214. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  18215. shadowCamera.position.copy( _lightPositionWorld$1 );
  18216. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  18217. shadowCamera.lookAt( _lookTarget$1 );
  18218. shadowCamera.updateMatrixWorld();
  18219. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  18220. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  18221. shadowMatrix.set(
  18222. 0.5, 0.0, 0.0, 0.5,
  18223. 0.0, 0.5, 0.0, 0.5,
  18224. 0.0, 0.0, 0.5, 0.5,
  18225. 0.0, 0.0, 0.0, 1.0
  18226. );
  18227. shadowMatrix.multiply( _projScreenMatrix$1 );
  18228. }
  18229. getViewport( viewportIndex ) {
  18230. return this._viewports[ viewportIndex ];
  18231. }
  18232. getFrameExtents() {
  18233. return this._frameExtents;
  18234. }
  18235. dispose() {
  18236. if ( this.map ) {
  18237. this.map.dispose();
  18238. }
  18239. if ( this.mapPass ) {
  18240. this.mapPass.dispose();
  18241. }
  18242. }
  18243. copy( source ) {
  18244. this.camera = source.camera.clone();
  18245. this.intensity = source.intensity;
  18246. this.bias = source.bias;
  18247. this.radius = source.radius;
  18248. this.mapSize.copy( source.mapSize );
  18249. return this;
  18250. }
  18251. clone() {
  18252. return new this.constructor().copy( this );
  18253. }
  18254. toJSON() {
  18255. const object = {};
  18256. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  18257. if ( this.bias !== 0 ) object.bias = this.bias;
  18258. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  18259. if ( this.radius !== 1 ) object.radius = this.radius;
  18260. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  18261. object.camera = this.camera.toJSON( false ).object;
  18262. delete object.camera.matrix;
  18263. return object;
  18264. }
  18265. }
  18266. class SpotLightShadow extends LightShadow {
  18267. constructor() {
  18268. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  18269. this.isSpotLightShadow = true;
  18270. this.focus = 1;
  18271. }
  18272. updateMatrices( light ) {
  18273. const camera = this.camera;
  18274. const fov = RAD2DEG * 2 * light.angle * this.focus;
  18275. const aspect = this.mapSize.width / this.mapSize.height;
  18276. const far = light.distance || camera.far;
  18277. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  18278. camera.fov = fov;
  18279. camera.aspect = aspect;
  18280. camera.far = far;
  18281. camera.updateProjectionMatrix();
  18282. }
  18283. super.updateMatrices( light );
  18284. }
  18285. copy( source ) {
  18286. super.copy( source );
  18287. this.focus = source.focus;
  18288. return this;
  18289. }
  18290. }
  18291. class SpotLight extends Light {
  18292. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  18293. super( color, intensity );
  18294. this.isSpotLight = true;
  18295. this.type = 'SpotLight';
  18296. this.position.copy( Object3D.DEFAULT_UP );
  18297. this.updateMatrix();
  18298. this.target = new Object3D();
  18299. this.distance = distance;
  18300. this.angle = angle;
  18301. this.penumbra = penumbra;
  18302. this.decay = decay;
  18303. this.map = null;
  18304. this.shadow = new SpotLightShadow();
  18305. }
  18306. get power() {
  18307. // compute the light's luminous power (in lumens) from its intensity (in candela)
  18308. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  18309. return this.intensity * Math.PI;
  18310. }
  18311. set power( power ) {
  18312. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  18313. this.intensity = power / Math.PI;
  18314. }
  18315. dispose() {
  18316. this.shadow.dispose();
  18317. }
  18318. copy( source, recursive ) {
  18319. super.copy( source, recursive );
  18320. this.distance = source.distance;
  18321. this.angle = source.angle;
  18322. this.penumbra = source.penumbra;
  18323. this.decay = source.decay;
  18324. this.target = source.target.clone();
  18325. this.shadow = source.shadow.clone();
  18326. return this;
  18327. }
  18328. }
  18329. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  18330. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  18331. const _lookTarget = /*@__PURE__*/ new Vector3();
  18332. class PointLightShadow extends LightShadow {
  18333. constructor() {
  18334. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  18335. this.isPointLightShadow = true;
  18336. this._frameExtents = new Vector2( 4, 2 );
  18337. this._viewportCount = 6;
  18338. this._viewports = [
  18339. // These viewports map a cube-map onto a 2D texture with the
  18340. // following orientation:
  18341. //
  18342. // xzXZ
  18343. // y Y
  18344. //
  18345. // X - Positive x direction
  18346. // x - Negative x direction
  18347. // Y - Positive y direction
  18348. // y - Negative y direction
  18349. // Z - Positive z direction
  18350. // z - Negative z direction
  18351. // positive X
  18352. new Vector4( 2, 1, 1, 1 ),
  18353. // negative X
  18354. new Vector4( 0, 1, 1, 1 ),
  18355. // positive Z
  18356. new Vector4( 3, 1, 1, 1 ),
  18357. // negative Z
  18358. new Vector4( 1, 1, 1, 1 ),
  18359. // positive Y
  18360. new Vector4( 3, 0, 1, 1 ),
  18361. // negative Y
  18362. new Vector4( 1, 0, 1, 1 )
  18363. ];
  18364. this._cubeDirections = [
  18365. new Vector3( 1, 0, 0 ), new Vector3( -1, 0, 0 ), new Vector3( 0, 0, 1 ),
  18366. new Vector3( 0, 0, -1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, -1, 0 )
  18367. ];
  18368. this._cubeUps = [
  18369. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  18370. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, -1 )
  18371. ];
  18372. }
  18373. updateMatrices( light, viewportIndex = 0 ) {
  18374. const camera = this.camera;
  18375. const shadowMatrix = this.matrix;
  18376. const far = light.distance || camera.far;
  18377. if ( far !== camera.far ) {
  18378. camera.far = far;
  18379. camera.updateProjectionMatrix();
  18380. }
  18381. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  18382. camera.position.copy( _lightPositionWorld );
  18383. _lookTarget.copy( camera.position );
  18384. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  18385. camera.up.copy( this._cubeUps[ viewportIndex ] );
  18386. camera.lookAt( _lookTarget );
  18387. camera.updateMatrixWorld();
  18388. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  18389. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  18390. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  18391. }
  18392. }
  18393. class PointLight extends Light {
  18394. constructor( color, intensity, distance = 0, decay = 2 ) {
  18395. super( color, intensity );
  18396. this.isPointLight = true;
  18397. this.type = 'PointLight';
  18398. this.distance = distance;
  18399. this.decay = decay;
  18400. this.shadow = new PointLightShadow();
  18401. }
  18402. get power() {
  18403. // compute the light's luminous power (in lumens) from its intensity (in candela)
  18404. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  18405. return this.intensity * 4 * Math.PI;
  18406. }
  18407. set power( power ) {
  18408. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  18409. this.intensity = power / ( 4 * Math.PI );
  18410. }
  18411. dispose() {
  18412. this.shadow.dispose();
  18413. }
  18414. copy( source, recursive ) {
  18415. super.copy( source, recursive );
  18416. this.distance = source.distance;
  18417. this.decay = source.decay;
  18418. this.shadow = source.shadow.clone();
  18419. return this;
  18420. }
  18421. }
  18422. class OrthographicCamera extends Camera {
  18423. constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) {
  18424. super();
  18425. this.isOrthographicCamera = true;
  18426. this.type = 'OrthographicCamera';
  18427. this.zoom = 1;
  18428. this.view = null;
  18429. this.left = left;
  18430. this.right = right;
  18431. this.top = top;
  18432. this.bottom = bottom;
  18433. this.near = near;
  18434. this.far = far;
  18435. this.updateProjectionMatrix();
  18436. }
  18437. copy( source, recursive ) {
  18438. super.copy( source, recursive );
  18439. this.left = source.left;
  18440. this.right = source.right;
  18441. this.top = source.top;
  18442. this.bottom = source.bottom;
  18443. this.near = source.near;
  18444. this.far = source.far;
  18445. this.zoom = source.zoom;
  18446. this.view = source.view === null ? null : Object.assign( {}, source.view );
  18447. return this;
  18448. }
  18449. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  18450. if ( this.view === null ) {
  18451. this.view = {
  18452. enabled: true,
  18453. fullWidth: 1,
  18454. fullHeight: 1,
  18455. offsetX: 0,
  18456. offsetY: 0,
  18457. width: 1,
  18458. height: 1
  18459. };
  18460. }
  18461. this.view.enabled = true;
  18462. this.view.fullWidth = fullWidth;
  18463. this.view.fullHeight = fullHeight;
  18464. this.view.offsetX = x;
  18465. this.view.offsetY = y;
  18466. this.view.width = width;
  18467. this.view.height = height;
  18468. this.updateProjectionMatrix();
  18469. }
  18470. clearViewOffset() {
  18471. if ( this.view !== null ) {
  18472. this.view.enabled = false;
  18473. }
  18474. this.updateProjectionMatrix();
  18475. }
  18476. updateProjectionMatrix() {
  18477. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  18478. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  18479. const cx = ( this.right + this.left ) / 2;
  18480. const cy = ( this.top + this.bottom ) / 2;
  18481. let left = cx - dx;
  18482. let right = cx + dx;
  18483. let top = cy + dy;
  18484. let bottom = cy - dy;
  18485. if ( this.view !== null && this.view.enabled ) {
  18486. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  18487. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  18488. left += scaleW * this.view.offsetX;
  18489. right = left + scaleW * this.view.width;
  18490. top -= scaleH * this.view.offsetY;
  18491. bottom = top - scaleH * this.view.height;
  18492. }
  18493. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem );
  18494. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  18495. }
  18496. toJSON( meta ) {
  18497. const data = super.toJSON( meta );
  18498. data.object.zoom = this.zoom;
  18499. data.object.left = this.left;
  18500. data.object.right = this.right;
  18501. data.object.top = this.top;
  18502. data.object.bottom = this.bottom;
  18503. data.object.near = this.near;
  18504. data.object.far = this.far;
  18505. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  18506. return data;
  18507. }
  18508. }
  18509. class DirectionalLightShadow extends LightShadow {
  18510. constructor() {
  18511. super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) );
  18512. this.isDirectionalLightShadow = true;
  18513. }
  18514. }
  18515. class DirectionalLight extends Light {
  18516. constructor( color, intensity ) {
  18517. super( color, intensity );
  18518. this.isDirectionalLight = true;
  18519. this.type = 'DirectionalLight';
  18520. this.position.copy( Object3D.DEFAULT_UP );
  18521. this.updateMatrix();
  18522. this.target = new Object3D();
  18523. this.shadow = new DirectionalLightShadow();
  18524. }
  18525. dispose() {
  18526. this.shadow.dispose();
  18527. }
  18528. copy( source ) {
  18529. super.copy( source );
  18530. this.target = source.target.clone();
  18531. this.shadow = source.shadow.clone();
  18532. return this;
  18533. }
  18534. }
  18535. class AmbientLight extends Light {
  18536. constructor( color, intensity ) {
  18537. super( color, intensity );
  18538. this.isAmbientLight = true;
  18539. this.type = 'AmbientLight';
  18540. }
  18541. }
  18542. class RectAreaLight extends Light {
  18543. constructor( color, intensity, width = 10, height = 10 ) {
  18544. super( color, intensity );
  18545. this.isRectAreaLight = true;
  18546. this.type = 'RectAreaLight';
  18547. this.width = width;
  18548. this.height = height;
  18549. }
  18550. get power() {
  18551. // compute the light's luminous power (in lumens) from its intensity (in nits)
  18552. return this.intensity * this.width * this.height * Math.PI;
  18553. }
  18554. set power( power ) {
  18555. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  18556. this.intensity = power / ( this.width * this.height * Math.PI );
  18557. }
  18558. copy( source ) {
  18559. super.copy( source );
  18560. this.width = source.width;
  18561. this.height = source.height;
  18562. return this;
  18563. }
  18564. toJSON( meta ) {
  18565. const data = super.toJSON( meta );
  18566. data.object.width = this.width;
  18567. data.object.height = this.height;
  18568. return data;
  18569. }
  18570. }
  18571. /**
  18572. * Primary reference:
  18573. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  18574. *
  18575. * Secondary reference:
  18576. * https://www.ppsloan.org/publications/StupidSH36.pdf
  18577. */
  18578. // 3-band SH defined by 9 coefficients
  18579. class SphericalHarmonics3 {
  18580. constructor() {
  18581. this.isSphericalHarmonics3 = true;
  18582. this.coefficients = [];
  18583. for ( let i = 0; i < 9; i ++ ) {
  18584. this.coefficients.push( new Vector3() );
  18585. }
  18586. }
  18587. set( coefficients ) {
  18588. for ( let i = 0; i < 9; i ++ ) {
  18589. this.coefficients[ i ].copy( coefficients[ i ] );
  18590. }
  18591. return this;
  18592. }
  18593. zero() {
  18594. for ( let i = 0; i < 9; i ++ ) {
  18595. this.coefficients[ i ].set( 0, 0, 0 );
  18596. }
  18597. return this;
  18598. }
  18599. // get the radiance in the direction of the normal
  18600. // target is a Vector3
  18601. getAt( normal, target ) {
  18602. // normal is assumed to be unit length
  18603. const x = normal.x, y = normal.y, z = normal.z;
  18604. const coeff = this.coefficients;
  18605. // band 0
  18606. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  18607. // band 1
  18608. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  18609. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  18610. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  18611. // band 2
  18612. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  18613. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  18614. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  18615. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  18616. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  18617. return target;
  18618. }
  18619. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  18620. // target is a Vector3
  18621. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  18622. getIrradianceAt( normal, target ) {
  18623. // normal is assumed to be unit length
  18624. const x = normal.x, y = normal.y, z = normal.z;
  18625. const coeff = this.coefficients;
  18626. // band 0
  18627. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  18628. // band 1
  18629. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  18630. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  18631. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  18632. // band 2
  18633. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  18634. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  18635. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  18636. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  18637. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  18638. return target;
  18639. }
  18640. add( sh ) {
  18641. for ( let i = 0; i < 9; i ++ ) {
  18642. this.coefficients[ i ].add( sh.coefficients[ i ] );
  18643. }
  18644. return this;
  18645. }
  18646. addScaledSH( sh, s ) {
  18647. for ( let i = 0; i < 9; i ++ ) {
  18648. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  18649. }
  18650. return this;
  18651. }
  18652. scale( s ) {
  18653. for ( let i = 0; i < 9; i ++ ) {
  18654. this.coefficients[ i ].multiplyScalar( s );
  18655. }
  18656. return this;
  18657. }
  18658. lerp( sh, alpha ) {
  18659. for ( let i = 0; i < 9; i ++ ) {
  18660. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  18661. }
  18662. return this;
  18663. }
  18664. equals( sh ) {
  18665. for ( let i = 0; i < 9; i ++ ) {
  18666. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  18667. return false;
  18668. }
  18669. }
  18670. return true;
  18671. }
  18672. copy( sh ) {
  18673. return this.set( sh.coefficients );
  18674. }
  18675. clone() {
  18676. return new this.constructor().copy( this );
  18677. }
  18678. fromArray( array, offset = 0 ) {
  18679. const coefficients = this.coefficients;
  18680. for ( let i = 0; i < 9; i ++ ) {
  18681. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  18682. }
  18683. return this;
  18684. }
  18685. toArray( array = [], offset = 0 ) {
  18686. const coefficients = this.coefficients;
  18687. for ( let i = 0; i < 9; i ++ ) {
  18688. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  18689. }
  18690. return array;
  18691. }
  18692. // evaluate the basis functions
  18693. // shBasis is an Array[ 9 ]
  18694. static getBasisAt( normal, shBasis ) {
  18695. // normal is assumed to be unit length
  18696. const x = normal.x, y = normal.y, z = normal.z;
  18697. // band 0
  18698. shBasis[ 0 ] = 0.282095;
  18699. // band 1
  18700. shBasis[ 1 ] = 0.488603 * y;
  18701. shBasis[ 2 ] = 0.488603 * z;
  18702. shBasis[ 3 ] = 0.488603 * x;
  18703. // band 2
  18704. shBasis[ 4 ] = 1.092548 * x * y;
  18705. shBasis[ 5 ] = 1.092548 * y * z;
  18706. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  18707. shBasis[ 7 ] = 1.092548 * x * z;
  18708. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  18709. }
  18710. }
  18711. class LightProbe extends Light {
  18712. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  18713. super( undefined, intensity );
  18714. this.isLightProbe = true;
  18715. this.sh = sh;
  18716. }
  18717. copy( source ) {
  18718. super.copy( source );
  18719. this.sh.copy( source.sh );
  18720. return this;
  18721. }
  18722. fromJSON( json ) {
  18723. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  18724. this.sh.fromArray( json.sh );
  18725. return this;
  18726. }
  18727. toJSON( meta ) {
  18728. const data = super.toJSON( meta );
  18729. data.object.sh = this.sh.toArray();
  18730. return data;
  18731. }
  18732. }
  18733. class MaterialLoader extends Loader {
  18734. constructor( manager ) {
  18735. super( manager );
  18736. this.textures = {};
  18737. }
  18738. load( url, onLoad, onProgress, onError ) {
  18739. const scope = this;
  18740. const loader = new FileLoader( scope.manager );
  18741. loader.setPath( scope.path );
  18742. loader.setRequestHeader( scope.requestHeader );
  18743. loader.setWithCredentials( scope.withCredentials );
  18744. loader.load( url, function ( text ) {
  18745. try {
  18746. onLoad( scope.parse( JSON.parse( text ) ) );
  18747. } catch ( e ) {
  18748. if ( onError ) {
  18749. onError( e );
  18750. } else {
  18751. console.error( e );
  18752. }
  18753. scope.manager.itemError( url );
  18754. }
  18755. }, onProgress, onError );
  18756. }
  18757. parse( json ) {
  18758. const textures = this.textures;
  18759. function getTexture( name ) {
  18760. if ( textures[ name ] === undefined ) {
  18761. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  18762. }
  18763. return textures[ name ];
  18764. }
  18765. const material = this.createMaterialFromType( json.type );
  18766. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  18767. if ( json.name !== undefined ) material.name = json.name;
  18768. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  18769. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  18770. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  18771. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  18772. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  18773. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  18774. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  18775. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  18776. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  18777. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  18778. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  18779. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  18780. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  18781. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  18782. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  18783. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  18784. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  18785. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  18786. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  18787. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  18788. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  18789. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  18790. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  18791. if ( json.fog !== undefined ) material.fog = json.fog;
  18792. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  18793. if ( json.blending !== undefined ) material.blending = json.blending;
  18794. if ( json.combine !== undefined ) material.combine = json.combine;
  18795. if ( json.side !== undefined ) material.side = json.side;
  18796. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  18797. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  18798. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  18799. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  18800. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  18801. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  18802. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  18803. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  18804. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  18805. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  18806. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  18807. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  18808. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  18809. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  18810. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  18811. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  18812. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  18813. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  18814. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  18815. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  18816. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  18817. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  18818. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  18819. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  18820. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  18821. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  18822. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  18823. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  18824. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  18825. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  18826. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  18827. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  18828. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  18829. if ( json.scale !== undefined ) material.scale = json.scale;
  18830. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  18831. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  18832. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  18833. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  18834. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  18835. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  18836. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  18837. if ( json.visible !== undefined ) material.visible = json.visible;
  18838. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  18839. if ( json.userData !== undefined ) material.userData = json.userData;
  18840. if ( json.vertexColors !== undefined ) {
  18841. if ( typeof json.vertexColors === 'number' ) {
  18842. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  18843. } else {
  18844. material.vertexColors = json.vertexColors;
  18845. }
  18846. }
  18847. // Shader Material
  18848. if ( json.uniforms !== undefined ) {
  18849. for ( const name in json.uniforms ) {
  18850. const uniform = json.uniforms[ name ];
  18851. material.uniforms[ name ] = {};
  18852. switch ( uniform.type ) {
  18853. case 't':
  18854. material.uniforms[ name ].value = getTexture( uniform.value );
  18855. break;
  18856. case 'c':
  18857. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  18858. break;
  18859. case 'v2':
  18860. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  18861. break;
  18862. case 'v3':
  18863. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  18864. break;
  18865. case 'v4':
  18866. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  18867. break;
  18868. case 'm3':
  18869. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  18870. break;
  18871. case 'm4':
  18872. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  18873. break;
  18874. default:
  18875. material.uniforms[ name ].value = uniform.value;
  18876. }
  18877. }
  18878. }
  18879. if ( json.defines !== undefined ) material.defines = json.defines;
  18880. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  18881. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  18882. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  18883. if ( json.extensions !== undefined ) {
  18884. for ( const key in json.extensions ) {
  18885. material.extensions[ key ] = json.extensions[ key ];
  18886. }
  18887. }
  18888. if ( json.lights !== undefined ) material.lights = json.lights;
  18889. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  18890. // for PointsMaterial
  18891. if ( json.size !== undefined ) material.size = json.size;
  18892. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  18893. // maps
  18894. if ( json.map !== undefined ) material.map = getTexture( json.map );
  18895. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  18896. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  18897. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  18898. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  18899. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  18900. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  18901. if ( json.normalScale !== undefined ) {
  18902. let normalScale = json.normalScale;
  18903. if ( Array.isArray( normalScale ) === false ) {
  18904. // Blender exporter used to export a scalar. See #7459
  18905. normalScale = [ normalScale, normalScale ];
  18906. }
  18907. material.normalScale = new Vector2().fromArray( normalScale );
  18908. }
  18909. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  18910. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  18911. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  18912. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  18913. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  18914. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  18915. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  18916. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  18917. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  18918. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  18919. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  18920. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  18921. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  18922. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  18923. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  18924. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  18925. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  18926. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  18927. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  18928. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  18929. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  18930. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  18931. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  18932. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  18933. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  18934. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  18935. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  18936. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  18937. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  18938. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  18939. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  18940. return material;
  18941. }
  18942. setTextures( value ) {
  18943. this.textures = value;
  18944. return this;
  18945. }
  18946. createMaterialFromType( type ) {
  18947. return MaterialLoader.createMaterialFromType( type );
  18948. }
  18949. static createMaterialFromType( type ) {
  18950. const materialLib = {
  18951. ShadowMaterial,
  18952. SpriteMaterial,
  18953. RawShaderMaterial,
  18954. ShaderMaterial,
  18955. PointsMaterial,
  18956. MeshPhysicalMaterial,
  18957. MeshStandardMaterial,
  18958. MeshPhongMaterial,
  18959. MeshToonMaterial,
  18960. MeshNormalMaterial,
  18961. MeshLambertMaterial,
  18962. MeshDepthMaterial,
  18963. MeshDistanceMaterial,
  18964. MeshBasicMaterial,
  18965. MeshMatcapMaterial,
  18966. LineDashedMaterial,
  18967. LineBasicMaterial,
  18968. Material
  18969. };
  18970. return new materialLib[ type ]();
  18971. }
  18972. }
  18973. class LoaderUtils {
  18974. static decodeText( array ) { // @deprecated, r165
  18975. console.warn( 'THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead.' );
  18976. if ( typeof TextDecoder !== 'undefined' ) {
  18977. return new TextDecoder().decode( array );
  18978. }
  18979. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  18980. // throws a "maximum call stack size exceeded" error for large arrays.
  18981. let s = '';
  18982. for ( let i = 0, il = array.length; i < il; i ++ ) {
  18983. // Implicitly assumes little-endian.
  18984. s += String.fromCharCode( array[ i ] );
  18985. }
  18986. try {
  18987. // merges multi-byte utf-8 characters.
  18988. return decodeURIComponent( escape( s ) );
  18989. } catch ( e ) { // see #16358
  18990. return s;
  18991. }
  18992. }
  18993. static extractUrlBase( url ) {
  18994. const index = url.lastIndexOf( '/' );
  18995. if ( index === -1 ) return './';
  18996. return url.slice( 0, index + 1 );
  18997. }
  18998. static resolveURL( url, path ) {
  18999. // Invalid URL
  19000. if ( typeof url !== 'string' || url === '' ) return '';
  19001. // Host Relative URL
  19002. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  19003. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  19004. }
  19005. // Absolute URL http://,https://,//
  19006. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  19007. // Data URI
  19008. if ( /^data:.*,.*$/i.test( url ) ) return url;
  19009. // Blob URL
  19010. if ( /^blob:.*$/i.test( url ) ) return url;
  19011. // Relative URL
  19012. return path + url;
  19013. }
  19014. }
  19015. class InstancedBufferGeometry extends BufferGeometry {
  19016. constructor() {
  19017. super();
  19018. this.isInstancedBufferGeometry = true;
  19019. this.type = 'InstancedBufferGeometry';
  19020. this.instanceCount = Infinity;
  19021. }
  19022. copy( source ) {
  19023. super.copy( source );
  19024. this.instanceCount = source.instanceCount;
  19025. return this;
  19026. }
  19027. toJSON() {
  19028. const data = super.toJSON();
  19029. data.instanceCount = this.instanceCount;
  19030. data.isInstancedBufferGeometry = true;
  19031. return data;
  19032. }
  19033. }
  19034. class BufferGeometryLoader extends Loader {
  19035. constructor( manager ) {
  19036. super( manager );
  19037. }
  19038. load( url, onLoad, onProgress, onError ) {
  19039. const scope = this;
  19040. const loader = new FileLoader( scope.manager );
  19041. loader.setPath( scope.path );
  19042. loader.setRequestHeader( scope.requestHeader );
  19043. loader.setWithCredentials( scope.withCredentials );
  19044. loader.load( url, function ( text ) {
  19045. try {
  19046. onLoad( scope.parse( JSON.parse( text ) ) );
  19047. } catch ( e ) {
  19048. if ( onError ) {
  19049. onError( e );
  19050. } else {
  19051. console.error( e );
  19052. }
  19053. scope.manager.itemError( url );
  19054. }
  19055. }, onProgress, onError );
  19056. }
  19057. parse( json ) {
  19058. const interleavedBufferMap = {};
  19059. const arrayBufferMap = {};
  19060. function getInterleavedBuffer( json, uuid ) {
  19061. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  19062. const interleavedBuffers = json.interleavedBuffers;
  19063. const interleavedBuffer = interleavedBuffers[ uuid ];
  19064. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  19065. const array = getTypedArray( interleavedBuffer.type, buffer );
  19066. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  19067. ib.uuid = interleavedBuffer.uuid;
  19068. interleavedBufferMap[ uuid ] = ib;
  19069. return ib;
  19070. }
  19071. function getArrayBuffer( json, uuid ) {
  19072. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  19073. const arrayBuffers = json.arrayBuffers;
  19074. const arrayBuffer = arrayBuffers[ uuid ];
  19075. const ab = new Uint32Array( arrayBuffer ).buffer;
  19076. arrayBufferMap[ uuid ] = ab;
  19077. return ab;
  19078. }
  19079. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  19080. const index = json.data.index;
  19081. if ( index !== undefined ) {
  19082. const typedArray = getTypedArray( index.type, index.array );
  19083. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  19084. }
  19085. const attributes = json.data.attributes;
  19086. for ( const key in attributes ) {
  19087. const attribute = attributes[ key ];
  19088. let bufferAttribute;
  19089. if ( attribute.isInterleavedBufferAttribute ) {
  19090. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  19091. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  19092. } else {
  19093. const typedArray = getTypedArray( attribute.type, attribute.array );
  19094. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  19095. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  19096. }
  19097. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  19098. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  19099. geometry.setAttribute( key, bufferAttribute );
  19100. }
  19101. const morphAttributes = json.data.morphAttributes;
  19102. if ( morphAttributes ) {
  19103. for ( const key in morphAttributes ) {
  19104. const attributeArray = morphAttributes[ key ];
  19105. const array = [];
  19106. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  19107. const attribute = attributeArray[ i ];
  19108. let bufferAttribute;
  19109. if ( attribute.isInterleavedBufferAttribute ) {
  19110. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  19111. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  19112. } else {
  19113. const typedArray = getTypedArray( attribute.type, attribute.array );
  19114. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  19115. }
  19116. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  19117. array.push( bufferAttribute );
  19118. }
  19119. geometry.morphAttributes[ key ] = array;
  19120. }
  19121. }
  19122. const morphTargetsRelative = json.data.morphTargetsRelative;
  19123. if ( morphTargetsRelative ) {
  19124. geometry.morphTargetsRelative = true;
  19125. }
  19126. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  19127. if ( groups !== undefined ) {
  19128. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  19129. const group = groups[ i ];
  19130. geometry.addGroup( group.start, group.count, group.materialIndex );
  19131. }
  19132. }
  19133. const boundingSphere = json.data.boundingSphere;
  19134. if ( boundingSphere !== undefined ) {
  19135. const center = new Vector3();
  19136. if ( boundingSphere.center !== undefined ) {
  19137. center.fromArray( boundingSphere.center );
  19138. }
  19139. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  19140. }
  19141. if ( json.name ) geometry.name = json.name;
  19142. if ( json.userData ) geometry.userData = json.userData;
  19143. return geometry;
  19144. }
  19145. }
  19146. class ObjectLoader extends Loader {
  19147. constructor( manager ) {
  19148. super( manager );
  19149. }
  19150. load( url, onLoad, onProgress, onError ) {
  19151. const scope = this;
  19152. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  19153. this.resourcePath = this.resourcePath || path;
  19154. const loader = new FileLoader( this.manager );
  19155. loader.setPath( this.path );
  19156. loader.setRequestHeader( this.requestHeader );
  19157. loader.setWithCredentials( this.withCredentials );
  19158. loader.load( url, function ( text ) {
  19159. let json = null;
  19160. try {
  19161. json = JSON.parse( text );
  19162. } catch ( error ) {
  19163. if ( onError !== undefined ) onError( error );
  19164. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  19165. return;
  19166. }
  19167. const metadata = json.metadata;
  19168. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  19169. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  19170. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  19171. return;
  19172. }
  19173. scope.parse( json, onLoad );
  19174. }, onProgress, onError );
  19175. }
  19176. async loadAsync( url, onProgress ) {
  19177. const scope = this;
  19178. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  19179. this.resourcePath = this.resourcePath || path;
  19180. const loader = new FileLoader( this.manager );
  19181. loader.setPath( this.path );
  19182. loader.setRequestHeader( this.requestHeader );
  19183. loader.setWithCredentials( this.withCredentials );
  19184. const text = await loader.loadAsync( url, onProgress );
  19185. const json = JSON.parse( text );
  19186. const metadata = json.metadata;
  19187. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  19188. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  19189. }
  19190. return await scope.parseAsync( json );
  19191. }
  19192. parse( json, onLoad ) {
  19193. const animations = this.parseAnimations( json.animations );
  19194. const shapes = this.parseShapes( json.shapes );
  19195. const geometries = this.parseGeometries( json.geometries, shapes );
  19196. const images = this.parseImages( json.images, function () {
  19197. if ( onLoad !== undefined ) onLoad( object );
  19198. } );
  19199. const textures = this.parseTextures( json.textures, images );
  19200. const materials = this.parseMaterials( json.materials, textures );
  19201. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  19202. const skeletons = this.parseSkeletons( json.skeletons, object );
  19203. this.bindSkeletons( object, skeletons );
  19204. this.bindLightTargets( object );
  19205. //
  19206. if ( onLoad !== undefined ) {
  19207. let hasImages = false;
  19208. for ( const uuid in images ) {
  19209. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  19210. hasImages = true;
  19211. break;
  19212. }
  19213. }
  19214. if ( hasImages === false ) onLoad( object );
  19215. }
  19216. return object;
  19217. }
  19218. async parseAsync( json ) {
  19219. const animations = this.parseAnimations( json.animations );
  19220. const shapes = this.parseShapes( json.shapes );
  19221. const geometries = this.parseGeometries( json.geometries, shapes );
  19222. const images = await this.parseImagesAsync( json.images );
  19223. const textures = this.parseTextures( json.textures, images );
  19224. const materials = this.parseMaterials( json.materials, textures );
  19225. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  19226. const skeletons = this.parseSkeletons( json.skeletons, object );
  19227. this.bindSkeletons( object, skeletons );
  19228. this.bindLightTargets( object );
  19229. return object;
  19230. }
  19231. parseShapes( json ) {
  19232. const shapes = {};
  19233. if ( json !== undefined ) {
  19234. for ( let i = 0, l = json.length; i < l; i ++ ) {
  19235. const shape = new Shape().fromJSON( json[ i ] );
  19236. shapes[ shape.uuid ] = shape;
  19237. }
  19238. }
  19239. return shapes;
  19240. }
  19241. parseSkeletons( json, object ) {
  19242. const skeletons = {};
  19243. const bones = {};
  19244. // generate bone lookup table
  19245. object.traverse( function ( child ) {
  19246. if ( child.isBone ) bones[ child.uuid ] = child;
  19247. } );
  19248. // create skeletons
  19249. if ( json !== undefined ) {
  19250. for ( let i = 0, l = json.length; i < l; i ++ ) {
  19251. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  19252. skeletons[ skeleton.uuid ] = skeleton;
  19253. }
  19254. }
  19255. return skeletons;
  19256. }
  19257. parseGeometries( json, shapes ) {
  19258. const geometries = {};
  19259. if ( json !== undefined ) {
  19260. const bufferGeometryLoader = new BufferGeometryLoader();
  19261. for ( let i = 0, l = json.length; i < l; i ++ ) {
  19262. let geometry;
  19263. const data = json[ i ];
  19264. switch ( data.type ) {
  19265. case 'BufferGeometry':
  19266. case 'InstancedBufferGeometry':
  19267. geometry = bufferGeometryLoader.parse( data );
  19268. break;
  19269. default:
  19270. if ( data.type in Geometries ) {
  19271. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  19272. } else {
  19273. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  19274. }
  19275. }
  19276. geometry.uuid = data.uuid;
  19277. if ( data.name !== undefined ) geometry.name = data.name;
  19278. if ( data.userData !== undefined ) geometry.userData = data.userData;
  19279. geometries[ data.uuid ] = geometry;
  19280. }
  19281. }
  19282. return geometries;
  19283. }
  19284. parseMaterials( json, textures ) {
  19285. const cache = {}; // MultiMaterial
  19286. const materials = {};
  19287. if ( json !== undefined ) {
  19288. const loader = new MaterialLoader();
  19289. loader.setTextures( textures );
  19290. for ( let i = 0, l = json.length; i < l; i ++ ) {
  19291. const data = json[ i ];
  19292. if ( cache[ data.uuid ] === undefined ) {
  19293. cache[ data.uuid ] = loader.parse( data );
  19294. }
  19295. materials[ data.uuid ] = cache[ data.uuid ];
  19296. }
  19297. }
  19298. return materials;
  19299. }
  19300. parseAnimations( json ) {
  19301. const animations = {};
  19302. if ( json !== undefined ) {
  19303. for ( let i = 0; i < json.length; i ++ ) {
  19304. const data = json[ i ];
  19305. const clip = AnimationClip.parse( data );
  19306. animations[ clip.uuid ] = clip;
  19307. }
  19308. }
  19309. return animations;
  19310. }
  19311. parseImages( json, onLoad ) {
  19312. const scope = this;
  19313. const images = {};
  19314. let loader;
  19315. function loadImage( url ) {
  19316. scope.manager.itemStart( url );
  19317. return loader.load( url, function () {
  19318. scope.manager.itemEnd( url );
  19319. }, undefined, function () {
  19320. scope.manager.itemError( url );
  19321. scope.manager.itemEnd( url );
  19322. } );
  19323. }
  19324. function deserializeImage( image ) {
  19325. if ( typeof image === 'string' ) {
  19326. const url = image;
  19327. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  19328. return loadImage( path );
  19329. } else {
  19330. if ( image.data ) {
  19331. return {
  19332. data: getTypedArray( image.type, image.data ),
  19333. width: image.width,
  19334. height: image.height
  19335. };
  19336. } else {
  19337. return null;
  19338. }
  19339. }
  19340. }
  19341. if ( json !== undefined && json.length > 0 ) {
  19342. const manager = new LoadingManager( onLoad );
  19343. loader = new ImageLoader( manager );
  19344. loader.setCrossOrigin( this.crossOrigin );
  19345. for ( let i = 0, il = json.length; i < il; i ++ ) {
  19346. const image = json[ i ];
  19347. const url = image.url;
  19348. if ( Array.isArray( url ) ) {
  19349. // load array of images e.g CubeTexture
  19350. const imageArray = [];
  19351. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  19352. const currentUrl = url[ j ];
  19353. const deserializedImage = deserializeImage( currentUrl );
  19354. if ( deserializedImage !== null ) {
  19355. if ( deserializedImage instanceof HTMLImageElement ) {
  19356. imageArray.push( deserializedImage );
  19357. } else {
  19358. // special case: handle array of data textures for cube textures
  19359. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  19360. }
  19361. }
  19362. }
  19363. images[ image.uuid ] = new Source( imageArray );
  19364. } else {
  19365. // load single image
  19366. const deserializedImage = deserializeImage( image.url );
  19367. images[ image.uuid ] = new Source( deserializedImage );
  19368. }
  19369. }
  19370. }
  19371. return images;
  19372. }
  19373. async parseImagesAsync( json ) {
  19374. const scope = this;
  19375. const images = {};
  19376. let loader;
  19377. async function deserializeImage( image ) {
  19378. if ( typeof image === 'string' ) {
  19379. const url = image;
  19380. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  19381. return await loader.loadAsync( path );
  19382. } else {
  19383. if ( image.data ) {
  19384. return {
  19385. data: getTypedArray( image.type, image.data ),
  19386. width: image.width,
  19387. height: image.height
  19388. };
  19389. } else {
  19390. return null;
  19391. }
  19392. }
  19393. }
  19394. if ( json !== undefined && json.length > 0 ) {
  19395. loader = new ImageLoader( this.manager );
  19396. loader.setCrossOrigin( this.crossOrigin );
  19397. for ( let i = 0, il = json.length; i < il; i ++ ) {
  19398. const image = json[ i ];
  19399. const url = image.url;
  19400. if ( Array.isArray( url ) ) {
  19401. // load array of images e.g CubeTexture
  19402. const imageArray = [];
  19403. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  19404. const currentUrl = url[ j ];
  19405. const deserializedImage = await deserializeImage( currentUrl );
  19406. if ( deserializedImage !== null ) {
  19407. if ( deserializedImage instanceof HTMLImageElement ) {
  19408. imageArray.push( deserializedImage );
  19409. } else {
  19410. // special case: handle array of data textures for cube textures
  19411. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  19412. }
  19413. }
  19414. }
  19415. images[ image.uuid ] = new Source( imageArray );
  19416. } else {
  19417. // load single image
  19418. const deserializedImage = await deserializeImage( image.url );
  19419. images[ image.uuid ] = new Source( deserializedImage );
  19420. }
  19421. }
  19422. }
  19423. return images;
  19424. }
  19425. parseTextures( json, images ) {
  19426. function parseConstant( value, type ) {
  19427. if ( typeof value === 'number' ) return value;
  19428. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  19429. return type[ value ];
  19430. }
  19431. const textures = {};
  19432. if ( json !== undefined ) {
  19433. for ( let i = 0, l = json.length; i < l; i ++ ) {
  19434. const data = json[ i ];
  19435. if ( data.image === undefined ) {
  19436. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  19437. }
  19438. if ( images[ data.image ] === undefined ) {
  19439. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  19440. }
  19441. const source = images[ data.image ];
  19442. const image = source.data;
  19443. let texture;
  19444. if ( Array.isArray( image ) ) {
  19445. texture = new CubeTexture();
  19446. if ( image.length === 6 ) texture.needsUpdate = true;
  19447. } else {
  19448. if ( image && image.data ) {
  19449. texture = new DataTexture();
  19450. } else {
  19451. texture = new Texture();
  19452. }
  19453. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  19454. }
  19455. texture.source = source;
  19456. texture.uuid = data.uuid;
  19457. if ( data.name !== undefined ) texture.name = data.name;
  19458. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  19459. if ( data.channel !== undefined ) texture.channel = data.channel;
  19460. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  19461. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  19462. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  19463. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  19464. if ( data.wrap !== undefined ) {
  19465. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  19466. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  19467. }
  19468. if ( data.format !== undefined ) texture.format = data.format;
  19469. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  19470. if ( data.type !== undefined ) texture.type = data.type;
  19471. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  19472. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  19473. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  19474. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  19475. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  19476. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  19477. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  19478. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  19479. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  19480. if ( data.userData !== undefined ) texture.userData = data.userData;
  19481. textures[ data.uuid ] = texture;
  19482. }
  19483. }
  19484. return textures;
  19485. }
  19486. parseObject( data, geometries, materials, textures, animations ) {
  19487. let object;
  19488. function getGeometry( name ) {
  19489. if ( geometries[ name ] === undefined ) {
  19490. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  19491. }
  19492. return geometries[ name ];
  19493. }
  19494. function getMaterial( name ) {
  19495. if ( name === undefined ) return undefined;
  19496. if ( Array.isArray( name ) ) {
  19497. const array = [];
  19498. for ( let i = 0, l = name.length; i < l; i ++ ) {
  19499. const uuid = name[ i ];
  19500. if ( materials[ uuid ] === undefined ) {
  19501. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  19502. }
  19503. array.push( materials[ uuid ] );
  19504. }
  19505. return array;
  19506. }
  19507. if ( materials[ name ] === undefined ) {
  19508. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  19509. }
  19510. return materials[ name ];
  19511. }
  19512. function getTexture( uuid ) {
  19513. if ( textures[ uuid ] === undefined ) {
  19514. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  19515. }
  19516. return textures[ uuid ];
  19517. }
  19518. let geometry, material;
  19519. switch ( data.type ) {
  19520. case 'Scene':
  19521. object = new Scene();
  19522. if ( data.background !== undefined ) {
  19523. if ( Number.isInteger( data.background ) ) {
  19524. object.background = new Color( data.background );
  19525. } else {
  19526. object.background = getTexture( data.background );
  19527. }
  19528. }
  19529. if ( data.environment !== undefined ) {
  19530. object.environment = getTexture( data.environment );
  19531. }
  19532. if ( data.fog !== undefined ) {
  19533. if ( data.fog.type === 'Fog' ) {
  19534. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  19535. } else if ( data.fog.type === 'FogExp2' ) {
  19536. object.fog = new FogExp2( data.fog.color, data.fog.density );
  19537. }
  19538. if ( data.fog.name !== '' ) {
  19539. object.fog.name = data.fog.name;
  19540. }
  19541. }
  19542. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  19543. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  19544. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  19545. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  19546. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  19547. break;
  19548. case 'PerspectiveCamera':
  19549. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  19550. if ( data.focus !== undefined ) object.focus = data.focus;
  19551. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  19552. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  19553. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  19554. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  19555. break;
  19556. case 'OrthographicCamera':
  19557. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  19558. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  19559. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  19560. break;
  19561. case 'AmbientLight':
  19562. object = new AmbientLight( data.color, data.intensity );
  19563. break;
  19564. case 'DirectionalLight':
  19565. object = new DirectionalLight( data.color, data.intensity );
  19566. object.target = data.target || '';
  19567. break;
  19568. case 'PointLight':
  19569. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  19570. break;
  19571. case 'RectAreaLight':
  19572. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  19573. break;
  19574. case 'SpotLight':
  19575. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  19576. object.target = data.target || '';
  19577. break;
  19578. case 'HemisphereLight':
  19579. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  19580. break;
  19581. case 'LightProbe':
  19582. object = new LightProbe().fromJSON( data );
  19583. break;
  19584. case 'SkinnedMesh':
  19585. geometry = getGeometry( data.geometry );
  19586. material = getMaterial( data.material );
  19587. object = new SkinnedMesh( geometry, material );
  19588. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  19589. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  19590. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  19591. break;
  19592. case 'Mesh':
  19593. geometry = getGeometry( data.geometry );
  19594. material = getMaterial( data.material );
  19595. object = new Mesh( geometry, material );
  19596. break;
  19597. case 'InstancedMesh':
  19598. geometry = getGeometry( data.geometry );
  19599. material = getMaterial( data.material );
  19600. const count = data.count;
  19601. const instanceMatrix = data.instanceMatrix;
  19602. const instanceColor = data.instanceColor;
  19603. object = new InstancedMesh( geometry, material, count );
  19604. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  19605. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  19606. break;
  19607. case 'BatchedMesh':
  19608. geometry = getGeometry( data.geometry );
  19609. material = getMaterial( data.material );
  19610. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  19611. object.geometry = geometry;
  19612. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  19613. object.sortObjects = data.sortObjects;
  19614. object._drawRanges = data.drawRanges;
  19615. object._reservedRanges = data.reservedRanges;
  19616. object._visibility = data.visibility;
  19617. object._active = data.active;
  19618. object._bounds = data.bounds.map( bound => {
  19619. const box = new Box3();
  19620. box.min.fromArray( bound.boxMin );
  19621. box.max.fromArray( bound.boxMax );
  19622. const sphere = new Sphere();
  19623. sphere.radius = bound.sphereRadius;
  19624. sphere.center.fromArray( bound.sphereCenter );
  19625. return {
  19626. boxInitialized: bound.boxInitialized,
  19627. box: box,
  19628. sphereInitialized: bound.sphereInitialized,
  19629. sphere: sphere
  19630. };
  19631. } );
  19632. object._maxInstanceCount = data.maxInstanceCount;
  19633. object._maxVertexCount = data.maxVertexCount;
  19634. object._maxIndexCount = data.maxIndexCount;
  19635. object._geometryInitialized = data.geometryInitialized;
  19636. object._geometryCount = data.geometryCount;
  19637. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  19638. if ( data.colorsTexture !== undefined ) object._colorsTexture = getTexture( data.colorsTexture.uuid );
  19639. break;
  19640. case 'LOD':
  19641. object = new LOD();
  19642. break;
  19643. case 'Line':
  19644. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  19645. break;
  19646. case 'LineLoop':
  19647. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  19648. break;
  19649. case 'LineSegments':
  19650. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  19651. break;
  19652. case 'PointCloud':
  19653. case 'Points':
  19654. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  19655. break;
  19656. case 'Sprite':
  19657. object = new Sprite( getMaterial( data.material ) );
  19658. break;
  19659. case 'Group':
  19660. object = new Group();
  19661. break;
  19662. case 'Bone':
  19663. object = new Bone();
  19664. break;
  19665. default:
  19666. object = new Object3D();
  19667. }
  19668. object.uuid = data.uuid;
  19669. if ( data.name !== undefined ) object.name = data.name;
  19670. if ( data.matrix !== undefined ) {
  19671. object.matrix.fromArray( data.matrix );
  19672. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  19673. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  19674. } else {
  19675. if ( data.position !== undefined ) object.position.fromArray( data.position );
  19676. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  19677. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  19678. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  19679. }
  19680. if ( data.up !== undefined ) object.up.fromArray( data.up );
  19681. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  19682. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  19683. if ( data.shadow ) {
  19684. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  19685. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  19686. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  19687. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  19688. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  19689. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  19690. }
  19691. if ( data.visible !== undefined ) object.visible = data.visible;
  19692. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  19693. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  19694. if ( data.userData !== undefined ) object.userData = data.userData;
  19695. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  19696. if ( data.children !== undefined ) {
  19697. const children = data.children;
  19698. for ( let i = 0; i < children.length; i ++ ) {
  19699. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  19700. }
  19701. }
  19702. if ( data.animations !== undefined ) {
  19703. const objectAnimations = data.animations;
  19704. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  19705. const uuid = objectAnimations[ i ];
  19706. object.animations.push( animations[ uuid ] );
  19707. }
  19708. }
  19709. if ( data.type === 'LOD' ) {
  19710. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  19711. const levels = data.levels;
  19712. for ( let l = 0; l < levels.length; l ++ ) {
  19713. const level = levels[ l ];
  19714. const child = object.getObjectByProperty( 'uuid', level.object );
  19715. if ( child !== undefined ) {
  19716. object.addLevel( child, level.distance, level.hysteresis );
  19717. }
  19718. }
  19719. }
  19720. return object;
  19721. }
  19722. bindSkeletons( object, skeletons ) {
  19723. if ( Object.keys( skeletons ).length === 0 ) return;
  19724. object.traverse( function ( child ) {
  19725. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  19726. const skeleton = skeletons[ child.skeleton ];
  19727. if ( skeleton === undefined ) {
  19728. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  19729. } else {
  19730. child.bind( skeleton, child.bindMatrix );
  19731. }
  19732. }
  19733. } );
  19734. }
  19735. bindLightTargets( object ) {
  19736. object.traverse( function ( child ) {
  19737. if ( child.isDirectionalLight || child.isSpotLight ) {
  19738. const uuid = child.target;
  19739. const target = object.getObjectByProperty( 'uuid', uuid );
  19740. if ( target !== undefined ) {
  19741. child.target = target;
  19742. } else {
  19743. child.target = new Object3D();
  19744. }
  19745. }
  19746. } );
  19747. }
  19748. }
  19749. const TEXTURE_MAPPING = {
  19750. UVMapping: UVMapping,
  19751. CubeReflectionMapping: CubeReflectionMapping,
  19752. CubeRefractionMapping: CubeRefractionMapping,
  19753. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  19754. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  19755. CubeUVReflectionMapping: CubeUVReflectionMapping
  19756. };
  19757. const TEXTURE_WRAPPING = {
  19758. RepeatWrapping: RepeatWrapping,
  19759. ClampToEdgeWrapping: ClampToEdgeWrapping,
  19760. MirroredRepeatWrapping: MirroredRepeatWrapping
  19761. };
  19762. const TEXTURE_FILTER = {
  19763. NearestFilter: NearestFilter,
  19764. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  19765. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  19766. LinearFilter: LinearFilter,
  19767. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  19768. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  19769. };
  19770. class ImageBitmapLoader extends Loader {
  19771. constructor( manager ) {
  19772. super( manager );
  19773. this.isImageBitmapLoader = true;
  19774. if ( typeof createImageBitmap === 'undefined' ) {
  19775. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  19776. }
  19777. if ( typeof fetch === 'undefined' ) {
  19778. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  19779. }
  19780. this.options = { premultiplyAlpha: 'none' };
  19781. }
  19782. setOptions( options ) {
  19783. this.options = options;
  19784. return this;
  19785. }
  19786. load( url, onLoad, onProgress, onError ) {
  19787. if ( url === undefined ) url = '';
  19788. if ( this.path !== undefined ) url = this.path + url;
  19789. url = this.manager.resolveURL( url );
  19790. const scope = this;
  19791. const cached = Cache.get( url );
  19792. if ( cached !== undefined ) {
  19793. scope.manager.itemStart( url );
  19794. // If cached is a promise, wait for it to resolve
  19795. if ( cached.then ) {
  19796. cached.then( imageBitmap => {
  19797. if ( onLoad ) onLoad( imageBitmap );
  19798. scope.manager.itemEnd( url );
  19799. } ).catch( e => {
  19800. if ( onError ) onError( e );
  19801. } );
  19802. return;
  19803. }
  19804. // If cached is not a promise (i.e., it's already an imageBitmap)
  19805. setTimeout( function () {
  19806. if ( onLoad ) onLoad( cached );
  19807. scope.manager.itemEnd( url );
  19808. }, 0 );
  19809. return cached;
  19810. }
  19811. const fetchOptions = {};
  19812. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  19813. fetchOptions.headers = this.requestHeader;
  19814. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  19815. return res.blob();
  19816. } ).then( function ( blob ) {
  19817. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  19818. } ).then( function ( imageBitmap ) {
  19819. Cache.add( url, imageBitmap );
  19820. if ( onLoad ) onLoad( imageBitmap );
  19821. scope.manager.itemEnd( url );
  19822. return imageBitmap;
  19823. } ).catch( function ( e ) {
  19824. if ( onError ) onError( e );
  19825. Cache.remove( url );
  19826. scope.manager.itemError( url );
  19827. scope.manager.itemEnd( url );
  19828. } );
  19829. Cache.add( url, promise );
  19830. scope.manager.itemStart( url );
  19831. }
  19832. }
  19833. let _context;
  19834. class AudioContext {
  19835. static getContext() {
  19836. if ( _context === undefined ) {
  19837. _context = new ( window.AudioContext || window.webkitAudioContext )();
  19838. }
  19839. return _context;
  19840. }
  19841. static setContext( value ) {
  19842. _context = value;
  19843. }
  19844. }
  19845. class AudioLoader extends Loader {
  19846. constructor( manager ) {
  19847. super( manager );
  19848. }
  19849. load( url, onLoad, onProgress, onError ) {
  19850. const scope = this;
  19851. const loader = new FileLoader( this.manager );
  19852. loader.setResponseType( 'arraybuffer' );
  19853. loader.setPath( this.path );
  19854. loader.setRequestHeader( this.requestHeader );
  19855. loader.setWithCredentials( this.withCredentials );
  19856. loader.load( url, function ( buffer ) {
  19857. try {
  19858. // Create a copy of the buffer. The `decodeAudioData` method
  19859. // detaches the buffer when complete, preventing reuse.
  19860. const bufferCopy = buffer.slice( 0 );
  19861. const context = AudioContext.getContext();
  19862. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  19863. onLoad( audioBuffer );
  19864. } ).catch( handleError );
  19865. } catch ( e ) {
  19866. handleError( e );
  19867. }
  19868. }, onProgress, onError );
  19869. function handleError( e ) {
  19870. if ( onError ) {
  19871. onError( e );
  19872. } else {
  19873. console.error( e );
  19874. }
  19875. scope.manager.itemError( url );
  19876. }
  19877. }
  19878. }
  19879. const _eyeRight = /*@__PURE__*/ new Matrix4();
  19880. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  19881. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  19882. class StereoCamera {
  19883. constructor() {
  19884. this.type = 'StereoCamera';
  19885. this.aspect = 1;
  19886. this.eyeSep = 0.064;
  19887. this.cameraL = new PerspectiveCamera();
  19888. this.cameraL.layers.enable( 1 );
  19889. this.cameraL.matrixAutoUpdate = false;
  19890. this.cameraR = new PerspectiveCamera();
  19891. this.cameraR.layers.enable( 2 );
  19892. this.cameraR.matrixAutoUpdate = false;
  19893. this._cache = {
  19894. focus: null,
  19895. fov: null,
  19896. aspect: null,
  19897. near: null,
  19898. far: null,
  19899. zoom: null,
  19900. eyeSep: null
  19901. };
  19902. }
  19903. update( camera ) {
  19904. const cache = this._cache;
  19905. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  19906. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  19907. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  19908. if ( needsUpdate ) {
  19909. cache.focus = camera.focus;
  19910. cache.fov = camera.fov;
  19911. cache.aspect = camera.aspect * this.aspect;
  19912. cache.near = camera.near;
  19913. cache.far = camera.far;
  19914. cache.zoom = camera.zoom;
  19915. cache.eyeSep = this.eyeSep;
  19916. // Off-axis stereoscopic effect based on
  19917. // http://paulbourke.net/stereographics/stereorender/
  19918. _projectionMatrix.copy( camera.projectionMatrix );
  19919. const eyeSepHalf = cache.eyeSep / 2;
  19920. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  19921. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  19922. let xmin, xmax;
  19923. // translate xOffset
  19924. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  19925. _eyeRight.elements[ 12 ] = eyeSepHalf;
  19926. // for left eye
  19927. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  19928. xmax = ymax * cache.aspect + eyeSepOnProjection;
  19929. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  19930. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  19931. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  19932. // for right eye
  19933. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  19934. xmax = ymax * cache.aspect - eyeSepOnProjection;
  19935. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  19936. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  19937. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  19938. }
  19939. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  19940. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  19941. }
  19942. }
  19943. class ArrayCamera extends PerspectiveCamera {
  19944. constructor( array = [] ) {
  19945. super();
  19946. this.isArrayCamera = true;
  19947. this.cameras = array;
  19948. this.index = 0;
  19949. }
  19950. }
  19951. class Clock {
  19952. constructor( autoStart = true ) {
  19953. this.autoStart = autoStart;
  19954. this.startTime = 0;
  19955. this.oldTime = 0;
  19956. this.elapsedTime = 0;
  19957. this.running = false;
  19958. }
  19959. start() {
  19960. this.startTime = now();
  19961. this.oldTime = this.startTime;
  19962. this.elapsedTime = 0;
  19963. this.running = true;
  19964. }
  19965. stop() {
  19966. this.getElapsedTime();
  19967. this.running = false;
  19968. this.autoStart = false;
  19969. }
  19970. getElapsedTime() {
  19971. this.getDelta();
  19972. return this.elapsedTime;
  19973. }
  19974. getDelta() {
  19975. let diff = 0;
  19976. if ( this.autoStart && ! this.running ) {
  19977. this.start();
  19978. return 0;
  19979. }
  19980. if ( this.running ) {
  19981. const newTime = now();
  19982. diff = ( newTime - this.oldTime ) / 1000;
  19983. this.oldTime = newTime;
  19984. this.elapsedTime += diff;
  19985. }
  19986. return diff;
  19987. }
  19988. }
  19989. function now() {
  19990. return performance.now();
  19991. }
  19992. const _position$1 = /*@__PURE__*/ new Vector3();
  19993. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  19994. const _scale$1 = /*@__PURE__*/ new Vector3();
  19995. const _orientation$1 = /*@__PURE__*/ new Vector3();
  19996. class AudioListener extends Object3D {
  19997. constructor() {
  19998. super();
  19999. this.type = 'AudioListener';
  20000. this.context = AudioContext.getContext();
  20001. this.gain = this.context.createGain();
  20002. this.gain.connect( this.context.destination );
  20003. this.filter = null;
  20004. this.timeDelta = 0;
  20005. // private
  20006. this._clock = new Clock();
  20007. }
  20008. getInput() {
  20009. return this.gain;
  20010. }
  20011. removeFilter() {
  20012. if ( this.filter !== null ) {
  20013. this.gain.disconnect( this.filter );
  20014. this.filter.disconnect( this.context.destination );
  20015. this.gain.connect( this.context.destination );
  20016. this.filter = null;
  20017. }
  20018. return this;
  20019. }
  20020. getFilter() {
  20021. return this.filter;
  20022. }
  20023. setFilter( value ) {
  20024. if ( this.filter !== null ) {
  20025. this.gain.disconnect( this.filter );
  20026. this.filter.disconnect( this.context.destination );
  20027. } else {
  20028. this.gain.disconnect( this.context.destination );
  20029. }
  20030. this.filter = value;
  20031. this.gain.connect( this.filter );
  20032. this.filter.connect( this.context.destination );
  20033. return this;
  20034. }
  20035. getMasterVolume() {
  20036. return this.gain.gain.value;
  20037. }
  20038. setMasterVolume( value ) {
  20039. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  20040. return this;
  20041. }
  20042. updateMatrixWorld( force ) {
  20043. super.updateMatrixWorld( force );
  20044. const listener = this.context.listener;
  20045. const up = this.up;
  20046. this.timeDelta = this._clock.getDelta();
  20047. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  20048. _orientation$1.set( 0, 0, -1 ).applyQuaternion( _quaternion$1 );
  20049. if ( listener.positionX ) {
  20050. // code path for Chrome (see #14393)
  20051. const endTime = this.context.currentTime + this.timeDelta;
  20052. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  20053. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  20054. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  20055. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  20056. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  20057. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  20058. listener.upX.linearRampToValueAtTime( up.x, endTime );
  20059. listener.upY.linearRampToValueAtTime( up.y, endTime );
  20060. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  20061. } else {
  20062. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  20063. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  20064. }
  20065. }
  20066. }
  20067. class Audio extends Object3D {
  20068. constructor( listener ) {
  20069. super();
  20070. this.type = 'Audio';
  20071. this.listener = listener;
  20072. this.context = listener.context;
  20073. this.gain = this.context.createGain();
  20074. this.gain.connect( listener.getInput() );
  20075. this.autoplay = false;
  20076. this.buffer = null;
  20077. this.detune = 0;
  20078. this.loop = false;
  20079. this.loopStart = 0;
  20080. this.loopEnd = 0;
  20081. this.offset = 0;
  20082. this.duration = undefined;
  20083. this.playbackRate = 1;
  20084. this.isPlaying = false;
  20085. this.hasPlaybackControl = true;
  20086. this.source = null;
  20087. this.sourceType = 'empty';
  20088. this._startedAt = 0;
  20089. this._progress = 0;
  20090. this._connected = false;
  20091. this.filters = [];
  20092. }
  20093. getOutput() {
  20094. return this.gain;
  20095. }
  20096. setNodeSource( audioNode ) {
  20097. this.hasPlaybackControl = false;
  20098. this.sourceType = 'audioNode';
  20099. this.source = audioNode;
  20100. this.connect();
  20101. return this;
  20102. }
  20103. setMediaElementSource( mediaElement ) {
  20104. this.hasPlaybackControl = false;
  20105. this.sourceType = 'mediaNode';
  20106. this.source = this.context.createMediaElementSource( mediaElement );
  20107. this.connect();
  20108. return this;
  20109. }
  20110. setMediaStreamSource( mediaStream ) {
  20111. this.hasPlaybackControl = false;
  20112. this.sourceType = 'mediaStreamNode';
  20113. this.source = this.context.createMediaStreamSource( mediaStream );
  20114. this.connect();
  20115. return this;
  20116. }
  20117. setBuffer( audioBuffer ) {
  20118. this.buffer = audioBuffer;
  20119. this.sourceType = 'buffer';
  20120. if ( this.autoplay ) this.play();
  20121. return this;
  20122. }
  20123. play( delay = 0 ) {
  20124. if ( this.isPlaying === true ) {
  20125. console.warn( 'THREE.Audio: Audio is already playing.' );
  20126. return;
  20127. }
  20128. if ( this.hasPlaybackControl === false ) {
  20129. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  20130. return;
  20131. }
  20132. this._startedAt = this.context.currentTime + delay;
  20133. const source = this.context.createBufferSource();
  20134. source.buffer = this.buffer;
  20135. source.loop = this.loop;
  20136. source.loopStart = this.loopStart;
  20137. source.loopEnd = this.loopEnd;
  20138. source.onended = this.onEnded.bind( this );
  20139. source.start( this._startedAt, this._progress + this.offset, this.duration );
  20140. this.isPlaying = true;
  20141. this.source = source;
  20142. this.setDetune( this.detune );
  20143. this.setPlaybackRate( this.playbackRate );
  20144. return this.connect();
  20145. }
  20146. pause() {
  20147. if ( this.hasPlaybackControl === false ) {
  20148. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  20149. return;
  20150. }
  20151. if ( this.isPlaying === true ) {
  20152. // update current progress
  20153. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  20154. if ( this.loop === true ) {
  20155. // ensure _progress does not exceed duration with looped audios
  20156. this._progress = this._progress % ( this.duration || this.buffer.duration );
  20157. }
  20158. this.source.stop();
  20159. this.source.onended = null;
  20160. this.isPlaying = false;
  20161. }
  20162. return this;
  20163. }
  20164. stop( delay = 0 ) {
  20165. if ( this.hasPlaybackControl === false ) {
  20166. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  20167. return;
  20168. }
  20169. this._progress = 0;
  20170. if ( this.source !== null ) {
  20171. this.source.stop( this.context.currentTime + delay );
  20172. this.source.onended = null;
  20173. }
  20174. this.isPlaying = false;
  20175. return this;
  20176. }
  20177. connect() {
  20178. if ( this.filters.length > 0 ) {
  20179. this.source.connect( this.filters[ 0 ] );
  20180. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  20181. this.filters[ i - 1 ].connect( this.filters[ i ] );
  20182. }
  20183. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  20184. } else {
  20185. this.source.connect( this.getOutput() );
  20186. }
  20187. this._connected = true;
  20188. return this;
  20189. }
  20190. disconnect() {
  20191. if ( this._connected === false ) {
  20192. return;
  20193. }
  20194. if ( this.filters.length > 0 ) {
  20195. this.source.disconnect( this.filters[ 0 ] );
  20196. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  20197. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  20198. }
  20199. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  20200. } else {
  20201. this.source.disconnect( this.getOutput() );
  20202. }
  20203. this._connected = false;
  20204. return this;
  20205. }
  20206. getFilters() {
  20207. return this.filters;
  20208. }
  20209. setFilters( value ) {
  20210. if ( ! value ) value = [];
  20211. if ( this._connected === true ) {
  20212. this.disconnect();
  20213. this.filters = value.slice();
  20214. this.connect();
  20215. } else {
  20216. this.filters = value.slice();
  20217. }
  20218. return this;
  20219. }
  20220. setDetune( value ) {
  20221. this.detune = value;
  20222. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  20223. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  20224. }
  20225. return this;
  20226. }
  20227. getDetune() {
  20228. return this.detune;
  20229. }
  20230. getFilter() {
  20231. return this.getFilters()[ 0 ];
  20232. }
  20233. setFilter( filter ) {
  20234. return this.setFilters( filter ? [ filter ] : [] );
  20235. }
  20236. setPlaybackRate( value ) {
  20237. if ( this.hasPlaybackControl === false ) {
  20238. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  20239. return;
  20240. }
  20241. this.playbackRate = value;
  20242. if ( this.isPlaying === true ) {
  20243. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  20244. }
  20245. return this;
  20246. }
  20247. getPlaybackRate() {
  20248. return this.playbackRate;
  20249. }
  20250. onEnded() {
  20251. this.isPlaying = false;
  20252. this._progress = 0;
  20253. }
  20254. getLoop() {
  20255. if ( this.hasPlaybackControl === false ) {
  20256. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  20257. return false;
  20258. }
  20259. return this.loop;
  20260. }
  20261. setLoop( value ) {
  20262. if ( this.hasPlaybackControl === false ) {
  20263. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  20264. return;
  20265. }
  20266. this.loop = value;
  20267. if ( this.isPlaying === true ) {
  20268. this.source.loop = this.loop;
  20269. }
  20270. return this;
  20271. }
  20272. setLoopStart( value ) {
  20273. this.loopStart = value;
  20274. return this;
  20275. }
  20276. setLoopEnd( value ) {
  20277. this.loopEnd = value;
  20278. return this;
  20279. }
  20280. getVolume() {
  20281. return this.gain.gain.value;
  20282. }
  20283. setVolume( value ) {
  20284. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  20285. return this;
  20286. }
  20287. copy( source, recursive ) {
  20288. super.copy( source, recursive );
  20289. if ( source.sourceType !== 'buffer' ) {
  20290. console.warn( 'THREE.Audio: Audio source type cannot be copied.' );
  20291. return this;
  20292. }
  20293. this.autoplay = source.autoplay;
  20294. this.buffer = source.buffer;
  20295. this.detune = source.detune;
  20296. this.loop = source.loop;
  20297. this.loopStart = source.loopStart;
  20298. this.loopEnd = source.loopEnd;
  20299. this.offset = source.offset;
  20300. this.duration = source.duration;
  20301. this.playbackRate = source.playbackRate;
  20302. this.hasPlaybackControl = source.hasPlaybackControl;
  20303. this.sourceType = source.sourceType;
  20304. this.filters = source.filters.slice();
  20305. return this;
  20306. }
  20307. clone( recursive ) {
  20308. return new this.constructor( this.listener ).copy( this, recursive );
  20309. }
  20310. }
  20311. const _position = /*@__PURE__*/ new Vector3();
  20312. const _quaternion = /*@__PURE__*/ new Quaternion();
  20313. const _scale = /*@__PURE__*/ new Vector3();
  20314. const _orientation = /*@__PURE__*/ new Vector3();
  20315. class PositionalAudio extends Audio {
  20316. constructor( listener ) {
  20317. super( listener );
  20318. this.panner = this.context.createPanner();
  20319. this.panner.panningModel = 'HRTF';
  20320. this.panner.connect( this.gain );
  20321. }
  20322. connect() {
  20323. super.connect();
  20324. this.panner.connect( this.gain );
  20325. }
  20326. disconnect() {
  20327. super.disconnect();
  20328. this.panner.disconnect( this.gain );
  20329. }
  20330. getOutput() {
  20331. return this.panner;
  20332. }
  20333. getRefDistance() {
  20334. return this.panner.refDistance;
  20335. }
  20336. setRefDistance( value ) {
  20337. this.panner.refDistance = value;
  20338. return this;
  20339. }
  20340. getRolloffFactor() {
  20341. return this.panner.rolloffFactor;
  20342. }
  20343. setRolloffFactor( value ) {
  20344. this.panner.rolloffFactor = value;
  20345. return this;
  20346. }
  20347. getDistanceModel() {
  20348. return this.panner.distanceModel;
  20349. }
  20350. setDistanceModel( value ) {
  20351. this.panner.distanceModel = value;
  20352. return this;
  20353. }
  20354. getMaxDistance() {
  20355. return this.panner.maxDistance;
  20356. }
  20357. setMaxDistance( value ) {
  20358. this.panner.maxDistance = value;
  20359. return this;
  20360. }
  20361. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  20362. this.panner.coneInnerAngle = coneInnerAngle;
  20363. this.panner.coneOuterAngle = coneOuterAngle;
  20364. this.panner.coneOuterGain = coneOuterGain;
  20365. return this;
  20366. }
  20367. updateMatrixWorld( force ) {
  20368. super.updateMatrixWorld( force );
  20369. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  20370. this.matrixWorld.decompose( _position, _quaternion, _scale );
  20371. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  20372. const panner = this.panner;
  20373. if ( panner.positionX ) {
  20374. // code path for Chrome and Firefox (see #14393)
  20375. const endTime = this.context.currentTime + this.listener.timeDelta;
  20376. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  20377. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  20378. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  20379. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  20380. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  20381. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  20382. } else {
  20383. panner.setPosition( _position.x, _position.y, _position.z );
  20384. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  20385. }
  20386. }
  20387. }
  20388. class AudioAnalyser {
  20389. constructor( audio, fftSize = 2048 ) {
  20390. this.analyser = audio.context.createAnalyser();
  20391. this.analyser.fftSize = fftSize;
  20392. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  20393. audio.getOutput().connect( this.analyser );
  20394. }
  20395. getFrequencyData() {
  20396. this.analyser.getByteFrequencyData( this.data );
  20397. return this.data;
  20398. }
  20399. getAverageFrequency() {
  20400. let value = 0;
  20401. const data = this.getFrequencyData();
  20402. for ( let i = 0; i < data.length; i ++ ) {
  20403. value += data[ i ];
  20404. }
  20405. return value / data.length;
  20406. }
  20407. }
  20408. class PropertyMixer {
  20409. constructor( binding, typeName, valueSize ) {
  20410. this.binding = binding;
  20411. this.valueSize = valueSize;
  20412. let mixFunction,
  20413. mixFunctionAdditive,
  20414. setIdentity;
  20415. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  20416. //
  20417. // interpolators can use .buffer as their .result
  20418. // the data then goes to 'incoming'
  20419. //
  20420. // 'accu0' and 'accu1' are used frame-interleaved for
  20421. // the cumulative result and are compared to detect
  20422. // changes
  20423. //
  20424. // 'orig' stores the original state of the property
  20425. //
  20426. // 'add' is used for additive cumulative results
  20427. //
  20428. // 'work' is optional and is only present for quaternion types. It is used
  20429. // to store intermediate quaternion multiplication results
  20430. switch ( typeName ) {
  20431. case 'quaternion':
  20432. mixFunction = this._slerp;
  20433. mixFunctionAdditive = this._slerpAdditive;
  20434. setIdentity = this._setAdditiveIdentityQuaternion;
  20435. this.buffer = new Float64Array( valueSize * 6 );
  20436. this._workIndex = 5;
  20437. break;
  20438. case 'string':
  20439. case 'bool':
  20440. mixFunction = this._select;
  20441. // Use the regular mix function and for additive on these types,
  20442. // additive is not relevant for non-numeric types
  20443. mixFunctionAdditive = this._select;
  20444. setIdentity = this._setAdditiveIdentityOther;
  20445. this.buffer = new Array( valueSize * 5 );
  20446. break;
  20447. default:
  20448. mixFunction = this._lerp;
  20449. mixFunctionAdditive = this._lerpAdditive;
  20450. setIdentity = this._setAdditiveIdentityNumeric;
  20451. this.buffer = new Float64Array( valueSize * 5 );
  20452. }
  20453. this._mixBufferRegion = mixFunction;
  20454. this._mixBufferRegionAdditive = mixFunctionAdditive;
  20455. this._setIdentity = setIdentity;
  20456. this._origIndex = 3;
  20457. this._addIndex = 4;
  20458. this.cumulativeWeight = 0;
  20459. this.cumulativeWeightAdditive = 0;
  20460. this.useCount = 0;
  20461. this.referenceCount = 0;
  20462. }
  20463. // accumulate data in the 'incoming' region into 'accu<i>'
  20464. accumulate( accuIndex, weight ) {
  20465. // note: happily accumulating nothing when weight = 0, the caller knows
  20466. // the weight and shouldn't have made the call in the first place
  20467. const buffer = this.buffer,
  20468. stride = this.valueSize,
  20469. offset = accuIndex * stride + stride;
  20470. let currentWeight = this.cumulativeWeight;
  20471. if ( currentWeight === 0 ) {
  20472. // accuN := incoming * weight
  20473. for ( let i = 0; i !== stride; ++ i ) {
  20474. buffer[ offset + i ] = buffer[ i ];
  20475. }
  20476. currentWeight = weight;
  20477. } else {
  20478. // accuN := accuN + incoming * weight
  20479. currentWeight += weight;
  20480. const mix = weight / currentWeight;
  20481. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  20482. }
  20483. this.cumulativeWeight = currentWeight;
  20484. }
  20485. // accumulate data in the 'incoming' region into 'add'
  20486. accumulateAdditive( weight ) {
  20487. const buffer = this.buffer,
  20488. stride = this.valueSize,
  20489. offset = stride * this._addIndex;
  20490. if ( this.cumulativeWeightAdditive === 0 ) {
  20491. // add = identity
  20492. this._setIdentity();
  20493. }
  20494. // add := add + incoming * weight
  20495. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  20496. this.cumulativeWeightAdditive += weight;
  20497. }
  20498. // apply the state of 'accu<i>' to the binding when accus differ
  20499. apply( accuIndex ) {
  20500. const stride = this.valueSize,
  20501. buffer = this.buffer,
  20502. offset = accuIndex * stride + stride,
  20503. weight = this.cumulativeWeight,
  20504. weightAdditive = this.cumulativeWeightAdditive,
  20505. binding = this.binding;
  20506. this.cumulativeWeight = 0;
  20507. this.cumulativeWeightAdditive = 0;
  20508. if ( weight < 1 ) {
  20509. // accuN := accuN + original * ( 1 - cumulativeWeight )
  20510. const originalValueOffset = stride * this._origIndex;
  20511. this._mixBufferRegion(
  20512. buffer, offset, originalValueOffset, 1 - weight, stride );
  20513. }
  20514. if ( weightAdditive > 0 ) {
  20515. // accuN := accuN + additive accuN
  20516. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  20517. }
  20518. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  20519. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  20520. // value has changed -> update scene graph
  20521. binding.setValue( buffer, offset );
  20522. break;
  20523. }
  20524. }
  20525. }
  20526. // remember the state of the bound property and copy it to both accus
  20527. saveOriginalState() {
  20528. const binding = this.binding;
  20529. const buffer = this.buffer,
  20530. stride = this.valueSize,
  20531. originalValueOffset = stride * this._origIndex;
  20532. binding.getValue( buffer, originalValueOffset );
  20533. // accu[0..1] := orig -- initially detect changes against the original
  20534. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  20535. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  20536. }
  20537. // Add to identity for additive
  20538. this._setIdentity();
  20539. this.cumulativeWeight = 0;
  20540. this.cumulativeWeightAdditive = 0;
  20541. }
  20542. // apply the state previously taken via 'saveOriginalState' to the binding
  20543. restoreOriginalState() {
  20544. const originalValueOffset = this.valueSize * 3;
  20545. this.binding.setValue( this.buffer, originalValueOffset );
  20546. }
  20547. _setAdditiveIdentityNumeric() {
  20548. const startIndex = this._addIndex * this.valueSize;
  20549. const endIndex = startIndex + this.valueSize;
  20550. for ( let i = startIndex; i < endIndex; i ++ ) {
  20551. this.buffer[ i ] = 0;
  20552. }
  20553. }
  20554. _setAdditiveIdentityQuaternion() {
  20555. this._setAdditiveIdentityNumeric();
  20556. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  20557. }
  20558. _setAdditiveIdentityOther() {
  20559. const startIndex = this._origIndex * this.valueSize;
  20560. const targetIndex = this._addIndex * this.valueSize;
  20561. for ( let i = 0; i < this.valueSize; i ++ ) {
  20562. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  20563. }
  20564. }
  20565. // mix functions
  20566. _select( buffer, dstOffset, srcOffset, t, stride ) {
  20567. if ( t >= 0.5 ) {
  20568. for ( let i = 0; i !== stride; ++ i ) {
  20569. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  20570. }
  20571. }
  20572. }
  20573. _slerp( buffer, dstOffset, srcOffset, t ) {
  20574. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  20575. }
  20576. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  20577. const workOffset = this._workIndex * stride;
  20578. // Store result in intermediate buffer offset
  20579. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  20580. // Slerp to the intermediate result
  20581. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  20582. }
  20583. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  20584. const s = 1 - t;
  20585. for ( let i = 0; i !== stride; ++ i ) {
  20586. const j = dstOffset + i;
  20587. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  20588. }
  20589. }
  20590. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  20591. for ( let i = 0; i !== stride; ++ i ) {
  20592. const j = dstOffset + i;
  20593. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  20594. }
  20595. }
  20596. }
  20597. // Characters [].:/ are reserved for track binding syntax.
  20598. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  20599. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  20600. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  20601. // only latin characters, and the unicode \p{L} is not yet supported. So
  20602. // instead, we exclude reserved characters and match everything else.
  20603. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  20604. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  20605. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  20606. // be matched to parse the rest of the track name.
  20607. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  20608. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  20609. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  20610. // Object on target node, and accessor. May not contain reserved
  20611. // characters. Accessor may contain any character except closing bracket.
  20612. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  20613. // Property and accessor. May not contain reserved characters. Accessor may
  20614. // contain any non-bracket characters.
  20615. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  20616. const _trackRe = new RegExp( ''
  20617. + '^'
  20618. + _directoryRe
  20619. + _nodeRe
  20620. + _objectRe
  20621. + _propertyRe
  20622. + '$'
  20623. );
  20624. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  20625. class Composite {
  20626. constructor( targetGroup, path, optionalParsedPath ) {
  20627. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  20628. this._targetGroup = targetGroup;
  20629. this._bindings = targetGroup.subscribe_( path, parsedPath );
  20630. }
  20631. getValue( array, offset ) {
  20632. this.bind(); // bind all binding
  20633. const firstValidIndex = this._targetGroup.nCachedObjects_,
  20634. binding = this._bindings[ firstValidIndex ];
  20635. // and only call .getValue on the first
  20636. if ( binding !== undefined ) binding.getValue( array, offset );
  20637. }
  20638. setValue( array, offset ) {
  20639. const bindings = this._bindings;
  20640. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  20641. bindings[ i ].setValue( array, offset );
  20642. }
  20643. }
  20644. bind() {
  20645. const bindings = this._bindings;
  20646. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  20647. bindings[ i ].bind();
  20648. }
  20649. }
  20650. unbind() {
  20651. const bindings = this._bindings;
  20652. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  20653. bindings[ i ].unbind();
  20654. }
  20655. }
  20656. }
  20657. // Note: This class uses a State pattern on a per-method basis:
  20658. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  20659. // prototype version of these methods with one that represents
  20660. // the bound state. When the property is not found, the methods
  20661. // become no-ops.
  20662. class PropertyBinding {
  20663. constructor( rootNode, path, parsedPath ) {
  20664. this.path = path;
  20665. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  20666. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  20667. this.rootNode = rootNode;
  20668. // initial state of these methods that calls 'bind'
  20669. this.getValue = this._getValue_unbound;
  20670. this.setValue = this._setValue_unbound;
  20671. }
  20672. static create( root, path, parsedPath ) {
  20673. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  20674. return new PropertyBinding( root, path, parsedPath );
  20675. } else {
  20676. return new PropertyBinding.Composite( root, path, parsedPath );
  20677. }
  20678. }
  20679. /**
  20680. * Replaces spaces with underscores and removes unsupported characters from
  20681. * node names, to ensure compatibility with parseTrackName().
  20682. *
  20683. * @param {string} name Node name to be sanitized.
  20684. * @return {string}
  20685. */
  20686. static sanitizeNodeName( name ) {
  20687. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  20688. }
  20689. static parseTrackName( trackName ) {
  20690. const matches = _trackRe.exec( trackName );
  20691. if ( matches === null ) {
  20692. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  20693. }
  20694. const results = {
  20695. // directoryName: matches[ 1 ], // (tschw) currently unused
  20696. nodeName: matches[ 2 ],
  20697. objectName: matches[ 3 ],
  20698. objectIndex: matches[ 4 ],
  20699. propertyName: matches[ 5 ], // required
  20700. propertyIndex: matches[ 6 ]
  20701. };
  20702. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  20703. if ( lastDot !== undefined && lastDot !== -1 ) {
  20704. const objectName = results.nodeName.substring( lastDot + 1 );
  20705. // Object names must be checked against an allowlist. Otherwise, there
  20706. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  20707. // 'bar' could be the objectName, or part of a nodeName (which can
  20708. // include '.' characters).
  20709. if ( _supportedObjectNames.indexOf( objectName ) !== -1 ) {
  20710. results.nodeName = results.nodeName.substring( 0, lastDot );
  20711. results.objectName = objectName;
  20712. }
  20713. }
  20714. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  20715. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  20716. }
  20717. return results;
  20718. }
  20719. static findNode( root, nodeName ) {
  20720. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  20721. return root;
  20722. }
  20723. // search into skeleton bones.
  20724. if ( root.skeleton ) {
  20725. const bone = root.skeleton.getBoneByName( nodeName );
  20726. if ( bone !== undefined ) {
  20727. return bone;
  20728. }
  20729. }
  20730. // search into node subtree.
  20731. if ( root.children ) {
  20732. const searchNodeSubtree = function ( children ) {
  20733. for ( let i = 0; i < children.length; i ++ ) {
  20734. const childNode = children[ i ];
  20735. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  20736. return childNode;
  20737. }
  20738. const result = searchNodeSubtree( childNode.children );
  20739. if ( result ) return result;
  20740. }
  20741. return null;
  20742. };
  20743. const subTreeNode = searchNodeSubtree( root.children );
  20744. if ( subTreeNode ) {
  20745. return subTreeNode;
  20746. }
  20747. }
  20748. return null;
  20749. }
  20750. // these are used to "bind" a nonexistent property
  20751. _getValue_unavailable() {}
  20752. _setValue_unavailable() {}
  20753. // Getters
  20754. _getValue_direct( buffer, offset ) {
  20755. buffer[ offset ] = this.targetObject[ this.propertyName ];
  20756. }
  20757. _getValue_array( buffer, offset ) {
  20758. const source = this.resolvedProperty;
  20759. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  20760. buffer[ offset ++ ] = source[ i ];
  20761. }
  20762. }
  20763. _getValue_arrayElement( buffer, offset ) {
  20764. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  20765. }
  20766. _getValue_toArray( buffer, offset ) {
  20767. this.resolvedProperty.toArray( buffer, offset );
  20768. }
  20769. // Direct
  20770. _setValue_direct( buffer, offset ) {
  20771. this.targetObject[ this.propertyName ] = buffer[ offset ];
  20772. }
  20773. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  20774. this.targetObject[ this.propertyName ] = buffer[ offset ];
  20775. this.targetObject.needsUpdate = true;
  20776. }
  20777. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  20778. this.targetObject[ this.propertyName ] = buffer[ offset ];
  20779. this.targetObject.matrixWorldNeedsUpdate = true;
  20780. }
  20781. // EntireArray
  20782. _setValue_array( buffer, offset ) {
  20783. const dest = this.resolvedProperty;
  20784. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  20785. dest[ i ] = buffer[ offset ++ ];
  20786. }
  20787. }
  20788. _setValue_array_setNeedsUpdate( buffer, offset ) {
  20789. const dest = this.resolvedProperty;
  20790. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  20791. dest[ i ] = buffer[ offset ++ ];
  20792. }
  20793. this.targetObject.needsUpdate = true;
  20794. }
  20795. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  20796. const dest = this.resolvedProperty;
  20797. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  20798. dest[ i ] = buffer[ offset ++ ];
  20799. }
  20800. this.targetObject.matrixWorldNeedsUpdate = true;
  20801. }
  20802. // ArrayElement
  20803. _setValue_arrayElement( buffer, offset ) {
  20804. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  20805. }
  20806. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  20807. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  20808. this.targetObject.needsUpdate = true;
  20809. }
  20810. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  20811. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  20812. this.targetObject.matrixWorldNeedsUpdate = true;
  20813. }
  20814. // HasToFromArray
  20815. _setValue_fromArray( buffer, offset ) {
  20816. this.resolvedProperty.fromArray( buffer, offset );
  20817. }
  20818. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  20819. this.resolvedProperty.fromArray( buffer, offset );
  20820. this.targetObject.needsUpdate = true;
  20821. }
  20822. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  20823. this.resolvedProperty.fromArray( buffer, offset );
  20824. this.targetObject.matrixWorldNeedsUpdate = true;
  20825. }
  20826. _getValue_unbound( targetArray, offset ) {
  20827. this.bind();
  20828. this.getValue( targetArray, offset );
  20829. }
  20830. _setValue_unbound( sourceArray, offset ) {
  20831. this.bind();
  20832. this.setValue( sourceArray, offset );
  20833. }
  20834. // create getter / setter pair for a property in the scene graph
  20835. bind() {
  20836. let targetObject = this.node;
  20837. const parsedPath = this.parsedPath;
  20838. const objectName = parsedPath.objectName;
  20839. const propertyName = parsedPath.propertyName;
  20840. let propertyIndex = parsedPath.propertyIndex;
  20841. if ( ! targetObject ) {
  20842. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  20843. this.node = targetObject;
  20844. }
  20845. // set fail state so we can just 'return' on error
  20846. this.getValue = this._getValue_unavailable;
  20847. this.setValue = this._setValue_unavailable;
  20848. // ensure there is a value node
  20849. if ( ! targetObject ) {
  20850. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  20851. return;
  20852. }
  20853. if ( objectName ) {
  20854. let objectIndex = parsedPath.objectIndex;
  20855. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  20856. switch ( objectName ) {
  20857. case 'materials':
  20858. if ( ! targetObject.material ) {
  20859. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  20860. return;
  20861. }
  20862. if ( ! targetObject.material.materials ) {
  20863. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  20864. return;
  20865. }
  20866. targetObject = targetObject.material.materials;
  20867. break;
  20868. case 'bones':
  20869. if ( ! targetObject.skeleton ) {
  20870. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  20871. return;
  20872. }
  20873. // potential future optimization: skip this if propertyIndex is already an integer
  20874. // and convert the integer string to a true integer.
  20875. targetObject = targetObject.skeleton.bones;
  20876. // support resolving morphTarget names into indices.
  20877. for ( let i = 0; i < targetObject.length; i ++ ) {
  20878. if ( targetObject[ i ].name === objectIndex ) {
  20879. objectIndex = i;
  20880. break;
  20881. }
  20882. }
  20883. break;
  20884. case 'map':
  20885. if ( 'map' in targetObject ) {
  20886. targetObject = targetObject.map;
  20887. break;
  20888. }
  20889. if ( ! targetObject.material ) {
  20890. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  20891. return;
  20892. }
  20893. if ( ! targetObject.material.map ) {
  20894. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  20895. return;
  20896. }
  20897. targetObject = targetObject.material.map;
  20898. break;
  20899. default:
  20900. if ( targetObject[ objectName ] === undefined ) {
  20901. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  20902. return;
  20903. }
  20904. targetObject = targetObject[ objectName ];
  20905. }
  20906. if ( objectIndex !== undefined ) {
  20907. if ( targetObject[ objectIndex ] === undefined ) {
  20908. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  20909. return;
  20910. }
  20911. targetObject = targetObject[ objectIndex ];
  20912. }
  20913. }
  20914. // resolve property
  20915. const nodeProperty = targetObject[ propertyName ];
  20916. if ( nodeProperty === undefined ) {
  20917. const nodeName = parsedPath.nodeName;
  20918. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  20919. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  20920. return;
  20921. }
  20922. // determine versioning scheme
  20923. let versioning = this.Versioning.None;
  20924. this.targetObject = targetObject;
  20925. if ( targetObject.isMaterial === true ) {
  20926. versioning = this.Versioning.NeedsUpdate;
  20927. } else if ( targetObject.isObject3D === true ) {
  20928. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  20929. }
  20930. // determine how the property gets bound
  20931. let bindingType = this.BindingType.Direct;
  20932. if ( propertyIndex !== undefined ) {
  20933. // access a sub element of the property array (only primitives are supported right now)
  20934. if ( propertyName === 'morphTargetInfluences' ) {
  20935. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  20936. // support resolving morphTarget names into indices.
  20937. if ( ! targetObject.geometry ) {
  20938. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  20939. return;
  20940. }
  20941. if ( ! targetObject.geometry.morphAttributes ) {
  20942. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  20943. return;
  20944. }
  20945. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  20946. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  20947. }
  20948. }
  20949. bindingType = this.BindingType.ArrayElement;
  20950. this.resolvedProperty = nodeProperty;
  20951. this.propertyIndex = propertyIndex;
  20952. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  20953. // must use copy for Object3D.Euler/Quaternion
  20954. bindingType = this.BindingType.HasFromToArray;
  20955. this.resolvedProperty = nodeProperty;
  20956. } else if ( Array.isArray( nodeProperty ) ) {
  20957. bindingType = this.BindingType.EntireArray;
  20958. this.resolvedProperty = nodeProperty;
  20959. } else {
  20960. this.propertyName = propertyName;
  20961. }
  20962. // select getter / setter
  20963. this.getValue = this.GetterByBindingType[ bindingType ];
  20964. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  20965. }
  20966. unbind() {
  20967. this.node = null;
  20968. // back to the prototype version of getValue / setValue
  20969. // note: avoiding to mutate the shape of 'this' via 'delete'
  20970. this.getValue = this._getValue_unbound;
  20971. this.setValue = this._setValue_unbound;
  20972. }
  20973. }
  20974. PropertyBinding.Composite = Composite;
  20975. PropertyBinding.prototype.BindingType = {
  20976. Direct: 0,
  20977. EntireArray: 1,
  20978. ArrayElement: 2,
  20979. HasFromToArray: 3
  20980. };
  20981. PropertyBinding.prototype.Versioning = {
  20982. None: 0,
  20983. NeedsUpdate: 1,
  20984. MatrixWorldNeedsUpdate: 2
  20985. };
  20986. PropertyBinding.prototype.GetterByBindingType = [
  20987. PropertyBinding.prototype._getValue_direct,
  20988. PropertyBinding.prototype._getValue_array,
  20989. PropertyBinding.prototype._getValue_arrayElement,
  20990. PropertyBinding.prototype._getValue_toArray,
  20991. ];
  20992. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  20993. [
  20994. // Direct
  20995. PropertyBinding.prototype._setValue_direct,
  20996. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  20997. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  20998. ], [
  20999. // EntireArray
  21000. PropertyBinding.prototype._setValue_array,
  21001. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  21002. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  21003. ], [
  21004. // ArrayElement
  21005. PropertyBinding.prototype._setValue_arrayElement,
  21006. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  21007. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  21008. ], [
  21009. // HasToFromArray
  21010. PropertyBinding.prototype._setValue_fromArray,
  21011. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  21012. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  21013. ]
  21014. ];
  21015. /**
  21016. *
  21017. * A group of objects that receives a shared animation state.
  21018. *
  21019. * Usage:
  21020. *
  21021. * - Add objects you would otherwise pass as 'root' to the
  21022. * constructor or the .clipAction method of AnimationMixer.
  21023. *
  21024. * - Instead pass this object as 'root'.
  21025. *
  21026. * - You can also add and remove objects later when the mixer
  21027. * is running.
  21028. *
  21029. * Note:
  21030. *
  21031. * Objects of this class appear as one object to the mixer,
  21032. * so cache control of the individual objects must be done
  21033. * on the group.
  21034. *
  21035. * Limitation:
  21036. *
  21037. * - The animated properties must be compatible among the
  21038. * all objects in the group.
  21039. *
  21040. * - A single property can either be controlled through a
  21041. * target group or directly, but not both.
  21042. */
  21043. class AnimationObjectGroup {
  21044. constructor() {
  21045. this.isAnimationObjectGroup = true;
  21046. this.uuid = generateUUID();
  21047. // cached objects followed by the active ones
  21048. this._objects = Array.prototype.slice.call( arguments );
  21049. this.nCachedObjects_ = 0; // threshold
  21050. // note: read by PropertyBinding.Composite
  21051. const indices = {};
  21052. this._indicesByUUID = indices; // for bookkeeping
  21053. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  21054. indices[ arguments[ i ].uuid ] = i;
  21055. }
  21056. this._paths = []; // inside: string
  21057. this._parsedPaths = []; // inside: { we don't care, here }
  21058. this._bindings = []; // inside: Array< PropertyBinding >
  21059. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  21060. const scope = this;
  21061. this.stats = {
  21062. objects: {
  21063. get total() {
  21064. return scope._objects.length;
  21065. },
  21066. get inUse() {
  21067. return this.total - scope.nCachedObjects_;
  21068. }
  21069. },
  21070. get bindingsPerObject() {
  21071. return scope._bindings.length;
  21072. }
  21073. };
  21074. }
  21075. add() {
  21076. const objects = this._objects,
  21077. indicesByUUID = this._indicesByUUID,
  21078. paths = this._paths,
  21079. parsedPaths = this._parsedPaths,
  21080. bindings = this._bindings,
  21081. nBindings = bindings.length;
  21082. let knownObject = undefined,
  21083. nObjects = objects.length,
  21084. nCachedObjects = this.nCachedObjects_;
  21085. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  21086. const object = arguments[ i ],
  21087. uuid = object.uuid;
  21088. let index = indicesByUUID[ uuid ];
  21089. if ( index === undefined ) {
  21090. // unknown object -> add it to the ACTIVE region
  21091. index = nObjects ++;
  21092. indicesByUUID[ uuid ] = index;
  21093. objects.push( object );
  21094. // accounting is done, now do the same for all bindings
  21095. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  21096. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  21097. }
  21098. } else if ( index < nCachedObjects ) {
  21099. knownObject = objects[ index ];
  21100. // move existing object to the ACTIVE region
  21101. const firstActiveIndex = -- nCachedObjects,
  21102. lastCachedObject = objects[ firstActiveIndex ];
  21103. indicesByUUID[ lastCachedObject.uuid ] = index;
  21104. objects[ index ] = lastCachedObject;
  21105. indicesByUUID[ uuid ] = firstActiveIndex;
  21106. objects[ firstActiveIndex ] = object;
  21107. // accounting is done, now do the same for all bindings
  21108. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  21109. const bindingsForPath = bindings[ j ],
  21110. lastCached = bindingsForPath[ firstActiveIndex ];
  21111. let binding = bindingsForPath[ index ];
  21112. bindingsForPath[ index ] = lastCached;
  21113. if ( binding === undefined ) {
  21114. // since we do not bother to create new bindings
  21115. // for objects that are cached, the binding may
  21116. // or may not exist
  21117. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  21118. }
  21119. bindingsForPath[ firstActiveIndex ] = binding;
  21120. }
  21121. } else if ( objects[ index ] !== knownObject ) {
  21122. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  21123. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  21124. } // else the object is already where we want it to be
  21125. } // for arguments
  21126. this.nCachedObjects_ = nCachedObjects;
  21127. }
  21128. remove() {
  21129. const objects = this._objects,
  21130. indicesByUUID = this._indicesByUUID,
  21131. bindings = this._bindings,
  21132. nBindings = bindings.length;
  21133. let nCachedObjects = this.nCachedObjects_;
  21134. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  21135. const object = arguments[ i ],
  21136. uuid = object.uuid,
  21137. index = indicesByUUID[ uuid ];
  21138. if ( index !== undefined && index >= nCachedObjects ) {
  21139. // move existing object into the CACHED region
  21140. const lastCachedIndex = nCachedObjects ++,
  21141. firstActiveObject = objects[ lastCachedIndex ];
  21142. indicesByUUID[ firstActiveObject.uuid ] = index;
  21143. objects[ index ] = firstActiveObject;
  21144. indicesByUUID[ uuid ] = lastCachedIndex;
  21145. objects[ lastCachedIndex ] = object;
  21146. // accounting is done, now do the same for all bindings
  21147. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  21148. const bindingsForPath = bindings[ j ],
  21149. firstActive = bindingsForPath[ lastCachedIndex ],
  21150. binding = bindingsForPath[ index ];
  21151. bindingsForPath[ index ] = firstActive;
  21152. bindingsForPath[ lastCachedIndex ] = binding;
  21153. }
  21154. }
  21155. } // for arguments
  21156. this.nCachedObjects_ = nCachedObjects;
  21157. }
  21158. // remove & forget
  21159. uncache() {
  21160. const objects = this._objects,
  21161. indicesByUUID = this._indicesByUUID,
  21162. bindings = this._bindings,
  21163. nBindings = bindings.length;
  21164. let nCachedObjects = this.nCachedObjects_,
  21165. nObjects = objects.length;
  21166. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  21167. const object = arguments[ i ],
  21168. uuid = object.uuid,
  21169. index = indicesByUUID[ uuid ];
  21170. if ( index !== undefined ) {
  21171. delete indicesByUUID[ uuid ];
  21172. if ( index < nCachedObjects ) {
  21173. // object is cached, shrink the CACHED region
  21174. const firstActiveIndex = -- nCachedObjects,
  21175. lastCachedObject = objects[ firstActiveIndex ],
  21176. lastIndex = -- nObjects,
  21177. lastObject = objects[ lastIndex ];
  21178. // last cached object takes this object's place
  21179. indicesByUUID[ lastCachedObject.uuid ] = index;
  21180. objects[ index ] = lastCachedObject;
  21181. // last object goes to the activated slot and pop
  21182. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  21183. objects[ firstActiveIndex ] = lastObject;
  21184. objects.pop();
  21185. // accounting is done, now do the same for all bindings
  21186. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  21187. const bindingsForPath = bindings[ j ],
  21188. lastCached = bindingsForPath[ firstActiveIndex ],
  21189. last = bindingsForPath[ lastIndex ];
  21190. bindingsForPath[ index ] = lastCached;
  21191. bindingsForPath[ firstActiveIndex ] = last;
  21192. bindingsForPath.pop();
  21193. }
  21194. } else {
  21195. // object is active, just swap with the last and pop
  21196. const lastIndex = -- nObjects,
  21197. lastObject = objects[ lastIndex ];
  21198. if ( lastIndex > 0 ) {
  21199. indicesByUUID[ lastObject.uuid ] = index;
  21200. }
  21201. objects[ index ] = lastObject;
  21202. objects.pop();
  21203. // accounting is done, now do the same for all bindings
  21204. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  21205. const bindingsForPath = bindings[ j ];
  21206. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  21207. bindingsForPath.pop();
  21208. }
  21209. } // cached or active
  21210. } // if object is known
  21211. } // for arguments
  21212. this.nCachedObjects_ = nCachedObjects;
  21213. }
  21214. // Internal interface used by befriended PropertyBinding.Composite:
  21215. subscribe_( path, parsedPath ) {
  21216. // returns an array of bindings for the given path that is changed
  21217. // according to the contained objects in the group
  21218. const indicesByPath = this._bindingsIndicesByPath;
  21219. let index = indicesByPath[ path ];
  21220. const bindings = this._bindings;
  21221. if ( index !== undefined ) return bindings[ index ];
  21222. const paths = this._paths,
  21223. parsedPaths = this._parsedPaths,
  21224. objects = this._objects,
  21225. nObjects = objects.length,
  21226. nCachedObjects = this.nCachedObjects_,
  21227. bindingsForPath = new Array( nObjects );
  21228. index = bindings.length;
  21229. indicesByPath[ path ] = index;
  21230. paths.push( path );
  21231. parsedPaths.push( parsedPath );
  21232. bindings.push( bindingsForPath );
  21233. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  21234. const object = objects[ i ];
  21235. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  21236. }
  21237. return bindingsForPath;
  21238. }
  21239. unsubscribe_( path ) {
  21240. // tells the group to forget about a property path and no longer
  21241. // update the array previously obtained with 'subscribe_'
  21242. const indicesByPath = this._bindingsIndicesByPath,
  21243. index = indicesByPath[ path ];
  21244. if ( index !== undefined ) {
  21245. const paths = this._paths,
  21246. parsedPaths = this._parsedPaths,
  21247. bindings = this._bindings,
  21248. lastBindingsIndex = bindings.length - 1,
  21249. lastBindings = bindings[ lastBindingsIndex ],
  21250. lastBindingsPath = path[ lastBindingsIndex ];
  21251. indicesByPath[ lastBindingsPath ] = index;
  21252. bindings[ index ] = lastBindings;
  21253. bindings.pop();
  21254. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  21255. parsedPaths.pop();
  21256. paths[ index ] = paths[ lastBindingsIndex ];
  21257. paths.pop();
  21258. }
  21259. }
  21260. }
  21261. class AnimationAction {
  21262. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  21263. this._mixer = mixer;
  21264. this._clip = clip;
  21265. this._localRoot = localRoot;
  21266. this.blendMode = blendMode;
  21267. const tracks = clip.tracks,
  21268. nTracks = tracks.length,
  21269. interpolants = new Array( nTracks );
  21270. const interpolantSettings = {
  21271. endingStart: ZeroCurvatureEnding,
  21272. endingEnd: ZeroCurvatureEnding
  21273. };
  21274. for ( let i = 0; i !== nTracks; ++ i ) {
  21275. const interpolant = tracks[ i ].createInterpolant( null );
  21276. interpolants[ i ] = interpolant;
  21277. interpolant.settings = interpolantSettings;
  21278. }
  21279. this._interpolantSettings = interpolantSettings;
  21280. this._interpolants = interpolants; // bound by the mixer
  21281. // inside: PropertyMixer (managed by the mixer)
  21282. this._propertyBindings = new Array( nTracks );
  21283. this._cacheIndex = null; // for the memory manager
  21284. this._byClipCacheIndex = null; // for the memory manager
  21285. this._timeScaleInterpolant = null;
  21286. this._weightInterpolant = null;
  21287. this.loop = LoopRepeat;
  21288. this._loopCount = -1;
  21289. // global mixer time when the action is to be started
  21290. // it's set back to 'null' upon start of the action
  21291. this._startTime = null;
  21292. // scaled local time of the action
  21293. // gets clamped or wrapped to 0..clip.duration according to loop
  21294. this.time = 0;
  21295. this.timeScale = 1;
  21296. this._effectiveTimeScale = 1;
  21297. this.weight = 1;
  21298. this._effectiveWeight = 1;
  21299. this.repetitions = Infinity; // no. of repetitions when looping
  21300. this.paused = false; // true -> zero effective time scale
  21301. this.enabled = true; // false -> zero effective weight
  21302. this.clampWhenFinished = false;// keep feeding the last frame?
  21303. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  21304. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  21305. }
  21306. // State & Scheduling
  21307. play() {
  21308. this._mixer._activateAction( this );
  21309. return this;
  21310. }
  21311. stop() {
  21312. this._mixer._deactivateAction( this );
  21313. return this.reset();
  21314. }
  21315. reset() {
  21316. this.paused = false;
  21317. this.enabled = true;
  21318. this.time = 0; // restart clip
  21319. this._loopCount = -1;// forget previous loops
  21320. this._startTime = null;// forget scheduling
  21321. return this.stopFading().stopWarping();
  21322. }
  21323. isRunning() {
  21324. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  21325. this._startTime === null && this._mixer._isActiveAction( this );
  21326. }
  21327. // return true when play has been called
  21328. isScheduled() {
  21329. return this._mixer._isActiveAction( this );
  21330. }
  21331. startAt( time ) {
  21332. this._startTime = time;
  21333. return this;
  21334. }
  21335. setLoop( mode, repetitions ) {
  21336. this.loop = mode;
  21337. this.repetitions = repetitions;
  21338. return this;
  21339. }
  21340. // Weight
  21341. // set the weight stopping any scheduled fading
  21342. // although .enabled = false yields an effective weight of zero, this
  21343. // method does *not* change .enabled, because it would be confusing
  21344. setEffectiveWeight( weight ) {
  21345. this.weight = weight;
  21346. // note: same logic as when updated at runtime
  21347. this._effectiveWeight = this.enabled ? weight : 0;
  21348. return this.stopFading();
  21349. }
  21350. // return the weight considering fading and .enabled
  21351. getEffectiveWeight() {
  21352. return this._effectiveWeight;
  21353. }
  21354. fadeIn( duration ) {
  21355. return this._scheduleFading( duration, 0, 1 );
  21356. }
  21357. fadeOut( duration ) {
  21358. return this._scheduleFading( duration, 1, 0 );
  21359. }
  21360. crossFadeFrom( fadeOutAction, duration, warp ) {
  21361. fadeOutAction.fadeOut( duration );
  21362. this.fadeIn( duration );
  21363. if ( warp ) {
  21364. const fadeInDuration = this._clip.duration,
  21365. fadeOutDuration = fadeOutAction._clip.duration,
  21366. startEndRatio = fadeOutDuration / fadeInDuration,
  21367. endStartRatio = fadeInDuration / fadeOutDuration;
  21368. fadeOutAction.warp( 1.0, startEndRatio, duration );
  21369. this.warp( endStartRatio, 1.0, duration );
  21370. }
  21371. return this;
  21372. }
  21373. crossFadeTo( fadeInAction, duration, warp ) {
  21374. return fadeInAction.crossFadeFrom( this, duration, warp );
  21375. }
  21376. stopFading() {
  21377. const weightInterpolant = this._weightInterpolant;
  21378. if ( weightInterpolant !== null ) {
  21379. this._weightInterpolant = null;
  21380. this._mixer._takeBackControlInterpolant( weightInterpolant );
  21381. }
  21382. return this;
  21383. }
  21384. // Time Scale Control
  21385. // set the time scale stopping any scheduled warping
  21386. // although .paused = true yields an effective time scale of zero, this
  21387. // method does *not* change .paused, because it would be confusing
  21388. setEffectiveTimeScale( timeScale ) {
  21389. this.timeScale = timeScale;
  21390. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  21391. return this.stopWarping();
  21392. }
  21393. // return the time scale considering warping and .paused
  21394. getEffectiveTimeScale() {
  21395. return this._effectiveTimeScale;
  21396. }
  21397. setDuration( duration ) {
  21398. this.timeScale = this._clip.duration / duration;
  21399. return this.stopWarping();
  21400. }
  21401. syncWith( action ) {
  21402. this.time = action.time;
  21403. this.timeScale = action.timeScale;
  21404. return this.stopWarping();
  21405. }
  21406. halt( duration ) {
  21407. return this.warp( this._effectiveTimeScale, 0, duration );
  21408. }
  21409. warp( startTimeScale, endTimeScale, duration ) {
  21410. const mixer = this._mixer,
  21411. now = mixer.time,
  21412. timeScale = this.timeScale;
  21413. let interpolant = this._timeScaleInterpolant;
  21414. if ( interpolant === null ) {
  21415. interpolant = mixer._lendControlInterpolant();
  21416. this._timeScaleInterpolant = interpolant;
  21417. }
  21418. const times = interpolant.parameterPositions,
  21419. values = interpolant.sampleValues;
  21420. times[ 0 ] = now;
  21421. times[ 1 ] = now + duration;
  21422. values[ 0 ] = startTimeScale / timeScale;
  21423. values[ 1 ] = endTimeScale / timeScale;
  21424. return this;
  21425. }
  21426. stopWarping() {
  21427. const timeScaleInterpolant = this._timeScaleInterpolant;
  21428. if ( timeScaleInterpolant !== null ) {
  21429. this._timeScaleInterpolant = null;
  21430. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  21431. }
  21432. return this;
  21433. }
  21434. // Object Accessors
  21435. getMixer() {
  21436. return this._mixer;
  21437. }
  21438. getClip() {
  21439. return this._clip;
  21440. }
  21441. getRoot() {
  21442. return this._localRoot || this._mixer._root;
  21443. }
  21444. // Interna
  21445. _update( time, deltaTime, timeDirection, accuIndex ) {
  21446. // called by the mixer
  21447. if ( ! this.enabled ) {
  21448. // call ._updateWeight() to update ._effectiveWeight
  21449. this._updateWeight( time );
  21450. return;
  21451. }
  21452. const startTime = this._startTime;
  21453. if ( startTime !== null ) {
  21454. // check for scheduled start of action
  21455. const timeRunning = ( time - startTime ) * timeDirection;
  21456. if ( timeRunning < 0 || timeDirection === 0 ) {
  21457. deltaTime = 0;
  21458. } else {
  21459. this._startTime = null; // unschedule
  21460. deltaTime = timeDirection * timeRunning;
  21461. }
  21462. }
  21463. // apply time scale and advance time
  21464. deltaTime *= this._updateTimeScale( time );
  21465. const clipTime = this._updateTime( deltaTime );
  21466. // note: _updateTime may disable the action resulting in
  21467. // an effective weight of 0
  21468. const weight = this._updateWeight( time );
  21469. if ( weight > 0 ) {
  21470. const interpolants = this._interpolants;
  21471. const propertyMixers = this._propertyBindings;
  21472. switch ( this.blendMode ) {
  21473. case AdditiveAnimationBlendMode:
  21474. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  21475. interpolants[ j ].evaluate( clipTime );
  21476. propertyMixers[ j ].accumulateAdditive( weight );
  21477. }
  21478. break;
  21479. case NormalAnimationBlendMode:
  21480. default:
  21481. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  21482. interpolants[ j ].evaluate( clipTime );
  21483. propertyMixers[ j ].accumulate( accuIndex, weight );
  21484. }
  21485. }
  21486. }
  21487. }
  21488. _updateWeight( time ) {
  21489. let weight = 0;
  21490. if ( this.enabled ) {
  21491. weight = this.weight;
  21492. const interpolant = this._weightInterpolant;
  21493. if ( interpolant !== null ) {
  21494. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  21495. weight *= interpolantValue;
  21496. if ( time > interpolant.parameterPositions[ 1 ] ) {
  21497. this.stopFading();
  21498. if ( interpolantValue === 0 ) {
  21499. // faded out, disable
  21500. this.enabled = false;
  21501. }
  21502. }
  21503. }
  21504. }
  21505. this._effectiveWeight = weight;
  21506. return weight;
  21507. }
  21508. _updateTimeScale( time ) {
  21509. let timeScale = 0;
  21510. if ( ! this.paused ) {
  21511. timeScale = this.timeScale;
  21512. const interpolant = this._timeScaleInterpolant;
  21513. if ( interpolant !== null ) {
  21514. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  21515. timeScale *= interpolantValue;
  21516. if ( time > interpolant.parameterPositions[ 1 ] ) {
  21517. this.stopWarping();
  21518. if ( timeScale === 0 ) {
  21519. // motion has halted, pause
  21520. this.paused = true;
  21521. } else {
  21522. // warp done - apply final time scale
  21523. this.timeScale = timeScale;
  21524. }
  21525. }
  21526. }
  21527. }
  21528. this._effectiveTimeScale = timeScale;
  21529. return timeScale;
  21530. }
  21531. _updateTime( deltaTime ) {
  21532. const duration = this._clip.duration;
  21533. const loop = this.loop;
  21534. let time = this.time + deltaTime;
  21535. let loopCount = this._loopCount;
  21536. const pingPong = ( loop === LoopPingPong );
  21537. if ( deltaTime === 0 ) {
  21538. if ( loopCount === -1 ) return time;
  21539. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  21540. }
  21541. if ( loop === LoopOnce ) {
  21542. if ( loopCount === -1 ) {
  21543. // just started
  21544. this._loopCount = 0;
  21545. this._setEndings( true, true, false );
  21546. }
  21547. handle_stop: {
  21548. if ( time >= duration ) {
  21549. time = duration;
  21550. } else if ( time < 0 ) {
  21551. time = 0;
  21552. } else {
  21553. this.time = time;
  21554. break handle_stop;
  21555. }
  21556. if ( this.clampWhenFinished ) this.paused = true;
  21557. else this.enabled = false;
  21558. this.time = time;
  21559. this._mixer.dispatchEvent( {
  21560. type: 'finished', action: this,
  21561. direction: deltaTime < 0 ? -1 : 1
  21562. } );
  21563. }
  21564. } else { // repetitive Repeat or PingPong
  21565. if ( loopCount === -1 ) {
  21566. // just started
  21567. if ( deltaTime >= 0 ) {
  21568. loopCount = 0;
  21569. this._setEndings( true, this.repetitions === 0, pingPong );
  21570. } else {
  21571. // when looping in reverse direction, the initial
  21572. // transition through zero counts as a repetition,
  21573. // so leave loopCount at -1
  21574. this._setEndings( this.repetitions === 0, true, pingPong );
  21575. }
  21576. }
  21577. if ( time >= duration || time < 0 ) {
  21578. // wrap around
  21579. const loopDelta = Math.floor( time / duration ); // signed
  21580. time -= duration * loopDelta;
  21581. loopCount += Math.abs( loopDelta );
  21582. const pending = this.repetitions - loopCount;
  21583. if ( pending <= 0 ) {
  21584. // have to stop (switch state, clamp time, fire event)
  21585. if ( this.clampWhenFinished ) this.paused = true;
  21586. else this.enabled = false;
  21587. time = deltaTime > 0 ? duration : 0;
  21588. this.time = time;
  21589. this._mixer.dispatchEvent( {
  21590. type: 'finished', action: this,
  21591. direction: deltaTime > 0 ? 1 : -1
  21592. } );
  21593. } else {
  21594. // keep running
  21595. if ( pending === 1 ) {
  21596. // entering the last round
  21597. const atStart = deltaTime < 0;
  21598. this._setEndings( atStart, ! atStart, pingPong );
  21599. } else {
  21600. this._setEndings( false, false, pingPong );
  21601. }
  21602. this._loopCount = loopCount;
  21603. this.time = time;
  21604. this._mixer.dispatchEvent( {
  21605. type: 'loop', action: this, loopDelta: loopDelta
  21606. } );
  21607. }
  21608. } else {
  21609. this.time = time;
  21610. }
  21611. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  21612. // invert time for the "pong round"
  21613. return duration - time;
  21614. }
  21615. }
  21616. return time;
  21617. }
  21618. _setEndings( atStart, atEnd, pingPong ) {
  21619. const settings = this._interpolantSettings;
  21620. if ( pingPong ) {
  21621. settings.endingStart = ZeroSlopeEnding;
  21622. settings.endingEnd = ZeroSlopeEnding;
  21623. } else {
  21624. // assuming for LoopOnce atStart == atEnd == true
  21625. if ( atStart ) {
  21626. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  21627. } else {
  21628. settings.endingStart = WrapAroundEnding;
  21629. }
  21630. if ( atEnd ) {
  21631. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  21632. } else {
  21633. settings.endingEnd = WrapAroundEnding;
  21634. }
  21635. }
  21636. }
  21637. _scheduleFading( duration, weightNow, weightThen ) {
  21638. const mixer = this._mixer, now = mixer.time;
  21639. let interpolant = this._weightInterpolant;
  21640. if ( interpolant === null ) {
  21641. interpolant = mixer._lendControlInterpolant();
  21642. this._weightInterpolant = interpolant;
  21643. }
  21644. const times = interpolant.parameterPositions,
  21645. values = interpolant.sampleValues;
  21646. times[ 0 ] = now;
  21647. values[ 0 ] = weightNow;
  21648. times[ 1 ] = now + duration;
  21649. values[ 1 ] = weightThen;
  21650. return this;
  21651. }
  21652. }
  21653. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  21654. class AnimationMixer extends EventDispatcher {
  21655. constructor( root ) {
  21656. super();
  21657. this._root = root;
  21658. this._initMemoryManager();
  21659. this._accuIndex = 0;
  21660. this.time = 0;
  21661. this.timeScale = 1.0;
  21662. }
  21663. _bindAction( action, prototypeAction ) {
  21664. const root = action._localRoot || this._root,
  21665. tracks = action._clip.tracks,
  21666. nTracks = tracks.length,
  21667. bindings = action._propertyBindings,
  21668. interpolants = action._interpolants,
  21669. rootUuid = root.uuid,
  21670. bindingsByRoot = this._bindingsByRootAndName;
  21671. let bindingsByName = bindingsByRoot[ rootUuid ];
  21672. if ( bindingsByName === undefined ) {
  21673. bindingsByName = {};
  21674. bindingsByRoot[ rootUuid ] = bindingsByName;
  21675. }
  21676. for ( let i = 0; i !== nTracks; ++ i ) {
  21677. const track = tracks[ i ],
  21678. trackName = track.name;
  21679. let binding = bindingsByName[ trackName ];
  21680. if ( binding !== undefined ) {
  21681. ++ binding.referenceCount;
  21682. bindings[ i ] = binding;
  21683. } else {
  21684. binding = bindings[ i ];
  21685. if ( binding !== undefined ) {
  21686. // existing binding, make sure the cache knows
  21687. if ( binding._cacheIndex === null ) {
  21688. ++ binding.referenceCount;
  21689. this._addInactiveBinding( binding, rootUuid, trackName );
  21690. }
  21691. continue;
  21692. }
  21693. const path = prototypeAction && prototypeAction.
  21694. _propertyBindings[ i ].binding.parsedPath;
  21695. binding = new PropertyMixer(
  21696. PropertyBinding.create( root, trackName, path ),
  21697. track.ValueTypeName, track.getValueSize() );
  21698. ++ binding.referenceCount;
  21699. this._addInactiveBinding( binding, rootUuid, trackName );
  21700. bindings[ i ] = binding;
  21701. }
  21702. interpolants[ i ].resultBuffer = binding.buffer;
  21703. }
  21704. }
  21705. _activateAction( action ) {
  21706. if ( ! this._isActiveAction( action ) ) {
  21707. if ( action._cacheIndex === null ) {
  21708. // this action has been forgotten by the cache, but the user
  21709. // appears to be still using it -> rebind
  21710. const rootUuid = ( action._localRoot || this._root ).uuid,
  21711. clipUuid = action._clip.uuid,
  21712. actionsForClip = this._actionsByClip[ clipUuid ];
  21713. this._bindAction( action,
  21714. actionsForClip && actionsForClip.knownActions[ 0 ] );
  21715. this._addInactiveAction( action, clipUuid, rootUuid );
  21716. }
  21717. const bindings = action._propertyBindings;
  21718. // increment reference counts / sort out state
  21719. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  21720. const binding = bindings[ i ];
  21721. if ( binding.useCount ++ === 0 ) {
  21722. this._lendBinding( binding );
  21723. binding.saveOriginalState();
  21724. }
  21725. }
  21726. this._lendAction( action );
  21727. }
  21728. }
  21729. _deactivateAction( action ) {
  21730. if ( this._isActiveAction( action ) ) {
  21731. const bindings = action._propertyBindings;
  21732. // decrement reference counts / sort out state
  21733. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  21734. const binding = bindings[ i ];
  21735. if ( -- binding.useCount === 0 ) {
  21736. binding.restoreOriginalState();
  21737. this._takeBackBinding( binding );
  21738. }
  21739. }
  21740. this._takeBackAction( action );
  21741. }
  21742. }
  21743. // Memory manager
  21744. _initMemoryManager() {
  21745. this._actions = []; // 'nActiveActions' followed by inactive ones
  21746. this._nActiveActions = 0;
  21747. this._actionsByClip = {};
  21748. // inside:
  21749. // {
  21750. // knownActions: Array< AnimationAction > - used as prototypes
  21751. // actionByRoot: AnimationAction - lookup
  21752. // }
  21753. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  21754. this._nActiveBindings = 0;
  21755. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  21756. this._controlInterpolants = []; // same game as above
  21757. this._nActiveControlInterpolants = 0;
  21758. const scope = this;
  21759. this.stats = {
  21760. actions: {
  21761. get total() {
  21762. return scope._actions.length;
  21763. },
  21764. get inUse() {
  21765. return scope._nActiveActions;
  21766. }
  21767. },
  21768. bindings: {
  21769. get total() {
  21770. return scope._bindings.length;
  21771. },
  21772. get inUse() {
  21773. return scope._nActiveBindings;
  21774. }
  21775. },
  21776. controlInterpolants: {
  21777. get total() {
  21778. return scope._controlInterpolants.length;
  21779. },
  21780. get inUse() {
  21781. return scope._nActiveControlInterpolants;
  21782. }
  21783. }
  21784. };
  21785. }
  21786. // Memory management for AnimationAction objects
  21787. _isActiveAction( action ) {
  21788. const index = action._cacheIndex;
  21789. return index !== null && index < this._nActiveActions;
  21790. }
  21791. _addInactiveAction( action, clipUuid, rootUuid ) {
  21792. const actions = this._actions,
  21793. actionsByClip = this._actionsByClip;
  21794. let actionsForClip = actionsByClip[ clipUuid ];
  21795. if ( actionsForClip === undefined ) {
  21796. actionsForClip = {
  21797. knownActions: [ action ],
  21798. actionByRoot: {}
  21799. };
  21800. action._byClipCacheIndex = 0;
  21801. actionsByClip[ clipUuid ] = actionsForClip;
  21802. } else {
  21803. const knownActions = actionsForClip.knownActions;
  21804. action._byClipCacheIndex = knownActions.length;
  21805. knownActions.push( action );
  21806. }
  21807. action._cacheIndex = actions.length;
  21808. actions.push( action );
  21809. actionsForClip.actionByRoot[ rootUuid ] = action;
  21810. }
  21811. _removeInactiveAction( action ) {
  21812. const actions = this._actions,
  21813. lastInactiveAction = actions[ actions.length - 1 ],
  21814. cacheIndex = action._cacheIndex;
  21815. lastInactiveAction._cacheIndex = cacheIndex;
  21816. actions[ cacheIndex ] = lastInactiveAction;
  21817. actions.pop();
  21818. action._cacheIndex = null;
  21819. const clipUuid = action._clip.uuid,
  21820. actionsByClip = this._actionsByClip,
  21821. actionsForClip = actionsByClip[ clipUuid ],
  21822. knownActionsForClip = actionsForClip.knownActions,
  21823. lastKnownAction =
  21824. knownActionsForClip[ knownActionsForClip.length - 1 ],
  21825. byClipCacheIndex = action._byClipCacheIndex;
  21826. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  21827. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  21828. knownActionsForClip.pop();
  21829. action._byClipCacheIndex = null;
  21830. const actionByRoot = actionsForClip.actionByRoot,
  21831. rootUuid = ( action._localRoot || this._root ).uuid;
  21832. delete actionByRoot[ rootUuid ];
  21833. if ( knownActionsForClip.length === 0 ) {
  21834. delete actionsByClip[ clipUuid ];
  21835. }
  21836. this._removeInactiveBindingsForAction( action );
  21837. }
  21838. _removeInactiveBindingsForAction( action ) {
  21839. const bindings = action._propertyBindings;
  21840. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  21841. const binding = bindings[ i ];
  21842. if ( -- binding.referenceCount === 0 ) {
  21843. this._removeInactiveBinding( binding );
  21844. }
  21845. }
  21846. }
  21847. _lendAction( action ) {
  21848. // [ active actions | inactive actions ]
  21849. // [ active actions >| inactive actions ]
  21850. // s a
  21851. // <-swap->
  21852. // a s
  21853. const actions = this._actions,
  21854. prevIndex = action._cacheIndex,
  21855. lastActiveIndex = this._nActiveActions ++,
  21856. firstInactiveAction = actions[ lastActiveIndex ];
  21857. action._cacheIndex = lastActiveIndex;
  21858. actions[ lastActiveIndex ] = action;
  21859. firstInactiveAction._cacheIndex = prevIndex;
  21860. actions[ prevIndex ] = firstInactiveAction;
  21861. }
  21862. _takeBackAction( action ) {
  21863. // [ active actions | inactive actions ]
  21864. // [ active actions |< inactive actions ]
  21865. // a s
  21866. // <-swap->
  21867. // s a
  21868. const actions = this._actions,
  21869. prevIndex = action._cacheIndex,
  21870. firstInactiveIndex = -- this._nActiveActions,
  21871. lastActiveAction = actions[ firstInactiveIndex ];
  21872. action._cacheIndex = firstInactiveIndex;
  21873. actions[ firstInactiveIndex ] = action;
  21874. lastActiveAction._cacheIndex = prevIndex;
  21875. actions[ prevIndex ] = lastActiveAction;
  21876. }
  21877. // Memory management for PropertyMixer objects
  21878. _addInactiveBinding( binding, rootUuid, trackName ) {
  21879. const bindingsByRoot = this._bindingsByRootAndName,
  21880. bindings = this._bindings;
  21881. let bindingByName = bindingsByRoot[ rootUuid ];
  21882. if ( bindingByName === undefined ) {
  21883. bindingByName = {};
  21884. bindingsByRoot[ rootUuid ] = bindingByName;
  21885. }
  21886. bindingByName[ trackName ] = binding;
  21887. binding._cacheIndex = bindings.length;
  21888. bindings.push( binding );
  21889. }
  21890. _removeInactiveBinding( binding ) {
  21891. const bindings = this._bindings,
  21892. propBinding = binding.binding,
  21893. rootUuid = propBinding.rootNode.uuid,
  21894. trackName = propBinding.path,
  21895. bindingsByRoot = this._bindingsByRootAndName,
  21896. bindingByName = bindingsByRoot[ rootUuid ],
  21897. lastInactiveBinding = bindings[ bindings.length - 1 ],
  21898. cacheIndex = binding._cacheIndex;
  21899. lastInactiveBinding._cacheIndex = cacheIndex;
  21900. bindings[ cacheIndex ] = lastInactiveBinding;
  21901. bindings.pop();
  21902. delete bindingByName[ trackName ];
  21903. if ( Object.keys( bindingByName ).length === 0 ) {
  21904. delete bindingsByRoot[ rootUuid ];
  21905. }
  21906. }
  21907. _lendBinding( binding ) {
  21908. const bindings = this._bindings,
  21909. prevIndex = binding._cacheIndex,
  21910. lastActiveIndex = this._nActiveBindings ++,
  21911. firstInactiveBinding = bindings[ lastActiveIndex ];
  21912. binding._cacheIndex = lastActiveIndex;
  21913. bindings[ lastActiveIndex ] = binding;
  21914. firstInactiveBinding._cacheIndex = prevIndex;
  21915. bindings[ prevIndex ] = firstInactiveBinding;
  21916. }
  21917. _takeBackBinding( binding ) {
  21918. const bindings = this._bindings,
  21919. prevIndex = binding._cacheIndex,
  21920. firstInactiveIndex = -- this._nActiveBindings,
  21921. lastActiveBinding = bindings[ firstInactiveIndex ];
  21922. binding._cacheIndex = firstInactiveIndex;
  21923. bindings[ firstInactiveIndex ] = binding;
  21924. lastActiveBinding._cacheIndex = prevIndex;
  21925. bindings[ prevIndex ] = lastActiveBinding;
  21926. }
  21927. // Memory management of Interpolants for weight and time scale
  21928. _lendControlInterpolant() {
  21929. const interpolants = this._controlInterpolants,
  21930. lastActiveIndex = this._nActiveControlInterpolants ++;
  21931. let interpolant = interpolants[ lastActiveIndex ];
  21932. if ( interpolant === undefined ) {
  21933. interpolant = new LinearInterpolant(
  21934. new Float32Array( 2 ), new Float32Array( 2 ),
  21935. 1, _controlInterpolantsResultBuffer );
  21936. interpolant.__cacheIndex = lastActiveIndex;
  21937. interpolants[ lastActiveIndex ] = interpolant;
  21938. }
  21939. return interpolant;
  21940. }
  21941. _takeBackControlInterpolant( interpolant ) {
  21942. const interpolants = this._controlInterpolants,
  21943. prevIndex = interpolant.__cacheIndex,
  21944. firstInactiveIndex = -- this._nActiveControlInterpolants,
  21945. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  21946. interpolant.__cacheIndex = firstInactiveIndex;
  21947. interpolants[ firstInactiveIndex ] = interpolant;
  21948. lastActiveInterpolant.__cacheIndex = prevIndex;
  21949. interpolants[ prevIndex ] = lastActiveInterpolant;
  21950. }
  21951. // return an action for a clip optionally using a custom root target
  21952. // object (this method allocates a lot of dynamic memory in case a
  21953. // previously unknown clip/root combination is specified)
  21954. clipAction( clip, optionalRoot, blendMode ) {
  21955. const root = optionalRoot || this._root,
  21956. rootUuid = root.uuid;
  21957. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  21958. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  21959. const actionsForClip = this._actionsByClip[ clipUuid ];
  21960. let prototypeAction = null;
  21961. if ( blendMode === undefined ) {
  21962. if ( clipObject !== null ) {
  21963. blendMode = clipObject.blendMode;
  21964. } else {
  21965. blendMode = NormalAnimationBlendMode;
  21966. }
  21967. }
  21968. if ( actionsForClip !== undefined ) {
  21969. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  21970. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  21971. return existingAction;
  21972. }
  21973. // we know the clip, so we don't have to parse all
  21974. // the bindings again but can just copy
  21975. prototypeAction = actionsForClip.knownActions[ 0 ];
  21976. // also, take the clip from the prototype action
  21977. if ( clipObject === null )
  21978. clipObject = prototypeAction._clip;
  21979. }
  21980. // clip must be known when specified via string
  21981. if ( clipObject === null ) return null;
  21982. // allocate all resources required to run it
  21983. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  21984. this._bindAction( newAction, prototypeAction );
  21985. // and make the action known to the memory manager
  21986. this._addInactiveAction( newAction, clipUuid, rootUuid );
  21987. return newAction;
  21988. }
  21989. // get an existing action
  21990. existingAction( clip, optionalRoot ) {
  21991. const root = optionalRoot || this._root,
  21992. rootUuid = root.uuid,
  21993. clipObject = typeof clip === 'string' ?
  21994. AnimationClip.findByName( root, clip ) : clip,
  21995. clipUuid = clipObject ? clipObject.uuid : clip,
  21996. actionsForClip = this._actionsByClip[ clipUuid ];
  21997. if ( actionsForClip !== undefined ) {
  21998. return actionsForClip.actionByRoot[ rootUuid ] || null;
  21999. }
  22000. return null;
  22001. }
  22002. // deactivates all previously scheduled actions
  22003. stopAllAction() {
  22004. const actions = this._actions,
  22005. nActions = this._nActiveActions;
  22006. for ( let i = nActions - 1; i >= 0; -- i ) {
  22007. actions[ i ].stop();
  22008. }
  22009. return this;
  22010. }
  22011. // advance the time and update apply the animation
  22012. update( deltaTime ) {
  22013. deltaTime *= this.timeScale;
  22014. const actions = this._actions,
  22015. nActions = this._nActiveActions,
  22016. time = this.time += deltaTime,
  22017. timeDirection = Math.sign( deltaTime ),
  22018. accuIndex = this._accuIndex ^= 1;
  22019. // run active actions
  22020. for ( let i = 0; i !== nActions; ++ i ) {
  22021. const action = actions[ i ];
  22022. action._update( time, deltaTime, timeDirection, accuIndex );
  22023. }
  22024. // update scene graph
  22025. const bindings = this._bindings,
  22026. nBindings = this._nActiveBindings;
  22027. for ( let i = 0; i !== nBindings; ++ i ) {
  22028. bindings[ i ].apply( accuIndex );
  22029. }
  22030. return this;
  22031. }
  22032. // Allows you to seek to a specific time in an animation.
  22033. setTime( timeInSeconds ) {
  22034. this.time = 0; // Zero out time attribute for AnimationMixer object;
  22035. for ( let i = 0; i < this._actions.length; i ++ ) {
  22036. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  22037. }
  22038. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  22039. }
  22040. // return this mixer's root target object
  22041. getRoot() {
  22042. return this._root;
  22043. }
  22044. // free all resources specific to a particular clip
  22045. uncacheClip( clip ) {
  22046. const actions = this._actions,
  22047. clipUuid = clip.uuid,
  22048. actionsByClip = this._actionsByClip,
  22049. actionsForClip = actionsByClip[ clipUuid ];
  22050. if ( actionsForClip !== undefined ) {
  22051. // note: just calling _removeInactiveAction would mess up the
  22052. // iteration state and also require updating the state we can
  22053. // just throw away
  22054. const actionsToRemove = actionsForClip.knownActions;
  22055. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  22056. const action = actionsToRemove[ i ];
  22057. this._deactivateAction( action );
  22058. const cacheIndex = action._cacheIndex,
  22059. lastInactiveAction = actions[ actions.length - 1 ];
  22060. action._cacheIndex = null;
  22061. action._byClipCacheIndex = null;
  22062. lastInactiveAction._cacheIndex = cacheIndex;
  22063. actions[ cacheIndex ] = lastInactiveAction;
  22064. actions.pop();
  22065. this._removeInactiveBindingsForAction( action );
  22066. }
  22067. delete actionsByClip[ clipUuid ];
  22068. }
  22069. }
  22070. // free all resources specific to a particular root target object
  22071. uncacheRoot( root ) {
  22072. const rootUuid = root.uuid,
  22073. actionsByClip = this._actionsByClip;
  22074. for ( const clipUuid in actionsByClip ) {
  22075. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  22076. action = actionByRoot[ rootUuid ];
  22077. if ( action !== undefined ) {
  22078. this._deactivateAction( action );
  22079. this._removeInactiveAction( action );
  22080. }
  22081. }
  22082. const bindingsByRoot = this._bindingsByRootAndName,
  22083. bindingByName = bindingsByRoot[ rootUuid ];
  22084. if ( bindingByName !== undefined ) {
  22085. for ( const trackName in bindingByName ) {
  22086. const binding = bindingByName[ trackName ];
  22087. binding.restoreOriginalState();
  22088. this._removeInactiveBinding( binding );
  22089. }
  22090. }
  22091. }
  22092. // remove a targeted clip from the cache
  22093. uncacheAction( clip, optionalRoot ) {
  22094. const action = this.existingAction( clip, optionalRoot );
  22095. if ( action !== null ) {
  22096. this._deactivateAction( action );
  22097. this._removeInactiveAction( action );
  22098. }
  22099. }
  22100. }
  22101. class RenderTarget3D extends RenderTarget {
  22102. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  22103. super( width, height, options );
  22104. this.isRenderTarget3D = true;
  22105. this.depth = depth;
  22106. this.texture = new Data3DTexture( null, width, height, depth );
  22107. this.texture.isRenderTargetTexture = true;
  22108. }
  22109. }
  22110. class RenderTargetArray extends RenderTarget {
  22111. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  22112. super( width, height, options );
  22113. this.isRenderTargetArray = true;
  22114. this.depth = depth;
  22115. this.texture = new DataArrayTexture( null, width, height, depth );
  22116. this.texture.isRenderTargetTexture = true;
  22117. }
  22118. }
  22119. class Uniform {
  22120. constructor( value ) {
  22121. this.value = value;
  22122. }
  22123. clone() {
  22124. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  22125. }
  22126. }
  22127. let _id = 0;
  22128. class UniformsGroup extends EventDispatcher {
  22129. constructor() {
  22130. super();
  22131. this.isUniformsGroup = true;
  22132. Object.defineProperty( this, 'id', { value: _id ++ } );
  22133. this.name = '';
  22134. this.usage = StaticDrawUsage;
  22135. this.uniforms = [];
  22136. }
  22137. add( uniform ) {
  22138. this.uniforms.push( uniform );
  22139. return this;
  22140. }
  22141. remove( uniform ) {
  22142. const index = this.uniforms.indexOf( uniform );
  22143. if ( index !== -1 ) this.uniforms.splice( index, 1 );
  22144. return this;
  22145. }
  22146. setName( name ) {
  22147. this.name = name;
  22148. return this;
  22149. }
  22150. setUsage( value ) {
  22151. this.usage = value;
  22152. return this;
  22153. }
  22154. dispose() {
  22155. this.dispatchEvent( { type: 'dispose' } );
  22156. return this;
  22157. }
  22158. copy( source ) {
  22159. this.name = source.name;
  22160. this.usage = source.usage;
  22161. const uniformsSource = source.uniforms;
  22162. this.uniforms.length = 0;
  22163. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  22164. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  22165. for ( let j = 0; j < uniforms.length; j ++ ) {
  22166. this.uniforms.push( uniforms[ j ].clone() );
  22167. }
  22168. }
  22169. return this;
  22170. }
  22171. clone() {
  22172. return new this.constructor().copy( this );
  22173. }
  22174. }
  22175. class InstancedInterleavedBuffer extends InterleavedBuffer {
  22176. constructor( array, stride, meshPerAttribute = 1 ) {
  22177. super( array, stride );
  22178. this.isInstancedInterleavedBuffer = true;
  22179. this.meshPerAttribute = meshPerAttribute;
  22180. }
  22181. copy( source ) {
  22182. super.copy( source );
  22183. this.meshPerAttribute = source.meshPerAttribute;
  22184. return this;
  22185. }
  22186. clone( data ) {
  22187. const ib = super.clone( data );
  22188. ib.meshPerAttribute = this.meshPerAttribute;
  22189. return ib;
  22190. }
  22191. toJSON( data ) {
  22192. const json = super.toJSON( data );
  22193. json.isInstancedInterleavedBuffer = true;
  22194. json.meshPerAttribute = this.meshPerAttribute;
  22195. return json;
  22196. }
  22197. }
  22198. class GLBufferAttribute {
  22199. constructor( buffer, type, itemSize, elementSize, count ) {
  22200. this.isGLBufferAttribute = true;
  22201. this.name = '';
  22202. this.buffer = buffer;
  22203. this.type = type;
  22204. this.itemSize = itemSize;
  22205. this.elementSize = elementSize;
  22206. this.count = count;
  22207. this.version = 0;
  22208. }
  22209. set needsUpdate( value ) {
  22210. if ( value === true ) this.version ++;
  22211. }
  22212. setBuffer( buffer ) {
  22213. this.buffer = buffer;
  22214. return this;
  22215. }
  22216. setType( type, elementSize ) {
  22217. this.type = type;
  22218. this.elementSize = elementSize;
  22219. return this;
  22220. }
  22221. setItemSize( itemSize ) {
  22222. this.itemSize = itemSize;
  22223. return this;
  22224. }
  22225. setCount( count ) {
  22226. this.count = count;
  22227. return this;
  22228. }
  22229. }
  22230. const _matrix = /*@__PURE__*/ new Matrix4();
  22231. class Raycaster {
  22232. constructor( origin, direction, near = 0, far = Infinity ) {
  22233. this.ray = new Ray( origin, direction );
  22234. // direction is assumed to be normalized (for accurate distance calculations)
  22235. this.near = near;
  22236. this.far = far;
  22237. this.camera = null;
  22238. this.layers = new Layers();
  22239. this.params = {
  22240. Mesh: {},
  22241. Line: { threshold: 1 },
  22242. LOD: {},
  22243. Points: { threshold: 1 },
  22244. Sprite: {}
  22245. };
  22246. }
  22247. set( origin, direction ) {
  22248. // direction is assumed to be normalized (for accurate distance calculations)
  22249. this.ray.set( origin, direction );
  22250. }
  22251. setFromCamera( coords, camera ) {
  22252. if ( camera.isPerspectiveCamera ) {
  22253. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  22254. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  22255. this.camera = camera;
  22256. } else if ( camera.isOrthographicCamera ) {
  22257. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  22258. this.ray.direction.set( 0, 0, -1 ).transformDirection( camera.matrixWorld );
  22259. this.camera = camera;
  22260. } else {
  22261. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  22262. }
  22263. }
  22264. setFromXRController( controller ) {
  22265. _matrix.identity().extractRotation( controller.matrixWorld );
  22266. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  22267. this.ray.direction.set( 0, 0, -1 ).applyMatrix4( _matrix );
  22268. return this;
  22269. }
  22270. intersectObject( object, recursive = true, intersects = [] ) {
  22271. intersect( object, this, intersects, recursive );
  22272. intersects.sort( ascSort );
  22273. return intersects;
  22274. }
  22275. intersectObjects( objects, recursive = true, intersects = [] ) {
  22276. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  22277. intersect( objects[ i ], this, intersects, recursive );
  22278. }
  22279. intersects.sort( ascSort );
  22280. return intersects;
  22281. }
  22282. }
  22283. function ascSort( a, b ) {
  22284. return a.distance - b.distance;
  22285. }
  22286. function intersect( object, raycaster, intersects, recursive ) {
  22287. let propagate = true;
  22288. if ( object.layers.test( raycaster.layers ) ) {
  22289. const result = object.raycast( raycaster, intersects );
  22290. if ( result === false ) propagate = false;
  22291. }
  22292. if ( propagate === true && recursive === true ) {
  22293. const children = object.children;
  22294. for ( let i = 0, l = children.length; i < l; i ++ ) {
  22295. intersect( children[ i ], raycaster, intersects, true );
  22296. }
  22297. }
  22298. }
  22299. /**
  22300. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  22301. *
  22302. * phi (the polar angle) is measured from the positive y-axis. The positive y-axis is up.
  22303. * theta (the azimuthal angle) is measured from the positive z-axis.
  22304. */
  22305. class Spherical {
  22306. constructor( radius = 1, phi = 0, theta = 0 ) {
  22307. this.radius = radius;
  22308. this.phi = phi; // polar angle
  22309. this.theta = theta; // azimuthal angle
  22310. return this;
  22311. }
  22312. set( radius, phi, theta ) {
  22313. this.radius = radius;
  22314. this.phi = phi;
  22315. this.theta = theta;
  22316. return this;
  22317. }
  22318. copy( other ) {
  22319. this.radius = other.radius;
  22320. this.phi = other.phi;
  22321. this.theta = other.theta;
  22322. return this;
  22323. }
  22324. // restrict phi to be between EPS and PI-EPS
  22325. makeSafe() {
  22326. const EPS = 0.000001;
  22327. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  22328. return this;
  22329. }
  22330. setFromVector3( v ) {
  22331. return this.setFromCartesianCoords( v.x, v.y, v.z );
  22332. }
  22333. setFromCartesianCoords( x, y, z ) {
  22334. this.radius = Math.sqrt( x * x + y * y + z * z );
  22335. if ( this.radius === 0 ) {
  22336. this.theta = 0;
  22337. this.phi = 0;
  22338. } else {
  22339. this.theta = Math.atan2( x, z );
  22340. this.phi = Math.acos( clamp( y / this.radius, -1, 1 ) );
  22341. }
  22342. return this;
  22343. }
  22344. clone() {
  22345. return new this.constructor().copy( this );
  22346. }
  22347. }
  22348. /**
  22349. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  22350. */
  22351. class Cylindrical {
  22352. constructor( radius = 1, theta = 0, y = 0 ) {
  22353. this.radius = radius; // distance from the origin to a point in the x-z plane
  22354. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  22355. this.y = y; // height above the x-z plane
  22356. return this;
  22357. }
  22358. set( radius, theta, y ) {
  22359. this.radius = radius;
  22360. this.theta = theta;
  22361. this.y = y;
  22362. return this;
  22363. }
  22364. copy( other ) {
  22365. this.radius = other.radius;
  22366. this.theta = other.theta;
  22367. this.y = other.y;
  22368. return this;
  22369. }
  22370. setFromVector3( v ) {
  22371. return this.setFromCartesianCoords( v.x, v.y, v.z );
  22372. }
  22373. setFromCartesianCoords( x, y, z ) {
  22374. this.radius = Math.sqrt( x * x + z * z );
  22375. this.theta = Math.atan2( x, z );
  22376. this.y = y;
  22377. return this;
  22378. }
  22379. clone() {
  22380. return new this.constructor().copy( this );
  22381. }
  22382. }
  22383. class Matrix2 {
  22384. constructor( n11, n12, n21, n22 ) {
  22385. Matrix2.prototype.isMatrix2 = true;
  22386. this.elements = [
  22387. 1, 0,
  22388. 0, 1,
  22389. ];
  22390. if ( n11 !== undefined ) {
  22391. this.set( n11, n12, n21, n22 );
  22392. }
  22393. }
  22394. identity() {
  22395. this.set(
  22396. 1, 0,
  22397. 0, 1,
  22398. );
  22399. return this;
  22400. }
  22401. fromArray( array, offset = 0 ) {
  22402. for ( let i = 0; i < 4; i ++ ) {
  22403. this.elements[ i ] = array[ i + offset ];
  22404. }
  22405. return this;
  22406. }
  22407. set( n11, n12, n21, n22 ) {
  22408. const te = this.elements;
  22409. te[ 0 ] = n11; te[ 2 ] = n12;
  22410. te[ 1 ] = n21; te[ 3 ] = n22;
  22411. return this;
  22412. }
  22413. }
  22414. const _vector$4 = /*@__PURE__*/ new Vector2();
  22415. class Box2 {
  22416. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  22417. this.isBox2 = true;
  22418. this.min = min;
  22419. this.max = max;
  22420. }
  22421. set( min, max ) {
  22422. this.min.copy( min );
  22423. this.max.copy( max );
  22424. return this;
  22425. }
  22426. setFromPoints( points ) {
  22427. this.makeEmpty();
  22428. for ( let i = 0, il = points.length; i < il; i ++ ) {
  22429. this.expandByPoint( points[ i ] );
  22430. }
  22431. return this;
  22432. }
  22433. setFromCenterAndSize( center, size ) {
  22434. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  22435. this.min.copy( center ).sub( halfSize );
  22436. this.max.copy( center ).add( halfSize );
  22437. return this;
  22438. }
  22439. clone() {
  22440. return new this.constructor().copy( this );
  22441. }
  22442. copy( box ) {
  22443. this.min.copy( box.min );
  22444. this.max.copy( box.max );
  22445. return this;
  22446. }
  22447. makeEmpty() {
  22448. this.min.x = this.min.y = + Infinity;
  22449. this.max.x = this.max.y = - Infinity;
  22450. return this;
  22451. }
  22452. isEmpty() {
  22453. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  22454. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  22455. }
  22456. getCenter( target ) {
  22457. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  22458. }
  22459. getSize( target ) {
  22460. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  22461. }
  22462. expandByPoint( point ) {
  22463. this.min.min( point );
  22464. this.max.max( point );
  22465. return this;
  22466. }
  22467. expandByVector( vector ) {
  22468. this.min.sub( vector );
  22469. this.max.add( vector );
  22470. return this;
  22471. }
  22472. expandByScalar( scalar ) {
  22473. this.min.addScalar( - scalar );
  22474. this.max.addScalar( scalar );
  22475. return this;
  22476. }
  22477. containsPoint( point ) {
  22478. return point.x >= this.min.x && point.x <= this.max.x &&
  22479. point.y >= this.min.y && point.y <= this.max.y;
  22480. }
  22481. containsBox( box ) {
  22482. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  22483. this.min.y <= box.min.y && box.max.y <= this.max.y;
  22484. }
  22485. getParameter( point, target ) {
  22486. // This can potentially have a divide by zero if the box
  22487. // has a size dimension of 0.
  22488. return target.set(
  22489. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  22490. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  22491. );
  22492. }
  22493. intersectsBox( box ) {
  22494. // using 4 splitting planes to rule out intersections
  22495. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  22496. box.max.y >= this.min.y && box.min.y <= this.max.y;
  22497. }
  22498. clampPoint( point, target ) {
  22499. return target.copy( point ).clamp( this.min, this.max );
  22500. }
  22501. distanceToPoint( point ) {
  22502. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  22503. }
  22504. intersect( box ) {
  22505. this.min.max( box.min );
  22506. this.max.min( box.max );
  22507. if ( this.isEmpty() ) this.makeEmpty();
  22508. return this;
  22509. }
  22510. union( box ) {
  22511. this.min.min( box.min );
  22512. this.max.max( box.max );
  22513. return this;
  22514. }
  22515. translate( offset ) {
  22516. this.min.add( offset );
  22517. this.max.add( offset );
  22518. return this;
  22519. }
  22520. equals( box ) {
  22521. return box.min.equals( this.min ) && box.max.equals( this.max );
  22522. }
  22523. }
  22524. const _startP = /*@__PURE__*/ new Vector3();
  22525. const _startEnd = /*@__PURE__*/ new Vector3();
  22526. class Line3 {
  22527. constructor( start = new Vector3(), end = new Vector3() ) {
  22528. this.start = start;
  22529. this.end = end;
  22530. }
  22531. set( start, end ) {
  22532. this.start.copy( start );
  22533. this.end.copy( end );
  22534. return this;
  22535. }
  22536. copy( line ) {
  22537. this.start.copy( line.start );
  22538. this.end.copy( line.end );
  22539. return this;
  22540. }
  22541. getCenter( target ) {
  22542. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  22543. }
  22544. delta( target ) {
  22545. return target.subVectors( this.end, this.start );
  22546. }
  22547. distanceSq() {
  22548. return this.start.distanceToSquared( this.end );
  22549. }
  22550. distance() {
  22551. return this.start.distanceTo( this.end );
  22552. }
  22553. at( t, target ) {
  22554. return this.delta( target ).multiplyScalar( t ).add( this.start );
  22555. }
  22556. closestPointToPointParameter( point, clampToLine ) {
  22557. _startP.subVectors( point, this.start );
  22558. _startEnd.subVectors( this.end, this.start );
  22559. const startEnd2 = _startEnd.dot( _startEnd );
  22560. const startEnd_startP = _startEnd.dot( _startP );
  22561. let t = startEnd_startP / startEnd2;
  22562. if ( clampToLine ) {
  22563. t = clamp( t, 0, 1 );
  22564. }
  22565. return t;
  22566. }
  22567. closestPointToPoint( point, clampToLine, target ) {
  22568. const t = this.closestPointToPointParameter( point, clampToLine );
  22569. return this.delta( target ).multiplyScalar( t ).add( this.start );
  22570. }
  22571. applyMatrix4( matrix ) {
  22572. this.start.applyMatrix4( matrix );
  22573. this.end.applyMatrix4( matrix );
  22574. return this;
  22575. }
  22576. equals( line ) {
  22577. return line.start.equals( this.start ) && line.end.equals( this.end );
  22578. }
  22579. clone() {
  22580. return new this.constructor().copy( this );
  22581. }
  22582. }
  22583. const _vector$3 = /*@__PURE__*/ new Vector3();
  22584. class SpotLightHelper extends Object3D {
  22585. constructor( light, color ) {
  22586. super();
  22587. this.light = light;
  22588. this.matrixAutoUpdate = false;
  22589. this.color = color;
  22590. this.type = 'SpotLightHelper';
  22591. const geometry = new BufferGeometry();
  22592. const positions = [
  22593. 0, 0, 0, 0, 0, 1,
  22594. 0, 0, 0, 1, 0, 1,
  22595. 0, 0, 0, -1, 0, 1,
  22596. 0, 0, 0, 0, 1, 1,
  22597. 0, 0, 0, 0, -1, 1
  22598. ];
  22599. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  22600. const p1 = ( i / l ) * Math.PI * 2;
  22601. const p2 = ( j / l ) * Math.PI * 2;
  22602. positions.push(
  22603. Math.cos( p1 ), Math.sin( p1 ), 1,
  22604. Math.cos( p2 ), Math.sin( p2 ), 1
  22605. );
  22606. }
  22607. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  22608. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  22609. this.cone = new LineSegments( geometry, material );
  22610. this.add( this.cone );
  22611. this.update();
  22612. }
  22613. dispose() {
  22614. this.cone.geometry.dispose();
  22615. this.cone.material.dispose();
  22616. }
  22617. update() {
  22618. this.light.updateWorldMatrix( true, false );
  22619. this.light.target.updateWorldMatrix( true, false );
  22620. // update the local matrix based on the parent and light target transforms
  22621. if ( this.parent ) {
  22622. this.parent.updateWorldMatrix( true );
  22623. this.matrix
  22624. .copy( this.parent.matrixWorld )
  22625. .invert()
  22626. .multiply( this.light.matrixWorld );
  22627. } else {
  22628. this.matrix.copy( this.light.matrixWorld );
  22629. }
  22630. this.matrixWorld.copy( this.light.matrixWorld );
  22631. const coneLength = this.light.distance ? this.light.distance : 1000;
  22632. const coneWidth = coneLength * Math.tan( this.light.angle );
  22633. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  22634. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  22635. this.cone.lookAt( _vector$3 );
  22636. if ( this.color !== undefined ) {
  22637. this.cone.material.color.set( this.color );
  22638. } else {
  22639. this.cone.material.color.copy( this.light.color );
  22640. }
  22641. }
  22642. }
  22643. const _vector$2 = /*@__PURE__*/ new Vector3();
  22644. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  22645. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  22646. class SkeletonHelper extends LineSegments {
  22647. constructor( object ) {
  22648. const bones = getBoneList( object );
  22649. const geometry = new BufferGeometry();
  22650. const vertices = [];
  22651. const colors = [];
  22652. const color1 = new Color( 0, 0, 1 );
  22653. const color2 = new Color( 0, 1, 0 );
  22654. for ( let i = 0; i < bones.length; i ++ ) {
  22655. const bone = bones[ i ];
  22656. if ( bone.parent && bone.parent.isBone ) {
  22657. vertices.push( 0, 0, 0 );
  22658. vertices.push( 0, 0, 0 );
  22659. colors.push( color1.r, color1.g, color1.b );
  22660. colors.push( color2.r, color2.g, color2.b );
  22661. }
  22662. }
  22663. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22664. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  22665. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  22666. super( geometry, material );
  22667. this.isSkeletonHelper = true;
  22668. this.type = 'SkeletonHelper';
  22669. this.root = object;
  22670. this.bones = bones;
  22671. this.matrix = object.matrixWorld;
  22672. this.matrixAutoUpdate = false;
  22673. }
  22674. updateMatrixWorld( force ) {
  22675. const bones = this.bones;
  22676. const geometry = this.geometry;
  22677. const position = geometry.getAttribute( 'position' );
  22678. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  22679. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  22680. const bone = bones[ i ];
  22681. if ( bone.parent && bone.parent.isBone ) {
  22682. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  22683. _vector$2.setFromMatrixPosition( _boneMatrix );
  22684. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  22685. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  22686. _vector$2.setFromMatrixPosition( _boneMatrix );
  22687. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  22688. j += 2;
  22689. }
  22690. }
  22691. geometry.getAttribute( 'position' ).needsUpdate = true;
  22692. super.updateMatrixWorld( force );
  22693. }
  22694. dispose() {
  22695. this.geometry.dispose();
  22696. this.material.dispose();
  22697. }
  22698. }
  22699. function getBoneList( object ) {
  22700. const boneList = [];
  22701. if ( object.isBone === true ) {
  22702. boneList.push( object );
  22703. }
  22704. for ( let i = 0; i < object.children.length; i ++ ) {
  22705. boneList.push( ...getBoneList( object.children[ i ] ) );
  22706. }
  22707. return boneList;
  22708. }
  22709. class PointLightHelper extends Mesh {
  22710. constructor( light, sphereSize, color ) {
  22711. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  22712. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  22713. super( geometry, material );
  22714. this.light = light;
  22715. this.color = color;
  22716. this.type = 'PointLightHelper';
  22717. this.matrix = this.light.matrixWorld;
  22718. this.matrixAutoUpdate = false;
  22719. this.update();
  22720. /*
  22721. // TODO: delete this comment?
  22722. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  22723. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  22724. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  22725. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  22726. const d = light.distance;
  22727. if ( d === 0.0 ) {
  22728. this.lightDistance.visible = false;
  22729. } else {
  22730. this.lightDistance.scale.set( d, d, d );
  22731. }
  22732. this.add( this.lightDistance );
  22733. */
  22734. }
  22735. dispose() {
  22736. this.geometry.dispose();
  22737. this.material.dispose();
  22738. }
  22739. update() {
  22740. this.light.updateWorldMatrix( true, false );
  22741. if ( this.color !== undefined ) {
  22742. this.material.color.set( this.color );
  22743. } else {
  22744. this.material.color.copy( this.light.color );
  22745. }
  22746. /*
  22747. const d = this.light.distance;
  22748. if ( d === 0.0 ) {
  22749. this.lightDistance.visible = false;
  22750. } else {
  22751. this.lightDistance.visible = true;
  22752. this.lightDistance.scale.set( d, d, d );
  22753. }
  22754. */
  22755. }
  22756. }
  22757. const _vector$1 = /*@__PURE__*/ new Vector3();
  22758. const _color1 = /*@__PURE__*/ new Color();
  22759. const _color2 = /*@__PURE__*/ new Color();
  22760. class HemisphereLightHelper extends Object3D {
  22761. constructor( light, size, color ) {
  22762. super();
  22763. this.light = light;
  22764. this.matrix = light.matrixWorld;
  22765. this.matrixAutoUpdate = false;
  22766. this.color = color;
  22767. this.type = 'HemisphereLightHelper';
  22768. const geometry = new OctahedronGeometry( size );
  22769. geometry.rotateY( Math.PI * 0.5 );
  22770. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  22771. if ( this.color === undefined ) this.material.vertexColors = true;
  22772. const position = geometry.getAttribute( 'position' );
  22773. const colors = new Float32Array( position.count * 3 );
  22774. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  22775. this.add( new Mesh( geometry, this.material ) );
  22776. this.update();
  22777. }
  22778. dispose() {
  22779. this.children[ 0 ].geometry.dispose();
  22780. this.children[ 0 ].material.dispose();
  22781. }
  22782. update() {
  22783. const mesh = this.children[ 0 ];
  22784. if ( this.color !== undefined ) {
  22785. this.material.color.set( this.color );
  22786. } else {
  22787. const colors = mesh.geometry.getAttribute( 'color' );
  22788. _color1.copy( this.light.color );
  22789. _color2.copy( this.light.groundColor );
  22790. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  22791. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  22792. colors.setXYZ( i, color.r, color.g, color.b );
  22793. }
  22794. colors.needsUpdate = true;
  22795. }
  22796. this.light.updateWorldMatrix( true, false );
  22797. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  22798. }
  22799. }
  22800. class GridHelper extends LineSegments {
  22801. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  22802. color1 = new Color( color1 );
  22803. color2 = new Color( color2 );
  22804. const center = divisions / 2;
  22805. const step = size / divisions;
  22806. const halfSize = size / 2;
  22807. const vertices = [], colors = [];
  22808. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  22809. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  22810. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  22811. const color = i === center ? color1 : color2;
  22812. color.toArray( colors, j ); j += 3;
  22813. color.toArray( colors, j ); j += 3;
  22814. color.toArray( colors, j ); j += 3;
  22815. color.toArray( colors, j ); j += 3;
  22816. }
  22817. const geometry = new BufferGeometry();
  22818. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22819. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  22820. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  22821. super( geometry, material );
  22822. this.type = 'GridHelper';
  22823. }
  22824. dispose() {
  22825. this.geometry.dispose();
  22826. this.material.dispose();
  22827. }
  22828. }
  22829. class PolarGridHelper extends LineSegments {
  22830. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  22831. color1 = new Color( color1 );
  22832. color2 = new Color( color2 );
  22833. const vertices = [];
  22834. const colors = [];
  22835. // create the sectors
  22836. if ( sectors > 1 ) {
  22837. for ( let i = 0; i < sectors; i ++ ) {
  22838. const v = ( i / sectors ) * ( Math.PI * 2 );
  22839. const x = Math.sin( v ) * radius;
  22840. const z = Math.cos( v ) * radius;
  22841. vertices.push( 0, 0, 0 );
  22842. vertices.push( x, 0, z );
  22843. const color = ( i & 1 ) ? color1 : color2;
  22844. colors.push( color.r, color.g, color.b );
  22845. colors.push( color.r, color.g, color.b );
  22846. }
  22847. }
  22848. // create the rings
  22849. for ( let i = 0; i < rings; i ++ ) {
  22850. const color = ( i & 1 ) ? color1 : color2;
  22851. const r = radius - ( radius / rings * i );
  22852. for ( let j = 0; j < divisions; j ++ ) {
  22853. // first vertex
  22854. let v = ( j / divisions ) * ( Math.PI * 2 );
  22855. let x = Math.sin( v ) * r;
  22856. let z = Math.cos( v ) * r;
  22857. vertices.push( x, 0, z );
  22858. colors.push( color.r, color.g, color.b );
  22859. // second vertex
  22860. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  22861. x = Math.sin( v ) * r;
  22862. z = Math.cos( v ) * r;
  22863. vertices.push( x, 0, z );
  22864. colors.push( color.r, color.g, color.b );
  22865. }
  22866. }
  22867. const geometry = new BufferGeometry();
  22868. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22869. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  22870. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  22871. super( geometry, material );
  22872. this.type = 'PolarGridHelper';
  22873. }
  22874. dispose() {
  22875. this.geometry.dispose();
  22876. this.material.dispose();
  22877. }
  22878. }
  22879. const _v1 = /*@__PURE__*/ new Vector3();
  22880. const _v2 = /*@__PURE__*/ new Vector3();
  22881. const _v3 = /*@__PURE__*/ new Vector3();
  22882. class DirectionalLightHelper extends Object3D {
  22883. constructor( light, size, color ) {
  22884. super();
  22885. this.light = light;
  22886. this.matrix = light.matrixWorld;
  22887. this.matrixAutoUpdate = false;
  22888. this.color = color;
  22889. this.type = 'DirectionalLightHelper';
  22890. if ( size === undefined ) size = 1;
  22891. let geometry = new BufferGeometry();
  22892. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  22893. - size, size, 0,
  22894. size, size, 0,
  22895. size, - size, 0,
  22896. - size, - size, 0,
  22897. - size, size, 0
  22898. ], 3 ) );
  22899. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  22900. this.lightPlane = new Line( geometry, material );
  22901. this.add( this.lightPlane );
  22902. geometry = new BufferGeometry();
  22903. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  22904. this.targetLine = new Line( geometry, material );
  22905. this.add( this.targetLine );
  22906. this.update();
  22907. }
  22908. dispose() {
  22909. this.lightPlane.geometry.dispose();
  22910. this.lightPlane.material.dispose();
  22911. this.targetLine.geometry.dispose();
  22912. this.targetLine.material.dispose();
  22913. }
  22914. update() {
  22915. this.light.updateWorldMatrix( true, false );
  22916. this.light.target.updateWorldMatrix( true, false );
  22917. _v1.setFromMatrixPosition( this.light.matrixWorld );
  22918. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  22919. _v3.subVectors( _v2, _v1 );
  22920. this.lightPlane.lookAt( _v2 );
  22921. if ( this.color !== undefined ) {
  22922. this.lightPlane.material.color.set( this.color );
  22923. this.targetLine.material.color.set( this.color );
  22924. } else {
  22925. this.lightPlane.material.color.copy( this.light.color );
  22926. this.targetLine.material.color.copy( this.light.color );
  22927. }
  22928. this.targetLine.lookAt( _v2 );
  22929. this.targetLine.scale.z = _v3.length();
  22930. }
  22931. }
  22932. const _vector = /*@__PURE__*/ new Vector3();
  22933. const _camera = /*@__PURE__*/ new Camera();
  22934. /**
  22935. * - shows frustum, line of sight and up of the camera
  22936. * - suitable for fast updates
  22937. * - based on frustum visualization in lightgl.js shadowmap example
  22938. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  22939. */
  22940. class CameraHelper extends LineSegments {
  22941. constructor( camera ) {
  22942. const geometry = new BufferGeometry();
  22943. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  22944. const vertices = [];
  22945. const colors = [];
  22946. const pointMap = {};
  22947. // near
  22948. addLine( 'n1', 'n2' );
  22949. addLine( 'n2', 'n4' );
  22950. addLine( 'n4', 'n3' );
  22951. addLine( 'n3', 'n1' );
  22952. // far
  22953. addLine( 'f1', 'f2' );
  22954. addLine( 'f2', 'f4' );
  22955. addLine( 'f4', 'f3' );
  22956. addLine( 'f3', 'f1' );
  22957. // sides
  22958. addLine( 'n1', 'f1' );
  22959. addLine( 'n2', 'f2' );
  22960. addLine( 'n3', 'f3' );
  22961. addLine( 'n4', 'f4' );
  22962. // cone
  22963. addLine( 'p', 'n1' );
  22964. addLine( 'p', 'n2' );
  22965. addLine( 'p', 'n3' );
  22966. addLine( 'p', 'n4' );
  22967. // up
  22968. addLine( 'u1', 'u2' );
  22969. addLine( 'u2', 'u3' );
  22970. addLine( 'u3', 'u1' );
  22971. // target
  22972. addLine( 'c', 't' );
  22973. addLine( 'p', 'c' );
  22974. // cross
  22975. addLine( 'cn1', 'cn2' );
  22976. addLine( 'cn3', 'cn4' );
  22977. addLine( 'cf1', 'cf2' );
  22978. addLine( 'cf3', 'cf4' );
  22979. function addLine( a, b ) {
  22980. addPoint( a );
  22981. addPoint( b );
  22982. }
  22983. function addPoint( id ) {
  22984. vertices.push( 0, 0, 0 );
  22985. colors.push( 0, 0, 0 );
  22986. if ( pointMap[ id ] === undefined ) {
  22987. pointMap[ id ] = [];
  22988. }
  22989. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  22990. }
  22991. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22992. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  22993. super( geometry, material );
  22994. this.type = 'CameraHelper';
  22995. this.camera = camera;
  22996. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  22997. this.matrix = camera.matrixWorld;
  22998. this.matrixAutoUpdate = false;
  22999. this.pointMap = pointMap;
  23000. this.update();
  23001. // colors
  23002. const colorFrustum = new Color( 0xffaa00 );
  23003. const colorCone = new Color( 0xff0000 );
  23004. const colorUp = new Color( 0x00aaff );
  23005. const colorTarget = new Color( 0xffffff );
  23006. const colorCross = new Color( 0x333333 );
  23007. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  23008. }
  23009. setColors( frustum, cone, up, target, cross ) {
  23010. const geometry = this.geometry;
  23011. const colorAttribute = geometry.getAttribute( 'color' );
  23012. // near
  23013. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  23014. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  23015. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  23016. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  23017. // far
  23018. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  23019. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  23020. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  23021. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  23022. // sides
  23023. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  23024. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  23025. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  23026. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  23027. // cone
  23028. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  23029. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  23030. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  23031. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  23032. // up
  23033. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  23034. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  23035. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  23036. // target
  23037. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  23038. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  23039. // cross
  23040. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  23041. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  23042. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  23043. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  23044. colorAttribute.needsUpdate = true;
  23045. }
  23046. update() {
  23047. const geometry = this.geometry;
  23048. const pointMap = this.pointMap;
  23049. const w = 1, h = 1;
  23050. // we need just camera projection matrix inverse
  23051. // world matrix must be identity
  23052. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  23053. // Adjust z values based on coordinate system
  23054. const nearZ = this.camera.coordinateSystem === WebGLCoordinateSystem ? -1 : 0;
  23055. // center / target
  23056. setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ );
  23057. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  23058. // near
  23059. setPoint( 'n1', pointMap, geometry, _camera, -1, -1, nearZ );
  23060. setPoint( 'n2', pointMap, geometry, _camera, w, -1, nearZ );
  23061. setPoint( 'n3', pointMap, geometry, _camera, -1, h, nearZ );
  23062. setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ );
  23063. // far
  23064. setPoint( 'f1', pointMap, geometry, _camera, -1, -1, 1 );
  23065. setPoint( 'f2', pointMap, geometry, _camera, w, -1, 1 );
  23066. setPoint( 'f3', pointMap, geometry, _camera, -1, h, 1 );
  23067. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  23068. // up
  23069. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ );
  23070. setPoint( 'u2', pointMap, geometry, _camera, -1 * 0.7, h * 1.1, nearZ );
  23071. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ );
  23072. // cross
  23073. setPoint( 'cf1', pointMap, geometry, _camera, -1, 0, 1 );
  23074. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  23075. setPoint( 'cf3', pointMap, geometry, _camera, 0, -1, 1 );
  23076. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  23077. setPoint( 'cn1', pointMap, geometry, _camera, -1, 0, nearZ );
  23078. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ );
  23079. setPoint( 'cn3', pointMap, geometry, _camera, 0, -1, nearZ );
  23080. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ );
  23081. geometry.getAttribute( 'position' ).needsUpdate = true;
  23082. }
  23083. dispose() {
  23084. this.geometry.dispose();
  23085. this.material.dispose();
  23086. }
  23087. }
  23088. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  23089. _vector.set( x, y, z ).unproject( camera );
  23090. const points = pointMap[ point ];
  23091. if ( points !== undefined ) {
  23092. const position = geometry.getAttribute( 'position' );
  23093. for ( let i = 0, l = points.length; i < l; i ++ ) {
  23094. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  23095. }
  23096. }
  23097. }
  23098. const _box = /*@__PURE__*/ new Box3();
  23099. class BoxHelper extends LineSegments {
  23100. constructor( object, color = 0xffff00 ) {
  23101. 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 ] );
  23102. const positions = new Float32Array( 8 * 3 );
  23103. const geometry = new BufferGeometry();
  23104. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  23105. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  23106. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  23107. this.object = object;
  23108. this.type = 'BoxHelper';
  23109. this.matrixAutoUpdate = false;
  23110. this.update();
  23111. }
  23112. update( object ) {
  23113. if ( object !== undefined ) {
  23114. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  23115. }
  23116. if ( this.object !== undefined ) {
  23117. _box.setFromObject( this.object );
  23118. }
  23119. if ( _box.isEmpty() ) return;
  23120. const min = _box.min;
  23121. const max = _box.max;
  23122. /*
  23123. 5____4
  23124. 1/___0/|
  23125. | 6__|_7
  23126. 2/___3/
  23127. 0: max.x, max.y, max.z
  23128. 1: min.x, max.y, max.z
  23129. 2: min.x, min.y, max.z
  23130. 3: max.x, min.y, max.z
  23131. 4: max.x, max.y, min.z
  23132. 5: min.x, max.y, min.z
  23133. 6: min.x, min.y, min.z
  23134. 7: max.x, min.y, min.z
  23135. */
  23136. const position = this.geometry.attributes.position;
  23137. const array = position.array;
  23138. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  23139. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  23140. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  23141. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  23142. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  23143. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  23144. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  23145. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  23146. position.needsUpdate = true;
  23147. this.geometry.computeBoundingSphere();
  23148. }
  23149. setFromObject( object ) {
  23150. this.object = object;
  23151. this.update();
  23152. return this;
  23153. }
  23154. copy( source, recursive ) {
  23155. super.copy( source, recursive );
  23156. this.object = source.object;
  23157. return this;
  23158. }
  23159. dispose() {
  23160. this.geometry.dispose();
  23161. this.material.dispose();
  23162. }
  23163. }
  23164. class Box3Helper extends LineSegments {
  23165. constructor( box, color = 0xffff00 ) {
  23166. 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 ] );
  23167. 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 ];
  23168. const geometry = new BufferGeometry();
  23169. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  23170. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  23171. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  23172. this.box = box;
  23173. this.type = 'Box3Helper';
  23174. this.geometry.computeBoundingSphere();
  23175. }
  23176. updateMatrixWorld( force ) {
  23177. const box = this.box;
  23178. if ( box.isEmpty() ) return;
  23179. box.getCenter( this.position );
  23180. box.getSize( this.scale );
  23181. this.scale.multiplyScalar( 0.5 );
  23182. super.updateMatrixWorld( force );
  23183. }
  23184. dispose() {
  23185. this.geometry.dispose();
  23186. this.material.dispose();
  23187. }
  23188. }
  23189. class PlaneHelper extends Line {
  23190. constructor( plane, size = 1, hex = 0xffff00 ) {
  23191. const color = hex;
  23192. const positions = [ 1, -1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, -1, 0, 1, 1, 0 ];
  23193. const geometry = new BufferGeometry();
  23194. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  23195. geometry.computeBoundingSphere();
  23196. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  23197. this.type = 'PlaneHelper';
  23198. this.plane = plane;
  23199. this.size = size;
  23200. const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ];
  23201. const geometry2 = new BufferGeometry();
  23202. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  23203. geometry2.computeBoundingSphere();
  23204. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  23205. }
  23206. updateMatrixWorld( force ) {
  23207. this.position.set( 0, 0, 0 );
  23208. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  23209. this.lookAt( this.plane.normal );
  23210. this.translateZ( - this.plane.constant );
  23211. super.updateMatrixWorld( force );
  23212. }
  23213. dispose() {
  23214. this.geometry.dispose();
  23215. this.material.dispose();
  23216. this.children[ 0 ].geometry.dispose();
  23217. this.children[ 0 ].material.dispose();
  23218. }
  23219. }
  23220. const _axis = /*@__PURE__*/ new Vector3();
  23221. let _lineGeometry, _coneGeometry;
  23222. class ArrowHelper extends Object3D {
  23223. // dir is assumed to be normalized
  23224. constructor( dir = new Vector3( 0, 0, 1 ), origin = new Vector3( 0, 0, 0 ), length = 1, color = 0xffff00, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  23225. super();
  23226. this.type = 'ArrowHelper';
  23227. if ( _lineGeometry === undefined ) {
  23228. _lineGeometry = new BufferGeometry();
  23229. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  23230. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  23231. _coneGeometry.translate( 0, -0.5, 0 );
  23232. }
  23233. this.position.copy( origin );
  23234. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  23235. this.line.matrixAutoUpdate = false;
  23236. this.add( this.line );
  23237. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  23238. this.cone.matrixAutoUpdate = false;
  23239. this.add( this.cone );
  23240. this.setDirection( dir );
  23241. this.setLength( length, headLength, headWidth );
  23242. }
  23243. setDirection( dir ) {
  23244. // dir is assumed to be normalized
  23245. if ( dir.y > 0.99999 ) {
  23246. this.quaternion.set( 0, 0, 0, 1 );
  23247. } else if ( dir.y < -0.99999 ) {
  23248. this.quaternion.set( 1, 0, 0, 0 );
  23249. } else {
  23250. _axis.set( dir.z, 0, - dir.x ).normalize();
  23251. const radians = Math.acos( dir.y );
  23252. this.quaternion.setFromAxisAngle( _axis, radians );
  23253. }
  23254. }
  23255. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  23256. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  23257. this.line.updateMatrix();
  23258. this.cone.scale.set( headWidth, headLength, headWidth );
  23259. this.cone.position.y = length;
  23260. this.cone.updateMatrix();
  23261. }
  23262. setColor( color ) {
  23263. this.line.material.color.set( color );
  23264. this.cone.material.color.set( color );
  23265. }
  23266. copy( source ) {
  23267. super.copy( source, false );
  23268. this.line.copy( source.line );
  23269. this.cone.copy( source.cone );
  23270. return this;
  23271. }
  23272. dispose() {
  23273. this.line.geometry.dispose();
  23274. this.line.material.dispose();
  23275. this.cone.geometry.dispose();
  23276. this.cone.material.dispose();
  23277. }
  23278. }
  23279. class AxesHelper extends LineSegments {
  23280. constructor( size = 1 ) {
  23281. const vertices = [
  23282. 0, 0, 0, size, 0, 0,
  23283. 0, 0, 0, 0, size, 0,
  23284. 0, 0, 0, 0, 0, size
  23285. ];
  23286. const colors = [
  23287. 1, 0, 0, 1, 0.6, 0,
  23288. 0, 1, 0, 0.6, 1, 0,
  23289. 0, 0, 1, 0, 0.6, 1
  23290. ];
  23291. const geometry = new BufferGeometry();
  23292. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23293. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  23294. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  23295. super( geometry, material );
  23296. this.type = 'AxesHelper';
  23297. }
  23298. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  23299. const color = new Color();
  23300. const array = this.geometry.attributes.color.array;
  23301. color.set( xAxisColor );
  23302. color.toArray( array, 0 );
  23303. color.toArray( array, 3 );
  23304. color.set( yAxisColor );
  23305. color.toArray( array, 6 );
  23306. color.toArray( array, 9 );
  23307. color.set( zAxisColor );
  23308. color.toArray( array, 12 );
  23309. color.toArray( array, 15 );
  23310. this.geometry.attributes.color.needsUpdate = true;
  23311. return this;
  23312. }
  23313. dispose() {
  23314. this.geometry.dispose();
  23315. this.material.dispose();
  23316. }
  23317. }
  23318. class ShapePath {
  23319. constructor() {
  23320. this.type = 'ShapePath';
  23321. this.color = new Color();
  23322. this.subPaths = [];
  23323. this.currentPath = null;
  23324. }
  23325. moveTo( x, y ) {
  23326. this.currentPath = new Path();
  23327. this.subPaths.push( this.currentPath );
  23328. this.currentPath.moveTo( x, y );
  23329. return this;
  23330. }
  23331. lineTo( x, y ) {
  23332. this.currentPath.lineTo( x, y );
  23333. return this;
  23334. }
  23335. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  23336. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  23337. return this;
  23338. }
  23339. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  23340. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  23341. return this;
  23342. }
  23343. splineThru( pts ) {
  23344. this.currentPath.splineThru( pts );
  23345. return this;
  23346. }
  23347. toShapes( isCCW ) {
  23348. function toShapesNoHoles( inSubpaths ) {
  23349. const shapes = [];
  23350. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  23351. const tmpPath = inSubpaths[ i ];
  23352. const tmpShape = new Shape();
  23353. tmpShape.curves = tmpPath.curves;
  23354. shapes.push( tmpShape );
  23355. }
  23356. return shapes;
  23357. }
  23358. function isPointInsidePolygon( inPt, inPolygon ) {
  23359. const polyLen = inPolygon.length;
  23360. // inPt on polygon contour => immediate success or
  23361. // toggling of inside/outside at every single! intersection point of an edge
  23362. // with the horizontal line through inPt, left of inPt
  23363. // not counting lowerY endpoints of edges and whole edges on that line
  23364. let inside = false;
  23365. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  23366. let edgeLowPt = inPolygon[ p ];
  23367. let edgeHighPt = inPolygon[ q ];
  23368. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  23369. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  23370. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  23371. // not parallel
  23372. if ( edgeDy < 0 ) {
  23373. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  23374. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  23375. }
  23376. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  23377. if ( inPt.y === edgeLowPt.y ) {
  23378. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  23379. // continue; // no intersection or edgeLowPt => doesn't count !!!
  23380. } else {
  23381. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  23382. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  23383. if ( perpEdge < 0 ) continue;
  23384. inside = ! inside; // true intersection left of inPt
  23385. }
  23386. } else {
  23387. // parallel or collinear
  23388. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  23389. // edge lies on the same horizontal line as inPt
  23390. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  23391. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  23392. // continue;
  23393. }
  23394. }
  23395. return inside;
  23396. }
  23397. const isClockWise = ShapeUtils.isClockWise;
  23398. const subPaths = this.subPaths;
  23399. if ( subPaths.length === 0 ) return [];
  23400. let solid, tmpPath, tmpShape;
  23401. const shapes = [];
  23402. if ( subPaths.length === 1 ) {
  23403. tmpPath = subPaths[ 0 ];
  23404. tmpShape = new Shape();
  23405. tmpShape.curves = tmpPath.curves;
  23406. shapes.push( tmpShape );
  23407. return shapes;
  23408. }
  23409. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  23410. holesFirst = isCCW ? ! holesFirst : holesFirst;
  23411. // console.log("Holes first", holesFirst);
  23412. const betterShapeHoles = [];
  23413. const newShapes = [];
  23414. let newShapeHoles = [];
  23415. let mainIdx = 0;
  23416. let tmpPoints;
  23417. newShapes[ mainIdx ] = undefined;
  23418. newShapeHoles[ mainIdx ] = [];
  23419. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  23420. tmpPath = subPaths[ i ];
  23421. tmpPoints = tmpPath.getPoints();
  23422. solid = isClockWise( tmpPoints );
  23423. solid = isCCW ? ! solid : solid;
  23424. if ( solid ) {
  23425. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  23426. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  23427. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  23428. if ( holesFirst ) mainIdx ++;
  23429. newShapeHoles[ mainIdx ] = [];
  23430. //console.log('cw', i);
  23431. } else {
  23432. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  23433. //console.log('ccw', i);
  23434. }
  23435. }
  23436. // only Holes? -> probably all Shapes with wrong orientation
  23437. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  23438. if ( newShapes.length > 1 ) {
  23439. let ambiguous = false;
  23440. let toChange = 0;
  23441. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  23442. betterShapeHoles[ sIdx ] = [];
  23443. }
  23444. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  23445. const sho = newShapeHoles[ sIdx ];
  23446. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  23447. const ho = sho[ hIdx ];
  23448. let hole_unassigned = true;
  23449. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  23450. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  23451. if ( sIdx !== s2Idx ) toChange ++;
  23452. if ( hole_unassigned ) {
  23453. hole_unassigned = false;
  23454. betterShapeHoles[ s2Idx ].push( ho );
  23455. } else {
  23456. ambiguous = true;
  23457. }
  23458. }
  23459. }
  23460. if ( hole_unassigned ) {
  23461. betterShapeHoles[ sIdx ].push( ho );
  23462. }
  23463. }
  23464. }
  23465. if ( toChange > 0 && ambiguous === false ) {
  23466. newShapeHoles = betterShapeHoles;
  23467. }
  23468. }
  23469. let tmpHoles;
  23470. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  23471. tmpShape = newShapes[ i ].s;
  23472. shapes.push( tmpShape );
  23473. tmpHoles = newShapeHoles[ i ];
  23474. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  23475. tmpShape.holes.push( tmpHoles[ j ].h );
  23476. }
  23477. }
  23478. //console.log("shape", shapes);
  23479. return shapes;
  23480. }
  23481. }
  23482. class Controls extends EventDispatcher {
  23483. constructor( object, domElement = null ) {
  23484. super();
  23485. this.object = object;
  23486. this.domElement = domElement;
  23487. this.enabled = true;
  23488. this.state = -1;
  23489. this.keys = {};
  23490. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  23491. this.touches = { ONE: null, TWO: null };
  23492. }
  23493. connect() {}
  23494. disconnect() {}
  23495. dispose() {}
  23496. update( /* delta */ ) {}
  23497. }
  23498. function contain( texture, aspect ) {
  23499. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  23500. if ( imageAspect > aspect ) {
  23501. texture.repeat.x = 1;
  23502. texture.repeat.y = imageAspect / aspect;
  23503. texture.offset.x = 0;
  23504. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  23505. } else {
  23506. texture.repeat.x = aspect / imageAspect;
  23507. texture.repeat.y = 1;
  23508. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  23509. texture.offset.y = 0;
  23510. }
  23511. return texture;
  23512. }
  23513. function cover( texture, aspect ) {
  23514. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  23515. if ( imageAspect > aspect ) {
  23516. texture.repeat.x = aspect / imageAspect;
  23517. texture.repeat.y = 1;
  23518. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  23519. texture.offset.y = 0;
  23520. } else {
  23521. texture.repeat.x = 1;
  23522. texture.repeat.y = imageAspect / aspect;
  23523. texture.offset.x = 0;
  23524. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  23525. }
  23526. return texture;
  23527. }
  23528. function fill( texture ) {
  23529. texture.repeat.x = 1;
  23530. texture.repeat.y = 1;
  23531. texture.offset.x = 0;
  23532. texture.offset.y = 0;
  23533. return texture;
  23534. }
  23535. /**
  23536. * Given the width, height, format, and type of a texture. Determines how many
  23537. * bytes must be used to represent the texture.
  23538. *
  23539. * @param {number} width
  23540. * @param {number} height
  23541. * @param {number} format
  23542. * @param {number} type
  23543. * @return {number} The number of bytes required to represent the texture.
  23544. */
  23545. function getByteLength( width, height, format, type ) {
  23546. const typeByteLength = getTextureTypeByteLength( type );
  23547. switch ( format ) {
  23548. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  23549. case AlphaFormat:
  23550. return width * height;
  23551. case LuminanceFormat:
  23552. return width * height;
  23553. case LuminanceAlphaFormat:
  23554. return width * height * 2;
  23555. case RedFormat:
  23556. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  23557. case RedIntegerFormat:
  23558. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  23559. case RGFormat:
  23560. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  23561. case RGIntegerFormat:
  23562. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  23563. case RGBFormat:
  23564. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  23565. case RGBAFormat:
  23566. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  23567. case RGBAIntegerFormat:
  23568. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  23569. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  23570. case RGB_S3TC_DXT1_Format:
  23571. case RGBA_S3TC_DXT1_Format:
  23572. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  23573. case RGBA_S3TC_DXT3_Format:
  23574. case RGBA_S3TC_DXT5_Format:
  23575. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  23576. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  23577. case RGB_PVRTC_2BPPV1_Format:
  23578. case RGBA_PVRTC_2BPPV1_Format:
  23579. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  23580. case RGB_PVRTC_4BPPV1_Format:
  23581. case RGBA_PVRTC_4BPPV1_Format:
  23582. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  23583. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  23584. case RGB_ETC1_Format:
  23585. case RGB_ETC2_Format:
  23586. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  23587. case RGBA_ETC2_EAC_Format:
  23588. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  23589. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  23590. case RGBA_ASTC_4x4_Format:
  23591. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  23592. case RGBA_ASTC_5x4_Format:
  23593. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  23594. case RGBA_ASTC_5x5_Format:
  23595. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  23596. case RGBA_ASTC_6x5_Format:
  23597. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  23598. case RGBA_ASTC_6x6_Format:
  23599. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  23600. case RGBA_ASTC_8x5_Format:
  23601. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  23602. case RGBA_ASTC_8x6_Format:
  23603. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  23604. case RGBA_ASTC_8x8_Format:
  23605. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  23606. case RGBA_ASTC_10x5_Format:
  23607. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  23608. case RGBA_ASTC_10x6_Format:
  23609. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  23610. case RGBA_ASTC_10x8_Format:
  23611. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  23612. case RGBA_ASTC_10x10_Format:
  23613. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  23614. case RGBA_ASTC_12x10_Format:
  23615. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  23616. case RGBA_ASTC_12x12_Format:
  23617. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  23618. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  23619. case RGBA_BPTC_Format:
  23620. case RGB_BPTC_SIGNED_Format:
  23621. case RGB_BPTC_UNSIGNED_Format:
  23622. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  23623. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  23624. case RED_RGTC1_Format:
  23625. case SIGNED_RED_RGTC1_Format:
  23626. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  23627. case RED_GREEN_RGTC2_Format:
  23628. case SIGNED_RED_GREEN_RGTC2_Format:
  23629. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  23630. }
  23631. throw new Error(
  23632. `Unable to determine texture byte length for ${format} format.`,
  23633. );
  23634. }
  23635. function getTextureTypeByteLength( type ) {
  23636. switch ( type ) {
  23637. case UnsignedByteType:
  23638. case ByteType:
  23639. return { byteLength: 1, components: 1 };
  23640. case UnsignedShortType:
  23641. case ShortType:
  23642. case HalfFloatType:
  23643. return { byteLength: 2, components: 1 };
  23644. case UnsignedShort4444Type:
  23645. case UnsignedShort5551Type:
  23646. return { byteLength: 2, components: 4 };
  23647. case UnsignedIntType:
  23648. case IntType:
  23649. case FloatType:
  23650. return { byteLength: 4, components: 1 };
  23651. case UnsignedInt5999Type:
  23652. return { byteLength: 4, components: 3 };
  23653. }
  23654. throw new Error( `Unknown texture type ${type}.` );
  23655. }
  23656. const TextureUtils = {
  23657. contain,
  23658. cover,
  23659. fill,
  23660. getByteLength
  23661. };
  23662. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  23663. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  23664. revision: REVISION,
  23665. } } ) );
  23666. }
  23667. if ( typeof window !== 'undefined' ) {
  23668. if ( window.__THREE__ ) {
  23669. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  23670. } else {
  23671. window.__THREE__ = REVISION;
  23672. }
  23673. }
  23674. export { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BackSide, BasicDepthPacking, BasicShadowMap, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CineonToneMapping, CircleGeometry, ClampToEdgeWrapping, Clock, Color, ColorKeyframeTrack, ColorManagement, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, Controls, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry, Cylindrical, Data3DTexture, DataArrayTexture, DataTexture, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DetachedBindMode, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, EqualCompare, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExtrudeGeometry, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, Fog, FogExp2, FramebufferTexture, FrontSide, Frustum, GLBufferAttribute, GLSL1, GLSL3, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry, Layers, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LineSegments, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, MOUSE, Material, MaterialLoader, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, NormalAnimationBlendMode, NormalBlending, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, ObjectSpaceNormalMap, OctahedronGeometry, OneFactor, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, PCFShadowMap, PCFSoftShadowMap, Path, PerspectiveCamera, Plane, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RAD2DEG, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBDepthPacking, RGBFormat, RGBIntegerFormat, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGDepthPacking, RGFormat, RGIntegerFormat, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RedFormat, RedIntegerFormat, ReinhardToneMapping, RenderTarget, RenderTarget3D, RenderTargetArray, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RingGeometry, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, ShaderMaterial, ShadowMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SpotLight, SpotLightHelper, Sprite, SpriteMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TOUCH, TangentSpaceNormalMap, TetrahedronGeometry, Texture, TextureLoader, TextureUtils, TimestampQuery, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, UniformsUtils, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGLRenderTarget, WebGPUCoordinateSystem, WebXRController, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, arrayNeedsUint32, cloneUniforms, createCanvasElement, createElementNS, getByteLength, getUnlitUniformColorSpace, mergeUniforms, probeAsync, toNormalizedProjectionMatrix, toReversedProjectionMatrix, warnOnce };
粤ICP备19079148号