three.core.js 1.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583
  1. /**
  2. * @license
  3. * Copyright 2010-2026 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '184dev';
  7. /**
  8. * Represents mouse buttons and interaction types in context of controls.
  9. *
  10. * @type {ConstantsMouse}
  11. * @constant
  12. */
  13. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  14. /**
  15. * Represents touch interaction types in context of controls.
  16. *
  17. * @type {ConstantsTouch}
  18. * @constant
  19. */
  20. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  21. /**
  22. * Disables face culling.
  23. *
  24. * @type {number}
  25. * @constant
  26. */
  27. const CullFaceNone = 0;
  28. /**
  29. * Culls back faces.
  30. *
  31. * @type {number}
  32. * @constant
  33. */
  34. const CullFaceBack = 1;
  35. /**
  36. * Culls front faces.
  37. *
  38. * @type {number}
  39. * @constant
  40. */
  41. const CullFaceFront = 2;
  42. /**
  43. * Culls both front and back faces.
  44. *
  45. * @type {number}
  46. * @constant
  47. */
  48. const CullFaceFrontBack = 3;
  49. /**
  50. * Gives unfiltered shadow maps - fastest, but lowest quality.
  51. *
  52. * @type {number}
  53. * @constant
  54. */
  55. const BasicShadowMap = 0;
  56. /**
  57. * Filters shadow maps using the Percentage-Closer Filtering (PCF) algorithm.
  58. *
  59. * @type {number}
  60. * @constant
  61. */
  62. const PCFShadowMap = 1;
  63. /**
  64. * Filters shadow maps using the Percentage-Closer Filtering (PCF) algorithm with
  65. * better soft shadows especially when using low-resolution shadow maps.
  66. *
  67. * @type {number}
  68. * @constant
  69. */
  70. const PCFSoftShadowMap = 2;
  71. /**
  72. * Filters shadow maps using the Variance Shadow Map (VSM) algorithm.
  73. * When using VSMShadowMap all shadow receivers will also cast shadows.
  74. *
  75. * @type {number}
  76. * @constant
  77. */
  78. const VSMShadowMap = 3;
  79. /**
  80. * Only front faces are rendered.
  81. *
  82. * @type {number}
  83. * @constant
  84. */
  85. const FrontSide = 0;
  86. /**
  87. * Only back faces are rendered.
  88. *
  89. * @type {number}
  90. * @constant
  91. */
  92. const BackSide = 1;
  93. /**
  94. * Both front and back faces are rendered.
  95. *
  96. * @type {number}
  97. * @constant
  98. */
  99. const DoubleSide = 2;
  100. /**
  101. * No blending is performed which effectively disables
  102. * alpha transparency.
  103. *
  104. * @type {number}
  105. * @constant
  106. */
  107. const NoBlending = 0;
  108. /**
  109. * The default blending.
  110. *
  111. * @type {number}
  112. * @constant
  113. */
  114. const NormalBlending = 1;
  115. /**
  116. * Represents additive blending.
  117. *
  118. * @type {number}
  119. * @constant
  120. */
  121. const AdditiveBlending = 2;
  122. /**
  123. * Represents subtractive blending.
  124. *
  125. * @type {number}
  126. * @constant
  127. */
  128. const SubtractiveBlending = 3;
  129. /**
  130. * Represents multiply blending.
  131. *
  132. * @type {number}
  133. * @constant
  134. */
  135. const MultiplyBlending = 4;
  136. /**
  137. * Represents custom blending.
  138. *
  139. * @type {number}
  140. * @constant
  141. */
  142. const CustomBlending = 5;
  143. /**
  144. * Represents material blending.
  145. *
  146. * @type {number}
  147. * @constant
  148. */
  149. const MaterialBlending = 6;
  150. /**
  151. * A `source + destination` blending equation.
  152. *
  153. * @type {number}
  154. * @constant
  155. */
  156. const AddEquation = 100;
  157. /**
  158. * A `source - destination` blending equation.
  159. *
  160. * @type {number}
  161. * @constant
  162. */
  163. const SubtractEquation = 101;
  164. /**
  165. * A `destination - source` blending equation.
  166. *
  167. * @type {number}
  168. * @constant
  169. */
  170. const ReverseSubtractEquation = 102;
  171. /**
  172. * A blend equation that uses the minimum of source and destination.
  173. *
  174. * @type {number}
  175. * @constant
  176. */
  177. const MinEquation = 103;
  178. /**
  179. * A blend equation that uses the maximum of source and destination.
  180. *
  181. * @type {number}
  182. * @constant
  183. */
  184. const MaxEquation = 104;
  185. /**
  186. * Multiplies all colors by `0`.
  187. *
  188. * @type {number}
  189. * @constant
  190. */
  191. const ZeroFactor = 200;
  192. /**
  193. * Multiplies all colors by `1`.
  194. *
  195. * @type {number}
  196. * @constant
  197. */
  198. const OneFactor = 201;
  199. /**
  200. * Multiplies all colors by the source colors.
  201. *
  202. * @type {number}
  203. * @constant
  204. */
  205. const SrcColorFactor = 202;
  206. /**
  207. * Multiplies all colors by `1` minus each source color.
  208. *
  209. * @type {number}
  210. * @constant
  211. */
  212. const OneMinusSrcColorFactor = 203;
  213. /**
  214. * Multiplies all colors by the source alpha value.
  215. *
  216. * @type {number}
  217. * @constant
  218. */
  219. const SrcAlphaFactor = 204;
  220. /**
  221. * Multiplies all colors by 1 minus the source alpha value.
  222. *
  223. * @type {number}
  224. * @constant
  225. */
  226. const OneMinusSrcAlphaFactor = 205;
  227. /**
  228. * Multiplies all colors by the destination alpha value.
  229. *
  230. * @type {number}
  231. * @constant
  232. */
  233. const DstAlphaFactor = 206;
  234. /**
  235. * Multiplies all colors by `1` minus the destination alpha value.
  236. *
  237. * @type {number}
  238. * @constant
  239. */
  240. const OneMinusDstAlphaFactor = 207;
  241. /**
  242. * Multiplies all colors by the destination color.
  243. *
  244. * @type {number}
  245. * @constant
  246. */
  247. const DstColorFactor = 208;
  248. /**
  249. * Multiplies all colors by `1` minus each destination color.
  250. *
  251. * @type {number}
  252. * @constant
  253. */
  254. const OneMinusDstColorFactor = 209;
  255. /**
  256. * Multiplies the RGB colors by the smaller of either the source alpha
  257. * value or the value of `1` minus the destination alpha value. The alpha
  258. * value is multiplied by `1`.
  259. *
  260. * @type {number}
  261. * @constant
  262. */
  263. const SrcAlphaSaturateFactor = 210;
  264. /**
  265. * Multiplies all colors by a constant color.
  266. *
  267. * @type {number}
  268. * @constant
  269. */
  270. const ConstantColorFactor = 211;
  271. /**
  272. * Multiplies all colors by `1` minus a constant color.
  273. *
  274. * @type {number}
  275. * @constant
  276. */
  277. const OneMinusConstantColorFactor = 212;
  278. /**
  279. * Multiplies all colors by a constant alpha value.
  280. *
  281. * @type {number}
  282. * @constant
  283. */
  284. const ConstantAlphaFactor = 213;
  285. /**
  286. * Multiplies all colors by 1 minus a constant alpha value.
  287. *
  288. * @type {number}
  289. * @constant
  290. */
  291. const OneMinusConstantAlphaFactor = 214;
  292. /**
  293. * Never pass.
  294. *
  295. * @type {number}
  296. * @constant
  297. */
  298. const NeverDepth = 0;
  299. /**
  300. * Always pass.
  301. *
  302. * @type {number}
  303. * @constant
  304. */
  305. const AlwaysDepth = 1;
  306. /**
  307. * Pass if the incoming value is less than the depth buffer value.
  308. *
  309. * @type {number}
  310. * @constant
  311. */
  312. const LessDepth = 2;
  313. /**
  314. * Pass if the incoming value is less than or equal to the depth buffer value.
  315. *
  316. * @type {number}
  317. * @constant
  318. */
  319. const LessEqualDepth = 3;
  320. /**
  321. * Pass if the incoming value equals the depth buffer value.
  322. *
  323. * @type {number}
  324. * @constant
  325. */
  326. const EqualDepth = 4;
  327. /**
  328. * Pass if the incoming value is greater than or equal to the depth buffer value.
  329. *
  330. * @type {number}
  331. * @constant
  332. */
  333. const GreaterEqualDepth = 5;
  334. /**
  335. * Pass if the incoming value is greater than the depth buffer value.
  336. *
  337. * @type {number}
  338. * @constant
  339. */
  340. const GreaterDepth = 6;
  341. /**
  342. * Pass if the incoming value is not equal to the depth buffer value.
  343. *
  344. * @type {number}
  345. * @constant
  346. */
  347. const NotEqualDepth = 7;
  348. /**
  349. * Multiplies the environment map color with the surface color.
  350. *
  351. * @type {number}
  352. * @constant
  353. */
  354. const MultiplyOperation = 0;
  355. /**
  356. * Uses reflectivity to blend between the two colors.
  357. *
  358. * @type {number}
  359. * @constant
  360. */
  361. const MixOperation = 1;
  362. /**
  363. * Adds the two colors.
  364. *
  365. * @type {number}
  366. * @constant
  367. */
  368. const AddOperation = 2;
  369. /**
  370. * No tone mapping is applied.
  371. *
  372. * @type {number}
  373. * @constant
  374. */
  375. const NoToneMapping = 0;
  376. /**
  377. * Linear tone mapping.
  378. *
  379. * @type {number}
  380. * @constant
  381. */
  382. const LinearToneMapping = 1;
  383. /**
  384. * Reinhard tone mapping.
  385. *
  386. * @type {number}
  387. * @constant
  388. */
  389. const ReinhardToneMapping = 2;
  390. /**
  391. * Cineon tone mapping.
  392. *
  393. * @type {number}
  394. * @constant
  395. */
  396. const CineonToneMapping = 3;
  397. /**
  398. * ACES Filmic tone mapping.
  399. *
  400. * @type {number}
  401. * @constant
  402. */
  403. const ACESFilmicToneMapping = 4;
  404. /**
  405. * Custom tone mapping.
  406. *
  407. * Expects a custom implementation by modifying shader code of the material's fragment shader.
  408. *
  409. * @type {number}
  410. * @constant
  411. */
  412. const CustomToneMapping = 5;
  413. /**
  414. * AgX tone mapping.
  415. *
  416. * @type {number}
  417. * @constant
  418. */
  419. const AgXToneMapping = 6;
  420. /**
  421. * Neutral tone mapping.
  422. *
  423. * Implementation based on the Khronos 3D Commerce Group standard tone mapping.
  424. *
  425. * @type {number}
  426. * @constant
  427. */
  428. const NeutralToneMapping = 7;
  429. /**
  430. * The skinned mesh shares the same world space as the skeleton.
  431. *
  432. * @type {string}
  433. * @constant
  434. */
  435. const AttachedBindMode = 'attached';
  436. /**
  437. * The skinned mesh does not share the same world space as the skeleton.
  438. * This is useful when a skeleton is shared across multiple skinned meshes.
  439. *
  440. * @type {string}
  441. * @constant
  442. */
  443. const DetachedBindMode = 'detached';
  444. /**
  445. * Maps textures using the geometry's UV coordinates.
  446. *
  447. * @type {number}
  448. * @constant
  449. */
  450. const UVMapping = 300;
  451. /**
  452. * Reflection mapping for cube textures.
  453. *
  454. * @type {number}
  455. * @constant
  456. */
  457. const CubeReflectionMapping = 301;
  458. /**
  459. * Refraction mapping for cube textures.
  460. *
  461. * @type {number}
  462. * @constant
  463. */
  464. const CubeRefractionMapping = 302;
  465. /**
  466. * Reflection mapping for equirectangular textures.
  467. *
  468. * @type {number}
  469. * @constant
  470. */
  471. const EquirectangularReflectionMapping = 303;
  472. /**
  473. * Refraction mapping for equirectangular textures.
  474. *
  475. * @type {number}
  476. * @constant
  477. */
  478. const EquirectangularRefractionMapping = 304;
  479. /**
  480. * Reflection mapping for PMREM textures.
  481. *
  482. * @type {number}
  483. * @constant
  484. */
  485. const CubeUVReflectionMapping = 306;
  486. /**
  487. * The texture will simply repeat to infinity.
  488. *
  489. * @type {number}
  490. * @constant
  491. */
  492. const RepeatWrapping = 1000;
  493. /**
  494. * The last pixel of the texture stretches to the edge of the mesh.
  495. *
  496. * @type {number}
  497. * @constant
  498. */
  499. const ClampToEdgeWrapping = 1001;
  500. /**
  501. * The texture will repeats to infinity, mirroring on each repeat.
  502. *
  503. * @type {number}
  504. * @constant
  505. */
  506. const MirroredRepeatWrapping = 1002;
  507. /**
  508. * Returns the value of the texture element that is nearest (in Manhattan distance)
  509. * to the specified texture coordinates.
  510. *
  511. * @type {number}
  512. * @constant
  513. */
  514. const NearestFilter = 1003;
  515. /**
  516. * Chooses the mipmap that most closely matches the size of the pixel being textured
  517. * and uses the `NearestFilter` criterion (the texel nearest to the center of the pixel)
  518. * to produce a texture value.
  519. *
  520. * @type {number}
  521. * @constant
  522. */
  523. const NearestMipmapNearestFilter = 1004;
  524. const NearestMipMapNearestFilter = 1004; // legacy
  525. /**
  526. * Chooses the two mipmaps that most closely match the size of the pixel being textured and
  527. * uses the `NearestFilter` criterion to produce a texture value from each mipmap.
  528. * The final texture value is a weighted average of those two values.
  529. *
  530. * @type {number}
  531. * @constant
  532. */
  533. const NearestMipmapLinearFilter = 1005;
  534. const NearestMipMapLinearFilter = 1005; // legacy
  535. /**
  536. * Returns the weighted average of the four texture elements that are closest to the specified
  537. * texture coordinates, and can include items wrapped or repeated from other parts of a texture,
  538. * depending on the values of `wrapS` and `wrapT`, and on the exact mapping.
  539. *
  540. * @type {number}
  541. * @constant
  542. */
  543. const LinearFilter = 1006;
  544. /**
  545. * Chooses the mipmap that most closely matches the size of the pixel being textured and uses
  546. * the `LinearFilter` criterion (a weighted average of the four texels that are closest to the
  547. * center of the pixel) to produce a texture value.
  548. *
  549. * @type {number}
  550. * @constant
  551. */
  552. const LinearMipmapNearestFilter = 1007;
  553. const LinearMipMapNearestFilter = 1007; // legacy
  554. /**
  555. * Chooses the two mipmaps that most closely match the size of the pixel being textured and uses
  556. * the `LinearFilter` criterion to produce a texture value from each mipmap. The final texture value
  557. * is a weighted average of those two values.
  558. *
  559. * @type {number}
  560. * @constant
  561. */
  562. const LinearMipmapLinearFilter = 1008;
  563. const LinearMipMapLinearFilter = 1008; // legacy
  564. /**
  565. * An unsigned byte data type for textures.
  566. *
  567. * @type {number}
  568. * @constant
  569. */
  570. const UnsignedByteType = 1009;
  571. /**
  572. * A byte data type for textures.
  573. *
  574. * @type {number}
  575. * @constant
  576. */
  577. const ByteType = 1010;
  578. /**
  579. * A short data type for textures.
  580. *
  581. * @type {number}
  582. * @constant
  583. */
  584. const ShortType = 1011;
  585. /**
  586. * An unsigned short data type for textures.
  587. *
  588. * @type {number}
  589. * @constant
  590. */
  591. const UnsignedShortType = 1012;
  592. /**
  593. * An int data type for textures.
  594. *
  595. * @type {number}
  596. * @constant
  597. */
  598. const IntType = 1013;
  599. /**
  600. * An unsigned int data type for textures.
  601. *
  602. * @type {number}
  603. * @constant
  604. */
  605. const UnsignedIntType = 1014;
  606. /**
  607. * A float data type for textures.
  608. *
  609. * @type {number}
  610. * @constant
  611. */
  612. const FloatType = 1015;
  613. /**
  614. * A half float data type for textures.
  615. *
  616. * @type {number}
  617. * @constant
  618. */
  619. const HalfFloatType = 1016;
  620. /**
  621. * An unsigned short 4_4_4_4 (packed) data type for textures.
  622. *
  623. * @type {number}
  624. * @constant
  625. */
  626. const UnsignedShort4444Type = 1017;
  627. /**
  628. * An unsigned short 5_5_5_1 (packed) data type for textures.
  629. *
  630. * @type {number}
  631. * @constant
  632. */
  633. const UnsignedShort5551Type = 1018;
  634. /**
  635. * An unsigned int 24_8 data type for textures.
  636. *
  637. * @type {number}
  638. * @constant
  639. */
  640. const UnsignedInt248Type = 1020;
  641. /**
  642. * An unsigned int 5_9_9_9 (packed) data type for textures.
  643. *
  644. * @type {number}
  645. * @constant
  646. */
  647. const UnsignedInt5999Type = 35902;
  648. /**
  649. * An unsigned int 10_11_11 (packed) data type for textures.
  650. *
  651. * @type {number}
  652. * @constant
  653. */
  654. const UnsignedInt101111Type = 35899;
  655. /**
  656. * Discards the red, green and blue components and reads just the alpha component.
  657. *
  658. * @type {number}
  659. * @constant
  660. */
  661. const AlphaFormat = 1021;
  662. /**
  663. * Discards the alpha component and reads the red, green and blue component.
  664. *
  665. * @type {number}
  666. * @constant
  667. */
  668. const RGBFormat = 1022;
  669. /**
  670. * Reads the red, green, blue and alpha components.
  671. *
  672. * @type {number}
  673. * @constant
  674. */
  675. const RGBAFormat = 1023;
  676. /**
  677. * Reads each element as a single depth value, converts it to floating point, and clamps to the range `[0,1]`.
  678. *
  679. * @type {number}
  680. * @constant
  681. */
  682. const DepthFormat = 1026;
  683. /**
  684. * Reads each element is a pair of depth and stencil values. The depth component of the pair is interpreted as
  685. * in `DepthFormat`. The stencil component is interpreted based on the depth + stencil internal format.
  686. *
  687. * @type {number}
  688. * @constant
  689. */
  690. const DepthStencilFormat = 1027;
  691. /**
  692. * Discards the green, blue and alpha components and reads just the red component.
  693. *
  694. * @type {number}
  695. * @constant
  696. */
  697. const RedFormat = 1028;
  698. /**
  699. * Discards the green, blue and alpha components and reads just the red component. The texels are read as integers instead of floating point.
  700. *
  701. * @type {number}
  702. * @constant
  703. */
  704. const RedIntegerFormat = 1029;
  705. /**
  706. * Discards the alpha, and blue components and reads the red, and green components.
  707. *
  708. * @type {number}
  709. * @constant
  710. */
  711. const RGFormat = 1030;
  712. /**
  713. * Discards the alpha, and blue components and reads the red, and green components. The texels are read as integers instead of floating point.
  714. *
  715. * @type {number}
  716. * @constant
  717. */
  718. const RGIntegerFormat = 1031;
  719. /**
  720. * Discards the alpha component and reads the red, green and blue component. The texels are read as integers instead of floating point.
  721. *
  722. * @type {number}
  723. * @constant
  724. */
  725. const RGBIntegerFormat = 1032;
  726. /**
  727. * Reads the red, green, blue and alpha components. The texels are read as integers instead of floating point.
  728. *
  729. * @type {number}
  730. * @constant
  731. */
  732. const RGBAIntegerFormat = 1033;
  733. /**
  734. * A DXT1-compressed image in an RGB image format.
  735. *
  736. * @type {number}
  737. * @constant
  738. */
  739. const RGB_S3TC_DXT1_Format = 33776;
  740. /**
  741. * A DXT1-compressed image in an RGB image format with a simple on/off alpha value.
  742. *
  743. * @type {number}
  744. * @constant
  745. */
  746. const RGBA_S3TC_DXT1_Format = 33777;
  747. /**
  748. * A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression.
  749. *
  750. * @type {number}
  751. * @constant
  752. */
  753. const RGBA_S3TC_DXT3_Format = 33778;
  754. /**
  755. * A DXT5-compressed image in an RGBA image format. It also provides a 4:1 compression, but differs to the DXT3
  756. * compression in how the alpha compression is done.
  757. *
  758. * @type {number}
  759. * @constant
  760. */
  761. const RGBA_S3TC_DXT5_Format = 33779;
  762. /**
  763. * PVRTC RGB compression in 4-bit mode. One block for each 4×4 pixels.
  764. *
  765. * @type {number}
  766. * @constant
  767. */
  768. const RGB_PVRTC_4BPPV1_Format = 35840;
  769. /**
  770. * PVRTC RGB compression in 2-bit mode. One block for each 8×4 pixels.
  771. *
  772. * @type {number}
  773. * @constant
  774. */
  775. const RGB_PVRTC_2BPPV1_Format = 35841;
  776. /**
  777. * PVRTC RGBA compression in 4-bit mode. One block for each 4×4 pixels.
  778. *
  779. * @type {number}
  780. * @constant
  781. */
  782. const RGBA_PVRTC_4BPPV1_Format = 35842;
  783. /**
  784. * PVRTC RGBA compression in 2-bit mode. One block for each 8×4 pixels.
  785. *
  786. * @type {number}
  787. * @constant
  788. */
  789. const RGBA_PVRTC_2BPPV1_Format = 35843;
  790. /**
  791. * ETC1 RGB format.
  792. *
  793. * @type {number}
  794. * @constant
  795. */
  796. const RGB_ETC1_Format = 36196;
  797. /**
  798. * ETC2 RGB format.
  799. *
  800. * @type {number}
  801. * @constant
  802. */
  803. const RGB_ETC2_Format = 37492;
  804. /**
  805. * ETC2 RGBA format.
  806. *
  807. * @type {number}
  808. * @constant
  809. */
  810. const RGBA_ETC2_EAC_Format = 37496;
  811. /**
  812. * EAC R11 UNORM format.
  813. *
  814. * @type {number}
  815. * @constant
  816. */
  817. const R11_EAC_Format = 37488; // 0x9270
  818. /**
  819. * EAC R11 SNORM format.
  820. *
  821. * @type {number}
  822. * @constant
  823. */
  824. const SIGNED_R11_EAC_Format = 37489; // 0x9271
  825. /**
  826. * EAC RG11 UNORM format.
  827. *
  828. * @type {number}
  829. * @constant
  830. */
  831. const RG11_EAC_Format = 37490; // 0x9272
  832. /**
  833. * EAC RG11 SNORM format.
  834. *
  835. * @type {number}
  836. * @constant
  837. */
  838. const SIGNED_RG11_EAC_Format = 37491; // 0x9273
  839. /**
  840. * ASTC RGBA 4x4 format.
  841. *
  842. * @type {number}
  843. * @constant
  844. */
  845. const RGBA_ASTC_4x4_Format = 37808;
  846. /**
  847. * ASTC RGBA 5x4 format.
  848. *
  849. * @type {number}
  850. * @constant
  851. */
  852. const RGBA_ASTC_5x4_Format = 37809;
  853. /**
  854. * ASTC RGBA 5x5 format.
  855. *
  856. * @type {number}
  857. * @constant
  858. */
  859. const RGBA_ASTC_5x5_Format = 37810;
  860. /**
  861. * ASTC RGBA 6x5 format.
  862. *
  863. * @type {number}
  864. * @constant
  865. */
  866. const RGBA_ASTC_6x5_Format = 37811;
  867. /**
  868. * ASTC RGBA 6x6 format.
  869. *
  870. * @type {number}
  871. * @constant
  872. */
  873. const RGBA_ASTC_6x6_Format = 37812;
  874. /**
  875. * ASTC RGBA 8x5 format.
  876. *
  877. * @type {number}
  878. * @constant
  879. */
  880. const RGBA_ASTC_8x5_Format = 37813;
  881. /**
  882. * ASTC RGBA 8x6 format.
  883. *
  884. * @type {number}
  885. * @constant
  886. */
  887. const RGBA_ASTC_8x6_Format = 37814;
  888. /**
  889. * ASTC RGBA 8x8 format.
  890. *
  891. * @type {number}
  892. * @constant
  893. */
  894. const RGBA_ASTC_8x8_Format = 37815;
  895. /**
  896. * ASTC RGBA 10x5 format.
  897. *
  898. * @type {number}
  899. * @constant
  900. */
  901. const RGBA_ASTC_10x5_Format = 37816;
  902. /**
  903. * ASTC RGBA 10x6 format.
  904. *
  905. * @type {number}
  906. * @constant
  907. */
  908. const RGBA_ASTC_10x6_Format = 37817;
  909. /**
  910. * ASTC RGBA 10x8 format.
  911. *
  912. * @type {number}
  913. * @constant
  914. */
  915. const RGBA_ASTC_10x8_Format = 37818;
  916. /**
  917. * ASTC RGBA 10x10 format.
  918. *
  919. * @type {number}
  920. * @constant
  921. */
  922. const RGBA_ASTC_10x10_Format = 37819;
  923. /**
  924. * ASTC RGBA 12x10 format.
  925. *
  926. * @type {number}
  927. * @constant
  928. */
  929. const RGBA_ASTC_12x10_Format = 37820;
  930. /**
  931. * ASTC RGBA 12x12 format.
  932. *
  933. * @type {number}
  934. * @constant
  935. */
  936. const RGBA_ASTC_12x12_Format = 37821;
  937. /**
  938. * BPTC RGBA format.
  939. *
  940. * @type {number}
  941. * @constant
  942. */
  943. const RGBA_BPTC_Format = 36492;
  944. /**
  945. * BPTC Signed RGB format.
  946. *
  947. * @type {number}
  948. * @constant
  949. */
  950. const RGB_BPTC_SIGNED_Format = 36494;
  951. /**
  952. * BPTC Unsigned RGB format.
  953. *
  954. * @type {number}
  955. * @constant
  956. */
  957. const RGB_BPTC_UNSIGNED_Format = 36495;
  958. /**
  959. * RGTC1 Red format.
  960. *
  961. * @type {number}
  962. * @constant
  963. */
  964. const RED_RGTC1_Format = 36283;
  965. /**
  966. * RGTC1 Signed Red format.
  967. *
  968. * @type {number}
  969. * @constant
  970. */
  971. const SIGNED_RED_RGTC1_Format = 36284;
  972. /**
  973. * RGTC2 Red Green format.
  974. *
  975. * @type {number}
  976. * @constant
  977. */
  978. const RED_GREEN_RGTC2_Format = 36285;
  979. /**
  980. * RGTC2 Signed Red Green format.
  981. *
  982. * @type {number}
  983. * @constant
  984. */
  985. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  986. /**
  987. * Animations are played once.
  988. *
  989. * @type {number}
  990. * @constant
  991. */
  992. const LoopOnce = 2200;
  993. /**
  994. * Animations are played with a chosen number of repetitions, each time jumping from
  995. * the end of the clip directly to its beginning.
  996. *
  997. * @type {number}
  998. * @constant
  999. */
  1000. const LoopRepeat = 2201;
  1001. /**
  1002. * Animations are played with a chosen number of repetitions, alternately playing forward
  1003. * and backward.
  1004. *
  1005. * @type {number}
  1006. * @constant
  1007. */
  1008. const LoopPingPong = 2202;
  1009. /**
  1010. * Discrete interpolation mode for keyframe tracks.
  1011. *
  1012. * @type {number}
  1013. * @constant
  1014. */
  1015. const InterpolateDiscrete = 2300;
  1016. /**
  1017. * Linear interpolation mode for keyframe tracks.
  1018. *
  1019. * @type {number}
  1020. * @constant
  1021. */
  1022. const InterpolateLinear = 2301;
  1023. /**
  1024. * Smooth interpolation mode for keyframe tracks.
  1025. *
  1026. * @type {number}
  1027. * @constant
  1028. */
  1029. const InterpolateSmooth = 2302;
  1030. /**
  1031. * Bezier interpolation mode for keyframe tracks.
  1032. *
  1033. * Uses cubic Bezier curves with explicit 2D control points.
  1034. * Requires tangent data to be set on the track.
  1035. *
  1036. * @type {number}
  1037. * @constant
  1038. */
  1039. const InterpolateBezier = 2303;
  1040. /**
  1041. * Zero curvature ending for animations.
  1042. *
  1043. * @type {number}
  1044. * @constant
  1045. */
  1046. const ZeroCurvatureEnding = 2400;
  1047. /**
  1048. * Zero slope ending for animations.
  1049. *
  1050. * @type {number}
  1051. * @constant
  1052. */
  1053. const ZeroSlopeEnding = 2401;
  1054. /**
  1055. * Wrap around ending for animations.
  1056. *
  1057. * @type {number}
  1058. * @constant
  1059. */
  1060. const WrapAroundEnding = 2402;
  1061. /**
  1062. * Default animation blend mode.
  1063. *
  1064. * @type {number}
  1065. * @constant
  1066. */
  1067. const NormalAnimationBlendMode = 2500;
  1068. /**
  1069. * Additive animation blend mode. Can be used to layer motions on top of
  1070. * each other to build complex performances from smaller re-usable assets.
  1071. *
  1072. * @type {number}
  1073. * @constant
  1074. */
  1075. const AdditiveAnimationBlendMode = 2501;
  1076. /**
  1077. * For every three vertices draw a single triangle.
  1078. *
  1079. * @type {number}
  1080. * @constant
  1081. */
  1082. const TrianglesDrawMode = 0;
  1083. /**
  1084. * For each vertex draw a triangle from the last three vertices.
  1085. *
  1086. * @type {number}
  1087. * @constant
  1088. */
  1089. const TriangleStripDrawMode = 1;
  1090. /**
  1091. * For each vertex draw a triangle from the first vertex and the last two vertices.
  1092. *
  1093. * @type {number}
  1094. * @constant
  1095. */
  1096. const TriangleFanDrawMode = 2;
  1097. /**
  1098. * The depth value is inverted (1.0 - z) for visualization purposes.
  1099. *
  1100. * @type {number}
  1101. * @constant
  1102. */
  1103. const BasicDepthPacking = 3200;
  1104. /**
  1105. * The depth value is packed into 32 bit RGBA.
  1106. *
  1107. * @type {number}
  1108. * @constant
  1109. */
  1110. const RGBADepthPacking = 3201;
  1111. /**
  1112. * The depth value is packed into 24 bit RGB.
  1113. *
  1114. * @type {number}
  1115. * @constant
  1116. */
  1117. const RGBDepthPacking = 3202;
  1118. /**
  1119. * The depth value is packed into 16 bit RG.
  1120. *
  1121. * @type {number}
  1122. * @constant
  1123. */
  1124. const RGDepthPacking = 3203;
  1125. /**
  1126. * Normal information is relative to the underlying surface.
  1127. *
  1128. * @type {number}
  1129. * @constant
  1130. */
  1131. const TangentSpaceNormalMap = 0;
  1132. /**
  1133. * Normal information is relative to the object orientation.
  1134. *
  1135. * @type {number}
  1136. * @constant
  1137. */
  1138. const ObjectSpaceNormalMap = 1;
  1139. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  1140. /**
  1141. * No color space.
  1142. *
  1143. * @type {string}
  1144. * @constant
  1145. */
  1146. const NoColorSpace = '';
  1147. /**
  1148. * sRGB color space.
  1149. *
  1150. * @type {string}
  1151. * @constant
  1152. */
  1153. const SRGBColorSpace = 'srgb';
  1154. /**
  1155. * sRGB-linear color space.
  1156. *
  1157. * @type {string}
  1158. * @constant
  1159. */
  1160. const LinearSRGBColorSpace = 'srgb-linear';
  1161. /**
  1162. * Linear transfer function.
  1163. *
  1164. * @type {string}
  1165. * @constant
  1166. */
  1167. const LinearTransfer = 'linear';
  1168. /**
  1169. * sRGB transfer function.
  1170. *
  1171. * @type {string}
  1172. * @constant
  1173. */
  1174. const SRGBTransfer = 'srgb';
  1175. /**
  1176. * No normal map packing.
  1177. *
  1178. * @type {string}
  1179. * @constant
  1180. */
  1181. const NoNormalPacking = '';
  1182. /**
  1183. * Normal RG packing.
  1184. *
  1185. * @type {string}
  1186. * @constant
  1187. */
  1188. const NormalRGPacking = 'rg';
  1189. /**
  1190. * Normal GA packing.
  1191. *
  1192. * @type {string}
  1193. * @constant
  1194. */
  1195. const NormalGAPacking = 'ga';
  1196. /**
  1197. * Sets the stencil buffer value to `0`.
  1198. *
  1199. * @type {number}
  1200. * @constant
  1201. */
  1202. const ZeroStencilOp = 0;
  1203. /**
  1204. * Keeps the current value.
  1205. *
  1206. * @type {number}
  1207. * @constant
  1208. */
  1209. const KeepStencilOp = 7680;
  1210. /**
  1211. * Sets the stencil buffer value to the specified reference value.
  1212. *
  1213. * @type {number}
  1214. * @constant
  1215. */
  1216. const ReplaceStencilOp = 7681;
  1217. /**
  1218. * Increments the current stencil buffer value. Clamps to the maximum representable unsigned value.
  1219. *
  1220. * @type {number}
  1221. * @constant
  1222. */
  1223. const IncrementStencilOp = 7682;
  1224. /**
  1225. * Decrements the current stencil buffer value. Clamps to `0`.
  1226. *
  1227. * @type {number}
  1228. * @constant
  1229. */
  1230. const DecrementStencilOp = 7683;
  1231. /**
  1232. * Increments the current stencil buffer value. Wraps stencil buffer value to zero when incrementing
  1233. * the maximum representable unsigned value.
  1234. *
  1235. * @type {number}
  1236. * @constant
  1237. */
  1238. const IncrementWrapStencilOp = 34055;
  1239. /**
  1240. * Decrements the current stencil buffer value. Wraps stencil buffer value to the maximum representable
  1241. * unsigned value when decrementing a stencil buffer value of `0`.
  1242. *
  1243. * @type {number}
  1244. * @constant
  1245. */
  1246. const DecrementWrapStencilOp = 34056;
  1247. /**
  1248. * Inverts the current stencil buffer value bitwise.
  1249. *
  1250. * @type {number}
  1251. * @constant
  1252. */
  1253. const InvertStencilOp = 5386;
  1254. /**
  1255. * Will never return true.
  1256. *
  1257. * @type {number}
  1258. * @constant
  1259. */
  1260. const NeverStencilFunc = 512;
  1261. /**
  1262. * Will return true if the stencil reference value is less than the current stencil value.
  1263. *
  1264. * @type {number}
  1265. * @constant
  1266. */
  1267. const LessStencilFunc = 513;
  1268. /**
  1269. * Will return true if the stencil reference value is equal to the current stencil value.
  1270. *
  1271. * @type {number}
  1272. * @constant
  1273. */
  1274. const EqualStencilFunc = 514;
  1275. /**
  1276. * Will return true if the stencil reference value is less than or equal to the current stencil value.
  1277. *
  1278. * @type {number}
  1279. * @constant
  1280. */
  1281. const LessEqualStencilFunc = 515;
  1282. /**
  1283. * Will return true if the stencil reference value is greater than the current stencil value.
  1284. *
  1285. * @type {number}
  1286. * @constant
  1287. */
  1288. const GreaterStencilFunc = 516;
  1289. /**
  1290. * Will return true if the stencil reference value is not equal to the current stencil value.
  1291. *
  1292. * @type {number}
  1293. * @constant
  1294. */
  1295. const NotEqualStencilFunc = 517;
  1296. /**
  1297. * Will return true if the stencil reference value is greater than or equal to the current stencil value.
  1298. *
  1299. * @type {number}
  1300. * @constant
  1301. */
  1302. const GreaterEqualStencilFunc = 518;
  1303. /**
  1304. * Will always return true.
  1305. *
  1306. * @type {number}
  1307. * @constant
  1308. */
  1309. const AlwaysStencilFunc = 519;
  1310. /**
  1311. * Never pass.
  1312. *
  1313. * @type {number}
  1314. * @constant
  1315. */
  1316. const NeverCompare = 512;
  1317. /**
  1318. * Pass if the incoming value is less than the texture value.
  1319. *
  1320. * @type {number}
  1321. * @constant
  1322. */
  1323. const LessCompare = 513;
  1324. /**
  1325. * Pass if the incoming value equals the texture value.
  1326. *
  1327. * @type {number}
  1328. * @constant
  1329. */
  1330. const EqualCompare = 514;
  1331. /**
  1332. * Pass if the incoming value is less than or equal to the texture value.
  1333. *
  1334. * @type {number}
  1335. * @constant
  1336. */
  1337. const LessEqualCompare = 515;
  1338. /**
  1339. * Pass if the incoming value is greater than the texture value.
  1340. *
  1341. * @type {number}
  1342. * @constant
  1343. */
  1344. const GreaterCompare = 516;
  1345. /**
  1346. * Pass if the incoming value is not equal to the texture value.
  1347. *
  1348. * @type {number}
  1349. * @constant
  1350. */
  1351. const NotEqualCompare = 517;
  1352. /**
  1353. * Pass if the incoming value is greater than or equal to the texture value.
  1354. *
  1355. * @type {number}
  1356. * @constant
  1357. */
  1358. const GreaterEqualCompare = 518;
  1359. /**
  1360. * Always pass.
  1361. *
  1362. * @type {number}
  1363. * @constant
  1364. */
  1365. const AlwaysCompare = 519;
  1366. /**
  1367. * The contents are intended to be specified once by the application, and used many
  1368. * times as the source for drawing and image specification commands.
  1369. *
  1370. * @type {number}
  1371. * @constant
  1372. */
  1373. const StaticDrawUsage = 35044;
  1374. /**
  1375. * The contents are intended to be respecified repeatedly by the application, and
  1376. * used many times as the source for drawing and image specification commands.
  1377. *
  1378. * @type {number}
  1379. * @constant
  1380. */
  1381. const DynamicDrawUsage = 35048;
  1382. /**
  1383. * The contents are intended to be specified once by the application, and used at most
  1384. * a few times as the source for drawing and image specification commands.
  1385. *
  1386. * @type {number}
  1387. * @constant
  1388. */
  1389. const StreamDrawUsage = 35040;
  1390. /**
  1391. * The contents are intended to be specified once by reading data from the 3D API, and queried
  1392. * many times by the application.
  1393. *
  1394. * @type {number}
  1395. * @constant
  1396. */
  1397. const StaticReadUsage = 35045;
  1398. /**
  1399. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and queried
  1400. * many times by the application.
  1401. *
  1402. * @type {number}
  1403. * @constant
  1404. */
  1405. const DynamicReadUsage = 35049;
  1406. /**
  1407. * The contents are intended to be specified once by reading data from the 3D API, and queried at most
  1408. * a few times by the application
  1409. *
  1410. * @type {number}
  1411. * @constant
  1412. */
  1413. const StreamReadUsage = 35041;
  1414. /**
  1415. * The contents are intended to be specified once by reading data from the 3D API, and used many times as
  1416. * the source for WebGL drawing and image specification commands.
  1417. *
  1418. * @type {number}
  1419. * @constant
  1420. */
  1421. const StaticCopyUsage = 35046;
  1422. /**
  1423. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and used many times
  1424. * as the source for WebGL drawing and image specification commands.
  1425. *
  1426. * @type {number}
  1427. * @constant
  1428. */
  1429. const DynamicCopyUsage = 35050;
  1430. /**
  1431. * The contents are intended to be specified once by reading data from the 3D API, and used at most a few times
  1432. * as the source for WebGL drawing and image specification commands.
  1433. *
  1434. * @type {number}
  1435. * @constant
  1436. */
  1437. const StreamCopyUsage = 35042;
  1438. /**
  1439. * GLSL 1 shader code.
  1440. *
  1441. * @type {string}
  1442. * @constant
  1443. */
  1444. const GLSL1 = '100';
  1445. /**
  1446. * GLSL 3 shader code.
  1447. *
  1448. * @type {string}
  1449. * @constant
  1450. */
  1451. const GLSL3 = '300 es';
  1452. /**
  1453. * WebGL coordinate system.
  1454. *
  1455. * @type {number}
  1456. * @constant
  1457. */
  1458. const WebGLCoordinateSystem = 2000;
  1459. /**
  1460. * WebGPU coordinate system.
  1461. *
  1462. * @type {number}
  1463. * @constant
  1464. */
  1465. const WebGPUCoordinateSystem = 2001;
  1466. /**
  1467. * Represents the different timestamp query types.
  1468. *
  1469. * @type {ConstantsTimestampQuery}
  1470. * @constant
  1471. */
  1472. const TimestampQuery = {
  1473. COMPUTE: 'compute',
  1474. RENDER: 'render'
  1475. };
  1476. /**
  1477. * Represents mouse buttons and interaction types in context of controls.
  1478. *
  1479. * @type {ConstantsInterpolationSamplingType}
  1480. * @constant
  1481. */
  1482. const InterpolationSamplingType = {
  1483. PERSPECTIVE: 'perspective',
  1484. LINEAR: 'linear',
  1485. FLAT: 'flat'
  1486. };
  1487. /**
  1488. * Represents the different interpolation sampling modes.
  1489. *
  1490. * @type {ConstantsInterpolationSamplingMode}
  1491. * @constant
  1492. */
  1493. const InterpolationSamplingMode = {
  1494. NORMAL: 'normal',
  1495. CENTROID: 'centroid',
  1496. SAMPLE: 'sample',
  1497. FIRST: 'first',
  1498. EITHER: 'either'
  1499. };
  1500. /**
  1501. * Compatibility flags for features that may not be supported across all platforms.
  1502. *
  1503. * @type {Object}
  1504. * @constant
  1505. */
  1506. const Compatibility = {
  1507. TEXTURE_COMPARE: 'depthTextureCompare'
  1508. };
  1509. /**
  1510. * This type represents mouse buttons and interaction types in context of controls.
  1511. *
  1512. * @typedef {Object} ConstantsMouse
  1513. * @property {number} MIDDLE - The left mouse button.
  1514. * @property {number} LEFT - The middle mouse button.
  1515. * @property {number} RIGHT - The right mouse button.
  1516. * @property {number} ROTATE - A rotate interaction.
  1517. * @property {number} DOLLY - A dolly interaction.
  1518. * @property {number} PAN - A pan interaction.
  1519. **/
  1520. /**
  1521. * This type represents touch interaction types in context of controls.
  1522. *
  1523. * @typedef {Object} ConstantsTouch
  1524. * @property {number} ROTATE - A rotate interaction.
  1525. * @property {number} PAN - A pan interaction.
  1526. * @property {number} DOLLY_PAN - The dolly-pan interaction.
  1527. * @property {number} DOLLY_ROTATE - A dolly-rotate interaction.
  1528. **/
  1529. /**
  1530. * This type represents the different timestamp query types.
  1531. *
  1532. * @typedef {Object} ConstantsTimestampQuery
  1533. * @property {string} COMPUTE - A `compute` timestamp query.
  1534. * @property {string} RENDER - A `render` timestamp query.
  1535. **/
  1536. /**
  1537. * Represents the different interpolation sampling types.
  1538. *
  1539. * @typedef {Object} ConstantsInterpolationSamplingType
  1540. * @property {string} PERSPECTIVE - Perspective-correct interpolation.
  1541. * @property {string} LINEAR - Linear interpolation.
  1542. * @property {string} FLAT - Flat interpolation.
  1543. */
  1544. /**
  1545. * Represents the different interpolation sampling modes.
  1546. *
  1547. * @typedef {Object} ConstantsInterpolationSamplingMode
  1548. * @property {string} NORMAL - Normal sampling mode.
  1549. * @property {string} CENTROID - Centroid sampling mode.
  1550. * @property {string} SAMPLE - Sample-specific sampling mode.
  1551. * @property {string} FIRST - Flat interpolation using the first vertex.
  1552. * @property {string} EITHER - Flat interpolation using either vertex.
  1553. */
  1554. /**
  1555. * Checks if an array contains values that require Uint32 representation.
  1556. *
  1557. * This function determines whether the array contains any values >= 65535,
  1558. * which would require a Uint32Array rather than a Uint16Array for proper storage.
  1559. * The function iterates from the end of the array, assuming larger values are
  1560. * typically located at the end.
  1561. *
  1562. * @private
  1563. * @param {Array<number>} array - The array to check.
  1564. * @return {boolean} True if the array contains values >= 65535, false otherwise.
  1565. */
  1566. function arrayNeedsUint32( array ) {
  1567. // assumes larger values usually on last
  1568. for ( let i = array.length - 1; i >= 0; -- i ) {
  1569. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  1570. }
  1571. return false;
  1572. }
  1573. /**
  1574. * Map of typed array constructor names to their constructors.
  1575. * This mapping enables dynamic creation of typed arrays based on string type names.
  1576. *
  1577. * @private
  1578. * @constant
  1579. * @type {Object<string, TypedArrayConstructor>}
  1580. */
  1581. const TYPED_ARRAYS = {
  1582. Int8Array: Int8Array,
  1583. Uint8Array: Uint8Array,
  1584. Uint8ClampedArray: Uint8ClampedArray,
  1585. Int16Array: Int16Array,
  1586. Uint16Array: Uint16Array,
  1587. Int32Array: Int32Array,
  1588. Uint32Array: Uint32Array,
  1589. Float32Array: Float32Array,
  1590. Float64Array: Float64Array
  1591. };
  1592. /**
  1593. * Creates a typed array of the specified type from the given buffer.
  1594. *
  1595. * @private
  1596. * @param {string} type - The name of the typed array type (e.g., 'Float32Array', 'Uint16Array').
  1597. * @param {ArrayBuffer} buffer - The buffer to create the typed array from.
  1598. * @return {TypedArray} A new typed array of the specified type.
  1599. */
  1600. function getTypedArray( type, buffer ) {
  1601. return new TYPED_ARRAYS[ type ]( buffer );
  1602. }
  1603. /**
  1604. * Returns `true` if the given object is a typed array.
  1605. *
  1606. * @param {any} array - The object to check.
  1607. * @return {boolean} Whether the given object is a typed array.
  1608. */
  1609. function isTypedArray( array ) {
  1610. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  1611. }
  1612. /**
  1613. * Creates an XHTML element with the specified tag name.
  1614. *
  1615. * This function uses the XHTML namespace to create DOM elements,
  1616. * ensuring proper element creation in XML-based contexts.
  1617. *
  1618. * @private
  1619. * @param {string} name - The tag name of the element to create (e.g., 'canvas', 'div').
  1620. * @return {HTMLElement} The created XHTML element.
  1621. */
  1622. function createElementNS( name ) {
  1623. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  1624. }
  1625. /**
  1626. * Creates a canvas element configured for block display.
  1627. *
  1628. * This is a convenience function that creates a canvas element with
  1629. * display style set to 'block', which is commonly used in three.js
  1630. * rendering contexts to avoid inline element spacing issues.
  1631. *
  1632. * @return {HTMLCanvasElement} A canvas element with display set to 'block'.
  1633. */
  1634. function createCanvasElement() {
  1635. const canvas = createElementNS( 'canvas' );
  1636. canvas.style.display = 'block';
  1637. return canvas;
  1638. }
  1639. /**
  1640. * Internal cache for tracking warning messages to prevent duplicate warnings.
  1641. *
  1642. * @private
  1643. * @type {Object<string, boolean>}
  1644. */
  1645. const _cache = {};
  1646. /**
  1647. * Custom console function handler for intercepting log, warn, and error calls.
  1648. *
  1649. * @private
  1650. * @type {Function|null}
  1651. */
  1652. let _setConsoleFunction = null;
  1653. /**
  1654. * Sets a custom function to handle console output.
  1655. *
  1656. * This allows external code to intercept and handle console.log, console.warn,
  1657. * and console.error calls made by three.js, which is useful for custom logging,
  1658. * testing, or debugging workflows.
  1659. *
  1660. * @param {Function} fn - The function to handle console output. Should accept
  1661. * (type, message, ...params) where type is 'log', 'warn', or 'error'.
  1662. */
  1663. function setConsoleFunction( fn ) {
  1664. _setConsoleFunction = fn;
  1665. }
  1666. /**
  1667. * Gets the currently set custom console function.
  1668. *
  1669. * @return {Function|null} The custom console function, or null if not set.
  1670. */
  1671. function getConsoleFunction() {
  1672. return _setConsoleFunction;
  1673. }
  1674. /**
  1675. * Logs an informational message with the 'THREE.' prefix.
  1676. *
  1677. * If a custom console function is set via setConsoleFunction(), it will be used
  1678. * instead of the native console.log. The first parameter is treated as the
  1679. * method name and is automatically prefixed with 'THREE.'.
  1680. *
  1681. * @param {...any} params - The message components. The first param is used as
  1682. * the method name and prefixed with 'THREE.'.
  1683. */
  1684. function log( ...params ) {
  1685. const message = 'THREE.' + params.shift();
  1686. if ( _setConsoleFunction ) {
  1687. _setConsoleFunction( 'log', message, ...params );
  1688. } else {
  1689. console.log( message, ...params );
  1690. }
  1691. }
  1692. /**
  1693. * Enhances log/warn/error messages related to TSL.
  1694. *
  1695. * @param {Array<any>} params - The original message parameters.
  1696. * @returns {Array<any>} The filtered and enhanced message parameters.
  1697. */
  1698. function enhanceLogMessage( params ) {
  1699. const message = params[ 0 ];
  1700. if ( typeof message === 'string' && message.startsWith( 'TSL:' ) ) {
  1701. const stackTrace = params[ 1 ];
  1702. if ( stackTrace && stackTrace.isStackTrace ) {
  1703. params[ 0 ] += ' ' + stackTrace.getLocation();
  1704. } else {
  1705. params[ 1 ] = 'Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.';
  1706. }
  1707. }
  1708. return params;
  1709. }
  1710. /**
  1711. * Logs a warning message with the 'THREE.' prefix.
  1712. *
  1713. * If a custom console function is set via setConsoleFunction(), it will be used
  1714. * instead of the native console.warn. The first parameter is treated as the
  1715. * method name and is automatically prefixed with 'THREE.'.
  1716. *
  1717. * @param {...any} params - The message components. The first param is used as
  1718. * the method name and prefixed with 'THREE.'.
  1719. */
  1720. function warn( ...params ) {
  1721. params = enhanceLogMessage( params );
  1722. const message = 'THREE.' + params.shift();
  1723. if ( _setConsoleFunction ) {
  1724. _setConsoleFunction( 'warn', message, ...params );
  1725. } else {
  1726. const stackTrace = params[ 0 ];
  1727. if ( stackTrace && stackTrace.isStackTrace ) {
  1728. console.warn( stackTrace.getError( message ) );
  1729. } else {
  1730. console.warn( message, ...params );
  1731. }
  1732. }
  1733. }
  1734. /**
  1735. * Logs an error message with the 'THREE.' prefix.
  1736. *
  1737. * If a custom console function is set via setConsoleFunction(), it will be used
  1738. * instead of the native console.error. The first parameter is treated as the
  1739. * method name and is automatically prefixed with 'THREE.'.
  1740. *
  1741. * @param {...any} params - The message components. The first param is used as
  1742. * the method name and prefixed with 'THREE.'.
  1743. */
  1744. function error( ...params ) {
  1745. params = enhanceLogMessage( params );
  1746. const message = 'THREE.' + params.shift();
  1747. if ( _setConsoleFunction ) {
  1748. _setConsoleFunction( 'error', message, ...params );
  1749. } else {
  1750. const stackTrace = params[ 0 ];
  1751. if ( stackTrace && stackTrace.isStackTrace ) {
  1752. console.error( stackTrace.getError( message ) );
  1753. } else {
  1754. console.error( message, ...params );
  1755. }
  1756. }
  1757. }
  1758. /**
  1759. * Logs a warning message only once, preventing duplicate warnings.
  1760. *
  1761. * This function maintains an internal cache of warning messages and will only
  1762. * output each unique warning message once. Useful for warnings that may be
  1763. * triggered repeatedly but should only be shown to the user once.
  1764. *
  1765. * @param {...any} params - The warning message components.
  1766. */
  1767. function warnOnce( ...params ) {
  1768. const message = params.join( ' ' );
  1769. if ( message in _cache ) return;
  1770. _cache[ message ] = true;
  1771. warn( ...params );
  1772. }
  1773. /**
  1774. * Yields execution to the main thread to allow rendering and other tasks.
  1775. * Uses scheduler.yield() when available (Chrome 115+), falls back to requestAnimationFrame.
  1776. *
  1777. * @return {Promise<void>}
  1778. */
  1779. function yieldToMain() {
  1780. if ( typeof self !== 'undefined' && typeof self.scheduler !== 'undefined' && typeof self.scheduler.yield !== 'undefined' ) {
  1781. return self.scheduler.yield();
  1782. }
  1783. return new Promise( resolve => {
  1784. requestAnimationFrame( resolve );
  1785. } );
  1786. }
  1787. /**
  1788. * Asynchronously probes for WebGL sync object completion.
  1789. *
  1790. * This function creates a promise that resolves when the WebGL sync object
  1791. * signals completion or rejects if the sync operation fails. It uses polling
  1792. * at the specified interval to check the sync status without blocking the
  1793. * main thread. This is useful for GPU-CPU synchronization in WebGL contexts.
  1794. *
  1795. * @private
  1796. * @param {WebGL2RenderingContext} gl - The WebGL rendering context.
  1797. * @param {WebGLSync} sync - The WebGL sync object to wait for.
  1798. * @param {number} interval - The polling interval in milliseconds.
  1799. * @return {Promise<void>} A promise that resolves when the sync completes or rejects if it fails.
  1800. */
  1801. function probeAsync( gl, sync, interval ) {
  1802. return new Promise( function ( resolve, reject ) {
  1803. function probe() {
  1804. switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
  1805. case gl.WAIT_FAILED:
  1806. reject();
  1807. break;
  1808. case gl.TIMEOUT_EXPIRED:
  1809. setTimeout( probe, interval );
  1810. break;
  1811. default:
  1812. resolve();
  1813. }
  1814. }
  1815. setTimeout( probe, interval );
  1816. } );
  1817. }
  1818. /**
  1819. * Used to select the correct depth functions
  1820. * when reversed depth buffer is used.
  1821. *
  1822. * @private
  1823. * @type {Object}
  1824. */
  1825. const ReversedDepthFuncs = {
  1826. [ NeverDepth ]: AlwaysDepth,
  1827. [ LessDepth ]: GreaterDepth,
  1828. [ EqualDepth ]: NotEqualDepth,
  1829. [ LessEqualDepth ]: GreaterEqualDepth,
  1830. [ AlwaysDepth ]: NeverDepth,
  1831. [ GreaterDepth ]: LessDepth,
  1832. [ NotEqualDepth ]: EqualDepth,
  1833. [ GreaterEqualDepth ]: LessEqualDepth,
  1834. };
  1835. /**
  1836. * This modules allows to dispatch event objects on custom JavaScript objects.
  1837. *
  1838. * Main repository: [eventdispatcher.js](https://github.com/mrdoob/eventdispatcher.js/)
  1839. *
  1840. * Code Example:
  1841. * ```js
  1842. * class Car extends EventDispatcher {
  1843. * start() {
  1844. * this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } );
  1845. * }
  1846. *};
  1847. *
  1848. * // Using events with the custom object
  1849. * const car = new Car();
  1850. * car.addEventListener( 'start', function ( event ) {
  1851. * alert( event.message );
  1852. * } );
  1853. *
  1854. * car.start();
  1855. * ```
  1856. */
  1857. class EventDispatcher {
  1858. /**
  1859. * Adds the given event listener to the given event type.
  1860. *
  1861. * @param {string} type - The type of event to listen to.
  1862. * @param {Function} listener - The function that gets called when the event is fired.
  1863. */
  1864. addEventListener( type, listener ) {
  1865. if ( this._listeners === undefined ) this._listeners = {};
  1866. const listeners = this._listeners;
  1867. if ( listeners[ type ] === undefined ) {
  1868. listeners[ type ] = [];
  1869. }
  1870. if ( listeners[ type ].indexOf( listener ) === -1 ) {
  1871. listeners[ type ].push( listener );
  1872. }
  1873. }
  1874. /**
  1875. * Returns `true` if the given event listener has been added to the given event type.
  1876. *
  1877. * @param {string} type - The type of event.
  1878. * @param {Function} listener - The listener to check.
  1879. * @return {boolean} Whether the given event listener has been added to the given event type.
  1880. */
  1881. hasEventListener( type, listener ) {
  1882. const listeners = this._listeners;
  1883. if ( listeners === undefined ) return false;
  1884. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== -1;
  1885. }
  1886. /**
  1887. * Removes the given event listener from the given event type.
  1888. *
  1889. * @param {string} type - The type of event.
  1890. * @param {Function} listener - The listener to remove.
  1891. */
  1892. removeEventListener( type, listener ) {
  1893. const listeners = this._listeners;
  1894. if ( listeners === undefined ) return;
  1895. const listenerArray = listeners[ type ];
  1896. if ( listenerArray !== undefined ) {
  1897. const index = listenerArray.indexOf( listener );
  1898. if ( index !== -1 ) {
  1899. listenerArray.splice( index, 1 );
  1900. }
  1901. }
  1902. }
  1903. /**
  1904. * Dispatches an event object.
  1905. *
  1906. * @param {Object} event - The event that gets fired.
  1907. */
  1908. dispatchEvent( event ) {
  1909. const listeners = this._listeners;
  1910. if ( listeners === undefined ) return;
  1911. const listenerArray = listeners[ event.type ];
  1912. if ( listenerArray !== undefined ) {
  1913. event.target = this;
  1914. // Make a copy, in case listeners are removed while iterating.
  1915. const array = listenerArray.slice( 0 );
  1916. for ( let i = 0, l = array.length; i < l; i ++ ) {
  1917. array[ i ].call( this, event );
  1918. }
  1919. event.target = null;
  1920. }
  1921. }
  1922. }
  1923. 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' ];
  1924. let _seed = 1234567;
  1925. const DEG2RAD = Math.PI / 180;
  1926. const RAD2DEG = 180 / Math.PI;
  1927. /**
  1928. * Generate a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier)
  1929. * (universally unique identifier).
  1930. *
  1931. * @return {string} The UUID.
  1932. */
  1933. function generateUUID() {
  1934. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  1935. const d0 = Math.random() * 0xffffffff | 0;
  1936. const d1 = Math.random() * 0xffffffff | 0;
  1937. const d2 = Math.random() * 0xffffffff | 0;
  1938. const d3 = Math.random() * 0xffffffff | 0;
  1939. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  1940. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  1941. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  1942. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  1943. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  1944. return uuid.toLowerCase();
  1945. }
  1946. /**
  1947. * Clamps the given value between min and max.
  1948. *
  1949. * @param {number} value - The value to clamp.
  1950. * @param {number} min - The min value.
  1951. * @param {number} max - The max value.
  1952. * @return {number} The clamped value.
  1953. */
  1954. function clamp( value, min, max ) {
  1955. return Math.max( min, Math.min( max, value ) );
  1956. }
  1957. /**
  1958. * Computes the Euclidean modulo of the given parameters that
  1959. * is `( ( n % m ) + m ) % m`.
  1960. *
  1961. * @param {number} n - The first parameter.
  1962. * @param {number} m - The second parameter.
  1963. * @return {number} The Euclidean modulo.
  1964. */
  1965. function euclideanModulo( n, m ) {
  1966. // https://en.wikipedia.org/wiki/Modulo_operation
  1967. return ( ( n % m ) + m ) % m;
  1968. }
  1969. /**
  1970. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  1971. * for the given value. `a2` must be greater than `a1`.
  1972. *
  1973. * @param {number} x - The value to be mapped.
  1974. * @param {number} a1 - Minimum value for range A.
  1975. * @param {number} a2 - Maximum value for range A.
  1976. * @param {number} b1 - Minimum value for range B.
  1977. * @param {number} b2 - Maximum value for range B.
  1978. * @return {number} The mapped value.
  1979. */
  1980. function mapLinear( x, a1, a2, b1, b2 ) {
  1981. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  1982. }
  1983. /**
  1984. * Returns the percentage in the closed interval `[0, 1]` of the given value
  1985. * between the start and end point.
  1986. *
  1987. * @param {number} x - The start point
  1988. * @param {number} y - The end point.
  1989. * @param {number} value - A value between start and end.
  1990. * @return {number} The interpolation factor.
  1991. */
  1992. function inverseLerp( x, y, value ) {
  1993. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  1994. if ( x !== y ) {
  1995. return ( value - x ) / ( y - x );
  1996. } else {
  1997. return 0;
  1998. }
  1999. }
  2000. /**
  2001. * Returns a value linearly interpolated from two known points based on the given interval -
  2002. * `t = 0` will return `x` and `t = 1` will return `y`.
  2003. *
  2004. * @param {number} x - The start point
  2005. * @param {number} y - The end point.
  2006. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  2007. * @return {number} The interpolated value.
  2008. */
  2009. function lerp( x, y, t ) {
  2010. return ( 1 - t ) * x + t * y;
  2011. }
  2012. /**
  2013. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  2014. * time to maintain frame rate independent movement. For details, see
  2015. * [Frame rate independent damping using lerp](http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/).
  2016. *
  2017. * @param {number} x - The current point.
  2018. * @param {number} y - The target point.
  2019. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  2020. * and a lower value will make the movement more gradual.
  2021. * @param {number} dt - Delta time in seconds.
  2022. * @return {number} The interpolated value.
  2023. */
  2024. function damp( x, y, lambda, dt ) {
  2025. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  2026. }
  2027. /**
  2028. * Returns a value that alternates between `0` and the given `length` parameter.
  2029. *
  2030. * @param {number} x - The value to pingpong.
  2031. * @param {number} [length=1] - The positive value the function will pingpong to.
  2032. * @return {number} The alternated value.
  2033. */
  2034. function pingpong( x, length = 1 ) {
  2035. // https://www.desmos.com/calculator/vcsjnyz7x4
  2036. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  2037. }
  2038. /**
  2039. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  2040. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  2041. * the `min` and `max`.
  2042. *
  2043. * See [Smoothstep](http://en.wikipedia.org/wiki/Smoothstep) for more details.
  2044. *
  2045. * @param {number} x - The value to evaluate based on its position between `min` and `max`.
  2046. * @param {number} min - The min value. Any `x` value below `min` will be `0`. `min` must be lower than `max`.
  2047. * @param {number} max - The max value. Any `x` value above `max` will be `1`. `max` must be greater than `min`.
  2048. * @return {number} The alternated value.
  2049. */
  2050. function smoothstep( x, min, max ) {
  2051. if ( x <= min ) return 0;
  2052. if ( x >= max ) return 1;
  2053. x = ( x - min ) / ( max - min );
  2054. return x * x * ( 3 - 2 * x );
  2055. }
  2056. /**
  2057. * A [variation on smoothstep](https://en.wikipedia.org/wiki/Smoothstep#Variations)
  2058. * that has zero 1st and 2nd order derivatives at `x=0` and `x=1`.
  2059. *
  2060. * @param {number} x - The value to evaluate based on its position between `min` and `max`.
  2061. * @param {number} min - The min value. Any `x` value below `min` will be `0`. `min` must be lower than `max`.
  2062. * @param {number} max - The max value. Any `x` value above `max` will be `1`. `max` must be greater than `min`.
  2063. * @return {number} The alternated value.
  2064. */
  2065. function smootherstep( x, min, max ) {
  2066. if ( x <= min ) return 0;
  2067. if ( x >= max ) return 1;
  2068. x = ( x - min ) / ( max - min );
  2069. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  2070. }
  2071. /**
  2072. * Returns a random integer from `<low, high>` interval.
  2073. *
  2074. * @param {number} low - The lower value boundary.
  2075. * @param {number} high - The upper value boundary
  2076. * @return {number} A random integer.
  2077. */
  2078. function randInt( low, high ) {
  2079. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  2080. }
  2081. /**
  2082. * Returns a random float from `<low, high>` interval.
  2083. *
  2084. * @param {number} low - The lower value boundary.
  2085. * @param {number} high - The upper value boundary
  2086. * @return {number} A random float.
  2087. */
  2088. function randFloat( low, high ) {
  2089. return low + Math.random() * ( high - low );
  2090. }
  2091. /**
  2092. * Returns a random integer from `<-range/2, range/2>` interval.
  2093. *
  2094. * @param {number} range - Defines the value range.
  2095. * @return {number} A random float.
  2096. */
  2097. function randFloatSpread( range ) {
  2098. return range * ( 0.5 - Math.random() );
  2099. }
  2100. /**
  2101. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  2102. *
  2103. * @param {number} [s] - The integer seed.
  2104. * @return {number} A random float.
  2105. */
  2106. function seededRandom( s ) {
  2107. if ( s !== undefined ) _seed = s;
  2108. // Mulberry32 generator
  2109. let t = _seed += 0x6D2B79F5;
  2110. t = Math.imul( t ^ t >>> 15, t | 1 );
  2111. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  2112. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  2113. }
  2114. /**
  2115. * Converts degrees to radians.
  2116. *
  2117. * @param {number} degrees - A value in degrees.
  2118. * @return {number} The converted value in radians.
  2119. */
  2120. function degToRad( degrees ) {
  2121. return degrees * DEG2RAD;
  2122. }
  2123. /**
  2124. * Converts radians to degrees.
  2125. *
  2126. * @param {number} radians - A value in radians.
  2127. * @return {number} The converted value in degrees.
  2128. */
  2129. function radToDeg( radians ) {
  2130. return radians * RAD2DEG;
  2131. }
  2132. /**
  2133. * Returns `true` if the given number is a power of two.
  2134. *
  2135. * @param {number} value - The value to check.
  2136. * @return {boolean} Whether the given number is a power of two or not.
  2137. */
  2138. function isPowerOfTwo( value ) {
  2139. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  2140. }
  2141. /**
  2142. * Returns the smallest power of two that is greater than or equal to the given number.
  2143. *
  2144. * @param {number} value - The value to find a POT for. Must be greater than `0`.
  2145. * @return {number} The smallest power of two that is greater than or equal to the given number.
  2146. */
  2147. function ceilPowerOfTwo( value ) {
  2148. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  2149. }
  2150. /**
  2151. * Returns the largest power of two that is less than or equal to the given number.
  2152. *
  2153. * @param {number} value - The value to find a POT for. Must be greater than `0`.
  2154. * @return {number} The largest power of two that is less than or equal to the given number.
  2155. */
  2156. function floorPowerOfTwo( value ) {
  2157. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  2158. }
  2159. /**
  2160. * Sets the given quaternion from the [Intrinsic Proper Euler Angles](https://en.wikipedia.org/wiki/Euler_angles)
  2161. * defined by the given angles and order.
  2162. *
  2163. * Rotations are applied to the axes in the order specified by order:
  2164. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  2165. *
  2166. * @param {Quaternion} q - The quaternion to set.
  2167. * @param {number} a - The rotation applied to the first axis, in radians.
  2168. * @param {number} b - The rotation applied to the second axis, in radians.
  2169. * @param {number} c - The rotation applied to the third axis, in radians.
  2170. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  2171. */
  2172. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  2173. const cos = Math.cos;
  2174. const sin = Math.sin;
  2175. const c2 = cos( b / 2 );
  2176. const s2 = sin( b / 2 );
  2177. const c13 = cos( ( a + c ) / 2 );
  2178. const s13 = sin( ( a + c ) / 2 );
  2179. const c1_3 = cos( ( a - c ) / 2 );
  2180. const s1_3 = sin( ( a - c ) / 2 );
  2181. const c3_1 = cos( ( c - a ) / 2 );
  2182. const s3_1 = sin( ( c - a ) / 2 );
  2183. switch ( order ) {
  2184. case 'XYX':
  2185. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  2186. break;
  2187. case 'YZY':
  2188. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  2189. break;
  2190. case 'ZXZ':
  2191. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  2192. break;
  2193. case 'XZX':
  2194. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  2195. break;
  2196. case 'YXY':
  2197. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  2198. break;
  2199. case 'ZYZ':
  2200. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  2201. break;
  2202. default:
  2203. warn( 'MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  2204. }
  2205. }
  2206. /**
  2207. * Denormalizes the given value according to the given typed array.
  2208. *
  2209. * @param {number} value - The value to denormalize.
  2210. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2211. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2212. */
  2213. function denormalize( value, array ) {
  2214. switch ( array.constructor ) {
  2215. case Float32Array:
  2216. return value;
  2217. case Uint32Array:
  2218. return value / 4294967295.0;
  2219. case Uint16Array:
  2220. return value / 65535.0;
  2221. case Uint8Array:
  2222. return value / 255.0;
  2223. case Int32Array:
  2224. return Math.max( value / 2147483647.0, -1 );
  2225. case Int16Array:
  2226. return Math.max( value / 32767.0, -1 );
  2227. case Int8Array:
  2228. return Math.max( value / 127.0, -1 );
  2229. default:
  2230. throw new Error( 'Invalid component type.' );
  2231. }
  2232. }
  2233. /**
  2234. * Normalizes the given value according to the given typed array.
  2235. *
  2236. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2237. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2238. * @return {number} The normalize value.
  2239. */
  2240. function normalize( value, array ) {
  2241. switch ( array.constructor ) {
  2242. case Float32Array:
  2243. return value;
  2244. case Uint32Array:
  2245. return Math.round( value * 4294967295.0 );
  2246. case Uint16Array:
  2247. return Math.round( value * 65535.0 );
  2248. case Uint8Array:
  2249. return Math.round( value * 255.0 );
  2250. case Int32Array:
  2251. return Math.round( value * 2147483647.0 );
  2252. case Int16Array:
  2253. return Math.round( value * 32767.0 );
  2254. case Int8Array:
  2255. return Math.round( value * 127.0 );
  2256. default:
  2257. throw new Error( 'Invalid component type.' );
  2258. }
  2259. }
  2260. /**
  2261. * @class
  2262. * @classdesc A collection of math utility functions.
  2263. * @hideconstructor
  2264. */
  2265. const MathUtils = {
  2266. DEG2RAD: DEG2RAD,
  2267. RAD2DEG: RAD2DEG,
  2268. /**
  2269. * Generate a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier)
  2270. * (universally unique identifier).
  2271. *
  2272. * @static
  2273. * @method
  2274. * @return {string} The UUID.
  2275. */
  2276. generateUUID: generateUUID,
  2277. /**
  2278. * Clamps the given value between min and max.
  2279. *
  2280. * @static
  2281. * @method
  2282. * @param {number} value - The value to clamp.
  2283. * @param {number} min - The min value.
  2284. * @param {number} max - The max value.
  2285. * @return {number} The clamped value.
  2286. */
  2287. clamp: clamp,
  2288. /**
  2289. * Computes the Euclidean modulo of the given parameters that
  2290. * is `( ( n % m ) + m ) % m`.
  2291. *
  2292. * @static
  2293. * @method
  2294. * @param {number} n - The first parameter.
  2295. * @param {number} m - The second parameter.
  2296. * @return {number} The Euclidean modulo.
  2297. */
  2298. euclideanModulo: euclideanModulo,
  2299. /**
  2300. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  2301. * for the given value.
  2302. *
  2303. * @static
  2304. * @method
  2305. * @param {number} x - The value to be mapped.
  2306. * @param {number} a1 - Minimum value for range A.
  2307. * @param {number} a2 - Maximum value for range A.
  2308. * @param {number} b1 - Minimum value for range B.
  2309. * @param {number} b2 - Maximum value for range B.
  2310. * @return {number} The mapped value.
  2311. */
  2312. mapLinear: mapLinear,
  2313. /**
  2314. * Returns the percentage in the closed interval `[0, 1]` of the given value
  2315. * between the start and end point.
  2316. *
  2317. * @static
  2318. * @method
  2319. * @param {number} x - The start point
  2320. * @param {number} y - The end point.
  2321. * @param {number} value - A value between start and end.
  2322. * @return {number} The interpolation factor.
  2323. */
  2324. inverseLerp: inverseLerp,
  2325. /**
  2326. * Returns a value linearly interpolated from two known points based on the given interval -
  2327. * `t = 0` will return `x` and `t = 1` will return `y`.
  2328. *
  2329. * @static
  2330. * @method
  2331. * @param {number} x - The start point
  2332. * @param {number} y - The end point.
  2333. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  2334. * @return {number} The interpolated value.
  2335. */
  2336. lerp: lerp,
  2337. /**
  2338. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  2339. * time to maintain frame rate independent movement. For details, see
  2340. * [Frame rate independent damping using lerp](http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/).
  2341. *
  2342. * @static
  2343. * @method
  2344. * @param {number} x - The current point.
  2345. * @param {number} y - The target point.
  2346. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  2347. * and a lower value will make the movement more gradual.
  2348. * @param {number} dt - Delta time in seconds.
  2349. * @return {number} The interpolated value.
  2350. */
  2351. damp: damp,
  2352. /**
  2353. * Returns a value that alternates between `0` and the given `length` parameter.
  2354. *
  2355. * @static
  2356. * @method
  2357. * @param {number} x - The value to pingpong.
  2358. * @param {number} [length=1] - The positive value the function will pingpong to.
  2359. * @return {number} The alternated value.
  2360. */
  2361. pingpong: pingpong,
  2362. /**
  2363. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  2364. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  2365. * the `min` and `max`.
  2366. *
  2367. * See [Smoothstep](http://en.wikipedia.org/wiki/Smoothstep) for more details.
  2368. *
  2369. * @static
  2370. * @method
  2371. * @param {number} x - The value to evaluate based on its position between min and max.
  2372. * @param {number} min - The min value. Any x value below min will be `0`.
  2373. * @param {number} max - The max value. Any x value above max will be `1`.
  2374. * @return {number} The alternated value.
  2375. */
  2376. smoothstep: smoothstep,
  2377. /**
  2378. * A [variation on smoothstep](https://en.wikipedia.org/wiki/Smoothstep#Variations)
  2379. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  2380. *
  2381. * @static
  2382. * @method
  2383. * @param {number} x - The value to evaluate based on its position between min and max.
  2384. * @param {number} min - The min value. Any x value below min will be `0`.
  2385. * @param {number} max - The max value. Any x value above max will be `1`.
  2386. * @return {number} The alternated value.
  2387. */
  2388. smootherstep: smootherstep,
  2389. /**
  2390. * Returns a random integer from `<low, high>` interval.
  2391. *
  2392. * @static
  2393. * @method
  2394. * @param {number} low - The lower value boundary.
  2395. * @param {number} high - The upper value boundary
  2396. * @return {number} A random integer.
  2397. */
  2398. randInt: randInt,
  2399. /**
  2400. * Returns a random float from `<low, high>` interval.
  2401. *
  2402. * @static
  2403. * @method
  2404. * @param {number} low - The lower value boundary.
  2405. * @param {number} high - The upper value boundary
  2406. * @return {number} A random float.
  2407. */
  2408. randFloat: randFloat,
  2409. /**
  2410. * Returns a random integer from `<-range/2, range/2>` interval.
  2411. *
  2412. * @static
  2413. * @method
  2414. * @param {number} range - Defines the value range.
  2415. * @return {number} A random float.
  2416. */
  2417. randFloatSpread: randFloatSpread,
  2418. /**
  2419. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  2420. *
  2421. * @static
  2422. * @method
  2423. * @param {number} [s] - The integer seed.
  2424. * @return {number} A random float.
  2425. */
  2426. seededRandom: seededRandom,
  2427. /**
  2428. * Converts degrees to radians.
  2429. *
  2430. * @static
  2431. * @method
  2432. * @param {number} degrees - A value in degrees.
  2433. * @return {number} The converted value in radians.
  2434. */
  2435. degToRad: degToRad,
  2436. /**
  2437. * Converts radians to degrees.
  2438. *
  2439. * @static
  2440. * @method
  2441. * @param {number} radians - A value in radians.
  2442. * @return {number} The converted value in degrees.
  2443. */
  2444. radToDeg: radToDeg,
  2445. /**
  2446. * Returns `true` if the given number is a power of two.
  2447. *
  2448. * @static
  2449. * @method
  2450. * @param {number} value - The value to check.
  2451. * @return {boolean} Whether the given number is a power of two or not.
  2452. */
  2453. isPowerOfTwo: isPowerOfTwo,
  2454. /**
  2455. * Returns the smallest power of two that is greater than or equal to the given number.
  2456. *
  2457. * @static
  2458. * @method
  2459. * @param {number} value - The value to find a POT for.
  2460. * @return {number} The smallest power of two that is greater than or equal to the given number.
  2461. */
  2462. ceilPowerOfTwo: ceilPowerOfTwo,
  2463. /**
  2464. * Returns the largest power of two that is less than or equal to the given number.
  2465. *
  2466. * @static
  2467. * @method
  2468. * @param {number} value - The value to find a POT for.
  2469. * @return {number} The largest power of two that is less than or equal to the given number.
  2470. */
  2471. floorPowerOfTwo: floorPowerOfTwo,
  2472. /**
  2473. * Sets the given quaternion from the [Intrinsic Proper Euler Angles](https://en.wikipedia.org/wiki/Euler_angles)
  2474. * defined by the given angles and order.
  2475. *
  2476. * Rotations are applied to the axes in the order specified by order:
  2477. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  2478. *
  2479. * @static
  2480. * @method
  2481. * @param {Quaternion} q - The quaternion to set.
  2482. * @param {number} a - The rotation applied to the first axis, in radians.
  2483. * @param {number} b - The rotation applied to the second axis, in radians.
  2484. * @param {number} c - The rotation applied to the third axis, in radians.
  2485. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  2486. */
  2487. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  2488. /**
  2489. * Normalizes the given value according to the given typed array.
  2490. *
  2491. * @static
  2492. * @method
  2493. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2494. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2495. * @return {number} The normalize value.
  2496. */
  2497. normalize: normalize,
  2498. /**
  2499. * Denormalizes the given value according to the given typed array.
  2500. *
  2501. * @static
  2502. * @method
  2503. * @param {number} value - The value to denormalize.
  2504. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2505. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2506. */
  2507. denormalize: denormalize
  2508. };
  2509. /**
  2510. * Class representing a 2D vector. A 2D vector is an ordered pair of numbers
  2511. * (labeled x and y), which can be used to represent a number of things, such as:
  2512. *
  2513. * - A point in 2D space (i.e. a position on a plane).
  2514. * - A direction and length across a plane. In three.js the length will
  2515. * always be the Euclidean distance(straight-line distance) from `(0, 0)` to `(x, y)`
  2516. * and the direction is also measured from `(0, 0)` towards `(x, y)`.
  2517. * - Any arbitrary ordered pair of numbers.
  2518. *
  2519. * There are other things a 2D vector can be used to represent, such as
  2520. * momentum vectors, complex numbers and so on, however these are the most
  2521. * common uses in three.js.
  2522. *
  2523. * Iterating through a vector instance will yield its components `(x, y)` in
  2524. * the corresponding order.
  2525. * ```js
  2526. * const a = new THREE.Vector2( 0, 1 );
  2527. *
  2528. * //no arguments; will be initialised to (0, 0)
  2529. * const b = new THREE.Vector2( );
  2530. *
  2531. * const d = a.distanceTo( b );
  2532. * ```
  2533. */
  2534. class Vector2 {
  2535. static {
  2536. /**
  2537. * This flag can be used for type testing.
  2538. *
  2539. * @type {boolean}
  2540. * @readonly
  2541. * @default true
  2542. */
  2543. Vector2.prototype.isVector2 = true;
  2544. }
  2545. /**
  2546. * Constructs a new 2D vector.
  2547. *
  2548. * @param {number} [x=0] - The x value of this vector.
  2549. * @param {number} [y=0] - The y value of this vector.
  2550. */
  2551. constructor( x = 0, y = 0 ) {
  2552. /**
  2553. * The x value of this vector.
  2554. *
  2555. * @type {number}
  2556. */
  2557. this.x = x;
  2558. /**
  2559. * The y value of this vector.
  2560. *
  2561. * @type {number}
  2562. */
  2563. this.y = y;
  2564. }
  2565. /**
  2566. * Alias for {@link Vector2#x}.
  2567. *
  2568. * @type {number}
  2569. */
  2570. get width() {
  2571. return this.x;
  2572. }
  2573. set width( value ) {
  2574. this.x = value;
  2575. }
  2576. /**
  2577. * Alias for {@link Vector2#y}.
  2578. *
  2579. * @type {number}
  2580. */
  2581. get height() {
  2582. return this.y;
  2583. }
  2584. set height( value ) {
  2585. this.y = value;
  2586. }
  2587. /**
  2588. * Sets the vector components.
  2589. *
  2590. * @param {number} x - The value of the x component.
  2591. * @param {number} y - The value of the y component.
  2592. * @return {Vector2} A reference to this vector.
  2593. */
  2594. set( x, y ) {
  2595. this.x = x;
  2596. this.y = y;
  2597. return this;
  2598. }
  2599. /**
  2600. * Sets the vector components to the same value.
  2601. *
  2602. * @param {number} scalar - The value to set for all vector components.
  2603. * @return {Vector2} A reference to this vector.
  2604. */
  2605. setScalar( scalar ) {
  2606. this.x = scalar;
  2607. this.y = scalar;
  2608. return this;
  2609. }
  2610. /**
  2611. * Sets the vector's x component to the given value
  2612. *
  2613. * @param {number} x - The value to set.
  2614. * @return {Vector2} A reference to this vector.
  2615. */
  2616. setX( x ) {
  2617. this.x = x;
  2618. return this;
  2619. }
  2620. /**
  2621. * Sets the vector's y component to the given value
  2622. *
  2623. * @param {number} y - The value to set.
  2624. * @return {Vector2} A reference to this vector.
  2625. */
  2626. setY( y ) {
  2627. this.y = y;
  2628. return this;
  2629. }
  2630. /**
  2631. * Allows to set a vector component with an index.
  2632. *
  2633. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2634. * @param {number} value - The value to set.
  2635. * @return {Vector2} A reference to this vector.
  2636. */
  2637. setComponent( index, value ) {
  2638. switch ( index ) {
  2639. case 0: this.x = value; break;
  2640. case 1: this.y = value; break;
  2641. default: throw new Error( 'index is out of range: ' + index );
  2642. }
  2643. return this;
  2644. }
  2645. /**
  2646. * Returns the value of the vector component which matches the given index.
  2647. *
  2648. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2649. * @return {number} A vector component value.
  2650. */
  2651. getComponent( index ) {
  2652. switch ( index ) {
  2653. case 0: return this.x;
  2654. case 1: return this.y;
  2655. default: throw new Error( 'index is out of range: ' + index );
  2656. }
  2657. }
  2658. /**
  2659. * Returns a new vector with copied values from this instance.
  2660. *
  2661. * @return {Vector2} A clone of this instance.
  2662. */
  2663. clone() {
  2664. return new this.constructor( this.x, this.y );
  2665. }
  2666. /**
  2667. * Copies the values of the given vector to this instance.
  2668. *
  2669. * @param {Vector2} v - The vector to copy.
  2670. * @return {Vector2} A reference to this vector.
  2671. */
  2672. copy( v ) {
  2673. this.x = v.x;
  2674. this.y = v.y;
  2675. return this;
  2676. }
  2677. /**
  2678. * Adds the given vector to this instance.
  2679. *
  2680. * @param {Vector2} v - The vector to add.
  2681. * @return {Vector2} A reference to this vector.
  2682. */
  2683. add( v ) {
  2684. this.x += v.x;
  2685. this.y += v.y;
  2686. return this;
  2687. }
  2688. /**
  2689. * Adds the given scalar value to all components of this instance.
  2690. *
  2691. * @param {number} s - The scalar to add.
  2692. * @return {Vector2} A reference to this vector.
  2693. */
  2694. addScalar( s ) {
  2695. this.x += s;
  2696. this.y += s;
  2697. return this;
  2698. }
  2699. /**
  2700. * Adds the given vectors and stores the result in this instance.
  2701. *
  2702. * @param {Vector2} a - The first vector.
  2703. * @param {Vector2} b - The second vector.
  2704. * @return {Vector2} A reference to this vector.
  2705. */
  2706. addVectors( a, b ) {
  2707. this.x = a.x + b.x;
  2708. this.y = a.y + b.y;
  2709. return this;
  2710. }
  2711. /**
  2712. * Adds the given vector scaled by the given factor to this instance.
  2713. *
  2714. * @param {Vector2} v - The vector.
  2715. * @param {number} s - The factor that scales `v`.
  2716. * @return {Vector2} A reference to this vector.
  2717. */
  2718. addScaledVector( v, s ) {
  2719. this.x += v.x * s;
  2720. this.y += v.y * s;
  2721. return this;
  2722. }
  2723. /**
  2724. * Subtracts the given vector from this instance.
  2725. *
  2726. * @param {Vector2} v - The vector to subtract.
  2727. * @return {Vector2} A reference to this vector.
  2728. */
  2729. sub( v ) {
  2730. this.x -= v.x;
  2731. this.y -= v.y;
  2732. return this;
  2733. }
  2734. /**
  2735. * Subtracts the given scalar value from all components of this instance.
  2736. *
  2737. * @param {number} s - The scalar to subtract.
  2738. * @return {Vector2} A reference to this vector.
  2739. */
  2740. subScalar( s ) {
  2741. this.x -= s;
  2742. this.y -= s;
  2743. return this;
  2744. }
  2745. /**
  2746. * Subtracts the given vectors and stores the result in this instance.
  2747. *
  2748. * @param {Vector2} a - The first vector.
  2749. * @param {Vector2} b - The second vector.
  2750. * @return {Vector2} A reference to this vector.
  2751. */
  2752. subVectors( a, b ) {
  2753. this.x = a.x - b.x;
  2754. this.y = a.y - b.y;
  2755. return this;
  2756. }
  2757. /**
  2758. * Multiplies the given vector with this instance.
  2759. *
  2760. * @param {Vector2} v - The vector to multiply.
  2761. * @return {Vector2} A reference to this vector.
  2762. */
  2763. multiply( v ) {
  2764. this.x *= v.x;
  2765. this.y *= v.y;
  2766. return this;
  2767. }
  2768. /**
  2769. * Multiplies the given scalar value with all components of this instance.
  2770. *
  2771. * @param {number} scalar - The scalar to multiply.
  2772. * @return {Vector2} A reference to this vector.
  2773. */
  2774. multiplyScalar( scalar ) {
  2775. this.x *= scalar;
  2776. this.y *= scalar;
  2777. return this;
  2778. }
  2779. /**
  2780. * Divides this instance by the given vector.
  2781. *
  2782. * @param {Vector2} v - The vector to divide.
  2783. * @return {Vector2} A reference to this vector.
  2784. */
  2785. divide( v ) {
  2786. this.x /= v.x;
  2787. this.y /= v.y;
  2788. return this;
  2789. }
  2790. /**
  2791. * Divides this vector by the given scalar.
  2792. *
  2793. * @param {number} scalar - The scalar to divide.
  2794. * @return {Vector2} A reference to this vector.
  2795. */
  2796. divideScalar( scalar ) {
  2797. return this.multiplyScalar( 1 / scalar );
  2798. }
  2799. /**
  2800. * Multiplies this vector (with an implicit 1 as the 3rd component) by
  2801. * the given 3x3 matrix.
  2802. *
  2803. * @param {Matrix3} m - The matrix to apply.
  2804. * @return {Vector2} A reference to this vector.
  2805. */
  2806. applyMatrix3( m ) {
  2807. const x = this.x, y = this.y;
  2808. const e = m.elements;
  2809. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  2810. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  2811. return this;
  2812. }
  2813. /**
  2814. * If this vector's x or y value is greater than the given vector's x or y
  2815. * value, replace that value with the corresponding min value.
  2816. *
  2817. * @param {Vector2} v - The vector.
  2818. * @return {Vector2} A reference to this vector.
  2819. */
  2820. min( v ) {
  2821. this.x = Math.min( this.x, v.x );
  2822. this.y = Math.min( this.y, v.y );
  2823. return this;
  2824. }
  2825. /**
  2826. * If this vector's x or y value is less than the given vector's x or y
  2827. * value, replace that value with the corresponding max value.
  2828. *
  2829. * @param {Vector2} v - The vector.
  2830. * @return {Vector2} A reference to this vector.
  2831. */
  2832. max( v ) {
  2833. this.x = Math.max( this.x, v.x );
  2834. this.y = Math.max( this.y, v.y );
  2835. return this;
  2836. }
  2837. /**
  2838. * If this vector's x or y value is greater than the max vector's x or y
  2839. * value, it is replaced by the corresponding value.
  2840. * If this vector's x or y value is less than the min vector's x or y value,
  2841. * it is replaced by the corresponding value.
  2842. *
  2843. * @param {Vector2} min - The minimum x and y values.
  2844. * @param {Vector2} max - The maximum x and y values in the desired range.
  2845. * @return {Vector2} A reference to this vector.
  2846. */
  2847. clamp( min, max ) {
  2848. // assumes min < max, componentwise
  2849. this.x = clamp( this.x, min.x, max.x );
  2850. this.y = clamp( this.y, min.y, max.y );
  2851. return this;
  2852. }
  2853. /**
  2854. * If this vector's x or y values are greater than the max value, they are
  2855. * replaced by the max value.
  2856. * If this vector's x or y values are less than the min value, they are
  2857. * replaced by the min value.
  2858. *
  2859. * @param {number} minVal - The minimum value the components will be clamped to.
  2860. * @param {number} maxVal - The maximum value the components will be clamped to.
  2861. * @return {Vector2} A reference to this vector.
  2862. */
  2863. clampScalar( minVal, maxVal ) {
  2864. this.x = clamp( this.x, minVal, maxVal );
  2865. this.y = clamp( this.y, minVal, maxVal );
  2866. return this;
  2867. }
  2868. /**
  2869. * If this vector's length is greater than the max value, it is replaced by
  2870. * the max value.
  2871. * If this vector's length is less than the min value, it is replaced by the
  2872. * min value.
  2873. *
  2874. * @param {number} min - The minimum value the vector length will be clamped to.
  2875. * @param {number} max - The maximum value the vector length will be clamped to.
  2876. * @return {Vector2} A reference to this vector.
  2877. */
  2878. clampLength( min, max ) {
  2879. const length = this.length();
  2880. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  2881. }
  2882. /**
  2883. * The components of this vector are rounded down to the nearest integer value.
  2884. *
  2885. * @return {Vector2} A reference to this vector.
  2886. */
  2887. floor() {
  2888. this.x = Math.floor( this.x );
  2889. this.y = Math.floor( this.y );
  2890. return this;
  2891. }
  2892. /**
  2893. * The components of this vector are rounded up to the nearest integer value.
  2894. *
  2895. * @return {Vector2} A reference to this vector.
  2896. */
  2897. ceil() {
  2898. this.x = Math.ceil( this.x );
  2899. this.y = Math.ceil( this.y );
  2900. return this;
  2901. }
  2902. /**
  2903. * The components of this vector are rounded to the nearest integer value
  2904. *
  2905. * @return {Vector2} A reference to this vector.
  2906. */
  2907. round() {
  2908. this.x = Math.round( this.x );
  2909. this.y = Math.round( this.y );
  2910. return this;
  2911. }
  2912. /**
  2913. * The components of this vector are rounded towards zero (up if negative,
  2914. * down if positive) to an integer value.
  2915. *
  2916. * @return {Vector2} A reference to this vector.
  2917. */
  2918. roundToZero() {
  2919. this.x = Math.trunc( this.x );
  2920. this.y = Math.trunc( this.y );
  2921. return this;
  2922. }
  2923. /**
  2924. * Inverts this vector - i.e. sets x = -x and y = -y.
  2925. *
  2926. * @return {Vector2} A reference to this vector.
  2927. */
  2928. negate() {
  2929. this.x = - this.x;
  2930. this.y = - this.y;
  2931. return this;
  2932. }
  2933. /**
  2934. * Calculates the dot product of the given vector with this instance.
  2935. *
  2936. * @param {Vector2} v - The vector to compute the dot product with.
  2937. * @return {number} The result of the dot product.
  2938. */
  2939. dot( v ) {
  2940. return this.x * v.x + this.y * v.y;
  2941. }
  2942. /**
  2943. * Calculates the cross product of the given vector with this instance.
  2944. *
  2945. * @param {Vector2} v - The vector to compute the cross product with.
  2946. * @return {number} The result of the cross product.
  2947. */
  2948. cross( v ) {
  2949. return this.x * v.y - this.y * v.x;
  2950. }
  2951. /**
  2952. * Computes the square of the Euclidean length (straight-line length) from
  2953. * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should
  2954. * compare the length squared instead as it is slightly more efficient to calculate.
  2955. *
  2956. * @return {number} The square length of this vector.
  2957. */
  2958. lengthSq() {
  2959. return this.x * this.x + this.y * this.y;
  2960. }
  2961. /**
  2962. * Computes the Euclidean length (straight-line length) from (0, 0) to (x, y).
  2963. *
  2964. * @return {number} The length of this vector.
  2965. */
  2966. length() {
  2967. return Math.sqrt( this.x * this.x + this.y * this.y );
  2968. }
  2969. /**
  2970. * Computes the Manhattan length of this vector.
  2971. *
  2972. * @return {number} The length of this vector.
  2973. */
  2974. manhattanLength() {
  2975. return Math.abs( this.x ) + Math.abs( this.y );
  2976. }
  2977. /**
  2978. * Converts this vector to a unit vector - that is, sets it equal to a vector
  2979. * with the same direction as this one, but with a vector length of `1`.
  2980. *
  2981. * @return {Vector2} A reference to this vector.
  2982. */
  2983. normalize() {
  2984. return this.divideScalar( this.length() || 1 );
  2985. }
  2986. /**
  2987. * Computes the angle in radians of this vector with respect to the positive x-axis.
  2988. *
  2989. * @return {number} The angle in radians.
  2990. */
  2991. angle() {
  2992. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  2993. return angle;
  2994. }
  2995. /**
  2996. * Returns the angle between the given vector and this instance in radians.
  2997. *
  2998. * @param {Vector2} v - The vector to compute the angle with.
  2999. * @return {number} The angle in radians.
  3000. */
  3001. angleTo( v ) {
  3002. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  3003. if ( denominator === 0 ) return Math.PI / 2;
  3004. const theta = this.dot( v ) / denominator;
  3005. // clamp, to handle numerical problems
  3006. return Math.acos( clamp( theta, -1, 1 ) );
  3007. }
  3008. /**
  3009. * Computes the distance from the given vector to this instance.
  3010. *
  3011. * @param {Vector2} v - The vector to compute the distance to.
  3012. * @return {number} The distance.
  3013. */
  3014. distanceTo( v ) {
  3015. return Math.sqrt( this.distanceToSquared( v ) );
  3016. }
  3017. /**
  3018. * Computes the squared distance from the given vector to this instance.
  3019. * If you are just comparing the distance with another distance, you should compare
  3020. * the distance squared instead as it is slightly more efficient to calculate.
  3021. *
  3022. * @param {Vector2} v - The vector to compute the squared distance to.
  3023. * @return {number} The squared distance.
  3024. */
  3025. distanceToSquared( v ) {
  3026. const dx = this.x - v.x, dy = this.y - v.y;
  3027. return dx * dx + dy * dy;
  3028. }
  3029. /**
  3030. * Computes the Manhattan distance from the given vector to this instance.
  3031. *
  3032. * @param {Vector2} v - The vector to compute the Manhattan distance to.
  3033. * @return {number} The Manhattan distance.
  3034. */
  3035. manhattanDistanceTo( v ) {
  3036. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  3037. }
  3038. /**
  3039. * Sets this vector to a vector with the same direction as this one, but
  3040. * with the specified length.
  3041. *
  3042. * @param {number} length - The new length of this vector.
  3043. * @return {Vector2} A reference to this vector.
  3044. */
  3045. setLength( length ) {
  3046. return this.normalize().multiplyScalar( length );
  3047. }
  3048. /**
  3049. * Linearly interpolates between the given vector and this instance, where
  3050. * alpha is the percent distance along the line - alpha = 0 will be this
  3051. * vector, and alpha = 1 will be the given one.
  3052. *
  3053. * @param {Vector2} v - The vector to interpolate towards.
  3054. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  3055. * @return {Vector2} A reference to this vector.
  3056. */
  3057. lerp( v, alpha ) {
  3058. this.x += ( v.x - this.x ) * alpha;
  3059. this.y += ( v.y - this.y ) * alpha;
  3060. return this;
  3061. }
  3062. /**
  3063. * Linearly interpolates between the given vectors, where alpha is the percent
  3064. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  3065. * be the second one. The result is stored in this instance.
  3066. *
  3067. * @param {Vector2} v1 - The first vector.
  3068. * @param {Vector2} v2 - The second vector.
  3069. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  3070. * @return {Vector2} A reference to this vector.
  3071. */
  3072. lerpVectors( v1, v2, alpha ) {
  3073. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  3074. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  3075. return this;
  3076. }
  3077. /**
  3078. * Returns `true` if this vector is equal with the given one.
  3079. *
  3080. * @param {Vector2} v - The vector to test for equality.
  3081. * @return {boolean} Whether this vector is equal with the given one.
  3082. */
  3083. equals( v ) {
  3084. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  3085. }
  3086. /**
  3087. * Sets this vector's x value to be `array[ offset ]` and y
  3088. * value to be `array[ offset + 1 ]`.
  3089. *
  3090. * @param {Array<number>} array - An array holding the vector component values.
  3091. * @param {number} [offset=0] - The offset into the array.
  3092. * @return {Vector2} A reference to this vector.
  3093. */
  3094. fromArray( array, offset = 0 ) {
  3095. this.x = array[ offset ];
  3096. this.y = array[ offset + 1 ];
  3097. return this;
  3098. }
  3099. /**
  3100. * Writes the components of this vector to the given array. If no array is provided,
  3101. * the method returns a new instance.
  3102. *
  3103. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  3104. * @param {number} [offset=0] - Index of the first element in the array.
  3105. * @return {Array<number>} The vector components.
  3106. */
  3107. toArray( array = [], offset = 0 ) {
  3108. array[ offset ] = this.x;
  3109. array[ offset + 1 ] = this.y;
  3110. return array;
  3111. }
  3112. /**
  3113. * Sets the components of this vector from the given buffer attribute.
  3114. *
  3115. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  3116. * @param {number} index - The index into the attribute.
  3117. * @return {Vector2} A reference to this vector.
  3118. */
  3119. fromBufferAttribute( attribute, index ) {
  3120. this.x = attribute.getX( index );
  3121. this.y = attribute.getY( index );
  3122. return this;
  3123. }
  3124. /**
  3125. * Rotates this vector around the given center by the given angle.
  3126. *
  3127. * @param {Vector2} center - The point around which to rotate.
  3128. * @param {number} angle - The angle to rotate, in radians.
  3129. * @return {Vector2} A reference to this vector.
  3130. */
  3131. rotateAround( center, angle ) {
  3132. const c = Math.cos( angle ), s = Math.sin( angle );
  3133. const x = this.x - center.x;
  3134. const y = this.y - center.y;
  3135. this.x = x * c - y * s + center.x;
  3136. this.y = x * s + y * c + center.y;
  3137. return this;
  3138. }
  3139. /**
  3140. * Sets each component of this vector to a pseudo-random value between `0` and
  3141. * `1`, excluding `1`.
  3142. *
  3143. * @return {Vector2} A reference to this vector.
  3144. */
  3145. random() {
  3146. this.x = Math.random();
  3147. this.y = Math.random();
  3148. return this;
  3149. }
  3150. *[ Symbol.iterator ]() {
  3151. yield this.x;
  3152. yield this.y;
  3153. }
  3154. }
  3155. /**
  3156. * Class for representing a Quaternion. Quaternions are used in three.js to represent rotations.
  3157. *
  3158. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  3159. * the corresponding order.
  3160. *
  3161. * Note that three.js expects Quaternions to be normalized.
  3162. * ```js
  3163. * const quaternion = new THREE.Quaternion();
  3164. * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 );
  3165. *
  3166. * const vector = new THREE.Vector3( 1, 0, 0 );
  3167. * vector.applyQuaternion( quaternion );
  3168. * ```
  3169. */
  3170. class Quaternion {
  3171. /**
  3172. * Constructs a new quaternion.
  3173. *
  3174. * @param {number} [x=0] - The x value of this quaternion.
  3175. * @param {number} [y=0] - The y value of this quaternion.
  3176. * @param {number} [z=0] - The z value of this quaternion.
  3177. * @param {number} [w=1] - The w value of this quaternion.
  3178. */
  3179. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  3180. /**
  3181. * This flag can be used for type testing.
  3182. *
  3183. * @type {boolean}
  3184. * @readonly
  3185. * @default true
  3186. */
  3187. this.isQuaternion = true;
  3188. this._x = x;
  3189. this._y = y;
  3190. this._z = z;
  3191. this._w = w;
  3192. }
  3193. /**
  3194. * Interpolates between two quaternions via SLERP. This implementation assumes the
  3195. * quaternion data are managed in flat arrays.
  3196. *
  3197. * @param {Array<number>} dst - The destination array.
  3198. * @param {number} dstOffset - An offset into the destination array.
  3199. * @param {Array<number>} src0 - The source array of the first quaternion.
  3200. * @param {number} srcOffset0 - An offset into the first source array.
  3201. * @param {Array<number>} src1 - The source array of the second quaternion.
  3202. * @param {number} srcOffset1 - An offset into the second source array.
  3203. * @param {number} t - The interpolation factor. A value in the range `[0,1]` will interpolate. A value outside the range `[0,1]` will extrapolate.
  3204. * @see {@link Quaternion#slerp}
  3205. */
  3206. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  3207. let x0 = src0[ srcOffset0 + 0 ],
  3208. y0 = src0[ srcOffset0 + 1 ],
  3209. z0 = src0[ srcOffset0 + 2 ],
  3210. w0 = src0[ srcOffset0 + 3 ];
  3211. let x1 = src1[ srcOffset1 + 0 ],
  3212. y1 = src1[ srcOffset1 + 1 ],
  3213. z1 = src1[ srcOffset1 + 2 ],
  3214. w1 = src1[ srcOffset1 + 3 ];
  3215. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  3216. let dot = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1;
  3217. if ( dot < 0 ) {
  3218. x1 = - x1;
  3219. y1 = - y1;
  3220. z1 = - z1;
  3221. w1 = - w1;
  3222. dot = - dot;
  3223. }
  3224. let s = 1 - t;
  3225. if ( dot < 0.9995 ) {
  3226. // slerp
  3227. const theta = Math.acos( dot );
  3228. const sin = Math.sin( theta );
  3229. s = Math.sin( s * theta ) / sin;
  3230. t = Math.sin( t * theta ) / sin;
  3231. x0 = x0 * s + x1 * t;
  3232. y0 = y0 * s + y1 * t;
  3233. z0 = z0 * s + z1 * t;
  3234. w0 = w0 * s + w1 * t;
  3235. } else {
  3236. // for small angles, lerp then normalize
  3237. x0 = x0 * s + x1 * t;
  3238. y0 = y0 * s + y1 * t;
  3239. z0 = z0 * s + z1 * t;
  3240. w0 = w0 * s + w1 * t;
  3241. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  3242. x0 *= f;
  3243. y0 *= f;
  3244. z0 *= f;
  3245. w0 *= f;
  3246. }
  3247. }
  3248. dst[ dstOffset ] = x0;
  3249. dst[ dstOffset + 1 ] = y0;
  3250. dst[ dstOffset + 2 ] = z0;
  3251. dst[ dstOffset + 3 ] = w0;
  3252. }
  3253. /**
  3254. * Multiplies two quaternions. This implementation assumes the quaternion data are managed
  3255. * in flat arrays.
  3256. *
  3257. * @param {Array<number>} dst - The destination array.
  3258. * @param {number} dstOffset - An offset into the destination array.
  3259. * @param {Array<number>} src0 - The source array of the first quaternion.
  3260. * @param {number} srcOffset0 - An offset into the first source array.
  3261. * @param {Array<number>} src1 - The source array of the second quaternion.
  3262. * @param {number} srcOffset1 - An offset into the second source array.
  3263. * @return {Array<number>} The destination array.
  3264. * @see {@link Quaternion#multiplyQuaternions}.
  3265. */
  3266. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  3267. const x0 = src0[ srcOffset0 ];
  3268. const y0 = src0[ srcOffset0 + 1 ];
  3269. const z0 = src0[ srcOffset0 + 2 ];
  3270. const w0 = src0[ srcOffset0 + 3 ];
  3271. const x1 = src1[ srcOffset1 ];
  3272. const y1 = src1[ srcOffset1 + 1 ];
  3273. const z1 = src1[ srcOffset1 + 2 ];
  3274. const w1 = src1[ srcOffset1 + 3 ];
  3275. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  3276. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  3277. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  3278. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  3279. return dst;
  3280. }
  3281. /**
  3282. * The x value of this quaternion.
  3283. *
  3284. * @type {number}
  3285. * @default 0
  3286. */
  3287. get x() {
  3288. return this._x;
  3289. }
  3290. set x( value ) {
  3291. this._x = value;
  3292. this._onChangeCallback();
  3293. }
  3294. /**
  3295. * The y value of this quaternion.
  3296. *
  3297. * @type {number}
  3298. * @default 0
  3299. */
  3300. get y() {
  3301. return this._y;
  3302. }
  3303. set y( value ) {
  3304. this._y = value;
  3305. this._onChangeCallback();
  3306. }
  3307. /**
  3308. * The z value of this quaternion.
  3309. *
  3310. * @type {number}
  3311. * @default 0
  3312. */
  3313. get z() {
  3314. return this._z;
  3315. }
  3316. set z( value ) {
  3317. this._z = value;
  3318. this._onChangeCallback();
  3319. }
  3320. /**
  3321. * The w value of this quaternion.
  3322. *
  3323. * @type {number}
  3324. * @default 1
  3325. */
  3326. get w() {
  3327. return this._w;
  3328. }
  3329. set w( value ) {
  3330. this._w = value;
  3331. this._onChangeCallback();
  3332. }
  3333. /**
  3334. * Sets the quaternion components.
  3335. *
  3336. * @param {number} x - The x value of this quaternion.
  3337. * @param {number} y - The y value of this quaternion.
  3338. * @param {number} z - The z value of this quaternion.
  3339. * @param {number} w - The w value of this quaternion.
  3340. * @return {Quaternion} A reference to this quaternion.
  3341. */
  3342. set( x, y, z, w ) {
  3343. this._x = x;
  3344. this._y = y;
  3345. this._z = z;
  3346. this._w = w;
  3347. this._onChangeCallback();
  3348. return this;
  3349. }
  3350. /**
  3351. * Returns a new quaternion with copied values from this instance.
  3352. *
  3353. * @return {Quaternion} A clone of this instance.
  3354. */
  3355. clone() {
  3356. return new this.constructor( this._x, this._y, this._z, this._w );
  3357. }
  3358. /**
  3359. * Copies the values of the given quaternion to this instance.
  3360. *
  3361. * @param {Quaternion} quaternion - The quaternion to copy.
  3362. * @return {Quaternion} A reference to this quaternion.
  3363. */
  3364. copy( quaternion ) {
  3365. this._x = quaternion.x;
  3366. this._y = quaternion.y;
  3367. this._z = quaternion.z;
  3368. this._w = quaternion.w;
  3369. this._onChangeCallback();
  3370. return this;
  3371. }
  3372. /**
  3373. * Sets this quaternion from the rotation specified by the given
  3374. * Euler angles.
  3375. *
  3376. * @param {Euler} euler - The Euler angles.
  3377. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  3378. * @return {Quaternion} A reference to this quaternion.
  3379. */
  3380. setFromEuler( euler, update = true ) {
  3381. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  3382. // http://www.mathworks.com/matlabcentral/fileexchange/
  3383. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  3384. // content/SpinCalc.m
  3385. const cos = Math.cos;
  3386. const sin = Math.sin;
  3387. const c1 = cos( x / 2 );
  3388. const c2 = cos( y / 2 );
  3389. const c3 = cos( z / 2 );
  3390. const s1 = sin( x / 2 );
  3391. const s2 = sin( y / 2 );
  3392. const s3 = sin( z / 2 );
  3393. switch ( order ) {
  3394. case 'XYZ':
  3395. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3396. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3397. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3398. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3399. break;
  3400. case 'YXZ':
  3401. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3402. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3403. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3404. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3405. break;
  3406. case 'ZXY':
  3407. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3408. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3409. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3410. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3411. break;
  3412. case 'ZYX':
  3413. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3414. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3415. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3416. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3417. break;
  3418. case 'YZX':
  3419. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3420. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3421. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3422. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3423. break;
  3424. case 'XZY':
  3425. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3426. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3427. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3428. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3429. break;
  3430. default:
  3431. warn( 'Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  3432. }
  3433. if ( update === true ) this._onChangeCallback();
  3434. return this;
  3435. }
  3436. /**
  3437. * Sets this quaternion from the given axis and angle.
  3438. *
  3439. * @param {Vector3} axis - The normalized axis.
  3440. * @param {number} angle - The angle in radians.
  3441. * @return {Quaternion} A reference to this quaternion.
  3442. */
  3443. setFromAxisAngle( axis, angle ) {
  3444. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  3445. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  3446. this._x = axis.x * s;
  3447. this._y = axis.y * s;
  3448. this._z = axis.z * s;
  3449. this._w = Math.cos( halfAngle );
  3450. this._onChangeCallback();
  3451. return this;
  3452. }
  3453. /**
  3454. * Sets this quaternion from the given rotation matrix.
  3455. *
  3456. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  3457. * @return {Quaternion} A reference to this quaternion.
  3458. */
  3459. setFromRotationMatrix( m ) {
  3460. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  3461. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3462. const te = m.elements,
  3463. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  3464. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  3465. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  3466. trace = m11 + m22 + m33;
  3467. if ( trace > 0 ) {
  3468. const s = 0.5 / Math.sqrt( trace + 1.0 );
  3469. this._w = 0.25 / s;
  3470. this._x = ( m32 - m23 ) * s;
  3471. this._y = ( m13 - m31 ) * s;
  3472. this._z = ( m21 - m12 ) * s;
  3473. } else if ( m11 > m22 && m11 > m33 ) {
  3474. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  3475. this._w = ( m32 - m23 ) / s;
  3476. this._x = 0.25 * s;
  3477. this._y = ( m12 + m21 ) / s;
  3478. this._z = ( m13 + m31 ) / s;
  3479. } else if ( m22 > m33 ) {
  3480. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  3481. this._w = ( m13 - m31 ) / s;
  3482. this._x = ( m12 + m21 ) / s;
  3483. this._y = 0.25 * s;
  3484. this._z = ( m23 + m32 ) / s;
  3485. } else {
  3486. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  3487. this._w = ( m21 - m12 ) / s;
  3488. this._x = ( m13 + m31 ) / s;
  3489. this._y = ( m23 + m32 ) / s;
  3490. this._z = 0.25 * s;
  3491. }
  3492. this._onChangeCallback();
  3493. return this;
  3494. }
  3495. /**
  3496. * Sets this quaternion to the rotation required to rotate the direction vector
  3497. * `vFrom` to the direction vector `vTo`.
  3498. *
  3499. * @param {Vector3} vFrom - The first (normalized) direction vector.
  3500. * @param {Vector3} vTo - The second (normalized) direction vector.
  3501. * @return {Quaternion} A reference to this quaternion.
  3502. */
  3503. setFromUnitVectors( vFrom, vTo ) {
  3504. // assumes direction vectors vFrom and vTo are normalized
  3505. let r = vFrom.dot( vTo ) + 1;
  3506. if ( r < 1e-8 ) { // the epsilon value has been discussed in #31286
  3507. // vFrom and vTo point in opposite directions
  3508. r = 0;
  3509. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  3510. this._x = - vFrom.y;
  3511. this._y = vFrom.x;
  3512. this._z = 0;
  3513. this._w = r;
  3514. } else {
  3515. this._x = 0;
  3516. this._y = - vFrom.z;
  3517. this._z = vFrom.y;
  3518. this._w = r;
  3519. }
  3520. } else {
  3521. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  3522. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  3523. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  3524. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  3525. this._w = r;
  3526. }
  3527. return this.normalize();
  3528. }
  3529. /**
  3530. * Returns the angle between this quaternion and the given one in radians.
  3531. *
  3532. * @param {Quaternion} q - The quaternion to compute the angle with.
  3533. * @return {number} The angle in radians.
  3534. */
  3535. angleTo( q ) {
  3536. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), -1, 1 ) ) );
  3537. }
  3538. /**
  3539. * Rotates this quaternion by a given angular step to the given quaternion.
  3540. * The method ensures that the final quaternion will not overshoot `q`.
  3541. *
  3542. * @param {Quaternion} q - The target quaternion.
  3543. * @param {number} step - The angular step in radians.
  3544. * @return {Quaternion} A reference to this quaternion.
  3545. */
  3546. rotateTowards( q, step ) {
  3547. const angle = this.angleTo( q );
  3548. if ( angle === 0 ) return this;
  3549. const t = Math.min( 1, step / angle );
  3550. this.slerp( q, t );
  3551. return this;
  3552. }
  3553. /**
  3554. * Sets this quaternion to the identity quaternion; that is, to the
  3555. * quaternion that represents "no rotation".
  3556. *
  3557. * @return {Quaternion} A reference to this quaternion.
  3558. */
  3559. identity() {
  3560. return this.set( 0, 0, 0, 1 );
  3561. }
  3562. /**
  3563. * Inverts this quaternion via {@link Quaternion#conjugate}. The
  3564. * quaternion is assumed to have unit length.
  3565. *
  3566. * @return {Quaternion} A reference to this quaternion.
  3567. */
  3568. invert() {
  3569. return this.conjugate();
  3570. }
  3571. /**
  3572. * Returns the rotational conjugate of this quaternion. The conjugate of a
  3573. * quaternion represents the same rotation in the opposite direction about
  3574. * the rotational axis.
  3575. *
  3576. * @return {Quaternion} A reference to this quaternion.
  3577. */
  3578. conjugate() {
  3579. this._x *= -1;
  3580. this._y *= -1;
  3581. this._z *= -1;
  3582. this._onChangeCallback();
  3583. return this;
  3584. }
  3585. /**
  3586. * Calculates the dot product of this quaternion and the given one.
  3587. *
  3588. * @param {Quaternion} v - The quaternion to compute the dot product with.
  3589. * @return {number} The result of the dot product.
  3590. */
  3591. dot( v ) {
  3592. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  3593. }
  3594. /**
  3595. * Computes the squared Euclidean length (straight-line length) of this quaternion,
  3596. * considered as a 4 dimensional vector. This can be useful if you are comparing the
  3597. * lengths of two quaternions, as this is a slightly more efficient calculation than
  3598. * {@link Quaternion#length}.
  3599. *
  3600. * @return {number} The squared Euclidean length.
  3601. */
  3602. lengthSq() {
  3603. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  3604. }
  3605. /**
  3606. * Computes the Euclidean length (straight-line length) of this quaternion,
  3607. * considered as a 4 dimensional vector.
  3608. *
  3609. * @return {number} The Euclidean length.
  3610. */
  3611. length() {
  3612. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  3613. }
  3614. /**
  3615. * Normalizes this quaternion - that is, calculated the quaternion that performs
  3616. * the same rotation as this one, but has a length equal to `1`.
  3617. *
  3618. * @return {Quaternion} A reference to this quaternion.
  3619. */
  3620. normalize() {
  3621. let l = this.length();
  3622. if ( l === 0 ) {
  3623. this._x = 0;
  3624. this._y = 0;
  3625. this._z = 0;
  3626. this._w = 1;
  3627. } else {
  3628. l = 1 / l;
  3629. this._x = this._x * l;
  3630. this._y = this._y * l;
  3631. this._z = this._z * l;
  3632. this._w = this._w * l;
  3633. }
  3634. this._onChangeCallback();
  3635. return this;
  3636. }
  3637. /**
  3638. * Multiplies this quaternion by the given one.
  3639. *
  3640. * @param {Quaternion} q - The quaternion.
  3641. * @return {Quaternion} A reference to this quaternion.
  3642. */
  3643. multiply( q ) {
  3644. return this.multiplyQuaternions( this, q );
  3645. }
  3646. /**
  3647. * Pre-multiplies this quaternion by the given one.
  3648. *
  3649. * @param {Quaternion} q - The quaternion.
  3650. * @return {Quaternion} A reference to this quaternion.
  3651. */
  3652. premultiply( q ) {
  3653. return this.multiplyQuaternions( q, this );
  3654. }
  3655. /**
  3656. * Multiplies the given quaternions and stores the result in this instance.
  3657. *
  3658. * @param {Quaternion} a - The first quaternion.
  3659. * @param {Quaternion} b - The second quaternion.
  3660. * @return {Quaternion} A reference to this quaternion.
  3661. */
  3662. multiplyQuaternions( a, b ) {
  3663. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  3664. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  3665. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  3666. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  3667. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  3668. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  3669. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  3670. this._onChangeCallback();
  3671. return this;
  3672. }
  3673. /**
  3674. * Performs a spherical linear interpolation between this quaternion and the target quaternion.
  3675. *
  3676. * @param {Quaternion} qb - The target quaternion.
  3677. * @param {number} t - The interpolation factor. A value in the range `[0,1]` will interpolate. A value outside the range `[0,1]` will extrapolate.
  3678. * @return {Quaternion} A reference to this quaternion.
  3679. */
  3680. slerp( qb, t ) {
  3681. let x = qb._x, y = qb._y, z = qb._z, w = qb._w;
  3682. let dot = this.dot( qb );
  3683. if ( dot < 0 ) {
  3684. x = - x;
  3685. y = - y;
  3686. z = - z;
  3687. w = - w;
  3688. dot = - dot;
  3689. }
  3690. let s = 1 - t;
  3691. if ( dot < 0.9995 ) {
  3692. // slerp
  3693. const theta = Math.acos( dot );
  3694. const sin = Math.sin( theta );
  3695. s = Math.sin( s * theta ) / sin;
  3696. t = Math.sin( t * theta ) / sin;
  3697. this._x = this._x * s + x * t;
  3698. this._y = this._y * s + y * t;
  3699. this._z = this._z * s + z * t;
  3700. this._w = this._w * s + w * t;
  3701. this._onChangeCallback();
  3702. } else {
  3703. // for small angles, lerp then normalize
  3704. this._x = this._x * s + x * t;
  3705. this._y = this._y * s + y * t;
  3706. this._z = this._z * s + z * t;
  3707. this._w = this._w * s + w * t;
  3708. this.normalize(); // normalize calls _onChangeCallback()
  3709. }
  3710. return this;
  3711. }
  3712. /**
  3713. * Performs a spherical linear interpolation between the given quaternions
  3714. * and stores the result in this quaternion.
  3715. *
  3716. * @param {Quaternion} qa - The source quaternion.
  3717. * @param {Quaternion} qb - The target quaternion.
  3718. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  3719. * @return {Quaternion} A reference to this quaternion.
  3720. */
  3721. slerpQuaternions( qa, qb, t ) {
  3722. return this.copy( qa ).slerp( qb, t );
  3723. }
  3724. /**
  3725. * Sets this quaternion to a uniformly random, normalized quaternion.
  3726. *
  3727. * @return {Quaternion} A reference to this quaternion.
  3728. */
  3729. random() {
  3730. // Ken Shoemake
  3731. // Uniform random rotations
  3732. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  3733. const theta1 = 2 * Math.PI * Math.random();
  3734. const theta2 = 2 * Math.PI * Math.random();
  3735. const x0 = Math.random();
  3736. const r1 = Math.sqrt( 1 - x0 );
  3737. const r2 = Math.sqrt( x0 );
  3738. return this.set(
  3739. r1 * Math.sin( theta1 ),
  3740. r1 * Math.cos( theta1 ),
  3741. r2 * Math.sin( theta2 ),
  3742. r2 * Math.cos( theta2 ),
  3743. );
  3744. }
  3745. /**
  3746. * Returns `true` if this quaternion is equal with the given one.
  3747. *
  3748. * @param {Quaternion} quaternion - The quaternion to test for equality.
  3749. * @return {boolean} Whether this quaternion is equal with the given one.
  3750. */
  3751. equals( quaternion ) {
  3752. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  3753. }
  3754. /**
  3755. * Sets this quaternion's components from the given array.
  3756. *
  3757. * @param {Array<number>} array - An array holding the quaternion component values.
  3758. * @param {number} [offset=0] - The offset into the array.
  3759. * @return {Quaternion} A reference to this quaternion.
  3760. */
  3761. fromArray( array, offset = 0 ) {
  3762. this._x = array[ offset ];
  3763. this._y = array[ offset + 1 ];
  3764. this._z = array[ offset + 2 ];
  3765. this._w = array[ offset + 3 ];
  3766. this._onChangeCallback();
  3767. return this;
  3768. }
  3769. /**
  3770. * Writes the components of this quaternion to the given array. If no array is provided,
  3771. * the method returns a new instance.
  3772. *
  3773. * @param {Array<number>} [array=[]] - The target array holding the quaternion components.
  3774. * @param {number} [offset=0] - Index of the first element in the array.
  3775. * @return {Array<number>} The quaternion components.
  3776. */
  3777. toArray( array = [], offset = 0 ) {
  3778. array[ offset ] = this._x;
  3779. array[ offset + 1 ] = this._y;
  3780. array[ offset + 2 ] = this._z;
  3781. array[ offset + 3 ] = this._w;
  3782. return array;
  3783. }
  3784. /**
  3785. * Sets the components of this quaternion from the given buffer attribute.
  3786. *
  3787. * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data.
  3788. * @param {number} index - The index into the attribute.
  3789. * @return {Quaternion} A reference to this quaternion.
  3790. */
  3791. fromBufferAttribute( attribute, index ) {
  3792. this._x = attribute.getX( index );
  3793. this._y = attribute.getY( index );
  3794. this._z = attribute.getZ( index );
  3795. this._w = attribute.getW( index );
  3796. this._onChangeCallback();
  3797. return this;
  3798. }
  3799. /**
  3800. * This methods defines the serialization result of this class. Returns the
  3801. * numerical elements of this quaternion in an array of format `[x, y, z, w]`.
  3802. *
  3803. * @return {Array<number>} The serialized quaternion.
  3804. */
  3805. toJSON() {
  3806. return this.toArray();
  3807. }
  3808. _onChange( callback ) {
  3809. this._onChangeCallback = callback;
  3810. return this;
  3811. }
  3812. _onChangeCallback() {}
  3813. *[ Symbol.iterator ]() {
  3814. yield this._x;
  3815. yield this._y;
  3816. yield this._z;
  3817. yield this._w;
  3818. }
  3819. }
  3820. /**
  3821. * Class representing a 3D vector. A 3D vector is an ordered triplet of numbers
  3822. * (labeled x, y and z), which can be used to represent a number of things, such as:
  3823. *
  3824. * - A point in 3D space.
  3825. * - A direction and length in 3D space. In three.js the length will
  3826. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0)` to `(x, y, z)`
  3827. * and the direction is also measured from `(0, 0, 0)` towards `(x, y, z)`.
  3828. * - Any arbitrary ordered triplet of numbers.
  3829. *
  3830. * There are other things a 3D vector can be used to represent, such as
  3831. * momentum vectors and so on, however these are the most
  3832. * common uses in three.js.
  3833. *
  3834. * Iterating through a vector instance will yield its components `(x, y, z)` in
  3835. * the corresponding order.
  3836. * ```js
  3837. * const a = new THREE.Vector3( 0, 1, 0 );
  3838. *
  3839. * //no arguments; will be initialised to (0, 0, 0)
  3840. * const b = new THREE.Vector3( );
  3841. *
  3842. * const d = a.distanceTo( b );
  3843. * ```
  3844. */
  3845. class Vector3 {
  3846. static {
  3847. /**
  3848. * This flag can be used for type testing.
  3849. *
  3850. * @type {boolean}
  3851. * @readonly
  3852. * @default true
  3853. */
  3854. Vector3.prototype.isVector3 = true;
  3855. }
  3856. /**
  3857. * Constructs a new 3D vector.
  3858. *
  3859. * @param {number} [x=0] - The x value of this vector.
  3860. * @param {number} [y=0] - The y value of this vector.
  3861. * @param {number} [z=0] - The z value of this vector.
  3862. */
  3863. constructor( x = 0, y = 0, z = 0 ) {
  3864. /**
  3865. * The x value of this vector.
  3866. *
  3867. * @type {number}
  3868. */
  3869. this.x = x;
  3870. /**
  3871. * The y value of this vector.
  3872. *
  3873. * @type {number}
  3874. */
  3875. this.y = y;
  3876. /**
  3877. * The z value of this vector.
  3878. *
  3879. * @type {number}
  3880. */
  3881. this.z = z;
  3882. }
  3883. /**
  3884. * Sets the vector components.
  3885. *
  3886. * @param {number} x - The value of the x component.
  3887. * @param {number} y - The value of the y component.
  3888. * @param {number} z - The value of the z component.
  3889. * @return {Vector3} A reference to this vector.
  3890. */
  3891. set( x, y, z ) {
  3892. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  3893. this.x = x;
  3894. this.y = y;
  3895. this.z = z;
  3896. return this;
  3897. }
  3898. /**
  3899. * Sets the vector components to the same value.
  3900. *
  3901. * @param {number} scalar - The value to set for all vector components.
  3902. * @return {Vector3} A reference to this vector.
  3903. */
  3904. setScalar( scalar ) {
  3905. this.x = scalar;
  3906. this.y = scalar;
  3907. this.z = scalar;
  3908. return this;
  3909. }
  3910. /**
  3911. * Sets the vector's x component to the given value.
  3912. *
  3913. * @param {number} x - The value to set.
  3914. * @return {Vector3} A reference to this vector.
  3915. */
  3916. setX( x ) {
  3917. this.x = x;
  3918. return this;
  3919. }
  3920. /**
  3921. * Sets the vector's y component to the given value.
  3922. *
  3923. * @param {number} y - The value to set.
  3924. * @return {Vector3} A reference to this vector.
  3925. */
  3926. setY( y ) {
  3927. this.y = y;
  3928. return this;
  3929. }
  3930. /**
  3931. * Sets the vector's z component to the given value.
  3932. *
  3933. * @param {number} z - The value to set.
  3934. * @return {Vector3} A reference to this vector.
  3935. */
  3936. setZ( z ) {
  3937. this.z = z;
  3938. return this;
  3939. }
  3940. /**
  3941. * Allows to set a vector component with an index.
  3942. *
  3943. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3944. * @param {number} value - The value to set.
  3945. * @return {Vector3} A reference to this vector.
  3946. */
  3947. setComponent( index, value ) {
  3948. switch ( index ) {
  3949. case 0: this.x = value; break;
  3950. case 1: this.y = value; break;
  3951. case 2: this.z = value; break;
  3952. default: throw new Error( 'index is out of range: ' + index );
  3953. }
  3954. return this;
  3955. }
  3956. /**
  3957. * Returns the value of the vector component which matches the given index.
  3958. *
  3959. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3960. * @return {number} A vector component value.
  3961. */
  3962. getComponent( index ) {
  3963. switch ( index ) {
  3964. case 0: return this.x;
  3965. case 1: return this.y;
  3966. case 2: return this.z;
  3967. default: throw new Error( 'index is out of range: ' + index );
  3968. }
  3969. }
  3970. /**
  3971. * Returns a new vector with copied values from this instance.
  3972. *
  3973. * @return {Vector3} A clone of this instance.
  3974. */
  3975. clone() {
  3976. return new this.constructor( this.x, this.y, this.z );
  3977. }
  3978. /**
  3979. * Copies the values of the given vector to this instance.
  3980. *
  3981. * @param {Vector3} v - The vector to copy.
  3982. * @return {Vector3} A reference to this vector.
  3983. */
  3984. copy( v ) {
  3985. this.x = v.x;
  3986. this.y = v.y;
  3987. this.z = v.z;
  3988. return this;
  3989. }
  3990. /**
  3991. * Adds the given vector to this instance.
  3992. *
  3993. * @param {Vector3} v - The vector to add.
  3994. * @return {Vector3} A reference to this vector.
  3995. */
  3996. add( v ) {
  3997. this.x += v.x;
  3998. this.y += v.y;
  3999. this.z += v.z;
  4000. return this;
  4001. }
  4002. /**
  4003. * Adds the given scalar value to all components of this instance.
  4004. *
  4005. * @param {number} s - The scalar to add.
  4006. * @return {Vector3} A reference to this vector.
  4007. */
  4008. addScalar( s ) {
  4009. this.x += s;
  4010. this.y += s;
  4011. this.z += s;
  4012. return this;
  4013. }
  4014. /**
  4015. * Adds the given vectors and stores the result in this instance.
  4016. *
  4017. * @param {Vector3} a - The first vector.
  4018. * @param {Vector3} b - The second vector.
  4019. * @return {Vector3} A reference to this vector.
  4020. */
  4021. addVectors( a, b ) {
  4022. this.x = a.x + b.x;
  4023. this.y = a.y + b.y;
  4024. this.z = a.z + b.z;
  4025. return this;
  4026. }
  4027. /**
  4028. * Adds the given vector scaled by the given factor to this instance.
  4029. *
  4030. * @param {Vector3|Vector4} v - The vector.
  4031. * @param {number} s - The factor that scales `v`.
  4032. * @return {Vector3} A reference to this vector.
  4033. */
  4034. addScaledVector( v, s ) {
  4035. this.x += v.x * s;
  4036. this.y += v.y * s;
  4037. this.z += v.z * s;
  4038. return this;
  4039. }
  4040. /**
  4041. * Subtracts the given vector from this instance.
  4042. *
  4043. * @param {Vector3} v - The vector to subtract.
  4044. * @return {Vector3} A reference to this vector.
  4045. */
  4046. sub( v ) {
  4047. this.x -= v.x;
  4048. this.y -= v.y;
  4049. this.z -= v.z;
  4050. return this;
  4051. }
  4052. /**
  4053. * Subtracts the given scalar value from all components of this instance.
  4054. *
  4055. * @param {number} s - The scalar to subtract.
  4056. * @return {Vector3} A reference to this vector.
  4057. */
  4058. subScalar( s ) {
  4059. this.x -= s;
  4060. this.y -= s;
  4061. this.z -= s;
  4062. return this;
  4063. }
  4064. /**
  4065. * Subtracts the given vectors and stores the result in this instance.
  4066. *
  4067. * @param {Vector3} a - The first vector.
  4068. * @param {Vector3} b - The second vector.
  4069. * @return {Vector3} A reference to this vector.
  4070. */
  4071. subVectors( a, b ) {
  4072. this.x = a.x - b.x;
  4073. this.y = a.y - b.y;
  4074. this.z = a.z - b.z;
  4075. return this;
  4076. }
  4077. /**
  4078. * Multiplies the given vector with this instance.
  4079. *
  4080. * @param {Vector3} v - The vector to multiply.
  4081. * @return {Vector3} A reference to this vector.
  4082. */
  4083. multiply( v ) {
  4084. this.x *= v.x;
  4085. this.y *= v.y;
  4086. this.z *= v.z;
  4087. return this;
  4088. }
  4089. /**
  4090. * Multiplies the given scalar value with all components of this instance.
  4091. *
  4092. * @param {number} scalar - The scalar to multiply.
  4093. * @return {Vector3} A reference to this vector.
  4094. */
  4095. multiplyScalar( scalar ) {
  4096. this.x *= scalar;
  4097. this.y *= scalar;
  4098. this.z *= scalar;
  4099. return this;
  4100. }
  4101. /**
  4102. * Multiplies the given vectors and stores the result in this instance.
  4103. *
  4104. * @param {Vector3} a - The first vector.
  4105. * @param {Vector3} b - The second vector.
  4106. * @return {Vector3} A reference to this vector.
  4107. */
  4108. multiplyVectors( a, b ) {
  4109. this.x = a.x * b.x;
  4110. this.y = a.y * b.y;
  4111. this.z = a.z * b.z;
  4112. return this;
  4113. }
  4114. /**
  4115. * Applies the given Euler rotation to this vector.
  4116. *
  4117. * @param {Euler} euler - The Euler angles.
  4118. * @return {Vector3} A reference to this vector.
  4119. */
  4120. applyEuler( euler ) {
  4121. return this.applyQuaternion( _quaternion$5.setFromEuler( euler ) );
  4122. }
  4123. /**
  4124. * Applies a rotation specified by an axis and an angle to this vector.
  4125. *
  4126. * @param {Vector3} axis - A normalized vector representing the rotation axis.
  4127. * @param {number} angle - The angle in radians.
  4128. * @return {Vector3} A reference to this vector.
  4129. */
  4130. applyAxisAngle( axis, angle ) {
  4131. return this.applyQuaternion( _quaternion$5.setFromAxisAngle( axis, angle ) );
  4132. }
  4133. /**
  4134. * Multiplies this vector with the given 3x3 matrix.
  4135. *
  4136. * @param {Matrix3} m - The 3x3 matrix.
  4137. * @return {Vector3} A reference to this vector.
  4138. */
  4139. applyMatrix3( m ) {
  4140. const x = this.x, y = this.y, z = this.z;
  4141. const e = m.elements;
  4142. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  4143. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  4144. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  4145. return this;
  4146. }
  4147. /**
  4148. * Multiplies this vector by the given normal matrix and normalizes
  4149. * the result.
  4150. *
  4151. * @param {Matrix3} m - The normal matrix.
  4152. * @return {Vector3} A reference to this vector.
  4153. */
  4154. applyNormalMatrix( m ) {
  4155. return this.applyMatrix3( m ).normalize();
  4156. }
  4157. /**
  4158. * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and
  4159. * divides by perspective.
  4160. *
  4161. * @param {Matrix4} m - The matrix to apply.
  4162. * @return {Vector3} A reference to this vector.
  4163. */
  4164. applyMatrix4( m ) {
  4165. const x = this.x, y = this.y, z = this.z;
  4166. const e = m.elements;
  4167. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  4168. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  4169. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  4170. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  4171. return this;
  4172. }
  4173. /**
  4174. * Applies the given Quaternion to this vector.
  4175. *
  4176. * @param {Quaternion} q - The Quaternion.
  4177. * @return {Vector3} A reference to this vector.
  4178. */
  4179. applyQuaternion( q ) {
  4180. // quaternion q is assumed to have unit length
  4181. const vx = this.x, vy = this.y, vz = this.z;
  4182. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  4183. // t = 2 * cross( q.xyz, v );
  4184. const tx = 2 * ( qy * vz - qz * vy );
  4185. const ty = 2 * ( qz * vx - qx * vz );
  4186. const tz = 2 * ( qx * vy - qy * vx );
  4187. // v + q.w * t + cross( q.xyz, t );
  4188. this.x = vx + qw * tx + qy * tz - qz * ty;
  4189. this.y = vy + qw * ty + qz * tx - qx * tz;
  4190. this.z = vz + qw * tz + qx * ty - qy * tx;
  4191. return this;
  4192. }
  4193. /**
  4194. * Projects this vector from world space into the camera's normalized
  4195. * device coordinate (NDC) space.
  4196. *
  4197. * @param {Camera} camera - The camera.
  4198. * @return {Vector3} A reference to this vector.
  4199. */
  4200. project( camera ) {
  4201. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  4202. }
  4203. /**
  4204. * Unprojects this vector from the camera's normalized device coordinate (NDC)
  4205. * space into world space.
  4206. *
  4207. * @param {Camera} camera - The camera.
  4208. * @return {Vector3} A reference to this vector.
  4209. */
  4210. unproject( camera ) {
  4211. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  4212. }
  4213. /**
  4214. * Transforms the direction of this vector by a matrix (the upper left 3 x 3
  4215. * subset of the given 4x4 matrix and then normalizes the result.
  4216. *
  4217. * @param {Matrix4} m - The matrix.
  4218. * @return {Vector3} A reference to this vector.
  4219. */
  4220. transformDirection( m ) {
  4221. // input: THREE.Matrix4 affine matrix
  4222. // vector interpreted as a direction
  4223. const x = this.x, y = this.y, z = this.z;
  4224. const e = m.elements;
  4225. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  4226. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  4227. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  4228. return this.normalize();
  4229. }
  4230. /**
  4231. * Divides this instance by the given vector.
  4232. *
  4233. * @param {Vector3} v - The vector to divide.
  4234. * @return {Vector3} A reference to this vector.
  4235. */
  4236. divide( v ) {
  4237. this.x /= v.x;
  4238. this.y /= v.y;
  4239. this.z /= v.z;
  4240. return this;
  4241. }
  4242. /**
  4243. * Divides this vector by the given scalar.
  4244. *
  4245. * @param {number} scalar - The scalar to divide.
  4246. * @return {Vector3} A reference to this vector.
  4247. */
  4248. divideScalar( scalar ) {
  4249. return this.multiplyScalar( 1 / scalar );
  4250. }
  4251. /**
  4252. * If this vector's x, y or z value is greater than the given vector's x, y or z
  4253. * value, replace that value with the corresponding min value.
  4254. *
  4255. * @param {Vector3} v - The vector.
  4256. * @return {Vector3} A reference to this vector.
  4257. */
  4258. min( v ) {
  4259. this.x = Math.min( this.x, v.x );
  4260. this.y = Math.min( this.y, v.y );
  4261. this.z = Math.min( this.z, v.z );
  4262. return this;
  4263. }
  4264. /**
  4265. * If this vector's x, y or z value is less than the given vector's x, y or z
  4266. * value, replace that value with the corresponding max value.
  4267. *
  4268. * @param {Vector3} v - The vector.
  4269. * @return {Vector3} A reference to this vector.
  4270. */
  4271. max( v ) {
  4272. this.x = Math.max( this.x, v.x );
  4273. this.y = Math.max( this.y, v.y );
  4274. this.z = Math.max( this.z, v.z );
  4275. return this;
  4276. }
  4277. /**
  4278. * If this vector's x, y or z value is greater than the max vector's x, y or z
  4279. * value, it is replaced by the corresponding value.
  4280. * If this vector's x, y or z value is less than the min vector's x, y or z value,
  4281. * it is replaced by the corresponding value.
  4282. *
  4283. * @param {Vector3} min - The minimum x, y and z values.
  4284. * @param {Vector3} max - The maximum x, y and z values in the desired range.
  4285. * @return {Vector3} A reference to this vector.
  4286. */
  4287. clamp( min, max ) {
  4288. // assumes min < max, componentwise
  4289. this.x = clamp( this.x, min.x, max.x );
  4290. this.y = clamp( this.y, min.y, max.y );
  4291. this.z = clamp( this.z, min.z, max.z );
  4292. return this;
  4293. }
  4294. /**
  4295. * If this vector's x, y or z values are greater than the max value, they are
  4296. * replaced by the max value.
  4297. * If this vector's x, y or z values are less than the min value, they are
  4298. * replaced by the min value.
  4299. *
  4300. * @param {number} minVal - The minimum value the components will be clamped to.
  4301. * @param {number} maxVal - The maximum value the components will be clamped to.
  4302. * @return {Vector3} A reference to this vector.
  4303. */
  4304. clampScalar( minVal, maxVal ) {
  4305. this.x = clamp( this.x, minVal, maxVal );
  4306. this.y = clamp( this.y, minVal, maxVal );
  4307. this.z = clamp( this.z, minVal, maxVal );
  4308. return this;
  4309. }
  4310. /**
  4311. * If this vector's length is greater than the max value, it is replaced by
  4312. * the max value.
  4313. * If this vector's length is less than the min value, it is replaced by the
  4314. * min value.
  4315. *
  4316. * @param {number} min - The minimum value the vector length will be clamped to.
  4317. * @param {number} max - The maximum value the vector length will be clamped to.
  4318. * @return {Vector3} A reference to this vector.
  4319. */
  4320. clampLength( min, max ) {
  4321. const length = this.length();
  4322. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  4323. }
  4324. /**
  4325. * The components of this vector are rounded down to the nearest integer value.
  4326. *
  4327. * @return {Vector3} A reference to this vector.
  4328. */
  4329. floor() {
  4330. this.x = Math.floor( this.x );
  4331. this.y = Math.floor( this.y );
  4332. this.z = Math.floor( this.z );
  4333. return this;
  4334. }
  4335. /**
  4336. * The components of this vector are rounded up to the nearest integer value.
  4337. *
  4338. * @return {Vector3} A reference to this vector.
  4339. */
  4340. ceil() {
  4341. this.x = Math.ceil( this.x );
  4342. this.y = Math.ceil( this.y );
  4343. this.z = Math.ceil( this.z );
  4344. return this;
  4345. }
  4346. /**
  4347. * The components of this vector are rounded to the nearest integer value
  4348. *
  4349. * @return {Vector3} A reference to this vector.
  4350. */
  4351. round() {
  4352. this.x = Math.round( this.x );
  4353. this.y = Math.round( this.y );
  4354. this.z = Math.round( this.z );
  4355. return this;
  4356. }
  4357. /**
  4358. * The components of this vector are rounded towards zero (up if negative,
  4359. * down if positive) to an integer value.
  4360. *
  4361. * @return {Vector3} A reference to this vector.
  4362. */
  4363. roundToZero() {
  4364. this.x = Math.trunc( this.x );
  4365. this.y = Math.trunc( this.y );
  4366. this.z = Math.trunc( this.z );
  4367. return this;
  4368. }
  4369. /**
  4370. * Inverts this vector - i.e. sets x = -x, y = -y and z = -z.
  4371. *
  4372. * @return {Vector3} A reference to this vector.
  4373. */
  4374. negate() {
  4375. this.x = - this.x;
  4376. this.y = - this.y;
  4377. this.z = - this.z;
  4378. return this;
  4379. }
  4380. /**
  4381. * Calculates the dot product of the given vector with this instance.
  4382. *
  4383. * @param {Vector3} v - The vector to compute the dot product with.
  4384. * @return {number} The result of the dot product.
  4385. */
  4386. dot( v ) {
  4387. return this.x * v.x + this.y * v.y + this.z * v.z;
  4388. }
  4389. /**
  4390. * Computes the square of the Euclidean length (straight-line length) from
  4391. * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should
  4392. * compare the length squared instead as it is slightly more efficient to calculate.
  4393. *
  4394. * @return {number} The square length of this vector.
  4395. */
  4396. lengthSq() {
  4397. return this.x * this.x + this.y * this.y + this.z * this.z;
  4398. }
  4399. /**
  4400. * Computes the Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z).
  4401. *
  4402. * @return {number} The length of this vector.
  4403. */
  4404. length() {
  4405. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  4406. }
  4407. /**
  4408. * Computes the Manhattan length of this vector.
  4409. *
  4410. * @return {number} The length of this vector.
  4411. */
  4412. manhattanLength() {
  4413. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  4414. }
  4415. /**
  4416. * Converts this vector to a unit vector - that is, sets it equal to a vector
  4417. * with the same direction as this one, but with a vector length of `1`.
  4418. *
  4419. * @return {Vector3} A reference to this vector.
  4420. */
  4421. normalize() {
  4422. return this.divideScalar( this.length() || 1 );
  4423. }
  4424. /**
  4425. * Sets this vector to a vector with the same direction as this one, but
  4426. * with the specified length.
  4427. *
  4428. * @param {number} length - The new length of this vector.
  4429. * @return {Vector3} A reference to this vector.
  4430. */
  4431. setLength( length ) {
  4432. return this.normalize().multiplyScalar( length );
  4433. }
  4434. /**
  4435. * Linearly interpolates between the given vector and this instance, where
  4436. * alpha is the percent distance along the line - alpha = 0 will be this
  4437. * vector, and alpha = 1 will be the given one.
  4438. *
  4439. * @param {Vector3} v - The vector to interpolate towards.
  4440. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4441. * @return {Vector3} A reference to this vector.
  4442. */
  4443. lerp( v, alpha ) {
  4444. this.x += ( v.x - this.x ) * alpha;
  4445. this.y += ( v.y - this.y ) * alpha;
  4446. this.z += ( v.z - this.z ) * alpha;
  4447. return this;
  4448. }
  4449. /**
  4450. * Linearly interpolates between the given vectors, where alpha is the percent
  4451. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  4452. * be the second one. The result is stored in this instance.
  4453. *
  4454. * @param {Vector3} v1 - The first vector.
  4455. * @param {Vector3} v2 - The second vector.
  4456. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4457. * @return {Vector3} A reference to this vector.
  4458. */
  4459. lerpVectors( v1, v2, alpha ) {
  4460. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  4461. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  4462. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  4463. return this;
  4464. }
  4465. /**
  4466. * Calculates the cross product of the given vector with this instance.
  4467. *
  4468. * @param {Vector3} v - The vector to compute the cross product with.
  4469. * @return {Vector3} The result of the cross product.
  4470. */
  4471. cross( v ) {
  4472. return this.crossVectors( this, v );
  4473. }
  4474. /**
  4475. * Calculates the cross product of the given vectors and stores the result
  4476. * in this instance.
  4477. *
  4478. * @param {Vector3} a - The first vector.
  4479. * @param {Vector3} b - The second vector.
  4480. * @return {Vector3} A reference to this vector.
  4481. */
  4482. crossVectors( a, b ) {
  4483. const ax = a.x, ay = a.y, az = a.z;
  4484. const bx = b.x, by = b.y, bz = b.z;
  4485. this.x = ay * bz - az * by;
  4486. this.y = az * bx - ax * bz;
  4487. this.z = ax * by - ay * bx;
  4488. return this;
  4489. }
  4490. /**
  4491. * Projects this vector onto the given one.
  4492. *
  4493. * @param {Vector3} v - The vector to project to.
  4494. * @return {Vector3} A reference to this vector.
  4495. */
  4496. projectOnVector( v ) {
  4497. const denominator = v.lengthSq();
  4498. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  4499. const scalar = v.dot( this ) / denominator;
  4500. return this.copy( v ).multiplyScalar( scalar );
  4501. }
  4502. /**
  4503. * Projects this vector onto a plane by subtracting this
  4504. * vector projected onto the plane's normal from this vector.
  4505. *
  4506. * @param {Vector3} planeNormal - The plane normal.
  4507. * @return {Vector3} A reference to this vector.
  4508. */
  4509. projectOnPlane( planeNormal ) {
  4510. _vector$c.copy( this ).projectOnVector( planeNormal );
  4511. return this.sub( _vector$c );
  4512. }
  4513. /**
  4514. * Reflects this vector off a plane orthogonal to the given normal vector.
  4515. *
  4516. * @param {Vector3} normal - The (normalized) normal vector.
  4517. * @return {Vector3} A reference to this vector.
  4518. */
  4519. reflect( normal ) {
  4520. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  4521. }
  4522. /**
  4523. * Returns the angle between the given vector and this instance in radians.
  4524. *
  4525. * @param {Vector3} v - The vector to compute the angle with.
  4526. * @return {number} The angle in radians.
  4527. */
  4528. angleTo( v ) {
  4529. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  4530. if ( denominator === 0 ) return Math.PI / 2;
  4531. const theta = this.dot( v ) / denominator;
  4532. // clamp, to handle numerical problems
  4533. return Math.acos( clamp( theta, -1, 1 ) );
  4534. }
  4535. /**
  4536. * Computes the distance from the given vector to this instance.
  4537. *
  4538. * @param {Vector3} v - The vector to compute the distance to.
  4539. * @return {number} The distance.
  4540. */
  4541. distanceTo( v ) {
  4542. return Math.sqrt( this.distanceToSquared( v ) );
  4543. }
  4544. /**
  4545. * Computes the squared distance from the given vector to this instance.
  4546. * If you are just comparing the distance with another distance, you should compare
  4547. * the distance squared instead as it is slightly more efficient to calculate.
  4548. *
  4549. * @param {Vector3} v - The vector to compute the squared distance to.
  4550. * @return {number} The squared distance.
  4551. */
  4552. distanceToSquared( v ) {
  4553. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  4554. return dx * dx + dy * dy + dz * dz;
  4555. }
  4556. /**
  4557. * Computes the Manhattan distance from the given vector to this instance.
  4558. *
  4559. * @param {Vector3} v - The vector to compute the Manhattan distance to.
  4560. * @return {number} The Manhattan distance.
  4561. */
  4562. manhattanDistanceTo( v ) {
  4563. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  4564. }
  4565. /**
  4566. * Sets the vector components from the given spherical coordinates.
  4567. *
  4568. * @param {Spherical} s - The spherical coordinates.
  4569. * @return {Vector3} A reference to this vector.
  4570. */
  4571. setFromSpherical( s ) {
  4572. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  4573. }
  4574. /**
  4575. * Sets the vector components from the given spherical coordinates.
  4576. *
  4577. * @param {number} radius - The radius.
  4578. * @param {number} phi - The phi angle in radians.
  4579. * @param {number} theta - The theta angle in radians.
  4580. * @return {Vector3} A reference to this vector.
  4581. */
  4582. setFromSphericalCoords( radius, phi, theta ) {
  4583. const sinPhiRadius = Math.sin( phi ) * radius;
  4584. this.x = sinPhiRadius * Math.sin( theta );
  4585. this.y = Math.cos( phi ) * radius;
  4586. this.z = sinPhiRadius * Math.cos( theta );
  4587. return this;
  4588. }
  4589. /**
  4590. * Sets the vector components from the given cylindrical coordinates.
  4591. *
  4592. * @param {Cylindrical} c - The cylindrical coordinates.
  4593. * @return {Vector3} A reference to this vector.
  4594. */
  4595. setFromCylindrical( c ) {
  4596. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  4597. }
  4598. /**
  4599. * Sets the vector components from the given cylindrical coordinates.
  4600. *
  4601. * @param {number} radius - The radius.
  4602. * @param {number} theta - The theta angle in radians.
  4603. * @param {number} y - The y value.
  4604. * @return {Vector3} A reference to this vector.
  4605. */
  4606. setFromCylindricalCoords( radius, theta, y ) {
  4607. this.x = radius * Math.sin( theta );
  4608. this.y = y;
  4609. this.z = radius * Math.cos( theta );
  4610. return this;
  4611. }
  4612. /**
  4613. * Sets the vector components to the position elements of the
  4614. * given transformation matrix.
  4615. *
  4616. * @param {Matrix4} m - The 4x4 matrix.
  4617. * @return {Vector3} A reference to this vector.
  4618. */
  4619. setFromMatrixPosition( m ) {
  4620. const e = m.elements;
  4621. this.x = e[ 12 ];
  4622. this.y = e[ 13 ];
  4623. this.z = e[ 14 ];
  4624. return this;
  4625. }
  4626. /**
  4627. * Sets the vector components to the scale elements of the
  4628. * given transformation matrix.
  4629. *
  4630. * @param {Matrix4} m - The 4x4 matrix.
  4631. * @return {Vector3} A reference to this vector.
  4632. */
  4633. setFromMatrixScale( m ) {
  4634. const sx = this.setFromMatrixColumn( m, 0 ).length();
  4635. const sy = this.setFromMatrixColumn( m, 1 ).length();
  4636. const sz = this.setFromMatrixColumn( m, 2 ).length();
  4637. this.x = sx;
  4638. this.y = sy;
  4639. this.z = sz;
  4640. return this;
  4641. }
  4642. /**
  4643. * Sets the vector components from the specified matrix column.
  4644. *
  4645. * @param {Matrix4} m - The 4x4 matrix.
  4646. * @param {number} index - The column index.
  4647. * @return {Vector3} A reference to this vector.
  4648. */
  4649. setFromMatrixColumn( m, index ) {
  4650. return this.fromArray( m.elements, index * 4 );
  4651. }
  4652. /**
  4653. * Sets the vector components from the specified matrix column.
  4654. *
  4655. * @param {Matrix3} m - The 3x3 matrix.
  4656. * @param {number} index - The column index.
  4657. * @return {Vector3} A reference to this vector.
  4658. */
  4659. setFromMatrix3Column( m, index ) {
  4660. return this.fromArray( m.elements, index * 3 );
  4661. }
  4662. /**
  4663. * Sets the vector components from the given Euler angles.
  4664. *
  4665. * @param {Euler} e - The Euler angles to set.
  4666. * @return {Vector3} A reference to this vector.
  4667. */
  4668. setFromEuler( e ) {
  4669. this.x = e._x;
  4670. this.y = e._y;
  4671. this.z = e._z;
  4672. return this;
  4673. }
  4674. /**
  4675. * Sets the vector components from the RGB components of the
  4676. * given color.
  4677. *
  4678. * @param {Color} c - The color to set.
  4679. * @return {Vector3} A reference to this vector.
  4680. */
  4681. setFromColor( c ) {
  4682. this.x = c.r;
  4683. this.y = c.g;
  4684. this.z = c.b;
  4685. return this;
  4686. }
  4687. /**
  4688. * Returns `true` if this vector is equal with the given one.
  4689. *
  4690. * @param {Vector3} v - The vector to test for equality.
  4691. * @return {boolean} Whether this vector is equal with the given one.
  4692. */
  4693. equals( v ) {
  4694. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  4695. }
  4696. /**
  4697. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`
  4698. * and z value to be `array[ offset + 2 ]`.
  4699. *
  4700. * @param {Array<number>} array - An array holding the vector component values.
  4701. * @param {number} [offset=0] - The offset into the array.
  4702. * @return {Vector3} A reference to this vector.
  4703. */
  4704. fromArray( array, offset = 0 ) {
  4705. this.x = array[ offset ];
  4706. this.y = array[ offset + 1 ];
  4707. this.z = array[ offset + 2 ];
  4708. return this;
  4709. }
  4710. /**
  4711. * Writes the components of this vector to the given array. If no array is provided,
  4712. * the method returns a new instance.
  4713. *
  4714. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  4715. * @param {number} [offset=0] - Index of the first element in the array.
  4716. * @return {Array<number>} The vector components.
  4717. */
  4718. toArray( array = [], offset = 0 ) {
  4719. array[ offset ] = this.x;
  4720. array[ offset + 1 ] = this.y;
  4721. array[ offset + 2 ] = this.z;
  4722. return array;
  4723. }
  4724. /**
  4725. * Sets the components of this vector from the given buffer attribute.
  4726. *
  4727. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  4728. * @param {number} index - The index into the attribute.
  4729. * @return {Vector3} A reference to this vector.
  4730. */
  4731. fromBufferAttribute( attribute, index ) {
  4732. this.x = attribute.getX( index );
  4733. this.y = attribute.getY( index );
  4734. this.z = attribute.getZ( index );
  4735. return this;
  4736. }
  4737. /**
  4738. * Sets each component of this vector to a pseudo-random value between `0` and
  4739. * `1`, excluding `1`.
  4740. *
  4741. * @return {Vector3} A reference to this vector.
  4742. */
  4743. random() {
  4744. this.x = Math.random();
  4745. this.y = Math.random();
  4746. this.z = Math.random();
  4747. return this;
  4748. }
  4749. /**
  4750. * Sets this vector to a uniformly random point on a unit sphere.
  4751. *
  4752. * @return {Vector3} A reference to this vector.
  4753. */
  4754. randomDirection() {
  4755. // https://mathworld.wolfram.com/SpherePointPicking.html
  4756. const theta = Math.random() * Math.PI * 2;
  4757. const u = Math.random() * 2 - 1;
  4758. const c = Math.sqrt( 1 - u * u );
  4759. this.x = c * Math.cos( theta );
  4760. this.y = u;
  4761. this.z = c * Math.sin( theta );
  4762. return this;
  4763. }
  4764. *[ Symbol.iterator ]() {
  4765. yield this.x;
  4766. yield this.y;
  4767. yield this.z;
  4768. }
  4769. }
  4770. const _vector$c = /*@__PURE__*/ new Vector3();
  4771. const _quaternion$5 = /*@__PURE__*/ new Quaternion();
  4772. /**
  4773. * Represents a 3x3 matrix.
  4774. *
  4775. * A Note on Row-Major and Column-Major Ordering:
  4776. *
  4777. * The constructor and {@link Matrix3#set} method take arguments in
  4778. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  4779. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  4780. * This means that calling:
  4781. * ```js
  4782. * const m = new THREE.Matrix();
  4783. * m.set( 11, 12, 13,
  4784. * 21, 22, 23,
  4785. * 31, 32, 33 );
  4786. * ```
  4787. * will result in the elements array containing:
  4788. * ```js
  4789. * m.elements = [ 11, 21, 31,
  4790. * 12, 22, 32,
  4791. * 13, 23, 33 ];
  4792. * ```
  4793. * and internally all calculations are performed using column-major ordering.
  4794. * However, as the actual ordering makes no difference mathematically and
  4795. * most people are used to thinking about matrices in row-major order, the
  4796. * three.js documentation shows matrices in row-major order. Just bear in
  4797. * mind that if you are reading the source code, you'll have to take the
  4798. * transpose of any matrices outlined here to make sense of the calculations.
  4799. */
  4800. class Matrix3 {
  4801. static {
  4802. /**
  4803. * This flag can be used for type testing.
  4804. *
  4805. * @type {boolean}
  4806. * @readonly
  4807. * @default true
  4808. */
  4809. Matrix3.prototype.isMatrix3 = true;
  4810. }
  4811. /**
  4812. * Constructs a new 3x3 matrix. The arguments are supposed to be
  4813. * in row-major order. If no arguments are provided, the constructor
  4814. * initializes the matrix as an identity matrix.
  4815. *
  4816. * @param {number} [n11] - 1-1 matrix element.
  4817. * @param {number} [n12] - 1-2 matrix element.
  4818. * @param {number} [n13] - 1-3 matrix element.
  4819. * @param {number} [n21] - 2-1 matrix element.
  4820. * @param {number} [n22] - 2-2 matrix element.
  4821. * @param {number} [n23] - 2-3 matrix element.
  4822. * @param {number} [n31] - 3-1 matrix element.
  4823. * @param {number} [n32] - 3-2 matrix element.
  4824. * @param {number} [n33] - 3-3 matrix element.
  4825. */
  4826. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4827. /**
  4828. * A column-major list of matrix values.
  4829. *
  4830. * @type {Array<number>}
  4831. */
  4832. this.elements = [
  4833. 1, 0, 0,
  4834. 0, 1, 0,
  4835. 0, 0, 1
  4836. ];
  4837. if ( n11 !== undefined ) {
  4838. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  4839. }
  4840. }
  4841. /**
  4842. * Sets the elements of the matrix.The arguments are supposed to be
  4843. * in row-major order.
  4844. *
  4845. * @param {number} [n11] - 1-1 matrix element.
  4846. * @param {number} [n12] - 1-2 matrix element.
  4847. * @param {number} [n13] - 1-3 matrix element.
  4848. * @param {number} [n21] - 2-1 matrix element.
  4849. * @param {number} [n22] - 2-2 matrix element.
  4850. * @param {number} [n23] - 2-3 matrix element.
  4851. * @param {number} [n31] - 3-1 matrix element.
  4852. * @param {number} [n32] - 3-2 matrix element.
  4853. * @param {number} [n33] - 3-3 matrix element.
  4854. * @return {Matrix3} A reference to this matrix.
  4855. */
  4856. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4857. const te = this.elements;
  4858. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  4859. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  4860. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  4861. return this;
  4862. }
  4863. /**
  4864. * Sets this matrix to the 3x3 identity matrix.
  4865. *
  4866. * @return {Matrix3} A reference to this matrix.
  4867. */
  4868. identity() {
  4869. this.set(
  4870. 1, 0, 0,
  4871. 0, 1, 0,
  4872. 0, 0, 1
  4873. );
  4874. return this;
  4875. }
  4876. /**
  4877. * Copies the values of the given matrix to this instance.
  4878. *
  4879. * @param {Matrix3} m - The matrix to copy.
  4880. * @return {Matrix3} A reference to this matrix.
  4881. */
  4882. copy( m ) {
  4883. const te = this.elements;
  4884. const me = m.elements;
  4885. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  4886. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  4887. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  4888. return this;
  4889. }
  4890. /**
  4891. * Extracts the basis of this matrix into the three axis vectors provided.
  4892. *
  4893. * @param {Vector3} xAxis - The basis's x axis.
  4894. * @param {Vector3} yAxis - The basis's y axis.
  4895. * @param {Vector3} zAxis - The basis's z axis.
  4896. * @return {Matrix3} A reference to this matrix.
  4897. */
  4898. extractBasis( xAxis, yAxis, zAxis ) {
  4899. xAxis.setFromMatrix3Column( this, 0 );
  4900. yAxis.setFromMatrix3Column( this, 1 );
  4901. zAxis.setFromMatrix3Column( this, 2 );
  4902. return this;
  4903. }
  4904. /**
  4905. * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix.
  4906. *
  4907. * @param {Matrix4} m - The 4x4 matrix.
  4908. * @return {Matrix3} A reference to this matrix.
  4909. */
  4910. setFromMatrix4( m ) {
  4911. const me = m.elements;
  4912. this.set(
  4913. me[ 0 ], me[ 4 ], me[ 8 ],
  4914. me[ 1 ], me[ 5 ], me[ 9 ],
  4915. me[ 2 ], me[ 6 ], me[ 10 ]
  4916. );
  4917. return this;
  4918. }
  4919. /**
  4920. * Post-multiplies this matrix by the given 3x3 matrix.
  4921. *
  4922. * @param {Matrix3} m - The matrix to multiply with.
  4923. * @return {Matrix3} A reference to this matrix.
  4924. */
  4925. multiply( m ) {
  4926. return this.multiplyMatrices( this, m );
  4927. }
  4928. /**
  4929. * Pre-multiplies this matrix by the given 3x3 matrix.
  4930. *
  4931. * @param {Matrix3} m - The matrix to multiply with.
  4932. * @return {Matrix3} A reference to this matrix.
  4933. */
  4934. premultiply( m ) {
  4935. return this.multiplyMatrices( m, this );
  4936. }
  4937. /**
  4938. * Multiples the given 3x3 matrices and stores the result
  4939. * in this matrix.
  4940. *
  4941. * @param {Matrix3} a - The first matrix.
  4942. * @param {Matrix3} b - The second matrix.
  4943. * @return {Matrix3} A reference to this matrix.
  4944. */
  4945. multiplyMatrices( a, b ) {
  4946. const ae = a.elements;
  4947. const be = b.elements;
  4948. const te = this.elements;
  4949. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  4950. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  4951. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  4952. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  4953. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  4954. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  4955. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  4956. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  4957. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  4958. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  4959. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  4960. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  4961. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  4962. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  4963. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  4964. return this;
  4965. }
  4966. /**
  4967. * Multiplies every component of the matrix by the given scalar.
  4968. *
  4969. * @param {number} s - The scalar.
  4970. * @return {Matrix3} A reference to this matrix.
  4971. */
  4972. multiplyScalar( s ) {
  4973. const te = this.elements;
  4974. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  4975. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  4976. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  4977. return this;
  4978. }
  4979. /**
  4980. * Computes and returns the determinant of this matrix.
  4981. *
  4982. * @return {number} The determinant.
  4983. */
  4984. determinant() {
  4985. const te = this.elements;
  4986. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  4987. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  4988. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  4989. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  4990. }
  4991. /**
  4992. * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution).
  4993. * You can not invert with a determinant of zero. If you attempt this, the method produces
  4994. * a zero matrix instead.
  4995. *
  4996. * @return {Matrix3} A reference to this matrix.
  4997. */
  4998. invert() {
  4999. const te = this.elements,
  5000. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  5001. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  5002. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  5003. t11 = n33 * n22 - n32 * n23,
  5004. t12 = n32 * n13 - n33 * n12,
  5005. t13 = n23 * n12 - n22 * n13,
  5006. det = n11 * t11 + n21 * t12 + n31 * t13;
  5007. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  5008. const detInv = 1 / det;
  5009. te[ 0 ] = t11 * detInv;
  5010. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  5011. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  5012. te[ 3 ] = t12 * detInv;
  5013. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  5014. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  5015. te[ 6 ] = t13 * detInv;
  5016. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  5017. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  5018. return this;
  5019. }
  5020. /**
  5021. * Transposes this matrix in place.
  5022. *
  5023. * @return {Matrix3} A reference to this matrix.
  5024. */
  5025. transpose() {
  5026. let tmp;
  5027. const m = this.elements;
  5028. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  5029. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  5030. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  5031. return this;
  5032. }
  5033. /**
  5034. * Computes the normal matrix which is the inverse transpose of the upper
  5035. * left 3x3 portion of the given 4x4 matrix.
  5036. *
  5037. * @param {Matrix4} matrix4 - The 4x4 matrix.
  5038. * @return {Matrix3} A reference to this matrix.
  5039. */
  5040. getNormalMatrix( matrix4 ) {
  5041. return this.setFromMatrix4( matrix4 ).invert().transpose();
  5042. }
  5043. /**
  5044. * Transposes this matrix into the supplied array, and returns itself unchanged.
  5045. *
  5046. * @param {Array<number>} r - An array to store the transposed matrix elements.
  5047. * @return {Matrix3} A reference to this matrix.
  5048. */
  5049. transposeIntoArray( r ) {
  5050. const m = this.elements;
  5051. r[ 0 ] = m[ 0 ];
  5052. r[ 1 ] = m[ 3 ];
  5053. r[ 2 ] = m[ 6 ];
  5054. r[ 3 ] = m[ 1 ];
  5055. r[ 4 ] = m[ 4 ];
  5056. r[ 5 ] = m[ 7 ];
  5057. r[ 6 ] = m[ 2 ];
  5058. r[ 7 ] = m[ 5 ];
  5059. r[ 8 ] = m[ 8 ];
  5060. return this;
  5061. }
  5062. /**
  5063. * Sets the UV transform matrix from offset, repeat, rotation, and center.
  5064. *
  5065. * @param {number} tx - Offset x.
  5066. * @param {number} ty - Offset y.
  5067. * @param {number} sx - Repeat x.
  5068. * @param {number} sy - Repeat y.
  5069. * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise.
  5070. * @param {number} cx - Center x of rotation.
  5071. * @param {number} cy - Center y of rotation
  5072. * @return {Matrix3} A reference to this matrix.
  5073. */
  5074. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  5075. const c = Math.cos( rotation );
  5076. const s = Math.sin( rotation );
  5077. this.set(
  5078. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  5079. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  5080. 0, 0, 1
  5081. );
  5082. return this;
  5083. }
  5084. /**
  5085. * Scales this matrix with the given scalar values.
  5086. *
  5087. * @param {number} sx - The amount to scale in the X axis.
  5088. * @param {number} sy - The amount to scale in the Y axis.
  5089. * @return {Matrix3} A reference to this matrix.
  5090. */
  5091. scale( sx, sy ) {
  5092. this.premultiply( _m3.makeScale( sx, sy ) );
  5093. return this;
  5094. }
  5095. /**
  5096. * Rotates this matrix by the given angle.
  5097. *
  5098. * @param {number} theta - The rotation in radians.
  5099. * @return {Matrix3} A reference to this matrix.
  5100. */
  5101. rotate( theta ) {
  5102. this.premultiply( _m3.makeRotation( - theta ) );
  5103. return this;
  5104. }
  5105. /**
  5106. * Translates this matrix by the given scalar values.
  5107. *
  5108. * @param {number} tx - The amount to translate in the X axis.
  5109. * @param {number} ty - The amount to translate in the Y axis.
  5110. * @return {Matrix3} A reference to this matrix.
  5111. */
  5112. translate( tx, ty ) {
  5113. this.premultiply( _m3.makeTranslation( tx, ty ) );
  5114. return this;
  5115. }
  5116. // for 2D Transforms
  5117. /**
  5118. * Sets this matrix as a 2D translation transform.
  5119. *
  5120. * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector.
  5121. * @param {number} y - The amount to translate in the Y axis.
  5122. * @return {Matrix3} A reference to this matrix.
  5123. */
  5124. makeTranslation( x, y ) {
  5125. if ( x.isVector2 ) {
  5126. this.set(
  5127. 1, 0, x.x,
  5128. 0, 1, x.y,
  5129. 0, 0, 1
  5130. );
  5131. } else {
  5132. this.set(
  5133. 1, 0, x,
  5134. 0, 1, y,
  5135. 0, 0, 1
  5136. );
  5137. }
  5138. return this;
  5139. }
  5140. /**
  5141. * Sets this matrix as a 2D rotational transformation.
  5142. *
  5143. * @param {number} theta - The rotation in radians.
  5144. * @return {Matrix3} A reference to this matrix.
  5145. */
  5146. makeRotation( theta ) {
  5147. // counterclockwise
  5148. const c = Math.cos( theta );
  5149. const s = Math.sin( theta );
  5150. this.set(
  5151. c, - s, 0,
  5152. s, c, 0,
  5153. 0, 0, 1
  5154. );
  5155. return this;
  5156. }
  5157. /**
  5158. * Sets this matrix as a 2D scale transform.
  5159. *
  5160. * @param {number} x - The amount to scale in the X axis.
  5161. * @param {number} y - The amount to scale in the Y axis.
  5162. * @return {Matrix3} A reference to this matrix.
  5163. */
  5164. makeScale( x, y ) {
  5165. this.set(
  5166. x, 0, 0,
  5167. 0, y, 0,
  5168. 0, 0, 1
  5169. );
  5170. return this;
  5171. }
  5172. /**
  5173. * Returns `true` if this matrix is equal with the given one.
  5174. *
  5175. * @param {Matrix3} matrix - The matrix to test for equality.
  5176. * @return {boolean} Whether this matrix is equal with the given one.
  5177. */
  5178. equals( matrix ) {
  5179. const te = this.elements;
  5180. const me = matrix.elements;
  5181. for ( let i = 0; i < 9; i ++ ) {
  5182. if ( te[ i ] !== me[ i ] ) return false;
  5183. }
  5184. return true;
  5185. }
  5186. /**
  5187. * Sets the elements of the matrix from the given array.
  5188. *
  5189. * @param {Array<number>} array - The matrix elements in column-major order.
  5190. * @param {number} [offset=0] - Index of the first element in the array.
  5191. * @return {Matrix3} A reference to this matrix.
  5192. */
  5193. fromArray( array, offset = 0 ) {
  5194. for ( let i = 0; i < 9; i ++ ) {
  5195. this.elements[ i ] = array[ i + offset ];
  5196. }
  5197. return this;
  5198. }
  5199. /**
  5200. * Writes the elements of this matrix to the given array. If no array is provided,
  5201. * the method returns a new instance.
  5202. *
  5203. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  5204. * @param {number} [offset=0] - Index of the first element in the array.
  5205. * @return {Array<number>} The matrix elements in column-major order.
  5206. */
  5207. toArray( array = [], offset = 0 ) {
  5208. const te = this.elements;
  5209. array[ offset ] = te[ 0 ];
  5210. array[ offset + 1 ] = te[ 1 ];
  5211. array[ offset + 2 ] = te[ 2 ];
  5212. array[ offset + 3 ] = te[ 3 ];
  5213. array[ offset + 4 ] = te[ 4 ];
  5214. array[ offset + 5 ] = te[ 5 ];
  5215. array[ offset + 6 ] = te[ 6 ];
  5216. array[ offset + 7 ] = te[ 7 ];
  5217. array[ offset + 8 ] = te[ 8 ];
  5218. return array;
  5219. }
  5220. /**
  5221. * Returns a matrix with copied values from this instance.
  5222. *
  5223. * @return {Matrix3} A clone of this instance.
  5224. */
  5225. clone() {
  5226. return new this.constructor().fromArray( this.elements );
  5227. }
  5228. }
  5229. const _m3 = /*@__PURE__*/ new Matrix3();
  5230. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  5231. 0.4123908, 0.3575843, 0.1804808,
  5232. 0.2126390, 0.7151687, 0.0721923,
  5233. 0.0193308, 0.1191948, 0.9505322
  5234. );
  5235. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  5236. 3.2409699, -1.5373832, -0.4986108,
  5237. -0.9692436, 1.8759675, 0.0415551,
  5238. 0.0556301, -0.203977, 1.0569715
  5239. );
  5240. function createColorManagement() {
  5241. const ColorManagement = {
  5242. enabled: true,
  5243. workingColorSpace: LinearSRGBColorSpace,
  5244. /**
  5245. * Implementations of supported color spaces.
  5246. *
  5247. * Required:
  5248. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  5249. * - whitePoint: reference white [ x y ]
  5250. * - transfer: transfer function (pre-defined)
  5251. * - toXYZ: Matrix3 RGB to XYZ transform
  5252. * - fromXYZ: Matrix3 XYZ to RGB transform
  5253. * - luminanceCoefficients: RGB luminance coefficients
  5254. *
  5255. * Optional:
  5256. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace, toneMappingMode: 'extended' | 'standard' }
  5257. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  5258. *
  5259. * Reference:
  5260. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  5261. */
  5262. spaces: {},
  5263. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  5264. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  5265. return color;
  5266. }
  5267. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  5268. color.r = SRGBToLinear( color.r );
  5269. color.g = SRGBToLinear( color.g );
  5270. color.b = SRGBToLinear( color.b );
  5271. }
  5272. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  5273. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  5274. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  5275. }
  5276. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  5277. color.r = LinearToSRGB( color.r );
  5278. color.g = LinearToSRGB( color.g );
  5279. color.b = LinearToSRGB( color.b );
  5280. }
  5281. return color;
  5282. },
  5283. workingToColorSpace: function ( color, targetColorSpace ) {
  5284. return this.convert( color, this.workingColorSpace, targetColorSpace );
  5285. },
  5286. colorSpaceToWorking: function ( color, sourceColorSpace ) {
  5287. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  5288. },
  5289. getPrimaries: function ( colorSpace ) {
  5290. return this.spaces[ colorSpace ].primaries;
  5291. },
  5292. getTransfer: function ( colorSpace ) {
  5293. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  5294. return this.spaces[ colorSpace ].transfer;
  5295. },
  5296. getToneMappingMode: function ( colorSpace ) {
  5297. return this.spaces[ colorSpace ].outputColorSpaceConfig.toneMappingMode || 'standard';
  5298. },
  5299. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  5300. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  5301. },
  5302. define: function ( colorSpaces ) {
  5303. Object.assign( this.spaces, colorSpaces );
  5304. },
  5305. // Internal APIs
  5306. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  5307. return targetMatrix
  5308. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  5309. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  5310. },
  5311. _getDrawingBufferColorSpace: function ( colorSpace ) {
  5312. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  5313. },
  5314. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  5315. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  5316. },
  5317. // Deprecated
  5318. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  5319. warnOnce( 'ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().' ); // @deprecated, r177
  5320. return ColorManagement.workingToColorSpace( color, targetColorSpace );
  5321. },
  5322. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  5323. warnOnce( 'ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().' ); // @deprecated, r177
  5324. return ColorManagement.colorSpaceToWorking( color, sourceColorSpace );
  5325. },
  5326. };
  5327. /******************************************************************************
  5328. * sRGB definitions
  5329. */
  5330. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  5331. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  5332. const D65 = [ 0.3127, 0.3290 ];
  5333. ColorManagement.define( {
  5334. [ LinearSRGBColorSpace ]: {
  5335. primaries: REC709_PRIMARIES,
  5336. whitePoint: D65,
  5337. transfer: LinearTransfer,
  5338. toXYZ: LINEAR_REC709_TO_XYZ,
  5339. fromXYZ: XYZ_TO_LINEAR_REC709,
  5340. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5341. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  5342. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5343. },
  5344. [ SRGBColorSpace ]: {
  5345. primaries: REC709_PRIMARIES,
  5346. whitePoint: D65,
  5347. transfer: SRGBTransfer,
  5348. toXYZ: LINEAR_REC709_TO_XYZ,
  5349. fromXYZ: XYZ_TO_LINEAR_REC709,
  5350. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5351. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5352. },
  5353. } );
  5354. return ColorManagement;
  5355. }
  5356. const ColorManagement = /*@__PURE__*/ createColorManagement();
  5357. function SRGBToLinear( c ) {
  5358. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  5359. }
  5360. function LinearToSRGB( c ) {
  5361. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  5362. }
  5363. let _canvas;
  5364. /**
  5365. * A class containing utility functions for images.
  5366. *
  5367. * @hideconstructor
  5368. */
  5369. class ImageUtils {
  5370. /**
  5371. * Returns a data URI containing a representation of the given image.
  5372. *
  5373. * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object.
  5374. * @param {string} [type='image/png'] - Indicates the image format.
  5375. * @return {string} The data URI.
  5376. */
  5377. static getDataURL( image, type = 'image/png' ) {
  5378. if ( /^data:/i.test( image.src ) ) {
  5379. return image.src;
  5380. }
  5381. if ( typeof HTMLCanvasElement === 'undefined' ) {
  5382. return image.src;
  5383. }
  5384. let canvas;
  5385. if ( image instanceof HTMLCanvasElement ) {
  5386. canvas = image;
  5387. } else {
  5388. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  5389. _canvas.width = image.width;
  5390. _canvas.height = image.height;
  5391. const context = _canvas.getContext( '2d' );
  5392. if ( image instanceof ImageData ) {
  5393. context.putImageData( image, 0, 0 );
  5394. } else {
  5395. context.drawImage( image, 0, 0, image.width, image.height );
  5396. }
  5397. canvas = _canvas;
  5398. }
  5399. return canvas.toDataURL( type );
  5400. }
  5401. /**
  5402. * Converts the given sRGB image data to linear color space.
  5403. *
  5404. * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object.
  5405. * @return {HTMLCanvasElement|Object} The converted image.
  5406. */
  5407. static sRGBToLinear( image ) {
  5408. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5409. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5410. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5411. const canvas = createElementNS( 'canvas' );
  5412. canvas.width = image.width;
  5413. canvas.height = image.height;
  5414. const context = canvas.getContext( '2d' );
  5415. context.drawImage( image, 0, 0, image.width, image.height );
  5416. const imageData = context.getImageData( 0, 0, image.width, image.height );
  5417. const data = imageData.data;
  5418. for ( let i = 0; i < data.length; i ++ ) {
  5419. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  5420. }
  5421. context.putImageData( imageData, 0, 0 );
  5422. return canvas;
  5423. } else if ( image.data ) {
  5424. const data = image.data.slice( 0 );
  5425. for ( let i = 0; i < data.length; i ++ ) {
  5426. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  5427. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  5428. } else {
  5429. // assuming float
  5430. data[ i ] = SRGBToLinear( data[ i ] );
  5431. }
  5432. }
  5433. return {
  5434. data: data,
  5435. width: image.width,
  5436. height: image.height
  5437. };
  5438. } else {
  5439. warn( 'ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  5440. return image;
  5441. }
  5442. }
  5443. }
  5444. let _sourceId = 0;
  5445. /**
  5446. * Represents the data source of a texture.
  5447. *
  5448. * The main purpose of this class is to decouple the data definition from the texture
  5449. * definition so the same data can be used with multiple texture instances.
  5450. */
  5451. class Source {
  5452. /**
  5453. * Constructs a new video texture.
  5454. *
  5455. * @param {any} [data=null] - The data definition of a texture.
  5456. */
  5457. constructor( data = null ) {
  5458. /**
  5459. * This flag can be used for type testing.
  5460. *
  5461. * @type {boolean}
  5462. * @readonly
  5463. * @default true
  5464. */
  5465. this.isSource = true;
  5466. /**
  5467. * The ID of the source.
  5468. *
  5469. * @name Source#id
  5470. * @type {number}
  5471. * @readonly
  5472. */
  5473. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  5474. /**
  5475. * The UUID of the source.
  5476. *
  5477. * @type {string}
  5478. * @readonly
  5479. */
  5480. this.uuid = generateUUID();
  5481. /**
  5482. * The data definition of a texture.
  5483. *
  5484. * @type {any}
  5485. */
  5486. this.data = data;
  5487. /**
  5488. * This property is only relevant when {@link Source#needsUpdate} is set to `true` and
  5489. * provides more control on how texture data should be processed. When `dataReady` is set
  5490. * to `false`, the engine performs the memory allocation (if necessary) but does not transfer
  5491. * the data into the GPU memory.
  5492. *
  5493. * @type {boolean}
  5494. * @default true
  5495. */
  5496. this.dataReady = true;
  5497. /**
  5498. * This starts at `0` and counts how many times {@link Source#needsUpdate} is set to `true`.
  5499. *
  5500. * @type {number}
  5501. * @readonly
  5502. * @default 0
  5503. */
  5504. this.version = 0;
  5505. }
  5506. /**
  5507. * Returns the dimensions of the source into the given target vector.
  5508. *
  5509. * @param {(Vector2|Vector3)} target - The target object the result is written into.
  5510. * @return {(Vector2|Vector3)} The dimensions of the source.
  5511. */
  5512. getSize( target ) {
  5513. const data = this.data;
  5514. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( data instanceof HTMLVideoElement ) ) {
  5515. target.set( data.videoWidth, data.videoHeight, 0 );
  5516. } else if ( ( typeof VideoFrame !== 'undefined' ) && ( data instanceof VideoFrame ) ) {
  5517. target.set( data.displayWidth, data.displayHeight, 0 );
  5518. } else if ( data !== null ) {
  5519. target.set( data.width, data.height, data.depth || 0 );
  5520. } else {
  5521. target.set( 0, 0, 0 );
  5522. }
  5523. return target;
  5524. }
  5525. /**
  5526. * When the property is set to `true`, the engine allocates the memory
  5527. * for the texture (if necessary) and triggers the actual texture upload
  5528. * to the GPU next time the source is used.
  5529. *
  5530. * @type {boolean}
  5531. * @default false
  5532. * @param {boolean} value
  5533. */
  5534. set needsUpdate( value ) {
  5535. if ( value === true ) this.version ++;
  5536. }
  5537. /**
  5538. * Serializes the source into JSON.
  5539. *
  5540. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5541. * @return {Object} A JSON object representing the serialized source.
  5542. * @see {@link ObjectLoader#parse}
  5543. */
  5544. toJSON( meta ) {
  5545. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5546. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  5547. return meta.images[ this.uuid ];
  5548. }
  5549. const output = {
  5550. uuid: this.uuid,
  5551. url: ''
  5552. };
  5553. const data = this.data;
  5554. if ( data !== null ) {
  5555. let url;
  5556. if ( Array.isArray( data ) ) {
  5557. // cube texture
  5558. url = [];
  5559. for ( let i = 0, l = data.length; i < l; i ++ ) {
  5560. if ( data[ i ].isDataTexture ) {
  5561. url.push( serializeImage( data[ i ].image ) );
  5562. } else {
  5563. url.push( serializeImage( data[ i ] ) );
  5564. }
  5565. }
  5566. } else {
  5567. // texture
  5568. url = serializeImage( data );
  5569. }
  5570. output.url = url;
  5571. }
  5572. if ( ! isRootObject ) {
  5573. meta.images[ this.uuid ] = output;
  5574. }
  5575. return output;
  5576. }
  5577. }
  5578. function serializeImage( image ) {
  5579. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5580. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5581. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5582. // default images
  5583. return ImageUtils.getDataURL( image );
  5584. } else {
  5585. if ( image.data ) {
  5586. // images of DataTexture
  5587. return {
  5588. data: Array.from( image.data ),
  5589. width: image.width,
  5590. height: image.height,
  5591. type: image.data.constructor.name
  5592. };
  5593. } else {
  5594. warn( 'Texture: Unable to serialize Texture.' );
  5595. return {};
  5596. }
  5597. }
  5598. }
  5599. let _textureId = 0;
  5600. const _tempVec3 = /*@__PURE__*/ new Vector3();
  5601. /**
  5602. * Base class for all textures.
  5603. *
  5604. * Note: After the initial use of a texture, its dimensions, format, and type
  5605. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  5606. *
  5607. * @augments EventDispatcher
  5608. */
  5609. class Texture extends EventDispatcher {
  5610. /**
  5611. * Constructs a new texture.
  5612. *
  5613. * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data.
  5614. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  5615. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  5616. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  5617. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  5618. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  5619. * @param {number} [format=RGBAFormat] - The texture format.
  5620. * @param {number} [type=UnsignedByteType] - The texture type.
  5621. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  5622. * @param {string} [colorSpace=NoColorSpace] - The color space.
  5623. */
  5624. 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 ) {
  5625. super();
  5626. /**
  5627. * This flag can be used for type testing.
  5628. *
  5629. * @type {boolean}
  5630. * @readonly
  5631. * @default true
  5632. */
  5633. this.isTexture = true;
  5634. /**
  5635. * The ID of the texture.
  5636. *
  5637. * @name Texture#id
  5638. * @type {number}
  5639. * @readonly
  5640. */
  5641. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  5642. /**
  5643. * The UUID of the texture.
  5644. *
  5645. * @type {string}
  5646. * @readonly
  5647. */
  5648. this.uuid = generateUUID();
  5649. /**
  5650. * The name of the texture.
  5651. *
  5652. * @type {string}
  5653. */
  5654. this.name = '';
  5655. /**
  5656. * The data definition of a texture. A reference to the data source can be
  5657. * shared across textures. This is often useful in context of spritesheets
  5658. * where multiple textures render the same data but with different texture
  5659. * transformations.
  5660. *
  5661. * @type {Source}
  5662. */
  5663. this.source = new Source( image );
  5664. /**
  5665. * An array holding user-defined mipmaps.
  5666. *
  5667. * @type {Array<Object>}
  5668. */
  5669. this.mipmaps = [];
  5670. /**
  5671. * How the texture is applied to the object. The value `UVMapping`
  5672. * is the default, where texture or uv coordinates are used to apply the map.
  5673. *
  5674. * @type {(UVMapping|CubeReflectionMapping|CubeRefractionMapping|EquirectangularReflectionMapping|EquirectangularRefractionMapping|CubeUVReflectionMapping)}
  5675. * @default UVMapping
  5676. */
  5677. this.mapping = mapping;
  5678. /**
  5679. * Lets you select the uv attribute to map the texture to. `0` for `uv`,
  5680. * `1` for `uv1`, `2` for `uv2` and `3` for `uv3`.
  5681. *
  5682. * @type {number}
  5683. * @default 0
  5684. */
  5685. this.channel = 0;
  5686. /**
  5687. * This defines how the texture is wrapped horizontally and corresponds to
  5688. * *U* in UV mapping.
  5689. *
  5690. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5691. * @default ClampToEdgeWrapping
  5692. */
  5693. this.wrapS = wrapS;
  5694. /**
  5695. * This defines how the texture is wrapped horizontally and corresponds to
  5696. * *V* in UV mapping.
  5697. *
  5698. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5699. * @default ClampToEdgeWrapping
  5700. */
  5701. this.wrapT = wrapT;
  5702. /**
  5703. * How the texture is sampled when a texel covers more than one pixel.
  5704. *
  5705. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5706. * @default LinearFilter
  5707. */
  5708. this.magFilter = magFilter;
  5709. /**
  5710. * How the texture is sampled when a texel covers less than one pixel.
  5711. *
  5712. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5713. * @default LinearMipmapLinearFilter
  5714. */
  5715. this.minFilter = minFilter;
  5716. /**
  5717. * The number of samples taken along the axis through the pixel that has the
  5718. * highest density of texels. By default, this value is `1`. A higher value
  5719. * gives a less blurry result than a basic mipmap, at the cost of more
  5720. * texture samples being used.
  5721. *
  5722. * @type {number}
  5723. * @default Texture.DEFAULT_ANISOTROPY
  5724. */
  5725. this.anisotropy = anisotropy;
  5726. /**
  5727. * The format of the texture.
  5728. *
  5729. * @type {number}
  5730. * @default RGBAFormat
  5731. */
  5732. this.format = format;
  5733. /**
  5734. * The default internal format is derived from {@link Texture#format} and {@link Texture#type} and
  5735. * defines how the texture data is going to be stored on the GPU.
  5736. *
  5737. * This property allows to overwrite the default format.
  5738. *
  5739. * @type {?string}
  5740. * @default null
  5741. */
  5742. this.internalFormat = null;
  5743. /**
  5744. * The data type of the texture.
  5745. *
  5746. * @type {number}
  5747. * @default UnsignedByteType
  5748. */
  5749. this.type = type;
  5750. /**
  5751. * How much a single repetition of the texture is offset from the beginning,
  5752. * in each direction U and V. Typical range is `0.0` to `1.0`.
  5753. *
  5754. * @type {Vector2}
  5755. * @default (0,0)
  5756. */
  5757. this.offset = new Vector2( 0, 0 );
  5758. /**
  5759. * How many times the texture is repeated across the surface, in each
  5760. * direction U and V. If repeat is set greater than `1` in either direction,
  5761. * the corresponding wrap parameter should also be set to `RepeatWrapping`
  5762. * or `MirroredRepeatWrapping` to achieve the desired tiling effect.
  5763. *
  5764. * @type {Vector2}
  5765. * @default (1,1)
  5766. */
  5767. this.repeat = new Vector2( 1, 1 );
  5768. /**
  5769. * The point around which rotation occurs. A value of `(0.5, 0.5)` corresponds
  5770. * to the center of the texture. Default is `(0, 0)`, the lower left.
  5771. *
  5772. * @type {Vector2}
  5773. * @default (0,0)
  5774. */
  5775. this.center = new Vector2( 0, 0 );
  5776. /**
  5777. * How much the texture is rotated around the center point, in radians.
  5778. * Positive values are counter-clockwise.
  5779. *
  5780. * @type {number}
  5781. * @default 0
  5782. */
  5783. this.rotation = 0;
  5784. /**
  5785. * Whether to update the texture's uv-transformation {@link Texture#matrix}
  5786. * from the properties {@link Texture#offset}, {@link Texture#repeat},
  5787. * {@link Texture#rotation}, and {@link Texture#center}.
  5788. *
  5789. * Set this to `false` if you are specifying the uv-transform matrix directly.
  5790. *
  5791. * @type {boolean}
  5792. * @default true
  5793. */
  5794. this.matrixAutoUpdate = true;
  5795. /**
  5796. * The uv-transformation matrix of the texture.
  5797. *
  5798. * @type {Matrix3}
  5799. */
  5800. this.matrix = new Matrix3();
  5801. /**
  5802. * Whether to generate mipmaps (if possible) for a texture.
  5803. *
  5804. * Set this to `false` if you are creating mipmaps manually.
  5805. *
  5806. * @type {boolean}
  5807. * @default true
  5808. */
  5809. this.generateMipmaps = true;
  5810. /**
  5811. * If set to `true`, the alpha channel, if present, is multiplied into the
  5812. * color channels when the texture is uploaded to the GPU.
  5813. *
  5814. * Note that this property has no effect when using `ImageBitmap`. You need to
  5815. * configure premultiply alpha on bitmap creation instead.
  5816. *
  5817. * @type {boolean}
  5818. * @default false
  5819. */
  5820. this.premultiplyAlpha = false;
  5821. /**
  5822. * If set to `true`, the texture is flipped along the vertical axis when
  5823. * uploaded to the GPU.
  5824. *
  5825. * Note that this property has no effect when using `ImageBitmap`. You need to
  5826. * configure the flip on bitmap creation instead.
  5827. *
  5828. * @type {boolean}
  5829. * @default true
  5830. */
  5831. this.flipY = true;
  5832. /**
  5833. * Specifies the alignment requirements for the start of each pixel row in memory.
  5834. * The allowable values are `1` (byte-alignment), `2` (rows aligned to even-numbered bytes),
  5835. * `4` (word-alignment), and `8` (rows start on double-word boundaries).
  5836. *
  5837. * @type {number}
  5838. * @default 4
  5839. */
  5840. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  5841. /**
  5842. * Textures containing color data should be annotated with `SRGBColorSpace` or `LinearSRGBColorSpace`.
  5843. *
  5844. * @type {string}
  5845. * @default NoColorSpace
  5846. */
  5847. this.colorSpace = colorSpace;
  5848. /**
  5849. * An object that can be used to store custom data about the texture. It
  5850. * should not hold references to functions as these will not be cloned.
  5851. *
  5852. * @type {Object}
  5853. */
  5854. this.userData = {};
  5855. /**
  5856. * This can be used to only update a subregion or specific rows of the texture (for example, just the
  5857. * first 3 rows). Use the `addUpdateRange()` function to add ranges to this array.
  5858. *
  5859. * @type {Array<Object>}
  5860. */
  5861. this.updateRanges = [];
  5862. /**
  5863. * This starts at `0` and counts how many times {@link Texture#needsUpdate} is set to `true`.
  5864. *
  5865. * @type {number}
  5866. * @readonly
  5867. * @default 0
  5868. */
  5869. this.version = 0;
  5870. /**
  5871. * A callback function, called when the texture is updated (e.g., when
  5872. * {@link Texture#needsUpdate} has been set to true and then the texture is used).
  5873. *
  5874. * @type {?Function}
  5875. * @default null
  5876. */
  5877. this.onUpdate = null;
  5878. /**
  5879. * An optional back reference to the textures render target.
  5880. *
  5881. * @type {?(RenderTarget|WebGLRenderTarget)}
  5882. * @default null
  5883. */
  5884. this.renderTarget = null;
  5885. /**
  5886. * Indicates whether a texture belongs to a render target or not.
  5887. *
  5888. * @type {boolean}
  5889. * @readonly
  5890. * @default false
  5891. */
  5892. this.isRenderTargetTexture = false;
  5893. /**
  5894. * Indicates if a texture should be handled like a texture array.
  5895. *
  5896. * @type {boolean}
  5897. * @readonly
  5898. * @default false
  5899. */
  5900. this.isArrayTexture = image && image.depth && image.depth > 1 ? true : false;
  5901. /**
  5902. * Indicates whether this texture should be processed by `PMREMGenerator` or not
  5903. * (only relevant for render target textures).
  5904. *
  5905. * @type {number}
  5906. * @readonly
  5907. * @default 0
  5908. */
  5909. this.pmremVersion = 0;
  5910. }
  5911. /**
  5912. * The width of the texture in pixels.
  5913. */
  5914. get width() {
  5915. return this.source.getSize( _tempVec3 ).x;
  5916. }
  5917. /**
  5918. * The height of the texture in pixels.
  5919. */
  5920. get height() {
  5921. return this.source.getSize( _tempVec3 ).y;
  5922. }
  5923. /**
  5924. * The depth of the texture in pixels.
  5925. */
  5926. get depth() {
  5927. return this.source.getSize( _tempVec3 ).z;
  5928. }
  5929. /**
  5930. * The image object holding the texture data.
  5931. *
  5932. * @type {?Object}
  5933. */
  5934. get image() {
  5935. return this.source.data;
  5936. }
  5937. set image( value ) {
  5938. this.source.data = value;
  5939. }
  5940. /**
  5941. * Updates the texture transformation matrix from the properties {@link Texture#offset},
  5942. * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
  5943. */
  5944. updateMatrix() {
  5945. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  5946. }
  5947. /**
  5948. * Adds a range of data in the data texture to be updated on the GPU.
  5949. *
  5950. * @param {number} start - Position at which to start update.
  5951. * @param {number} count - The number of components to update.
  5952. */
  5953. addUpdateRange( start, count ) {
  5954. this.updateRanges.push( { start, count } );
  5955. }
  5956. /**
  5957. * Clears the update ranges.
  5958. */
  5959. clearUpdateRanges() {
  5960. this.updateRanges.length = 0;
  5961. }
  5962. /**
  5963. * Returns a new texture with copied values from this instance.
  5964. *
  5965. * @return {Texture} A clone of this instance.
  5966. */
  5967. clone() {
  5968. return new this.constructor().copy( this );
  5969. }
  5970. /**
  5971. * Copies the values of the given texture to this instance.
  5972. *
  5973. * @param {Texture} source - The texture to copy.
  5974. * @return {Texture} A reference to this instance.
  5975. */
  5976. copy( source ) {
  5977. this.name = source.name;
  5978. this.source = source.source;
  5979. this.mipmaps = source.mipmaps.slice( 0 );
  5980. this.mapping = source.mapping;
  5981. this.channel = source.channel;
  5982. this.wrapS = source.wrapS;
  5983. this.wrapT = source.wrapT;
  5984. this.magFilter = source.magFilter;
  5985. this.minFilter = source.minFilter;
  5986. this.anisotropy = source.anisotropy;
  5987. this.format = source.format;
  5988. this.internalFormat = source.internalFormat;
  5989. this.type = source.type;
  5990. this.offset.copy( source.offset );
  5991. this.repeat.copy( source.repeat );
  5992. this.center.copy( source.center );
  5993. this.rotation = source.rotation;
  5994. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5995. this.matrix.copy( source.matrix );
  5996. this.generateMipmaps = source.generateMipmaps;
  5997. this.premultiplyAlpha = source.premultiplyAlpha;
  5998. this.flipY = source.flipY;
  5999. this.unpackAlignment = source.unpackAlignment;
  6000. this.colorSpace = source.colorSpace;
  6001. this.renderTarget = source.renderTarget;
  6002. this.isRenderTargetTexture = source.isRenderTargetTexture;
  6003. this.isArrayTexture = source.isArrayTexture;
  6004. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  6005. this.needsUpdate = true;
  6006. return this;
  6007. }
  6008. /**
  6009. * Sets this texture's properties based on `values`.
  6010. * @param {Object} values - A container with texture parameters.
  6011. */
  6012. setValues( values ) {
  6013. for ( const key in values ) {
  6014. const newValue = values[ key ];
  6015. if ( newValue === undefined ) {
  6016. warn( `Texture.setValues(): parameter '${ key }' has value of undefined.` );
  6017. continue;
  6018. }
  6019. const currentValue = this[ key ];
  6020. if ( currentValue === undefined ) {
  6021. warn( `Texture.setValues(): property '${ key }' does not exist.` );
  6022. continue;
  6023. }
  6024. if ( ( currentValue && newValue ) && ( currentValue.isVector2 && newValue.isVector2 ) ) {
  6025. currentValue.copy( newValue );
  6026. } else if ( ( currentValue && newValue ) && ( currentValue.isVector3 && newValue.isVector3 ) ) {
  6027. currentValue.copy( newValue );
  6028. } else if ( ( currentValue && newValue ) && ( currentValue.isMatrix3 && newValue.isMatrix3 ) ) {
  6029. currentValue.copy( newValue );
  6030. } else {
  6031. this[ key ] = newValue;
  6032. }
  6033. }
  6034. }
  6035. /**
  6036. * Serializes the texture into JSON.
  6037. *
  6038. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  6039. * @return {Object} A JSON object representing the serialized texture.
  6040. * @see {@link ObjectLoader#parse}
  6041. */
  6042. toJSON( meta ) {
  6043. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  6044. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  6045. return meta.textures[ this.uuid ];
  6046. }
  6047. const output = {
  6048. metadata: {
  6049. version: 4.7,
  6050. type: 'Texture',
  6051. generator: 'Texture.toJSON'
  6052. },
  6053. uuid: this.uuid,
  6054. name: this.name,
  6055. image: this.source.toJSON( meta ).uuid,
  6056. mapping: this.mapping,
  6057. channel: this.channel,
  6058. repeat: [ this.repeat.x, this.repeat.y ],
  6059. offset: [ this.offset.x, this.offset.y ],
  6060. center: [ this.center.x, this.center.y ],
  6061. rotation: this.rotation,
  6062. wrap: [ this.wrapS, this.wrapT ],
  6063. format: this.format,
  6064. internalFormat: this.internalFormat,
  6065. type: this.type,
  6066. colorSpace: this.colorSpace,
  6067. minFilter: this.minFilter,
  6068. magFilter: this.magFilter,
  6069. anisotropy: this.anisotropy,
  6070. flipY: this.flipY,
  6071. generateMipmaps: this.generateMipmaps,
  6072. premultiplyAlpha: this.premultiplyAlpha,
  6073. unpackAlignment: this.unpackAlignment
  6074. };
  6075. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  6076. if ( ! isRootObject ) {
  6077. meta.textures[ this.uuid ] = output;
  6078. }
  6079. return output;
  6080. }
  6081. /**
  6082. * Frees the GPU-related resources allocated by this instance. Call this
  6083. * method whenever this instance is no longer used in your app.
  6084. *
  6085. * @fires Texture#dispose
  6086. */
  6087. dispose() {
  6088. /**
  6089. * Fires when the texture has been disposed of.
  6090. *
  6091. * @event Texture#dispose
  6092. * @type {Object}
  6093. */
  6094. this.dispatchEvent( { type: 'dispose' } );
  6095. }
  6096. /**
  6097. * Transforms the given uv vector with the textures uv transformation matrix.
  6098. *
  6099. * @param {Vector2} uv - The uv vector.
  6100. * @return {Vector2} The transformed uv vector.
  6101. */
  6102. transformUv( uv ) {
  6103. if ( this.mapping !== UVMapping ) return uv;
  6104. uv.applyMatrix3( this.matrix );
  6105. if ( uv.x < 0 || uv.x > 1 ) {
  6106. switch ( this.wrapS ) {
  6107. case RepeatWrapping:
  6108. uv.x = uv.x - Math.floor( uv.x );
  6109. break;
  6110. case ClampToEdgeWrapping:
  6111. uv.x = uv.x < 0 ? 0 : 1;
  6112. break;
  6113. case MirroredRepeatWrapping:
  6114. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  6115. uv.x = Math.ceil( uv.x ) - uv.x;
  6116. } else {
  6117. uv.x = uv.x - Math.floor( uv.x );
  6118. }
  6119. break;
  6120. }
  6121. }
  6122. if ( uv.y < 0 || uv.y > 1 ) {
  6123. switch ( this.wrapT ) {
  6124. case RepeatWrapping:
  6125. uv.y = uv.y - Math.floor( uv.y );
  6126. break;
  6127. case ClampToEdgeWrapping:
  6128. uv.y = uv.y < 0 ? 0 : 1;
  6129. break;
  6130. case MirroredRepeatWrapping:
  6131. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  6132. uv.y = Math.ceil( uv.y ) - uv.y;
  6133. } else {
  6134. uv.y = uv.y - Math.floor( uv.y );
  6135. }
  6136. break;
  6137. }
  6138. }
  6139. if ( this.flipY ) {
  6140. uv.y = 1 - uv.y;
  6141. }
  6142. return uv;
  6143. }
  6144. /**
  6145. * Setting this property to `true` indicates the engine the texture
  6146. * must be updated in the next render. This triggers a texture upload
  6147. * to the GPU and ensures correct texture parameter configuration.
  6148. *
  6149. * @type {boolean}
  6150. * @default false
  6151. * @param {boolean} value
  6152. */
  6153. set needsUpdate( value ) {
  6154. if ( value === true ) {
  6155. this.version ++;
  6156. this.source.needsUpdate = true;
  6157. }
  6158. }
  6159. /**
  6160. * Setting this property to `true` indicates the engine the PMREM
  6161. * must be regenerated.
  6162. *
  6163. * @type {boolean}
  6164. * @default false
  6165. * @param {boolean} value
  6166. */
  6167. set needsPMREMUpdate( value ) {
  6168. if ( value === true ) {
  6169. this.pmremVersion ++;
  6170. }
  6171. }
  6172. }
  6173. /**
  6174. * The default image for all textures.
  6175. *
  6176. * @static
  6177. * @type {?Image}
  6178. * @default null
  6179. */
  6180. Texture.DEFAULT_IMAGE = null;
  6181. /**
  6182. * The default mapping for all textures.
  6183. *
  6184. * @static
  6185. * @type {number}
  6186. * @default UVMapping
  6187. */
  6188. Texture.DEFAULT_MAPPING = UVMapping;
  6189. /**
  6190. * The default anisotropy value for all textures.
  6191. *
  6192. * @static
  6193. * @type {number}
  6194. * @default 1
  6195. */
  6196. Texture.DEFAULT_ANISOTROPY = 1;
  6197. /**
  6198. * Class representing a 4D vector. A 4D vector is an ordered quadruplet of numbers
  6199. * (labeled x, y, z and w), which can be used to represent a number of things, such as:
  6200. *
  6201. * - A point in 4D space.
  6202. * - A direction and length in 4D space. In three.js the length will
  6203. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0, 0)` to `(x, y, z, w)`
  6204. * and the direction is also measured from `(0, 0, 0, 0)` towards `(x, y, z, w)`.
  6205. * - Any arbitrary ordered quadruplet of numbers.
  6206. *
  6207. * There are other things a 4D vector can be used to represent, however these
  6208. * are the most common uses in *three.js*.
  6209. *
  6210. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  6211. * the corresponding order.
  6212. * ```js
  6213. * const a = new THREE.Vector4( 0, 1, 0, 0 );
  6214. *
  6215. * //no arguments; will be initialised to (0, 0, 0, 1)
  6216. * const b = new THREE.Vector4( );
  6217. *
  6218. * const d = a.dot( b );
  6219. * ```
  6220. */
  6221. class Vector4 {
  6222. static {
  6223. /**
  6224. * This flag can be used for type testing.
  6225. *
  6226. * @type {boolean}
  6227. * @readonly
  6228. * @default true
  6229. */
  6230. Vector4.prototype.isVector4 = true;
  6231. }
  6232. /**
  6233. * Constructs a new 4D vector.
  6234. *
  6235. * @param {number} [x=0] - The x value of this vector.
  6236. * @param {number} [y=0] - The y value of this vector.
  6237. * @param {number} [z=0] - The z value of this vector.
  6238. * @param {number} [w=1] - The w value of this vector.
  6239. */
  6240. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  6241. /**
  6242. * The x value of this vector.
  6243. *
  6244. * @type {number}
  6245. */
  6246. this.x = x;
  6247. /**
  6248. * The y value of this vector.
  6249. *
  6250. * @type {number}
  6251. */
  6252. this.y = y;
  6253. /**
  6254. * The z value of this vector.
  6255. *
  6256. * @type {number}
  6257. */
  6258. this.z = z;
  6259. /**
  6260. * The w value of this vector.
  6261. *
  6262. * @type {number}
  6263. */
  6264. this.w = w;
  6265. }
  6266. /**
  6267. * Alias for {@link Vector4#z}.
  6268. *
  6269. * @type {number}
  6270. */
  6271. get width() {
  6272. return this.z;
  6273. }
  6274. set width( value ) {
  6275. this.z = value;
  6276. }
  6277. /**
  6278. * Alias for {@link Vector4#w}.
  6279. *
  6280. * @type {number}
  6281. */
  6282. get height() {
  6283. return this.w;
  6284. }
  6285. set height( value ) {
  6286. this.w = value;
  6287. }
  6288. /**
  6289. * Sets the vector components.
  6290. *
  6291. * @param {number} x - The value of the x component.
  6292. * @param {number} y - The value of the y component.
  6293. * @param {number} z - The value of the z component.
  6294. * @param {number} w - The value of the w component.
  6295. * @return {Vector4} A reference to this vector.
  6296. */
  6297. set( x, y, z, w ) {
  6298. this.x = x;
  6299. this.y = y;
  6300. this.z = z;
  6301. this.w = w;
  6302. return this;
  6303. }
  6304. /**
  6305. * Sets the vector components to the same value.
  6306. *
  6307. * @param {number} scalar - The value to set for all vector components.
  6308. * @return {Vector4} A reference to this vector.
  6309. */
  6310. setScalar( scalar ) {
  6311. this.x = scalar;
  6312. this.y = scalar;
  6313. this.z = scalar;
  6314. this.w = scalar;
  6315. return this;
  6316. }
  6317. /**
  6318. * Sets the vector's x component to the given value
  6319. *
  6320. * @param {number} x - The value to set.
  6321. * @return {Vector4} A reference to this vector.
  6322. */
  6323. setX( x ) {
  6324. this.x = x;
  6325. return this;
  6326. }
  6327. /**
  6328. * Sets the vector's y component to the given value
  6329. *
  6330. * @param {number} y - The value to set.
  6331. * @return {Vector4} A reference to this vector.
  6332. */
  6333. setY( y ) {
  6334. this.y = y;
  6335. return this;
  6336. }
  6337. /**
  6338. * Sets the vector's z component to the given value
  6339. *
  6340. * @param {number} z - The value to set.
  6341. * @return {Vector4} A reference to this vector.
  6342. */
  6343. setZ( z ) {
  6344. this.z = z;
  6345. return this;
  6346. }
  6347. /**
  6348. * Sets the vector's w component to the given value
  6349. *
  6350. * @param {number} w - The value to set.
  6351. * @return {Vector4} A reference to this vector.
  6352. */
  6353. setW( w ) {
  6354. this.w = w;
  6355. return this;
  6356. }
  6357. /**
  6358. * Allows to set a vector component with an index.
  6359. *
  6360. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6361. * `2` equals to z, `3` equals to w.
  6362. * @param {number} value - The value to set.
  6363. * @return {Vector4} A reference to this vector.
  6364. */
  6365. setComponent( index, value ) {
  6366. switch ( index ) {
  6367. case 0: this.x = value; break;
  6368. case 1: this.y = value; break;
  6369. case 2: this.z = value; break;
  6370. case 3: this.w = value; break;
  6371. default: throw new Error( 'index is out of range: ' + index );
  6372. }
  6373. return this;
  6374. }
  6375. /**
  6376. * Returns the value of the vector component which matches the given index.
  6377. *
  6378. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6379. * `2` equals to z, `3` equals to w.
  6380. * @return {number} A vector component value.
  6381. */
  6382. getComponent( index ) {
  6383. switch ( index ) {
  6384. case 0: return this.x;
  6385. case 1: return this.y;
  6386. case 2: return this.z;
  6387. case 3: return this.w;
  6388. default: throw new Error( 'index is out of range: ' + index );
  6389. }
  6390. }
  6391. /**
  6392. * Returns a new vector with copied values from this instance.
  6393. *
  6394. * @return {Vector4} A clone of this instance.
  6395. */
  6396. clone() {
  6397. return new this.constructor( this.x, this.y, this.z, this.w );
  6398. }
  6399. /**
  6400. * Copies the values of the given vector to this instance.
  6401. *
  6402. * @param {Vector3|Vector4} v - The vector to copy.
  6403. * @return {Vector4} A reference to this vector.
  6404. */
  6405. copy( v ) {
  6406. this.x = v.x;
  6407. this.y = v.y;
  6408. this.z = v.z;
  6409. this.w = ( v.w !== undefined ) ? v.w : 1;
  6410. return this;
  6411. }
  6412. /**
  6413. * Adds the given vector to this instance.
  6414. *
  6415. * @param {Vector4} v - The vector to add.
  6416. * @return {Vector4} A reference to this vector.
  6417. */
  6418. add( v ) {
  6419. this.x += v.x;
  6420. this.y += v.y;
  6421. this.z += v.z;
  6422. this.w += v.w;
  6423. return this;
  6424. }
  6425. /**
  6426. * Adds the given scalar value to all components of this instance.
  6427. *
  6428. * @param {number} s - The scalar to add.
  6429. * @return {Vector4} A reference to this vector.
  6430. */
  6431. addScalar( s ) {
  6432. this.x += s;
  6433. this.y += s;
  6434. this.z += s;
  6435. this.w += s;
  6436. return this;
  6437. }
  6438. /**
  6439. * Adds the given vectors and stores the result in this instance.
  6440. *
  6441. * @param {Vector4} a - The first vector.
  6442. * @param {Vector4} b - The second vector.
  6443. * @return {Vector4} A reference to this vector.
  6444. */
  6445. addVectors( a, b ) {
  6446. this.x = a.x + b.x;
  6447. this.y = a.y + b.y;
  6448. this.z = a.z + b.z;
  6449. this.w = a.w + b.w;
  6450. return this;
  6451. }
  6452. /**
  6453. * Adds the given vector scaled by the given factor to this instance.
  6454. *
  6455. * @param {Vector4} v - The vector.
  6456. * @param {number} s - The factor that scales `v`.
  6457. * @return {Vector4} A reference to this vector.
  6458. */
  6459. addScaledVector( v, s ) {
  6460. this.x += v.x * s;
  6461. this.y += v.y * s;
  6462. this.z += v.z * s;
  6463. this.w += v.w * s;
  6464. return this;
  6465. }
  6466. /**
  6467. * Subtracts the given vector from this instance.
  6468. *
  6469. * @param {Vector4} v - The vector to subtract.
  6470. * @return {Vector4} A reference to this vector.
  6471. */
  6472. sub( v ) {
  6473. this.x -= v.x;
  6474. this.y -= v.y;
  6475. this.z -= v.z;
  6476. this.w -= v.w;
  6477. return this;
  6478. }
  6479. /**
  6480. * Subtracts the given scalar value from all components of this instance.
  6481. *
  6482. * @param {number} s - The scalar to subtract.
  6483. * @return {Vector4} A reference to this vector.
  6484. */
  6485. subScalar( s ) {
  6486. this.x -= s;
  6487. this.y -= s;
  6488. this.z -= s;
  6489. this.w -= s;
  6490. return this;
  6491. }
  6492. /**
  6493. * Subtracts the given vectors and stores the result in this instance.
  6494. *
  6495. * @param {Vector4} a - The first vector.
  6496. * @param {Vector4} b - The second vector.
  6497. * @return {Vector4} A reference to this vector.
  6498. */
  6499. subVectors( a, b ) {
  6500. this.x = a.x - b.x;
  6501. this.y = a.y - b.y;
  6502. this.z = a.z - b.z;
  6503. this.w = a.w - b.w;
  6504. return this;
  6505. }
  6506. /**
  6507. * Multiplies the given vector with this instance.
  6508. *
  6509. * @param {Vector4} v - The vector to multiply.
  6510. * @return {Vector4} A reference to this vector.
  6511. */
  6512. multiply( v ) {
  6513. this.x *= v.x;
  6514. this.y *= v.y;
  6515. this.z *= v.z;
  6516. this.w *= v.w;
  6517. return this;
  6518. }
  6519. /**
  6520. * Multiplies the given scalar value with all components of this instance.
  6521. *
  6522. * @param {number} scalar - The scalar to multiply.
  6523. * @return {Vector4} A reference to this vector.
  6524. */
  6525. multiplyScalar( scalar ) {
  6526. this.x *= scalar;
  6527. this.y *= scalar;
  6528. this.z *= scalar;
  6529. this.w *= scalar;
  6530. return this;
  6531. }
  6532. /**
  6533. * Multiplies this vector with the given 4x4 matrix.
  6534. *
  6535. * @param {Matrix4} m - The 4x4 matrix.
  6536. * @return {Vector4} A reference to this vector.
  6537. */
  6538. applyMatrix4( m ) {
  6539. const x = this.x, y = this.y, z = this.z, w = this.w;
  6540. const e = m.elements;
  6541. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  6542. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  6543. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  6544. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  6545. return this;
  6546. }
  6547. /**
  6548. * Divides this instance by the given vector.
  6549. *
  6550. * @param {Vector4} v - The vector to divide.
  6551. * @return {Vector4} A reference to this vector.
  6552. */
  6553. divide( v ) {
  6554. this.x /= v.x;
  6555. this.y /= v.y;
  6556. this.z /= v.z;
  6557. this.w /= v.w;
  6558. return this;
  6559. }
  6560. /**
  6561. * Divides this vector by the given scalar.
  6562. *
  6563. * @param {number} scalar - The scalar to divide.
  6564. * @return {Vector4} A reference to this vector.
  6565. */
  6566. divideScalar( scalar ) {
  6567. return this.multiplyScalar( 1 / scalar );
  6568. }
  6569. /**
  6570. * Sets the x, y and z components of this
  6571. * vector to the quaternion's axis and w to the angle.
  6572. *
  6573. * @param {Quaternion} q - The Quaternion to set.
  6574. * @return {Vector4} A reference to this vector.
  6575. */
  6576. setAxisAngleFromQuaternion( q ) {
  6577. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  6578. // q is assumed to be normalized
  6579. this.w = 2 * Math.acos( q.w );
  6580. const s = Math.sqrt( 1 - q.w * q.w );
  6581. if ( s < 0.0001 ) {
  6582. this.x = 1;
  6583. this.y = 0;
  6584. this.z = 0;
  6585. } else {
  6586. this.x = q.x / s;
  6587. this.y = q.y / s;
  6588. this.z = q.z / s;
  6589. }
  6590. return this;
  6591. }
  6592. /**
  6593. * Sets the x, y and z components of this
  6594. * vector to the axis of rotation and w to the angle.
  6595. *
  6596. * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix.
  6597. * @return {Vector4} A reference to this vector.
  6598. */
  6599. setAxisAngleFromRotationMatrix( m ) {
  6600. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  6601. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6602. let angle, x, y, z; // variables for result
  6603. const epsilon = 0.01, // margin to allow for rounding errors
  6604. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  6605. te = m.elements,
  6606. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  6607. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  6608. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6609. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  6610. ( Math.abs( m13 - m31 ) < epsilon ) &&
  6611. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  6612. // singularity found
  6613. // first check for identity matrix which must have +1 for all terms
  6614. // in leading diagonal and zero in other terms
  6615. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  6616. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  6617. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  6618. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  6619. // this singularity is identity matrix so angle = 0
  6620. this.set( 1, 0, 0, 0 );
  6621. return this; // zero angle, arbitrary axis
  6622. }
  6623. // otherwise this singularity is angle = 180
  6624. angle = Math.PI;
  6625. const xx = ( m11 + 1 ) / 2;
  6626. const yy = ( m22 + 1 ) / 2;
  6627. const zz = ( m33 + 1 ) / 2;
  6628. const xy = ( m12 + m21 ) / 4;
  6629. const xz = ( m13 + m31 ) / 4;
  6630. const yz = ( m23 + m32 ) / 4;
  6631. if ( ( xx > yy ) && ( xx > zz ) ) {
  6632. // m11 is the largest diagonal term
  6633. if ( xx < epsilon ) {
  6634. x = 0;
  6635. y = 0.707106781;
  6636. z = 0.707106781;
  6637. } else {
  6638. x = Math.sqrt( xx );
  6639. y = xy / x;
  6640. z = xz / x;
  6641. }
  6642. } else if ( yy > zz ) {
  6643. // m22 is the largest diagonal term
  6644. if ( yy < epsilon ) {
  6645. x = 0.707106781;
  6646. y = 0;
  6647. z = 0.707106781;
  6648. } else {
  6649. y = Math.sqrt( yy );
  6650. x = xy / y;
  6651. z = yz / y;
  6652. }
  6653. } else {
  6654. // m33 is the largest diagonal term so base result on this
  6655. if ( zz < epsilon ) {
  6656. x = 0.707106781;
  6657. y = 0.707106781;
  6658. z = 0;
  6659. } else {
  6660. z = Math.sqrt( zz );
  6661. x = xz / z;
  6662. y = yz / z;
  6663. }
  6664. }
  6665. this.set( x, y, z, angle );
  6666. return this; // return 180 deg rotation
  6667. }
  6668. // as we have reached here there are no singularities so we can handle normally
  6669. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  6670. ( m13 - m31 ) * ( m13 - m31 ) +
  6671. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  6672. if ( Math.abs( s ) < 0.001 ) s = 1;
  6673. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  6674. // caught by singularity test above, but I've left it in just in case
  6675. this.x = ( m32 - m23 ) / s;
  6676. this.y = ( m13 - m31 ) / s;
  6677. this.z = ( m21 - m12 ) / s;
  6678. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  6679. return this;
  6680. }
  6681. /**
  6682. * Sets the vector components to the position elements of the
  6683. * given transformation matrix.
  6684. *
  6685. * @param {Matrix4} m - The 4x4 matrix.
  6686. * @return {Vector4} A reference to this vector.
  6687. */
  6688. setFromMatrixPosition( m ) {
  6689. const e = m.elements;
  6690. this.x = e[ 12 ];
  6691. this.y = e[ 13 ];
  6692. this.z = e[ 14 ];
  6693. this.w = e[ 15 ];
  6694. return this;
  6695. }
  6696. /**
  6697. * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w
  6698. * value, replace that value with the corresponding min value.
  6699. *
  6700. * @param {Vector4} v - The vector.
  6701. * @return {Vector4} A reference to this vector.
  6702. */
  6703. min( v ) {
  6704. this.x = Math.min( this.x, v.x );
  6705. this.y = Math.min( this.y, v.y );
  6706. this.z = Math.min( this.z, v.z );
  6707. this.w = Math.min( this.w, v.w );
  6708. return this;
  6709. }
  6710. /**
  6711. * If this vector's x, y, z or w value is less than the given vector's x, y, z or w
  6712. * value, replace that value with the corresponding max value.
  6713. *
  6714. * @param {Vector4} v - The vector.
  6715. * @return {Vector4} A reference to this vector.
  6716. */
  6717. max( v ) {
  6718. this.x = Math.max( this.x, v.x );
  6719. this.y = Math.max( this.y, v.y );
  6720. this.z = Math.max( this.z, v.z );
  6721. this.w = Math.max( this.w, v.w );
  6722. return this;
  6723. }
  6724. /**
  6725. * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w
  6726. * value, it is replaced by the corresponding value.
  6727. * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value,
  6728. * it is replaced by the corresponding value.
  6729. *
  6730. * @param {Vector4} min - The minimum x, y and z values.
  6731. * @param {Vector4} max - The maximum x, y and z values in the desired range.
  6732. * @return {Vector4} A reference to this vector.
  6733. */
  6734. clamp( min, max ) {
  6735. // assumes min < max, componentwise
  6736. this.x = clamp( this.x, min.x, max.x );
  6737. this.y = clamp( this.y, min.y, max.y );
  6738. this.z = clamp( this.z, min.z, max.z );
  6739. this.w = clamp( this.w, min.w, max.w );
  6740. return this;
  6741. }
  6742. /**
  6743. * If this vector's x, y, z or w values are greater than the max value, they are
  6744. * replaced by the max value.
  6745. * If this vector's x, y, z or w values are less than the min value, they are
  6746. * replaced by the min value.
  6747. *
  6748. * @param {number} minVal - The minimum value the components will be clamped to.
  6749. * @param {number} maxVal - The maximum value the components will be clamped to.
  6750. * @return {Vector4} A reference to this vector.
  6751. */
  6752. clampScalar( minVal, maxVal ) {
  6753. this.x = clamp( this.x, minVal, maxVal );
  6754. this.y = clamp( this.y, minVal, maxVal );
  6755. this.z = clamp( this.z, minVal, maxVal );
  6756. this.w = clamp( this.w, minVal, maxVal );
  6757. return this;
  6758. }
  6759. /**
  6760. * If this vector's length is greater than the max value, it is replaced by
  6761. * the max value.
  6762. * If this vector's length is less than the min value, it is replaced by the
  6763. * min value.
  6764. *
  6765. * @param {number} min - The minimum value the vector length will be clamped to.
  6766. * @param {number} max - The maximum value the vector length will be clamped to.
  6767. * @return {Vector4} A reference to this vector.
  6768. */
  6769. clampLength( min, max ) {
  6770. const length = this.length();
  6771. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  6772. }
  6773. /**
  6774. * The components of this vector are rounded down to the nearest integer value.
  6775. *
  6776. * @return {Vector4} A reference to this vector.
  6777. */
  6778. floor() {
  6779. this.x = Math.floor( this.x );
  6780. this.y = Math.floor( this.y );
  6781. this.z = Math.floor( this.z );
  6782. this.w = Math.floor( this.w );
  6783. return this;
  6784. }
  6785. /**
  6786. * The components of this vector are rounded up to the nearest integer value.
  6787. *
  6788. * @return {Vector4} A reference to this vector.
  6789. */
  6790. ceil() {
  6791. this.x = Math.ceil( this.x );
  6792. this.y = Math.ceil( this.y );
  6793. this.z = Math.ceil( this.z );
  6794. this.w = Math.ceil( this.w );
  6795. return this;
  6796. }
  6797. /**
  6798. * The components of this vector are rounded to the nearest integer value
  6799. *
  6800. * @return {Vector4} A reference to this vector.
  6801. */
  6802. round() {
  6803. this.x = Math.round( this.x );
  6804. this.y = Math.round( this.y );
  6805. this.z = Math.round( this.z );
  6806. this.w = Math.round( this.w );
  6807. return this;
  6808. }
  6809. /**
  6810. * The components of this vector are rounded towards zero (up if negative,
  6811. * down if positive) to an integer value.
  6812. *
  6813. * @return {Vector4} A reference to this vector.
  6814. */
  6815. roundToZero() {
  6816. this.x = Math.trunc( this.x );
  6817. this.y = Math.trunc( this.y );
  6818. this.z = Math.trunc( this.z );
  6819. this.w = Math.trunc( this.w );
  6820. return this;
  6821. }
  6822. /**
  6823. * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w.
  6824. *
  6825. * @return {Vector4} A reference to this vector.
  6826. */
  6827. negate() {
  6828. this.x = - this.x;
  6829. this.y = - this.y;
  6830. this.z = - this.z;
  6831. this.w = - this.w;
  6832. return this;
  6833. }
  6834. /**
  6835. * Calculates the dot product of the given vector with this instance.
  6836. *
  6837. * @param {Vector4} v - The vector to compute the dot product with.
  6838. * @return {number} The result of the dot product.
  6839. */
  6840. dot( v ) {
  6841. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  6842. }
  6843. /**
  6844. * Computes the square of the Euclidean length (straight-line length) from
  6845. * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should
  6846. * compare the length squared instead as it is slightly more efficient to calculate.
  6847. *
  6848. * @return {number} The square length of this vector.
  6849. */
  6850. lengthSq() {
  6851. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  6852. }
  6853. /**
  6854. * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w).
  6855. *
  6856. * @return {number} The length of this vector.
  6857. */
  6858. length() {
  6859. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  6860. }
  6861. /**
  6862. * Computes the Manhattan length of this vector.
  6863. *
  6864. * @return {number} The length of this vector.
  6865. */
  6866. manhattanLength() {
  6867. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  6868. }
  6869. /**
  6870. * Converts this vector to a unit vector - that is, sets it equal to a vector
  6871. * with the same direction as this one, but with a vector length of `1`.
  6872. *
  6873. * @return {Vector4} A reference to this vector.
  6874. */
  6875. normalize() {
  6876. return this.divideScalar( this.length() || 1 );
  6877. }
  6878. /**
  6879. * Sets this vector to a vector with the same direction as this one, but
  6880. * with the specified length.
  6881. *
  6882. * @param {number} length - The new length of this vector.
  6883. * @return {Vector4} A reference to this vector.
  6884. */
  6885. setLength( length ) {
  6886. return this.normalize().multiplyScalar( length );
  6887. }
  6888. /**
  6889. * Linearly interpolates between the given vector and this instance, where
  6890. * alpha is the percent distance along the line - alpha = 0 will be this
  6891. * vector, and alpha = 1 will be the given one.
  6892. *
  6893. * @param {Vector4} v - The vector to interpolate towards.
  6894. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6895. * @return {Vector4} A reference to this vector.
  6896. */
  6897. lerp( v, alpha ) {
  6898. this.x += ( v.x - this.x ) * alpha;
  6899. this.y += ( v.y - this.y ) * alpha;
  6900. this.z += ( v.z - this.z ) * alpha;
  6901. this.w += ( v.w - this.w ) * alpha;
  6902. return this;
  6903. }
  6904. /**
  6905. * Linearly interpolates between the given vectors, where alpha is the percent
  6906. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  6907. * be the second one. The result is stored in this instance.
  6908. *
  6909. * @param {Vector4} v1 - The first vector.
  6910. * @param {Vector4} v2 - The second vector.
  6911. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6912. * @return {Vector4} A reference to this vector.
  6913. */
  6914. lerpVectors( v1, v2, alpha ) {
  6915. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  6916. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  6917. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  6918. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  6919. return this;
  6920. }
  6921. /**
  6922. * Returns `true` if this vector is equal with the given one.
  6923. *
  6924. * @param {Vector4} v - The vector to test for equality.
  6925. * @return {boolean} Whether this vector is equal with the given one.
  6926. */
  6927. equals( v ) {
  6928. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  6929. }
  6930. /**
  6931. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`,
  6932. * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`.
  6933. *
  6934. * @param {Array<number>} array - An array holding the vector component values.
  6935. * @param {number} [offset=0] - The offset into the array.
  6936. * @return {Vector4} A reference to this vector.
  6937. */
  6938. fromArray( array, offset = 0 ) {
  6939. this.x = array[ offset ];
  6940. this.y = array[ offset + 1 ];
  6941. this.z = array[ offset + 2 ];
  6942. this.w = array[ offset + 3 ];
  6943. return this;
  6944. }
  6945. /**
  6946. * Writes the components of this vector to the given array. If no array is provided,
  6947. * the method returns a new instance.
  6948. *
  6949. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  6950. * @param {number} [offset=0] - Index of the first element in the array.
  6951. * @return {Array<number>} The vector components.
  6952. */
  6953. toArray( array = [], offset = 0 ) {
  6954. array[ offset ] = this.x;
  6955. array[ offset + 1 ] = this.y;
  6956. array[ offset + 2 ] = this.z;
  6957. array[ offset + 3 ] = this.w;
  6958. return array;
  6959. }
  6960. /**
  6961. * Sets the components of this vector from the given buffer attribute.
  6962. *
  6963. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  6964. * @param {number} index - The index into the attribute.
  6965. * @return {Vector4} A reference to this vector.
  6966. */
  6967. fromBufferAttribute( attribute, index ) {
  6968. this.x = attribute.getX( index );
  6969. this.y = attribute.getY( index );
  6970. this.z = attribute.getZ( index );
  6971. this.w = attribute.getW( index );
  6972. return this;
  6973. }
  6974. /**
  6975. * Sets each component of this vector to a pseudo-random value between `0` and
  6976. * `1`, excluding `1`.
  6977. *
  6978. * @return {Vector4} A reference to this vector.
  6979. */
  6980. random() {
  6981. this.x = Math.random();
  6982. this.y = Math.random();
  6983. this.z = Math.random();
  6984. this.w = Math.random();
  6985. return this;
  6986. }
  6987. *[ Symbol.iterator ]() {
  6988. yield this.x;
  6989. yield this.y;
  6990. yield this.z;
  6991. yield this.w;
  6992. }
  6993. }
  6994. /**
  6995. * A render target is a buffer where the video card draws pixels for a scene
  6996. * that is being rendered in the background. It is used in different effects,
  6997. * such as applying postprocessing to a rendered image before displaying it
  6998. * on the screen.
  6999. *
  7000. * @augments EventDispatcher
  7001. */
  7002. class RenderTarget extends EventDispatcher {
  7003. /**
  7004. * Render target options.
  7005. *
  7006. * @typedef {Object} RenderTarget~Options
  7007. * @property {boolean} [generateMipmaps=false] - Whether to generate mipmaps or not.
  7008. * @property {number} [magFilter=LinearFilter] - The mag filter.
  7009. * @property {number} [minFilter=LinearFilter] - The min filter.
  7010. * @property {number} [format=RGBAFormat] - The texture format.
  7011. * @property {number} [type=UnsignedByteType] - The texture type.
  7012. * @property {?string} [internalFormat=null] - The texture's internal format.
  7013. * @property {number} [wrapS=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  7014. * @property {number} [wrapT=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  7015. * @property {number} [anisotropy=1] - The texture's anisotropy value.
  7016. * @property {string} [colorSpace=NoColorSpace] - The texture's color space.
  7017. * @property {boolean} [depthBuffer=true] - Whether to allocate a depth buffer or not.
  7018. * @property {boolean} [stencilBuffer=false] - Whether to allocate a stencil buffer or not.
  7019. * @property {boolean} [resolveDepthBuffer=true] - Whether to resolve the depth buffer or not.
  7020. * @property {boolean} [resolveStencilBuffer=true] - Whether to resolve the stencil buffer or not.
  7021. * @property {?Texture} [depthTexture=null] - Reference to a depth texture.
  7022. * @property {number} [samples=0] - The MSAA samples count.
  7023. * @property {number} [count=1] - Defines the number of color attachments . Must be at least `1`.
  7024. * @property {number} [depth=1] - The texture depth.
  7025. * @property {boolean} [multiview=false] - Whether this target is used for multiview rendering.
  7026. */
  7027. /**
  7028. * Constructs a new render target.
  7029. *
  7030. * @param {number} [width=1] - The width of the render target.
  7031. * @param {number} [height=1] - The height of the render target.
  7032. * @param {RenderTarget~Options} [options] - The configuration object.
  7033. */
  7034. constructor( width = 1, height = 1, options = {} ) {
  7035. super();
  7036. options = Object.assign( {
  7037. generateMipmaps: false,
  7038. internalFormat: null,
  7039. minFilter: LinearFilter,
  7040. depthBuffer: true,
  7041. stencilBuffer: false,
  7042. resolveDepthBuffer: true,
  7043. resolveStencilBuffer: true,
  7044. depthTexture: null,
  7045. samples: 0,
  7046. count: 1,
  7047. depth: 1,
  7048. multiview: false
  7049. }, options );
  7050. /**
  7051. * This flag can be used for type testing.
  7052. *
  7053. * @type {boolean}
  7054. * @readonly
  7055. * @default true
  7056. */
  7057. this.isRenderTarget = true;
  7058. /**
  7059. * The width of the render target.
  7060. *
  7061. * @type {number}
  7062. * @default 1
  7063. */
  7064. this.width = width;
  7065. /**
  7066. * The height of the render target.
  7067. *
  7068. * @type {number}
  7069. * @default 1
  7070. */
  7071. this.height = height;
  7072. /**
  7073. * The depth of the render target.
  7074. *
  7075. * @type {number}
  7076. * @default 1
  7077. */
  7078. this.depth = options.depth;
  7079. /**
  7080. * A rectangular area inside the render target's viewport. Fragments that are
  7081. * outside the area will be discarded.
  7082. *
  7083. * @type {Vector4}
  7084. * @default (0,0,width,height)
  7085. */
  7086. this.scissor = new Vector4( 0, 0, width, height );
  7087. /**
  7088. * Indicates whether the scissor test should be enabled when rendering into
  7089. * this render target or not.
  7090. *
  7091. * @type {boolean}
  7092. * @default false
  7093. */
  7094. this.scissorTest = false;
  7095. /**
  7096. * A rectangular area representing the render target's viewport.
  7097. *
  7098. * @type {Vector4}
  7099. * @default (0,0,width,height)
  7100. */
  7101. this.viewport = new Vector4( 0, 0, width, height );
  7102. /**
  7103. * An array of textures. Each color attachment is represented as a separate texture.
  7104. * Has at least a single entry for the default color attachment.
  7105. *
  7106. * @type {Array<Texture>}
  7107. */
  7108. this.textures = [];
  7109. const image = { width: width, height: height, depth: options.depth };
  7110. const texture = new Texture( image );
  7111. const count = options.count;
  7112. for ( let i = 0; i < count; i ++ ) {
  7113. this.textures[ i ] = texture.clone();
  7114. this.textures[ i ].isRenderTargetTexture = true;
  7115. this.textures[ i ].renderTarget = this;
  7116. }
  7117. this._setTextureOptions( options );
  7118. /**
  7119. * Whether to allocate a depth buffer or not.
  7120. *
  7121. * @type {boolean}
  7122. * @default true
  7123. */
  7124. this.depthBuffer = options.depthBuffer;
  7125. /**
  7126. * Whether to allocate a stencil buffer or not.
  7127. *
  7128. * @type {boolean}
  7129. * @default false
  7130. */
  7131. this.stencilBuffer = options.stencilBuffer;
  7132. /**
  7133. * Whether to resolve the depth buffer or not.
  7134. *
  7135. * @type {boolean}
  7136. * @default true
  7137. */
  7138. this.resolveDepthBuffer = options.resolveDepthBuffer;
  7139. /**
  7140. * Whether to resolve the stencil buffer or not.
  7141. *
  7142. * @type {boolean}
  7143. * @default true
  7144. */
  7145. this.resolveStencilBuffer = options.resolveStencilBuffer;
  7146. this._depthTexture = null;
  7147. this.depthTexture = options.depthTexture;
  7148. /**
  7149. * The number of MSAA samples.
  7150. *
  7151. * A value of `0` disables MSAA.
  7152. *
  7153. * @type {number}
  7154. * @default 0
  7155. */
  7156. this.samples = options.samples;
  7157. /**
  7158. * Whether to this target is used in multiview rendering.
  7159. *
  7160. * @type {boolean}
  7161. * @default false
  7162. */
  7163. this.multiview = options.multiview;
  7164. }
  7165. _setTextureOptions( options = {} ) {
  7166. const values = {
  7167. minFilter: LinearFilter,
  7168. generateMipmaps: false,
  7169. flipY: false,
  7170. internalFormat: null
  7171. };
  7172. if ( options.mapping !== undefined ) values.mapping = options.mapping;
  7173. if ( options.wrapS !== undefined ) values.wrapS = options.wrapS;
  7174. if ( options.wrapT !== undefined ) values.wrapT = options.wrapT;
  7175. if ( options.wrapR !== undefined ) values.wrapR = options.wrapR;
  7176. if ( options.magFilter !== undefined ) values.magFilter = options.magFilter;
  7177. if ( options.minFilter !== undefined ) values.minFilter = options.minFilter;
  7178. if ( options.format !== undefined ) values.format = options.format;
  7179. if ( options.type !== undefined ) values.type = options.type;
  7180. if ( options.anisotropy !== undefined ) values.anisotropy = options.anisotropy;
  7181. if ( options.colorSpace !== undefined ) values.colorSpace = options.colorSpace;
  7182. if ( options.flipY !== undefined ) values.flipY = options.flipY;
  7183. if ( options.generateMipmaps !== undefined ) values.generateMipmaps = options.generateMipmaps;
  7184. if ( options.internalFormat !== undefined ) values.internalFormat = options.internalFormat;
  7185. for ( let i = 0; i < this.textures.length; i ++ ) {
  7186. const texture = this.textures[ i ];
  7187. texture.setValues( values );
  7188. }
  7189. }
  7190. /**
  7191. * The texture representing the default color attachment.
  7192. *
  7193. * @type {Texture}
  7194. */
  7195. get texture() {
  7196. return this.textures[ 0 ];
  7197. }
  7198. set texture( value ) {
  7199. this.textures[ 0 ] = value;
  7200. }
  7201. set depthTexture( current ) {
  7202. if ( this._depthTexture !== null ) this._depthTexture.renderTarget = null;
  7203. if ( current !== null ) current.renderTarget = this;
  7204. this._depthTexture = current;
  7205. }
  7206. /**
  7207. * Instead of saving the depth in a renderbuffer, a texture
  7208. * can be used instead which is useful for further processing
  7209. * e.g. in context of post-processing.
  7210. *
  7211. * @type {?DepthTexture}
  7212. * @default null
  7213. */
  7214. get depthTexture() {
  7215. return this._depthTexture;
  7216. }
  7217. /**
  7218. * Sets the size of this render target.
  7219. *
  7220. * @param {number} width - The width.
  7221. * @param {number} height - The height.
  7222. * @param {number} [depth=1] - The depth.
  7223. */
  7224. setSize( width, height, depth = 1 ) {
  7225. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  7226. this.width = width;
  7227. this.height = height;
  7228. this.depth = depth;
  7229. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  7230. this.textures[ i ].image.width = width;
  7231. this.textures[ i ].image.height = height;
  7232. this.textures[ i ].image.depth = depth;
  7233. if ( this.textures[ i ].isData3DTexture !== true ) { // Fix for #31693
  7234. // TODO: Reconsider setting isArrayTexture flag here and in the ctor of Texture.
  7235. // Maybe a method `isArrayTexture()` or just a getter could replace a flag since
  7236. // both are evaluated on each call?
  7237. this.textures[ i ].isArrayTexture = this.textures[ i ].image.depth > 1;
  7238. }
  7239. }
  7240. this.dispose();
  7241. }
  7242. this.viewport.set( 0, 0, width, height );
  7243. this.scissor.set( 0, 0, width, height );
  7244. }
  7245. /**
  7246. * Returns a new render target with copied values from this instance.
  7247. *
  7248. * @return {RenderTarget} A clone of this instance.
  7249. */
  7250. clone() {
  7251. return new this.constructor().copy( this );
  7252. }
  7253. /**
  7254. * Copies the settings of the given render target. This is a structural copy so
  7255. * no resources are shared between render targets after the copy. That includes
  7256. * all MRT textures and the depth texture.
  7257. *
  7258. * @param {RenderTarget} source - The render target to copy.
  7259. * @return {RenderTarget} A reference to this instance.
  7260. */
  7261. copy( source ) {
  7262. this.width = source.width;
  7263. this.height = source.height;
  7264. this.depth = source.depth;
  7265. this.scissor.copy( source.scissor );
  7266. this.scissorTest = source.scissorTest;
  7267. this.viewport.copy( source.viewport );
  7268. this.textures.length = 0;
  7269. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  7270. this.textures[ i ] = source.textures[ i ].clone();
  7271. this.textures[ i ].isRenderTargetTexture = true;
  7272. this.textures[ i ].renderTarget = this;
  7273. // ensure image object is not shared, see #20328
  7274. const image = Object.assign( {}, source.textures[ i ].image );
  7275. this.textures[ i ].source = new Source( image );
  7276. }
  7277. this.depthBuffer = source.depthBuffer;
  7278. this.stencilBuffer = source.stencilBuffer;
  7279. this.resolveDepthBuffer = source.resolveDepthBuffer;
  7280. this.resolveStencilBuffer = source.resolveStencilBuffer;
  7281. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  7282. this.samples = source.samples;
  7283. return this;
  7284. }
  7285. /**
  7286. * Frees the GPU-related resources allocated by this instance. Call this
  7287. * method whenever this instance is no longer used in your app.
  7288. *
  7289. * @fires RenderTarget#dispose
  7290. */
  7291. dispose() {
  7292. this.dispatchEvent( { type: 'dispose' } );
  7293. }
  7294. }
  7295. /**
  7296. * A render target used in context of {@link WebGLRenderer}.
  7297. *
  7298. * @augments RenderTarget
  7299. */
  7300. class WebGLRenderTarget extends RenderTarget {
  7301. /**
  7302. * Constructs a new 3D render target.
  7303. *
  7304. * @param {number} [width=1] - The width of the render target.
  7305. * @param {number} [height=1] - The height of the render target.
  7306. * @param {RenderTarget~Options} [options] - The configuration object.
  7307. */
  7308. constructor( width = 1, height = 1, options = {} ) {
  7309. super( width, height, options );
  7310. /**
  7311. * This flag can be used for type testing.
  7312. *
  7313. * @type {boolean}
  7314. * @readonly
  7315. * @default true
  7316. */
  7317. this.isWebGLRenderTarget = true;
  7318. }
  7319. }
  7320. /**
  7321. * Creates an array of textures directly from raw buffer data.
  7322. *
  7323. * @augments Texture
  7324. */
  7325. class DataArrayTexture extends Texture {
  7326. /**
  7327. * Constructs a new data array texture.
  7328. *
  7329. * @param {?TypedArray} [data=null] - The buffer data.
  7330. * @param {number} [width=1] - The width of the texture.
  7331. * @param {number} [height=1] - The height of the texture.
  7332. * @param {number} [depth=1] - The depth of the texture.
  7333. */
  7334. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7335. super( null );
  7336. /**
  7337. * This flag can be used for type testing.
  7338. *
  7339. * @type {boolean}
  7340. * @readonly
  7341. * @default true
  7342. */
  7343. this.isDataArrayTexture = true;
  7344. /**
  7345. * The image definition of a data texture.
  7346. *
  7347. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7348. */
  7349. this.image = { data, width, height, depth };
  7350. /**
  7351. * How the texture is sampled when a texel covers more than one pixel.
  7352. *
  7353. * Overwritten and set to `NearestFilter` by default.
  7354. *
  7355. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7356. * @default NearestFilter
  7357. */
  7358. this.magFilter = NearestFilter;
  7359. /**
  7360. * How the texture is sampled when a texel covers less than one pixel.
  7361. *
  7362. * Overwritten and set to `NearestFilter` by default.
  7363. *
  7364. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7365. * @default NearestFilter
  7366. */
  7367. this.minFilter = NearestFilter;
  7368. /**
  7369. * This defines how the texture is wrapped in the depth and corresponds to
  7370. * *W* in UVW mapping.
  7371. *
  7372. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7373. * @default ClampToEdgeWrapping
  7374. */
  7375. this.wrapR = ClampToEdgeWrapping;
  7376. /**
  7377. * Whether to generate mipmaps (if possible) for a texture.
  7378. *
  7379. * Overwritten and set to `false` by default.
  7380. *
  7381. * @type {boolean}
  7382. * @default false
  7383. */
  7384. this.generateMipmaps = false;
  7385. /**
  7386. * If set to `true`, the texture is flipped along the vertical axis when
  7387. * uploaded to the GPU.
  7388. *
  7389. * Overwritten and set to `false` by default.
  7390. *
  7391. * @type {boolean}
  7392. * @default false
  7393. */
  7394. this.flipY = false;
  7395. /**
  7396. * Specifies the alignment requirements for the start of each pixel row in memory.
  7397. *
  7398. * Overwritten and set to `1` by default.
  7399. *
  7400. * @type {boolean}
  7401. * @default 1
  7402. */
  7403. this.unpackAlignment = 1;
  7404. /**
  7405. * A set of all layers which need to be updated in the texture.
  7406. *
  7407. * @type {Set<number>}
  7408. */
  7409. this.layerUpdates = new Set();
  7410. }
  7411. /**
  7412. * Describes that a specific layer of the texture needs to be updated.
  7413. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  7414. * entire data texture array is sent to the GPU. Marking specific
  7415. * layers will only transmit subsets of all mipmaps associated with a
  7416. * specific depth in the array which is often much more performant.
  7417. *
  7418. * @param {number} layerIndex - The layer index that should be updated.
  7419. */
  7420. addLayerUpdate( layerIndex ) {
  7421. this.layerUpdates.add( layerIndex );
  7422. }
  7423. /**
  7424. * Resets the layer updates registry.
  7425. */
  7426. clearLayerUpdates() {
  7427. this.layerUpdates.clear();
  7428. }
  7429. }
  7430. /**
  7431. * An array render target used in context of {@link WebGLRenderer}.
  7432. *
  7433. * @augments WebGLRenderTarget
  7434. */
  7435. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  7436. /**
  7437. * Constructs a new array render target.
  7438. *
  7439. * @param {number} [width=1] - The width of the render target.
  7440. * @param {number} [height=1] - The height of the render target.
  7441. * @param {number} [depth=1] - The height of the render target.
  7442. * @param {RenderTarget~Options} [options] - The configuration object.
  7443. */
  7444. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7445. super( width, height, options );
  7446. /**
  7447. * This flag can be used for type testing.
  7448. *
  7449. * @type {boolean}
  7450. * @readonly
  7451. * @default true
  7452. */
  7453. this.isWebGLArrayRenderTarget = true;
  7454. this.depth = depth;
  7455. /**
  7456. * Overwritten with a different texture type.
  7457. *
  7458. * @type {DataArrayTexture}
  7459. */
  7460. this.texture = new DataArrayTexture( null, width, height, depth );
  7461. this._setTextureOptions( options );
  7462. this.texture.isRenderTargetTexture = true;
  7463. }
  7464. }
  7465. /**
  7466. * Creates a three-dimensional texture from raw data, with parameters to
  7467. * divide it into width, height, and depth.
  7468. *
  7469. * @augments Texture
  7470. */
  7471. class Data3DTexture extends Texture {
  7472. /**
  7473. * Constructs a new data array texture.
  7474. *
  7475. * @param {?TypedArray} [data=null] - The buffer data.
  7476. * @param {number} [width=1] - The width of the texture.
  7477. * @param {number} [height=1] - The height of the texture.
  7478. * @param {number} [depth=1] - The depth of the texture.
  7479. */
  7480. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7481. // We're going to add .setXXX() methods for setting properties later.
  7482. // Users can still set in Data3DTexture directly.
  7483. //
  7484. // const texture = new THREE.Data3DTexture( data, width, height, depth );
  7485. // texture.anisotropy = 16;
  7486. //
  7487. // See #14839
  7488. super( null );
  7489. /**
  7490. * This flag can be used for type testing.
  7491. *
  7492. * @type {boolean}
  7493. * @readonly
  7494. * @default true
  7495. */
  7496. this.isData3DTexture = true;
  7497. /**
  7498. * The image definition of a data texture.
  7499. *
  7500. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7501. */
  7502. this.image = { data, width, height, depth };
  7503. /**
  7504. * How the texture is sampled when a texel covers more than one pixel.
  7505. *
  7506. * Overwritten and set to `NearestFilter` by default.
  7507. *
  7508. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7509. * @default NearestFilter
  7510. */
  7511. this.magFilter = NearestFilter;
  7512. /**
  7513. * How the texture is sampled when a texel covers less than one pixel.
  7514. *
  7515. * Overwritten and set to `NearestFilter` by default.
  7516. *
  7517. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7518. * @default NearestFilter
  7519. */
  7520. this.minFilter = NearestFilter;
  7521. /**
  7522. * This defines how the texture is wrapped in the depth and corresponds to
  7523. * *W* in UVW mapping.
  7524. *
  7525. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7526. * @default ClampToEdgeWrapping
  7527. */
  7528. this.wrapR = ClampToEdgeWrapping;
  7529. /**
  7530. * Whether to generate mipmaps (if possible) for a texture.
  7531. *
  7532. * Overwritten and set to `false` by default.
  7533. *
  7534. * @type {boolean}
  7535. * @default false
  7536. */
  7537. this.generateMipmaps = false;
  7538. /**
  7539. * If set to `true`, the texture is flipped along the vertical axis when
  7540. * uploaded to the GPU.
  7541. *
  7542. * Overwritten and set to `false` by default.
  7543. *
  7544. * @type {boolean}
  7545. * @default false
  7546. */
  7547. this.flipY = false;
  7548. /**
  7549. * Specifies the alignment requirements for the start of each pixel row in memory.
  7550. *
  7551. * Overwritten and set to `1` by default.
  7552. *
  7553. * @type {boolean}
  7554. * @default 1
  7555. */
  7556. this.unpackAlignment = 1;
  7557. }
  7558. }
  7559. /**
  7560. * A 3D render target used in context of {@link WebGLRenderer}.
  7561. *
  7562. * @augments WebGLRenderTarget
  7563. */
  7564. class WebGL3DRenderTarget extends WebGLRenderTarget {
  7565. /**
  7566. * Constructs a new 3D render target.
  7567. *
  7568. * @param {number} [width=1] - The width of the render target.
  7569. * @param {number} [height=1] - The height of the render target.
  7570. * @param {number} [depth=1] - The height of the render target.
  7571. * @param {RenderTarget~Options} [options] - The configuration object.
  7572. */
  7573. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7574. super( width, height, options );
  7575. /**
  7576. * This flag can be used for type testing.
  7577. *
  7578. * @type {boolean}
  7579. * @readonly
  7580. * @default true
  7581. */
  7582. this.isWebGL3DRenderTarget = true;
  7583. this.depth = depth;
  7584. /**
  7585. * Overwritten with a different texture type.
  7586. *
  7587. * @type {Data3DTexture}
  7588. */
  7589. this.texture = new Data3DTexture( null, width, height, depth );
  7590. this._setTextureOptions( options );
  7591. this.texture.isRenderTargetTexture = true;
  7592. }
  7593. }
  7594. /**
  7595. * Represents a 4x4 matrix.
  7596. *
  7597. * The most common use of a 4x4 matrix in 3D computer graphics is as a transformation matrix.
  7598. * For an introduction to transformation matrices as used in WebGL, check out [this tutorial](https://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices)
  7599. *
  7600. * This allows a 3D vector representing a point in 3D space to undergo
  7601. * transformations such as translation, rotation, shear, scale, reflection,
  7602. * orthogonal or perspective projection and so on, by being multiplied by the
  7603. * matrix. This is known as `applying` the matrix to the vector.
  7604. *
  7605. * A Note on Row-Major and Column-Major Ordering:
  7606. *
  7607. * The constructor and {@link Matrix3#set} method take arguments in
  7608. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  7609. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  7610. * This means that calling:
  7611. * ```js
  7612. * const m = new THREE.Matrix4();
  7613. * m.set( 11, 12, 13, 14,
  7614. * 21, 22, 23, 24,
  7615. * 31, 32, 33, 34,
  7616. * 41, 42, 43, 44 );
  7617. * ```
  7618. * will result in the elements array containing:
  7619. * ```js
  7620. * m.elements = [ 11, 21, 31, 41,
  7621. * 12, 22, 32, 42,
  7622. * 13, 23, 33, 43,
  7623. * 14, 24, 34, 44 ];
  7624. * ```
  7625. * and internally all calculations are performed using column-major ordering.
  7626. * However, as the actual ordering makes no difference mathematically and
  7627. * most people are used to thinking about matrices in row-major order, the
  7628. * three.js documentation shows matrices in row-major order. Just bear in
  7629. * mind that if you are reading the source code, you'll have to take the
  7630. * transpose of any matrices outlined here to make sense of the calculations.
  7631. */
  7632. class Matrix4 {
  7633. static {
  7634. /**
  7635. * This flag can be used for type testing.
  7636. *
  7637. * @type {boolean}
  7638. * @readonly
  7639. * @default true
  7640. */
  7641. Matrix4.prototype.isMatrix4 = true;
  7642. }
  7643. /**
  7644. * Constructs a new 4x4 matrix. The arguments are supposed to be
  7645. * in row-major order. If no arguments are provided, the constructor
  7646. * initializes the matrix as an identity matrix.
  7647. *
  7648. * @param {number} [n11] - 1-1 matrix element.
  7649. * @param {number} [n12] - 1-2 matrix element.
  7650. * @param {number} [n13] - 1-3 matrix element.
  7651. * @param {number} [n14] - 1-4 matrix element.
  7652. * @param {number} [n21] - 2-1 matrix element.
  7653. * @param {number} [n22] - 2-2 matrix element.
  7654. * @param {number} [n23] - 2-3 matrix element.
  7655. * @param {number} [n24] - 2-4 matrix element.
  7656. * @param {number} [n31] - 3-1 matrix element.
  7657. * @param {number} [n32] - 3-2 matrix element.
  7658. * @param {number} [n33] - 3-3 matrix element.
  7659. * @param {number} [n34] - 3-4 matrix element.
  7660. * @param {number} [n41] - 4-1 matrix element.
  7661. * @param {number} [n42] - 4-2 matrix element.
  7662. * @param {number} [n43] - 4-3 matrix element.
  7663. * @param {number} [n44] - 4-4 matrix element.
  7664. */
  7665. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  7666. /**
  7667. * A column-major list of matrix values.
  7668. *
  7669. * @type {Array<number>}
  7670. */
  7671. this.elements = [
  7672. 1, 0, 0, 0,
  7673. 0, 1, 0, 0,
  7674. 0, 0, 1, 0,
  7675. 0, 0, 0, 1
  7676. ];
  7677. if ( n11 !== undefined ) {
  7678. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  7679. }
  7680. }
  7681. /**
  7682. * Sets the elements of the matrix.The arguments are supposed to be
  7683. * in row-major order.
  7684. *
  7685. * @param {number} [n11] - 1-1 matrix element.
  7686. * @param {number} [n12] - 1-2 matrix element.
  7687. * @param {number} [n13] - 1-3 matrix element.
  7688. * @param {number} [n14] - 1-4 matrix element.
  7689. * @param {number} [n21] - 2-1 matrix element.
  7690. * @param {number} [n22] - 2-2 matrix element.
  7691. * @param {number} [n23] - 2-3 matrix element.
  7692. * @param {number} [n24] - 2-4 matrix element.
  7693. * @param {number} [n31] - 3-1 matrix element.
  7694. * @param {number} [n32] - 3-2 matrix element.
  7695. * @param {number} [n33] - 3-3 matrix element.
  7696. * @param {number} [n34] - 3-4 matrix element.
  7697. * @param {number} [n41] - 4-1 matrix element.
  7698. * @param {number} [n42] - 4-2 matrix element.
  7699. * @param {number} [n43] - 4-3 matrix element.
  7700. * @param {number} [n44] - 4-4 matrix element.
  7701. * @return {Matrix4} A reference to this matrix.
  7702. */
  7703. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  7704. const te = this.elements;
  7705. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  7706. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  7707. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  7708. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  7709. return this;
  7710. }
  7711. /**
  7712. * Sets this matrix to the 4x4 identity matrix.
  7713. *
  7714. * @return {Matrix4} A reference to this matrix.
  7715. */
  7716. identity() {
  7717. this.set(
  7718. 1, 0, 0, 0,
  7719. 0, 1, 0, 0,
  7720. 0, 0, 1, 0,
  7721. 0, 0, 0, 1
  7722. );
  7723. return this;
  7724. }
  7725. /**
  7726. * Returns a matrix with copied values from this instance.
  7727. *
  7728. * @return {Matrix4} A clone of this instance.
  7729. */
  7730. clone() {
  7731. return new Matrix4().fromArray( this.elements );
  7732. }
  7733. /**
  7734. * Copies the values of the given matrix to this instance.
  7735. *
  7736. * @param {Matrix4} m - The matrix to copy.
  7737. * @return {Matrix4} A reference to this matrix.
  7738. */
  7739. copy( m ) {
  7740. const te = this.elements;
  7741. const me = m.elements;
  7742. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  7743. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  7744. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  7745. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  7746. return this;
  7747. }
  7748. /**
  7749. * Copies the translation component of the given matrix
  7750. * into this matrix's translation component.
  7751. *
  7752. * @param {Matrix4} m - The matrix to copy the translation component.
  7753. * @return {Matrix4} A reference to this matrix.
  7754. */
  7755. copyPosition( m ) {
  7756. const te = this.elements, me = m.elements;
  7757. te[ 12 ] = me[ 12 ];
  7758. te[ 13 ] = me[ 13 ];
  7759. te[ 14 ] = me[ 14 ];
  7760. return this;
  7761. }
  7762. /**
  7763. * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix.
  7764. *
  7765. * @param {Matrix3} m - The 3x3 matrix.
  7766. * @return {Matrix4} A reference to this matrix.
  7767. */
  7768. setFromMatrix3( m ) {
  7769. const me = m.elements;
  7770. this.set(
  7771. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  7772. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  7773. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  7774. 0, 0, 0, 1
  7775. );
  7776. return this;
  7777. }
  7778. /**
  7779. * Extracts the basis of this matrix into the three axis vectors provided.
  7780. *
  7781. * @param {Vector3} xAxis - The basis's x axis.
  7782. * @param {Vector3} yAxis - The basis's y axis.
  7783. * @param {Vector3} zAxis - The basis's z axis.
  7784. * @return {Matrix4} A reference to this matrix.
  7785. */
  7786. extractBasis( xAxis, yAxis, zAxis ) {
  7787. if ( this.determinant() === 0 ) {
  7788. xAxis.set( 1, 0, 0 );
  7789. yAxis.set( 0, 1, 0 );
  7790. zAxis.set( 0, 0, 1 );
  7791. return this;
  7792. }
  7793. xAxis.setFromMatrixColumn( this, 0 );
  7794. yAxis.setFromMatrixColumn( this, 1 );
  7795. zAxis.setFromMatrixColumn( this, 2 );
  7796. return this;
  7797. }
  7798. /**
  7799. * Sets the given basis vectors to this matrix.
  7800. *
  7801. * @param {Vector3} xAxis - The basis's x axis.
  7802. * @param {Vector3} yAxis - The basis's y axis.
  7803. * @param {Vector3} zAxis - The basis's z axis.
  7804. * @return {Matrix4} A reference to this matrix.
  7805. */
  7806. makeBasis( xAxis, yAxis, zAxis ) {
  7807. this.set(
  7808. xAxis.x, yAxis.x, zAxis.x, 0,
  7809. xAxis.y, yAxis.y, zAxis.y, 0,
  7810. xAxis.z, yAxis.z, zAxis.z, 0,
  7811. 0, 0, 0, 1
  7812. );
  7813. return this;
  7814. }
  7815. /**
  7816. * Extracts the rotation component of the given matrix
  7817. * into this matrix's rotation component.
  7818. *
  7819. * Note: This method does not support reflection matrices.
  7820. *
  7821. * @param {Matrix4} m - The matrix.
  7822. * @return {Matrix4} A reference to this matrix.
  7823. */
  7824. extractRotation( m ) {
  7825. if ( m.determinant() === 0 ) {
  7826. return this.identity();
  7827. }
  7828. const te = this.elements;
  7829. const me = m.elements;
  7830. const scaleX = 1 / _v1$7.setFromMatrixColumn( m, 0 ).length();
  7831. const scaleY = 1 / _v1$7.setFromMatrixColumn( m, 1 ).length();
  7832. const scaleZ = 1 / _v1$7.setFromMatrixColumn( m, 2 ).length();
  7833. te[ 0 ] = me[ 0 ] * scaleX;
  7834. te[ 1 ] = me[ 1 ] * scaleX;
  7835. te[ 2 ] = me[ 2 ] * scaleX;
  7836. te[ 3 ] = 0;
  7837. te[ 4 ] = me[ 4 ] * scaleY;
  7838. te[ 5 ] = me[ 5 ] * scaleY;
  7839. te[ 6 ] = me[ 6 ] * scaleY;
  7840. te[ 7 ] = 0;
  7841. te[ 8 ] = me[ 8 ] * scaleZ;
  7842. te[ 9 ] = me[ 9 ] * scaleZ;
  7843. te[ 10 ] = me[ 10 ] * scaleZ;
  7844. te[ 11 ] = 0;
  7845. te[ 12 ] = 0;
  7846. te[ 13 ] = 0;
  7847. te[ 14 ] = 0;
  7848. te[ 15 ] = 1;
  7849. return this;
  7850. }
  7851. /**
  7852. * Sets the rotation component (the upper left 3x3 matrix) of this matrix to
  7853. * the rotation specified by the given Euler angles. The rest of
  7854. * the matrix is set to the identity. Depending on the {@link Euler#order},
  7855. * there are six possible outcomes. See [this page](https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix)
  7856. * for a complete list.
  7857. *
  7858. * @param {Euler} euler - The Euler angles.
  7859. * @return {Matrix4} A reference to this matrix.
  7860. */
  7861. makeRotationFromEuler( euler ) {
  7862. const te = this.elements;
  7863. const x = euler.x, y = euler.y, z = euler.z;
  7864. const a = Math.cos( x ), b = Math.sin( x );
  7865. const c = Math.cos( y ), d = Math.sin( y );
  7866. const e = Math.cos( z ), f = Math.sin( z );
  7867. if ( euler.order === 'XYZ' ) {
  7868. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  7869. te[ 0 ] = c * e;
  7870. te[ 4 ] = - c * f;
  7871. te[ 8 ] = d;
  7872. te[ 1 ] = af + be * d;
  7873. te[ 5 ] = ae - bf * d;
  7874. te[ 9 ] = - b * c;
  7875. te[ 2 ] = bf - ae * d;
  7876. te[ 6 ] = be + af * d;
  7877. te[ 10 ] = a * c;
  7878. } else if ( euler.order === 'YXZ' ) {
  7879. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  7880. te[ 0 ] = ce + df * b;
  7881. te[ 4 ] = de * b - cf;
  7882. te[ 8 ] = a * d;
  7883. te[ 1 ] = a * f;
  7884. te[ 5 ] = a * e;
  7885. te[ 9 ] = - b;
  7886. te[ 2 ] = cf * b - de;
  7887. te[ 6 ] = df + ce * b;
  7888. te[ 10 ] = a * c;
  7889. } else if ( euler.order === 'ZXY' ) {
  7890. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  7891. te[ 0 ] = ce - df * b;
  7892. te[ 4 ] = - a * f;
  7893. te[ 8 ] = de + cf * b;
  7894. te[ 1 ] = cf + de * b;
  7895. te[ 5 ] = a * e;
  7896. te[ 9 ] = df - ce * b;
  7897. te[ 2 ] = - a * d;
  7898. te[ 6 ] = b;
  7899. te[ 10 ] = a * c;
  7900. } else if ( euler.order === 'ZYX' ) {
  7901. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  7902. te[ 0 ] = c * e;
  7903. te[ 4 ] = be * d - af;
  7904. te[ 8 ] = ae * d + bf;
  7905. te[ 1 ] = c * f;
  7906. te[ 5 ] = bf * d + ae;
  7907. te[ 9 ] = af * d - be;
  7908. te[ 2 ] = - d;
  7909. te[ 6 ] = b * c;
  7910. te[ 10 ] = a * c;
  7911. } else if ( euler.order === 'YZX' ) {
  7912. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  7913. te[ 0 ] = c * e;
  7914. te[ 4 ] = bd - ac * f;
  7915. te[ 8 ] = bc * f + ad;
  7916. te[ 1 ] = f;
  7917. te[ 5 ] = a * e;
  7918. te[ 9 ] = - b * e;
  7919. te[ 2 ] = - d * e;
  7920. te[ 6 ] = ad * f + bc;
  7921. te[ 10 ] = ac - bd * f;
  7922. } else if ( euler.order === 'XZY' ) {
  7923. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  7924. te[ 0 ] = c * e;
  7925. te[ 4 ] = - f;
  7926. te[ 8 ] = d * e;
  7927. te[ 1 ] = ac * f + bd;
  7928. te[ 5 ] = a * e;
  7929. te[ 9 ] = ad * f - bc;
  7930. te[ 2 ] = bc * f - ad;
  7931. te[ 6 ] = b * e;
  7932. te[ 10 ] = bd * f + ac;
  7933. }
  7934. // bottom row
  7935. te[ 3 ] = 0;
  7936. te[ 7 ] = 0;
  7937. te[ 11 ] = 0;
  7938. // last column
  7939. te[ 12 ] = 0;
  7940. te[ 13 ] = 0;
  7941. te[ 14 ] = 0;
  7942. te[ 15 ] = 1;
  7943. return this;
  7944. }
  7945. /**
  7946. * Sets the rotation component of this matrix to the rotation specified by
  7947. * the given Quaternion as outlined [here](https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion)
  7948. * The rest of the matrix is set to the identity.
  7949. *
  7950. * @param {Quaternion} q - The Quaternion.
  7951. * @return {Matrix4} A reference to this matrix.
  7952. */
  7953. makeRotationFromQuaternion( q ) {
  7954. return this.compose( _zero, q, _one );
  7955. }
  7956. /**
  7957. * Sets the rotation component of the transformation matrix, looking from `eye` towards
  7958. * `target`, and oriented by the up-direction.
  7959. *
  7960. * @param {Vector3} eye - The eye vector.
  7961. * @param {Vector3} target - The target vector.
  7962. * @param {Vector3} up - The up vector.
  7963. * @return {Matrix4} A reference to this matrix.
  7964. */
  7965. lookAt( eye, target, up ) {
  7966. const te = this.elements;
  7967. _z.subVectors( eye, target );
  7968. if ( _z.lengthSq() === 0 ) {
  7969. // eye and target are in the same position
  7970. _z.z = 1;
  7971. }
  7972. _z.normalize();
  7973. _x.crossVectors( up, _z );
  7974. if ( _x.lengthSq() === 0 ) {
  7975. // up and z are parallel
  7976. if ( Math.abs( up.z ) === 1 ) {
  7977. _z.x += 0.0001;
  7978. } else {
  7979. _z.z += 0.0001;
  7980. }
  7981. _z.normalize();
  7982. _x.crossVectors( up, _z );
  7983. }
  7984. _x.normalize();
  7985. _y.crossVectors( _z, _x );
  7986. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  7987. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  7988. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  7989. return this;
  7990. }
  7991. /**
  7992. * Post-multiplies this matrix by the given 4x4 matrix.
  7993. *
  7994. * @param {Matrix4} m - The matrix to multiply with.
  7995. * @return {Matrix4} A reference to this matrix.
  7996. */
  7997. multiply( m ) {
  7998. return this.multiplyMatrices( this, m );
  7999. }
  8000. /**
  8001. * Pre-multiplies this matrix by the given 4x4 matrix.
  8002. *
  8003. * @param {Matrix4} m - The matrix to multiply with.
  8004. * @return {Matrix4} A reference to this matrix.
  8005. */
  8006. premultiply( m ) {
  8007. return this.multiplyMatrices( m, this );
  8008. }
  8009. /**
  8010. * Multiples the given 4x4 matrices and stores the result
  8011. * in this matrix.
  8012. *
  8013. * @param {Matrix4} a - The first matrix.
  8014. * @param {Matrix4} b - The second matrix.
  8015. * @return {Matrix4} A reference to this matrix.
  8016. */
  8017. multiplyMatrices( a, b ) {
  8018. const ae = a.elements;
  8019. const be = b.elements;
  8020. const te = this.elements;
  8021. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  8022. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  8023. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  8024. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  8025. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  8026. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  8027. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  8028. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  8029. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  8030. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  8031. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  8032. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  8033. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  8034. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  8035. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  8036. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  8037. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  8038. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  8039. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  8040. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  8041. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  8042. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  8043. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  8044. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  8045. return this;
  8046. }
  8047. /**
  8048. * Multiplies every component of the matrix by the given scalar.
  8049. *
  8050. * @param {number} s - The scalar.
  8051. * @return {Matrix4} A reference to this matrix.
  8052. */
  8053. multiplyScalar( s ) {
  8054. const te = this.elements;
  8055. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  8056. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  8057. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  8058. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  8059. return this;
  8060. }
  8061. /**
  8062. * Computes and returns the determinant of this matrix.
  8063. *
  8064. * Based on the method outlined [here](http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html).
  8065. *
  8066. * @return {number} The determinant.
  8067. */
  8068. determinant() {
  8069. const te = this.elements;
  8070. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  8071. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  8072. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  8073. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  8074. const t11 = n23 * n34 - n24 * n33;
  8075. const t12 = n22 * n34 - n24 * n32;
  8076. const t13 = n22 * n33 - n23 * n32;
  8077. const t21 = n21 * n34 - n24 * n31;
  8078. const t22 = n21 * n33 - n23 * n31;
  8079. const t23 = n21 * n32 - n22 * n31;
  8080. return n11 * ( n42 * t11 - n43 * t12 + n44 * t13 ) -
  8081. n12 * ( n41 * t11 - n43 * t21 + n44 * t22 ) +
  8082. n13 * ( n41 * t12 - n42 * t21 + n44 * t23 ) -
  8083. n14 * ( n41 * t13 - n42 * t22 + n43 * t23 );
  8084. }
  8085. /**
  8086. * Transposes this matrix in place.
  8087. *
  8088. * @return {Matrix4} A reference to this matrix.
  8089. */
  8090. transpose() {
  8091. const te = this.elements;
  8092. let tmp;
  8093. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  8094. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  8095. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  8096. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  8097. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  8098. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  8099. return this;
  8100. }
  8101. /**
  8102. * Sets the position component for this matrix from the given vector,
  8103. * without affecting the rest of the matrix.
  8104. *
  8105. * @param {number|Vector3} x - The x component of the vector or alternatively the vector object.
  8106. * @param {number} y - The y component of the vector.
  8107. * @param {number} z - The z component of the vector.
  8108. * @return {Matrix4} A reference to this matrix.
  8109. */
  8110. setPosition( x, y, z ) {
  8111. const te = this.elements;
  8112. if ( x.isVector3 ) {
  8113. te[ 12 ] = x.x;
  8114. te[ 13 ] = x.y;
  8115. te[ 14 ] = x.z;
  8116. } else {
  8117. te[ 12 ] = x;
  8118. te[ 13 ] = y;
  8119. te[ 14 ] = z;
  8120. }
  8121. return this;
  8122. }
  8123. /**
  8124. * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution).
  8125. * You can not invert with a determinant of zero. If you attempt this, the method produces
  8126. * a zero matrix instead.
  8127. *
  8128. * @return {Matrix4} A reference to this matrix.
  8129. */
  8130. invert() {
  8131. // based on https://github.com/toji/gl-matrix
  8132. const te = this.elements,
  8133. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  8134. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  8135. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  8136. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  8137. t1 = n11 * n22 - n21 * n12,
  8138. t2 = n11 * n32 - n31 * n12,
  8139. t3 = n11 * n42 - n41 * n12,
  8140. t4 = n21 * n32 - n31 * n22,
  8141. t5 = n21 * n42 - n41 * n22,
  8142. t6 = n31 * n42 - n41 * n32,
  8143. t7 = n13 * n24 - n23 * n14,
  8144. t8 = n13 * n34 - n33 * n14,
  8145. t9 = n13 * n44 - n43 * n14,
  8146. t10 = n23 * n34 - n33 * n24,
  8147. t11 = n23 * n44 - n43 * n24,
  8148. t12 = n33 * n44 - n43 * n34;
  8149. const det = t1 * t12 - t2 * t11 + t3 * t10 + t4 * t9 - t5 * t8 + t6 * t7;
  8150. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  8151. const detInv = 1 / det;
  8152. te[ 0 ] = ( n22 * t12 - n32 * t11 + n42 * t10 ) * detInv;
  8153. te[ 1 ] = ( n31 * t11 - n21 * t12 - n41 * t10 ) * detInv;
  8154. te[ 2 ] = ( n24 * t6 - n34 * t5 + n44 * t4 ) * detInv;
  8155. te[ 3 ] = ( n33 * t5 - n23 * t6 - n43 * t4 ) * detInv;
  8156. te[ 4 ] = ( n32 * t9 - n12 * t12 - n42 * t8 ) * detInv;
  8157. te[ 5 ] = ( n11 * t12 - n31 * t9 + n41 * t8 ) * detInv;
  8158. te[ 6 ] = ( n34 * t3 - n14 * t6 - n44 * t2 ) * detInv;
  8159. te[ 7 ] = ( n13 * t6 - n33 * t3 + n43 * t2 ) * detInv;
  8160. te[ 8 ] = ( n12 * t11 - n22 * t9 + n42 * t7 ) * detInv;
  8161. te[ 9 ] = ( n21 * t9 - n11 * t11 - n41 * t7 ) * detInv;
  8162. te[ 10 ] = ( n14 * t5 - n24 * t3 + n44 * t1 ) * detInv;
  8163. te[ 11 ] = ( n23 * t3 - n13 * t5 - n43 * t1 ) * detInv;
  8164. te[ 12 ] = ( n22 * t8 - n12 * t10 - n32 * t7 ) * detInv;
  8165. te[ 13 ] = ( n11 * t10 - n21 * t8 + n31 * t7 ) * detInv;
  8166. te[ 14 ] = ( n24 * t2 - n14 * t4 - n34 * t1 ) * detInv;
  8167. te[ 15 ] = ( n13 * t4 - n23 * t2 + n33 * t1 ) * detInv;
  8168. return this;
  8169. }
  8170. /**
  8171. * Multiplies the columns of this matrix by the given vector.
  8172. *
  8173. * @param {Vector3} v - The scale vector.
  8174. * @return {Matrix4} A reference to this matrix.
  8175. */
  8176. scale( v ) {
  8177. const te = this.elements;
  8178. const x = v.x, y = v.y, z = v.z;
  8179. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  8180. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  8181. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  8182. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  8183. return this;
  8184. }
  8185. /**
  8186. * Gets the maximum scale value of the three axes.
  8187. *
  8188. * @return {number} The maximum scale.
  8189. */
  8190. getMaxScaleOnAxis() {
  8191. const te = this.elements;
  8192. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  8193. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  8194. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  8195. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  8196. }
  8197. /**
  8198. * Sets this matrix as a translation transform from the given vector.
  8199. *
  8200. * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector.
  8201. * @param {number} y - The amount to translate in the Y axis.
  8202. * @param {number} z - The amount to translate in the z axis.
  8203. * @return {Matrix4} A reference to this matrix.
  8204. */
  8205. makeTranslation( x, y, z ) {
  8206. if ( x.isVector3 ) {
  8207. this.set(
  8208. 1, 0, 0, x.x,
  8209. 0, 1, 0, x.y,
  8210. 0, 0, 1, x.z,
  8211. 0, 0, 0, 1
  8212. );
  8213. } else {
  8214. this.set(
  8215. 1, 0, 0, x,
  8216. 0, 1, 0, y,
  8217. 0, 0, 1, z,
  8218. 0, 0, 0, 1
  8219. );
  8220. }
  8221. return this;
  8222. }
  8223. /**
  8224. * Sets this matrix as a rotational transformation around the X axis by
  8225. * the given angle.
  8226. *
  8227. * @param {number} theta - The rotation in radians.
  8228. * @return {Matrix4} A reference to this matrix.
  8229. */
  8230. makeRotationX( theta ) {
  8231. const c = Math.cos( theta ), s = Math.sin( theta );
  8232. this.set(
  8233. 1, 0, 0, 0,
  8234. 0, c, - s, 0,
  8235. 0, s, c, 0,
  8236. 0, 0, 0, 1
  8237. );
  8238. return this;
  8239. }
  8240. /**
  8241. * Sets this matrix as a rotational transformation around the Y axis by
  8242. * the given angle.
  8243. *
  8244. * @param {number} theta - The rotation in radians.
  8245. * @return {Matrix4} A reference to this matrix.
  8246. */
  8247. makeRotationY( theta ) {
  8248. const c = Math.cos( theta ), s = Math.sin( theta );
  8249. this.set(
  8250. c, 0, s, 0,
  8251. 0, 1, 0, 0,
  8252. - s, 0, c, 0,
  8253. 0, 0, 0, 1
  8254. );
  8255. return this;
  8256. }
  8257. /**
  8258. * Sets this matrix as a rotational transformation around the Z axis by
  8259. * the given angle.
  8260. *
  8261. * @param {number} theta - The rotation in radians.
  8262. * @return {Matrix4} A reference to this matrix.
  8263. */
  8264. makeRotationZ( theta ) {
  8265. const c = Math.cos( theta ), s = Math.sin( theta );
  8266. this.set(
  8267. c, - s, 0, 0,
  8268. s, c, 0, 0,
  8269. 0, 0, 1, 0,
  8270. 0, 0, 0, 1
  8271. );
  8272. return this;
  8273. }
  8274. /**
  8275. * Sets this matrix as a rotational transformation around the given axis by
  8276. * the given angle.
  8277. *
  8278. * This is a somewhat controversial but mathematically sound alternative to
  8279. * rotating via Quaternions. See the discussion [here](https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199).
  8280. *
  8281. * @param {Vector3} axis - The normalized rotation axis.
  8282. * @param {number} angle - The rotation in radians.
  8283. * @return {Matrix4} A reference to this matrix.
  8284. */
  8285. makeRotationAxis( axis, angle ) {
  8286. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  8287. const c = Math.cos( angle );
  8288. const s = Math.sin( angle );
  8289. const t = 1 - c;
  8290. const x = axis.x, y = axis.y, z = axis.z;
  8291. const tx = t * x, ty = t * y;
  8292. this.set(
  8293. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  8294. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  8295. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  8296. 0, 0, 0, 1
  8297. );
  8298. return this;
  8299. }
  8300. /**
  8301. * Sets this matrix as a scale transformation.
  8302. *
  8303. * @param {number} x - The amount to scale in the X axis.
  8304. * @param {number} y - The amount to scale in the Y axis.
  8305. * @param {number} z - The amount to scale in the Z axis.
  8306. * @return {Matrix4} A reference to this matrix.
  8307. */
  8308. makeScale( x, y, z ) {
  8309. this.set(
  8310. x, 0, 0, 0,
  8311. 0, y, 0, 0,
  8312. 0, 0, z, 0,
  8313. 0, 0, 0, 1
  8314. );
  8315. return this;
  8316. }
  8317. /**
  8318. * Sets this matrix as a shear transformation.
  8319. *
  8320. * @param {number} xy - The amount to shear X by Y.
  8321. * @param {number} xz - The amount to shear X by Z.
  8322. * @param {number} yx - The amount to shear Y by X.
  8323. * @param {number} yz - The amount to shear Y by Z.
  8324. * @param {number} zx - The amount to shear Z by X.
  8325. * @param {number} zy - The amount to shear Z by Y.
  8326. * @return {Matrix4} A reference to this matrix.
  8327. */
  8328. makeShear( xy, xz, yx, yz, zx, zy ) {
  8329. this.set(
  8330. 1, yx, zx, 0,
  8331. xy, 1, zy, 0,
  8332. xz, yz, 1, 0,
  8333. 0, 0, 0, 1
  8334. );
  8335. return this;
  8336. }
  8337. /**
  8338. * Sets this matrix to the transformation composed of the given position,
  8339. * rotation (Quaternion) and scale.
  8340. *
  8341. * @param {Vector3} position - The position vector.
  8342. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  8343. * @param {Vector3} scale - The scale vector.
  8344. * @return {Matrix4} A reference to this matrix.
  8345. */
  8346. compose( position, quaternion, scale ) {
  8347. const te = this.elements;
  8348. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  8349. const x2 = x + x, y2 = y + y, z2 = z + z;
  8350. const xx = x * x2, xy = x * y2, xz = x * z2;
  8351. const yy = y * y2, yz = y * z2, zz = z * z2;
  8352. const wx = w * x2, wy = w * y2, wz = w * z2;
  8353. const sx = scale.x, sy = scale.y, sz = scale.z;
  8354. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  8355. te[ 1 ] = ( xy + wz ) * sx;
  8356. te[ 2 ] = ( xz - wy ) * sx;
  8357. te[ 3 ] = 0;
  8358. te[ 4 ] = ( xy - wz ) * sy;
  8359. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  8360. te[ 6 ] = ( yz + wx ) * sy;
  8361. te[ 7 ] = 0;
  8362. te[ 8 ] = ( xz + wy ) * sz;
  8363. te[ 9 ] = ( yz - wx ) * sz;
  8364. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  8365. te[ 11 ] = 0;
  8366. te[ 12 ] = position.x;
  8367. te[ 13 ] = position.y;
  8368. te[ 14 ] = position.z;
  8369. te[ 15 ] = 1;
  8370. return this;
  8371. }
  8372. /**
  8373. * Decomposes this matrix into its position, rotation and scale components
  8374. * and provides the result in the given objects.
  8375. *
  8376. * Note: Not all matrices are decomposable in this way. For example, if an
  8377. * object has a non-uniformly scaled parent, then the object's world matrix
  8378. * may not be decomposable, and this method may not be appropriate.
  8379. *
  8380. * @param {Vector3} position - The position vector.
  8381. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  8382. * @param {Vector3} scale - The scale vector.
  8383. * @return {Matrix4} A reference to this matrix.
  8384. */
  8385. decompose( position, quaternion, scale ) {
  8386. const te = this.elements;
  8387. position.x = te[ 12 ];
  8388. position.y = te[ 13 ];
  8389. position.z = te[ 14 ];
  8390. const det = this.determinant();
  8391. if ( det === 0 ) {
  8392. scale.set( 1, 1, 1 );
  8393. quaternion.identity();
  8394. return this;
  8395. }
  8396. let sx = _v1$7.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  8397. const sy = _v1$7.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  8398. const sz = _v1$7.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  8399. // if determinant is negative, we need to invert one scale
  8400. if ( det < 0 ) sx = - sx;
  8401. // scale the rotation part
  8402. _m1$2.copy( this );
  8403. const invSX = 1 / sx;
  8404. const invSY = 1 / sy;
  8405. const invSZ = 1 / sz;
  8406. _m1$2.elements[ 0 ] *= invSX;
  8407. _m1$2.elements[ 1 ] *= invSX;
  8408. _m1$2.elements[ 2 ] *= invSX;
  8409. _m1$2.elements[ 4 ] *= invSY;
  8410. _m1$2.elements[ 5 ] *= invSY;
  8411. _m1$2.elements[ 6 ] *= invSY;
  8412. _m1$2.elements[ 8 ] *= invSZ;
  8413. _m1$2.elements[ 9 ] *= invSZ;
  8414. _m1$2.elements[ 10 ] *= invSZ;
  8415. quaternion.setFromRotationMatrix( _m1$2 );
  8416. scale.x = sx;
  8417. scale.y = sy;
  8418. scale.z = sz;
  8419. return this;
  8420. }
  8421. /**
  8422. * Creates a perspective projection matrix. This is used internally by
  8423. * {@link PerspectiveCamera#updateProjectionMatrix}.
  8424. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  8425. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  8426. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  8427. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  8428. * @param {number} near - The distance from the camera to the near plane.
  8429. * @param {number} far - The distance from the camera to the far plane.
  8430. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  8431. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  8432. * @return {Matrix4} A reference to this matrix.
  8433. */
  8434. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  8435. const te = this.elements;
  8436. const x = 2 * near / ( right - left );
  8437. const y = 2 * near / ( top - bottom );
  8438. const a = ( right + left ) / ( right - left );
  8439. const b = ( top + bottom ) / ( top - bottom );
  8440. let c, d;
  8441. if ( reversedDepth ) {
  8442. c = near / ( far - near );
  8443. d = ( far * near ) / ( far - near );
  8444. } else {
  8445. if ( coordinateSystem === WebGLCoordinateSystem ) {
  8446. c = - ( far + near ) / ( far - near );
  8447. d = ( -2 * far * near ) / ( far - near );
  8448. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  8449. c = - far / ( far - near );
  8450. d = ( - far * near ) / ( far - near );
  8451. } else {
  8452. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  8453. }
  8454. }
  8455. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  8456. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  8457. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  8458. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = -1; te[ 15 ] = 0;
  8459. return this;
  8460. }
  8461. /**
  8462. * Creates a orthographic projection matrix. This is used internally by
  8463. * {@link OrthographicCamera#updateProjectionMatrix}.
  8464. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  8465. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  8466. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  8467. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  8468. * @param {number} near - The distance from the camera to the near plane.
  8469. * @param {number} far - The distance from the camera to the far plane.
  8470. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  8471. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  8472. * @return {Matrix4} A reference to this matrix.
  8473. */
  8474. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  8475. const te = this.elements;
  8476. const x = 2 / ( right - left );
  8477. const y = 2 / ( top - bottom );
  8478. const a = - ( right + left ) / ( right - left );
  8479. const b = - ( top + bottom ) / ( top - bottom );
  8480. let c, d;
  8481. if ( reversedDepth ) {
  8482. c = 1 / ( far - near );
  8483. d = far / ( far - near );
  8484. } else {
  8485. if ( coordinateSystem === WebGLCoordinateSystem ) {
  8486. c = -2 / ( far - near );
  8487. d = - ( far + near ) / ( far - near );
  8488. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  8489. c = -1 / ( far - near );
  8490. d = - near / ( far - near );
  8491. } else {
  8492. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  8493. }
  8494. }
  8495. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = a;
  8496. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = 0; te[ 13 ] = b;
  8497. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  8498. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  8499. return this;
  8500. }
  8501. /**
  8502. * Returns `true` if this matrix is equal with the given one.
  8503. *
  8504. * @param {Matrix4} matrix - The matrix to test for equality.
  8505. * @return {boolean} Whether this matrix is equal with the given one.
  8506. */
  8507. equals( matrix ) {
  8508. const te = this.elements;
  8509. const me = matrix.elements;
  8510. for ( let i = 0; i < 16; i ++ ) {
  8511. if ( te[ i ] !== me[ i ] ) return false;
  8512. }
  8513. return true;
  8514. }
  8515. /**
  8516. * Sets the elements of the matrix from the given array.
  8517. *
  8518. * @param {Array<number>} array - The matrix elements in column-major order.
  8519. * @param {number} [offset=0] - Index of the first element in the array.
  8520. * @return {Matrix4} A reference to this matrix.
  8521. */
  8522. fromArray( array, offset = 0 ) {
  8523. for ( let i = 0; i < 16; i ++ ) {
  8524. this.elements[ i ] = array[ i + offset ];
  8525. }
  8526. return this;
  8527. }
  8528. /**
  8529. * Writes the elements of this matrix to the given array. If no array is provided,
  8530. * the method returns a new instance.
  8531. *
  8532. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  8533. * @param {number} [offset=0] - Index of the first element in the array.
  8534. * @return {Array<number>} The matrix elements in column-major order.
  8535. */
  8536. toArray( array = [], offset = 0 ) {
  8537. const te = this.elements;
  8538. array[ offset ] = te[ 0 ];
  8539. array[ offset + 1 ] = te[ 1 ];
  8540. array[ offset + 2 ] = te[ 2 ];
  8541. array[ offset + 3 ] = te[ 3 ];
  8542. array[ offset + 4 ] = te[ 4 ];
  8543. array[ offset + 5 ] = te[ 5 ];
  8544. array[ offset + 6 ] = te[ 6 ];
  8545. array[ offset + 7 ] = te[ 7 ];
  8546. array[ offset + 8 ] = te[ 8 ];
  8547. array[ offset + 9 ] = te[ 9 ];
  8548. array[ offset + 10 ] = te[ 10 ];
  8549. array[ offset + 11 ] = te[ 11 ];
  8550. array[ offset + 12 ] = te[ 12 ];
  8551. array[ offset + 13 ] = te[ 13 ];
  8552. array[ offset + 14 ] = te[ 14 ];
  8553. array[ offset + 15 ] = te[ 15 ];
  8554. return array;
  8555. }
  8556. }
  8557. const _v1$7 = /*@__PURE__*/ new Vector3();
  8558. const _m1$2 = /*@__PURE__*/ new Matrix4();
  8559. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  8560. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  8561. const _x = /*@__PURE__*/ new Vector3();
  8562. const _y = /*@__PURE__*/ new Vector3();
  8563. const _z = /*@__PURE__*/ new Vector3();
  8564. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  8565. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  8566. /**
  8567. * A class representing Euler angles.
  8568. *
  8569. * Euler angles describe a rotational transformation by rotating an object on
  8570. * its various axes in specified amounts per axis, and a specified axis
  8571. * order.
  8572. *
  8573. * Iterating through an instance will yield its components (x, y, z,
  8574. * order) in the corresponding order.
  8575. *
  8576. * ```js
  8577. * const a = new THREE.Euler( 0, 1, 1.57, 'XYZ' );
  8578. * const b = new THREE.Vector3( 1, 0, 1 );
  8579. * b.applyEuler(a);
  8580. * ```
  8581. */
  8582. class Euler {
  8583. /**
  8584. * Constructs a new euler instance.
  8585. *
  8586. * @param {number} [x=0] - The angle of the x axis in radians.
  8587. * @param {number} [y=0] - The angle of the y axis in radians.
  8588. * @param {number} [z=0] - The angle of the z axis in radians.
  8589. * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
  8590. */
  8591. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  8592. /**
  8593. * This flag can be used for type testing.
  8594. *
  8595. * @type {boolean}
  8596. * @readonly
  8597. * @default true
  8598. */
  8599. this.isEuler = true;
  8600. this._x = x;
  8601. this._y = y;
  8602. this._z = z;
  8603. this._order = order;
  8604. }
  8605. /**
  8606. * The angle of the x axis in radians.
  8607. *
  8608. * @type {number}
  8609. * @default 0
  8610. */
  8611. get x() {
  8612. return this._x;
  8613. }
  8614. set x( value ) {
  8615. this._x = value;
  8616. this._onChangeCallback();
  8617. }
  8618. /**
  8619. * The angle of the y axis in radians.
  8620. *
  8621. * @type {number}
  8622. * @default 0
  8623. */
  8624. get y() {
  8625. return this._y;
  8626. }
  8627. set y( value ) {
  8628. this._y = value;
  8629. this._onChangeCallback();
  8630. }
  8631. /**
  8632. * The angle of the z axis in radians.
  8633. *
  8634. * @type {number}
  8635. * @default 0
  8636. */
  8637. get z() {
  8638. return this._z;
  8639. }
  8640. set z( value ) {
  8641. this._z = value;
  8642. this._onChangeCallback();
  8643. }
  8644. /**
  8645. * A string representing the order that the rotations are applied.
  8646. *
  8647. * @type {string}
  8648. * @default 'XYZ'
  8649. */
  8650. get order() {
  8651. return this._order;
  8652. }
  8653. set order( value ) {
  8654. this._order = value;
  8655. this._onChangeCallback();
  8656. }
  8657. /**
  8658. * Sets the Euler components.
  8659. *
  8660. * @param {number} x - The angle of the x axis in radians.
  8661. * @param {number} y - The angle of the y axis in radians.
  8662. * @param {number} z - The angle of the z axis in radians.
  8663. * @param {string} [order] - A string representing the order that the rotations are applied.
  8664. * @return {Euler} A reference to this Euler instance.
  8665. */
  8666. set( x, y, z, order = this._order ) {
  8667. this._x = x;
  8668. this._y = y;
  8669. this._z = z;
  8670. this._order = order;
  8671. this._onChangeCallback();
  8672. return this;
  8673. }
  8674. /**
  8675. * Returns a new Euler instance with copied values from this instance.
  8676. *
  8677. * @return {Euler} A clone of this instance.
  8678. */
  8679. clone() {
  8680. return new this.constructor( this._x, this._y, this._z, this._order );
  8681. }
  8682. /**
  8683. * Copies the values of the given Euler instance to this instance.
  8684. *
  8685. * @param {Euler} euler - The Euler instance to copy.
  8686. * @return {Euler} A reference to this Euler instance.
  8687. */
  8688. copy( euler ) {
  8689. this._x = euler._x;
  8690. this._y = euler._y;
  8691. this._z = euler._z;
  8692. this._order = euler._order;
  8693. this._onChangeCallback();
  8694. return this;
  8695. }
  8696. /**
  8697. * Sets the angles of this Euler instance from a pure rotation matrix.
  8698. *
  8699. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  8700. * @param {string} [order] - A string representing the order that the rotations are applied.
  8701. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  8702. * @return {Euler} A reference to this Euler instance.
  8703. */
  8704. setFromRotationMatrix( m, order = this._order, update = true ) {
  8705. const te = m.elements;
  8706. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  8707. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  8708. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  8709. switch ( order ) {
  8710. case 'XYZ':
  8711. this._y = Math.asin( clamp( m13, -1, 1 ) );
  8712. if ( Math.abs( m13 ) < 0.9999999 ) {
  8713. this._x = Math.atan2( - m23, m33 );
  8714. this._z = Math.atan2( - m12, m11 );
  8715. } else {
  8716. this._x = Math.atan2( m32, m22 );
  8717. this._z = 0;
  8718. }
  8719. break;
  8720. case 'YXZ':
  8721. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  8722. if ( Math.abs( m23 ) < 0.9999999 ) {
  8723. this._y = Math.atan2( m13, m33 );
  8724. this._z = Math.atan2( m21, m22 );
  8725. } else {
  8726. this._y = Math.atan2( - m31, m11 );
  8727. this._z = 0;
  8728. }
  8729. break;
  8730. case 'ZXY':
  8731. this._x = Math.asin( clamp( m32, -1, 1 ) );
  8732. if ( Math.abs( m32 ) < 0.9999999 ) {
  8733. this._y = Math.atan2( - m31, m33 );
  8734. this._z = Math.atan2( - m12, m22 );
  8735. } else {
  8736. this._y = 0;
  8737. this._z = Math.atan2( m21, m11 );
  8738. }
  8739. break;
  8740. case 'ZYX':
  8741. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  8742. if ( Math.abs( m31 ) < 0.9999999 ) {
  8743. this._x = Math.atan2( m32, m33 );
  8744. this._z = Math.atan2( m21, m11 );
  8745. } else {
  8746. this._x = 0;
  8747. this._z = Math.atan2( - m12, m22 );
  8748. }
  8749. break;
  8750. case 'YZX':
  8751. this._z = Math.asin( clamp( m21, -1, 1 ) );
  8752. if ( Math.abs( m21 ) < 0.9999999 ) {
  8753. this._x = Math.atan2( - m23, m22 );
  8754. this._y = Math.atan2( - m31, m11 );
  8755. } else {
  8756. this._x = 0;
  8757. this._y = Math.atan2( m13, m33 );
  8758. }
  8759. break;
  8760. case 'XZY':
  8761. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  8762. if ( Math.abs( m12 ) < 0.9999999 ) {
  8763. this._x = Math.atan2( m32, m22 );
  8764. this._y = Math.atan2( m13, m11 );
  8765. } else {
  8766. this._x = Math.atan2( - m23, m33 );
  8767. this._y = 0;
  8768. }
  8769. break;
  8770. default:
  8771. warn( 'Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  8772. }
  8773. this._order = order;
  8774. if ( update === true ) this._onChangeCallback();
  8775. return this;
  8776. }
  8777. /**
  8778. * Sets the angles of this Euler instance from a normalized quaternion.
  8779. *
  8780. * @param {Quaternion} q - A normalized Quaternion.
  8781. * @param {string} [order] - A string representing the order that the rotations are applied.
  8782. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  8783. * @return {Euler} A reference to this Euler instance.
  8784. */
  8785. setFromQuaternion( q, order, update ) {
  8786. _matrix$2.makeRotationFromQuaternion( q );
  8787. return this.setFromRotationMatrix( _matrix$2, order, update );
  8788. }
  8789. /**
  8790. * Sets the angles of this Euler instance from the given vector.
  8791. *
  8792. * @param {Vector3} v - The vector.
  8793. * @param {string} [order] - A string representing the order that the rotations are applied.
  8794. * @return {Euler} A reference to this Euler instance.
  8795. */
  8796. setFromVector3( v, order = this._order ) {
  8797. return this.set( v.x, v.y, v.z, order );
  8798. }
  8799. /**
  8800. * Resets the euler angle with a new order by creating a quaternion from this
  8801. * euler angle and then setting this euler angle with the quaternion and the
  8802. * new order.
  8803. *
  8804. * Warning: This discards revolution information.
  8805. *
  8806. * @param {string} [newOrder] - A string representing the new order that the rotations are applied.
  8807. * @return {Euler} A reference to this Euler instance.
  8808. */
  8809. reorder( newOrder ) {
  8810. _quaternion$4.setFromEuler( this );
  8811. return this.setFromQuaternion( _quaternion$4, newOrder );
  8812. }
  8813. /**
  8814. * Returns `true` if this Euler instance is equal with the given one.
  8815. *
  8816. * @param {Euler} euler - The Euler instance to test for equality.
  8817. * @return {boolean} Whether this Euler instance is equal with the given one.
  8818. */
  8819. equals( euler ) {
  8820. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  8821. }
  8822. /**
  8823. * Sets this Euler instance's components to values from the given array. The first three
  8824. * entries of the array are assign to the x,y and z components. An optional fourth entry
  8825. * defines the Euler order.
  8826. *
  8827. * @param {Array<number,number,number,?string>} array - An array holding the Euler component values.
  8828. * @return {Euler} A reference to this Euler instance.
  8829. */
  8830. fromArray( array ) {
  8831. this._x = array[ 0 ];
  8832. this._y = array[ 1 ];
  8833. this._z = array[ 2 ];
  8834. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  8835. this._onChangeCallback();
  8836. return this;
  8837. }
  8838. /**
  8839. * Writes the components of this Euler instance to the given array. If no array is provided,
  8840. * the method returns a new instance.
  8841. *
  8842. * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components.
  8843. * @param {number} [offset=0] - Index of the first element in the array.
  8844. * @return {Array<number,number,number,string>} The Euler components.
  8845. */
  8846. toArray( array = [], offset = 0 ) {
  8847. array[ offset ] = this._x;
  8848. array[ offset + 1 ] = this._y;
  8849. array[ offset + 2 ] = this._z;
  8850. array[ offset + 3 ] = this._order;
  8851. return array;
  8852. }
  8853. _onChange( callback ) {
  8854. this._onChangeCallback = callback;
  8855. return this;
  8856. }
  8857. _onChangeCallback() {}
  8858. *[ Symbol.iterator ]() {
  8859. yield this._x;
  8860. yield this._y;
  8861. yield this._z;
  8862. yield this._order;
  8863. }
  8864. }
  8865. /**
  8866. * The default Euler angle order.
  8867. *
  8868. * @static
  8869. * @type {string}
  8870. * @default 'XYZ'
  8871. */
  8872. Euler.DEFAULT_ORDER = 'XYZ';
  8873. /**
  8874. * A layers object assigns an 3D object to 1 or more of 32
  8875. * layers numbered `0` to `31` - internally the layers are stored as a
  8876. * bit mask], and by default all 3D objects are a member of layer `0`.
  8877. *
  8878. * This can be used to control visibility - an object must share a layer with
  8879. * a camera to be visible when that camera's view is
  8880. * rendered.
  8881. *
  8882. * All classes that inherit from {@link Object3D} have an `layers` property which
  8883. * is an instance of this class.
  8884. */
  8885. class Layers {
  8886. /**
  8887. * Constructs a new layers instance, with membership
  8888. * initially set to layer `0`.
  8889. */
  8890. constructor() {
  8891. /**
  8892. * A bit mask storing which of the 32 layers this layers object is currently
  8893. * a member of.
  8894. *
  8895. * @type {number}
  8896. */
  8897. this.mask = 1 | 0;
  8898. }
  8899. /**
  8900. * Sets membership to the given layer, and remove membership all other layers.
  8901. *
  8902. * @param {number} layer - The layer to set.
  8903. */
  8904. set( layer ) {
  8905. this.mask = ( 1 << layer | 0 ) >>> 0;
  8906. }
  8907. /**
  8908. * Adds membership of the given layer.
  8909. *
  8910. * @param {number} layer - The layer to enable.
  8911. */
  8912. enable( layer ) {
  8913. this.mask |= 1 << layer | 0;
  8914. }
  8915. /**
  8916. * Adds membership to all layers.
  8917. */
  8918. enableAll() {
  8919. this.mask = 0xffffffff | 0;
  8920. }
  8921. /**
  8922. * Toggles the membership of the given layer.
  8923. *
  8924. * @param {number} layer - The layer to toggle.
  8925. */
  8926. toggle( layer ) {
  8927. this.mask ^= 1 << layer | 0;
  8928. }
  8929. /**
  8930. * Removes membership of the given layer.
  8931. *
  8932. * @param {number} layer - The layer to enable.
  8933. */
  8934. disable( layer ) {
  8935. this.mask &= ~ ( 1 << layer | 0 );
  8936. }
  8937. /**
  8938. * Removes the membership from all layers.
  8939. */
  8940. disableAll() {
  8941. this.mask = 0;
  8942. }
  8943. /**
  8944. * Returns `true` if this and the given layers object have at least one
  8945. * layer in common.
  8946. *
  8947. * @param {Layers} layers - The layers to test.
  8948. * @return {boolean } Whether this and the given layers object have at least one layer in common or not.
  8949. */
  8950. test( layers ) {
  8951. return ( this.mask & layers.mask ) !== 0;
  8952. }
  8953. /**
  8954. * Returns `true` if the given layer is enabled.
  8955. *
  8956. * @param {number} layer - The layer to test.
  8957. * @return {boolean } Whether the given layer is enabled or not.
  8958. */
  8959. isEnabled( layer ) {
  8960. return ( this.mask & ( 1 << layer | 0 ) ) !== 0;
  8961. }
  8962. }
  8963. let _object3DId = 0;
  8964. const _v1$6 = /*@__PURE__*/ new Vector3();
  8965. const _q1 = /*@__PURE__*/ new Quaternion();
  8966. const _m1$1 = /*@__PURE__*/ new Matrix4();
  8967. const _target = /*@__PURE__*/ new Vector3();
  8968. const _position$4 = /*@__PURE__*/ new Vector3();
  8969. const _scale$3 = /*@__PURE__*/ new Vector3();
  8970. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  8971. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  8972. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  8973. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  8974. /**
  8975. * Fires when the object has been added to its parent object.
  8976. *
  8977. * @event Object3D#added
  8978. * @type {Object}
  8979. */
  8980. const _addedEvent = { type: 'added' };
  8981. /**
  8982. * Fires when the object has been removed from its parent object.
  8983. *
  8984. * @event Object3D#removed
  8985. * @type {Object}
  8986. */
  8987. const _removedEvent = { type: 'removed' };
  8988. /**
  8989. * Fires when a new child object has been added.
  8990. *
  8991. * @event Object3D#childadded
  8992. * @type {Object}
  8993. */
  8994. const _childaddedEvent = { type: 'childadded', child: null };
  8995. /**
  8996. * Fires when a child object has been removed.
  8997. *
  8998. * @event Object3D#childremoved
  8999. * @type {Object}
  9000. */
  9001. const _childremovedEvent = { type: 'childremoved', child: null };
  9002. /**
  9003. * This is the base class for most objects in three.js and provides a set of
  9004. * properties and methods for manipulating objects in 3D space.
  9005. *
  9006. * @augments EventDispatcher
  9007. */
  9008. class Object3D extends EventDispatcher {
  9009. /**
  9010. * Constructs a new 3D object.
  9011. */
  9012. constructor() {
  9013. super();
  9014. /**
  9015. * This flag can be used for type testing.
  9016. *
  9017. * @type {boolean}
  9018. * @readonly
  9019. * @default true
  9020. */
  9021. this.isObject3D = true;
  9022. /**
  9023. * The ID of the 3D object.
  9024. *
  9025. * @name Object3D#id
  9026. * @type {number}
  9027. * @readonly
  9028. */
  9029. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  9030. /**
  9031. * The UUID of the 3D object.
  9032. *
  9033. * @type {string}
  9034. * @readonly
  9035. */
  9036. this.uuid = generateUUID();
  9037. /**
  9038. * The name of the 3D object.
  9039. *
  9040. * @type {string}
  9041. */
  9042. this.name = '';
  9043. /**
  9044. * The type property is used for detecting the object type
  9045. * in context of serialization/deserialization.
  9046. *
  9047. * @type {string}
  9048. * @readonly
  9049. */
  9050. this.type = 'Object3D';
  9051. /**
  9052. * A reference to the parent object.
  9053. *
  9054. * @type {?Object3D}
  9055. * @default null
  9056. */
  9057. this.parent = null;
  9058. /**
  9059. * An array holding the child 3D objects of this instance.
  9060. *
  9061. * @type {Array<Object3D>}
  9062. */
  9063. this.children = [];
  9064. /**
  9065. * Defines the `up` direction of the 3D object which influences
  9066. * the orientation via methods like {@link Object3D#lookAt}.
  9067. *
  9068. * The default values for all 3D objects is defined by `Object3D.DEFAULT_UP`.
  9069. *
  9070. * @type {Vector3}
  9071. */
  9072. this.up = Object3D.DEFAULT_UP.clone();
  9073. const position = new Vector3();
  9074. const rotation = new Euler();
  9075. const quaternion = new Quaternion();
  9076. const scale = new Vector3( 1, 1, 1 );
  9077. function onRotationChange() {
  9078. quaternion.setFromEuler( rotation, false );
  9079. }
  9080. function onQuaternionChange() {
  9081. rotation.setFromQuaternion( quaternion, undefined, false );
  9082. }
  9083. rotation._onChange( onRotationChange );
  9084. quaternion._onChange( onQuaternionChange );
  9085. Object.defineProperties( this, {
  9086. /**
  9087. * Represents the object's local position.
  9088. *
  9089. * @name Object3D#position
  9090. * @type {Vector3}
  9091. * @default (0,0,0)
  9092. */
  9093. position: {
  9094. configurable: true,
  9095. enumerable: true,
  9096. value: position
  9097. },
  9098. /**
  9099. * Represents the object's local rotation as Euler angles, in radians.
  9100. *
  9101. * @name Object3D#rotation
  9102. * @type {Euler}
  9103. * @default (0,0,0)
  9104. */
  9105. rotation: {
  9106. configurable: true,
  9107. enumerable: true,
  9108. value: rotation
  9109. },
  9110. /**
  9111. * Represents the object's local rotation as Quaternions.
  9112. *
  9113. * @name Object3D#quaternion
  9114. * @type {Quaternion}
  9115. */
  9116. quaternion: {
  9117. configurable: true,
  9118. enumerable: true,
  9119. value: quaternion
  9120. },
  9121. /**
  9122. * Represents the object's local scale.
  9123. *
  9124. * @name Object3D#scale
  9125. * @type {Vector3}
  9126. * @default (1,1,1)
  9127. */
  9128. scale: {
  9129. configurable: true,
  9130. enumerable: true,
  9131. value: scale
  9132. },
  9133. /**
  9134. * Represents the object's model-view matrix.
  9135. *
  9136. * @name Object3D#modelViewMatrix
  9137. * @type {Matrix4}
  9138. */
  9139. modelViewMatrix: {
  9140. value: new Matrix4()
  9141. },
  9142. /**
  9143. * Represents the object's normal matrix.
  9144. *
  9145. * @name Object3D#normalMatrix
  9146. * @type {Matrix3}
  9147. */
  9148. normalMatrix: {
  9149. value: new Matrix3()
  9150. }
  9151. } );
  9152. /**
  9153. * Represents the object's transformation matrix in local space.
  9154. *
  9155. * @type {Matrix4}
  9156. */
  9157. this.matrix = new Matrix4();
  9158. /**
  9159. * Represents the object's transformation matrix in world space.
  9160. * If the 3D object has no parent, then it's identical to the local transformation matrix
  9161. *
  9162. * @type {Matrix4}
  9163. */
  9164. this.matrixWorld = new Matrix4();
  9165. /**
  9166. * When set to `true`, the engine automatically computes the local matrix from position,
  9167. * rotation and scale every frame. If set to `false`, the app is responsible for recomputing
  9168. * the local matrix by calling `updateMatrix()`.
  9169. *
  9170. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_AUTO_UPDATE`.
  9171. *
  9172. * @type {boolean}
  9173. * @default true
  9174. */
  9175. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  9176. /**
  9177. * When set to `true`, the engine automatically computes the world matrix from the current local
  9178. * matrix and the object's transformation hierarchy. If set to `false`, the app is responsible for
  9179. * recomputing the world matrix by directly updating the `matrixWorld` property.
  9180. *
  9181. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE`.
  9182. *
  9183. * @type {boolean}
  9184. * @default true
  9185. */
  9186. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  9187. /**
  9188. * When set to `true`, it calculates the world matrix in that frame and resets this property
  9189. * to `false`.
  9190. *
  9191. * @type {boolean}
  9192. * @default false
  9193. */
  9194. this.matrixWorldNeedsUpdate = false;
  9195. /**
  9196. * The layer membership of the 3D object. The 3D object is only visible if it has
  9197. * at least one layer in common with the camera in use. This property can also be
  9198. * used to filter out unwanted objects in ray-intersection tests when using {@link Raycaster}.
  9199. *
  9200. * @type {Layers}
  9201. */
  9202. this.layers = new Layers();
  9203. /**
  9204. * When set to `true`, the 3D object gets rendered.
  9205. *
  9206. * @type {boolean}
  9207. * @default true
  9208. */
  9209. this.visible = true;
  9210. /**
  9211. * When set to `true`, the 3D object gets rendered into shadow maps.
  9212. *
  9213. * @type {boolean}
  9214. * @default false
  9215. */
  9216. this.castShadow = false;
  9217. /**
  9218. * When set to `true`, the 3D object is affected by shadows in the scene.
  9219. *
  9220. * @type {boolean}
  9221. * @default false
  9222. */
  9223. this.receiveShadow = false;
  9224. /**
  9225. * When set to `true`, the 3D object is honored by view frustum culling.
  9226. *
  9227. * @type {boolean}
  9228. * @default true
  9229. */
  9230. this.frustumCulled = true;
  9231. /**
  9232. * This value allows the default rendering order of scene graph objects to be
  9233. * overridden although opaque and transparent objects remain sorted independently.
  9234. * When this property is set for an instance of {@link Group},all descendants
  9235. * objects will be sorted and rendered together. Sorting is from lowest to highest
  9236. * render order.
  9237. *
  9238. * @type {number}
  9239. * @default 0
  9240. */
  9241. this.renderOrder = 0;
  9242. /**
  9243. * An array holding the animation clips of the 3D object.
  9244. *
  9245. * @type {Array<AnimationClip>}
  9246. */
  9247. this.animations = [];
  9248. /**
  9249. * Custom depth material to be used when rendering to the depth map. Can only be used
  9250. * in context of meshes. When shadow-casting with a {@link DirectionalLight} or {@link SpotLight},
  9251. * if you are modifying vertex positions in the vertex shader you must specify a custom depth
  9252. * material for proper shadows.
  9253. *
  9254. * Only relevant in context of {@link WebGLRenderer}.
  9255. *
  9256. * @type {(Material|undefined)}
  9257. * @default undefined
  9258. */
  9259. this.customDepthMaterial = undefined;
  9260. /**
  9261. * Same as {@link Object3D#customDepthMaterial}, but used with {@link PointLight}.
  9262. *
  9263. * Only relevant in context of {@link WebGLRenderer}.
  9264. *
  9265. * @type {(Material|undefined)}
  9266. * @default undefined
  9267. */
  9268. this.customDistanceMaterial = undefined;
  9269. /**
  9270. * Whether the 3D object is supposed to be static or not. If set to `true`, it means
  9271. * the 3D object is not going to be changed after the initial renderer. This includes
  9272. * geometry and material settings. A static 3D object can be processed by the renderer
  9273. * slightly faster since certain state checks can be bypassed.
  9274. *
  9275. * Only relevant in context of {@link WebGPURenderer}.
  9276. *
  9277. * @type {boolean}
  9278. * @default false
  9279. */
  9280. this.static = false;
  9281. /**
  9282. * An object that can be used to store custom data about the 3D object. It
  9283. * should not hold references to functions as these will not be cloned.
  9284. *
  9285. * @type {Object}
  9286. */
  9287. this.userData = {};
  9288. /**
  9289. * The pivot point for rotation and scale transformations.
  9290. * When set, rotation and scale are applied around this point
  9291. * instead of the object's origin.
  9292. *
  9293. * @type {?Vector3}
  9294. * @default null
  9295. */
  9296. this.pivot = null;
  9297. }
  9298. /**
  9299. * A callback that is executed immediately before a 3D object is rendered to a shadow map.
  9300. *
  9301. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  9302. * @param {Object3D} object - The 3D object.
  9303. * @param {Camera} camera - The camera that is used to render the scene.
  9304. * @param {Camera} shadowCamera - The shadow camera.
  9305. * @param {BufferGeometry} geometry - The 3D object's geometry.
  9306. * @param {Material} depthMaterial - The depth material.
  9307. * @param {Object} group - The geometry group data.
  9308. */
  9309. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  9310. /**
  9311. * A callback that is executed immediately after a 3D object is rendered to a shadow map.
  9312. *
  9313. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  9314. * @param {Object3D} object - The 3D object.
  9315. * @param {Camera} camera - The camera that is used to render the scene.
  9316. * @param {Camera} shadowCamera - The shadow camera.
  9317. * @param {BufferGeometry} geometry - The 3D object's geometry.
  9318. * @param {Material} depthMaterial - The depth material.
  9319. * @param {Object} group - The geometry group data.
  9320. */
  9321. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  9322. /**
  9323. * A callback that is executed immediately before a 3D object is rendered.
  9324. *
  9325. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  9326. * @param {Object3D} object - The 3D object.
  9327. * @param {Camera} camera - The camera that is used to render the scene.
  9328. * @param {BufferGeometry} geometry - The 3D object's geometry.
  9329. * @param {Material} material - The 3D object's material.
  9330. * @param {Object} group - The geometry group data.
  9331. */
  9332. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  9333. /**
  9334. * A callback that is executed immediately after a 3D object is rendered.
  9335. *
  9336. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  9337. * @param {Object3D} object - The 3D object.
  9338. * @param {Camera} camera - The camera that is used to render the scene.
  9339. * @param {BufferGeometry} geometry - The 3D object's geometry.
  9340. * @param {Material} material - The 3D object's material.
  9341. * @param {Object} group - The geometry group data.
  9342. */
  9343. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  9344. /**
  9345. * Applies the given transformation matrix to the object and updates the object's position,
  9346. * rotation and scale.
  9347. *
  9348. * @param {Matrix4} matrix - The transformation matrix.
  9349. */
  9350. applyMatrix4( matrix ) {
  9351. if ( this.matrixAutoUpdate ) this.updateMatrix();
  9352. this.matrix.premultiply( matrix );
  9353. this.matrix.decompose( this.position, this.quaternion, this.scale );
  9354. }
  9355. /**
  9356. * Applies a rotation represented by given the quaternion to the 3D object.
  9357. *
  9358. * @param {Quaternion} q - The quaternion.
  9359. * @return {Object3D} A reference to this instance.
  9360. */
  9361. applyQuaternion( q ) {
  9362. this.quaternion.premultiply( q );
  9363. return this;
  9364. }
  9365. /**
  9366. * Sets the given rotation represented as an axis/angle couple to the 3D object.
  9367. *
  9368. * @param {Vector3} axis - The (normalized) axis vector.
  9369. * @param {number} angle - The angle in radians.
  9370. */
  9371. setRotationFromAxisAngle( axis, angle ) {
  9372. // assumes axis is normalized
  9373. this.quaternion.setFromAxisAngle( axis, angle );
  9374. }
  9375. /**
  9376. * Sets the given rotation represented as Euler angles to the 3D object.
  9377. *
  9378. * @param {Euler} euler - The Euler angles.
  9379. */
  9380. setRotationFromEuler( euler ) {
  9381. this.quaternion.setFromEuler( euler, true );
  9382. }
  9383. /**
  9384. * Sets the given rotation represented as rotation matrix to the 3D object.
  9385. *
  9386. * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
  9387. * a pure rotation matrix (i.e, unscaled).
  9388. */
  9389. setRotationFromMatrix( m ) {
  9390. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  9391. this.quaternion.setFromRotationMatrix( m );
  9392. }
  9393. /**
  9394. * Sets the given rotation represented as a Quaternion to the 3D object.
  9395. *
  9396. * @param {Quaternion} q - The Quaternion
  9397. */
  9398. setRotationFromQuaternion( q ) {
  9399. // assumes q is normalized
  9400. this.quaternion.copy( q );
  9401. }
  9402. /**
  9403. * Rotates the 3D object along an axis in local space.
  9404. *
  9405. * @param {Vector3} axis - The (normalized) axis vector.
  9406. * @param {number} angle - The angle in radians.
  9407. * @return {Object3D} A reference to this instance.
  9408. */
  9409. rotateOnAxis( axis, angle ) {
  9410. // rotate object on axis in object space
  9411. // axis is assumed to be normalized
  9412. _q1.setFromAxisAngle( axis, angle );
  9413. this.quaternion.multiply( _q1 );
  9414. return this;
  9415. }
  9416. /**
  9417. * Rotates the 3D object along an axis in world space.
  9418. *
  9419. * @param {Vector3} axis - The (normalized) axis vector.
  9420. * @param {number} angle - The angle in radians.
  9421. * @return {Object3D} A reference to this instance.
  9422. */
  9423. rotateOnWorldAxis( axis, angle ) {
  9424. // rotate object on axis in world space
  9425. // axis is assumed to be normalized
  9426. // method assumes no rotated parent
  9427. _q1.setFromAxisAngle( axis, angle );
  9428. this.quaternion.premultiply( _q1 );
  9429. return this;
  9430. }
  9431. /**
  9432. * Rotates the 3D object around its X axis in local space.
  9433. *
  9434. * @param {number} angle - The angle in radians.
  9435. * @return {Object3D} A reference to this instance.
  9436. */
  9437. rotateX( angle ) {
  9438. return this.rotateOnAxis( _xAxis, angle );
  9439. }
  9440. /**
  9441. * Rotates the 3D object around its Y axis in local space.
  9442. *
  9443. * @param {number} angle - The angle in radians.
  9444. * @return {Object3D} A reference to this instance.
  9445. */
  9446. rotateY( angle ) {
  9447. return this.rotateOnAxis( _yAxis, angle );
  9448. }
  9449. /**
  9450. * Rotates the 3D object around its Z axis in local space.
  9451. *
  9452. * @param {number} angle - The angle in radians.
  9453. * @return {Object3D} A reference to this instance.
  9454. */
  9455. rotateZ( angle ) {
  9456. return this.rotateOnAxis( _zAxis, angle );
  9457. }
  9458. /**
  9459. * Translate the 3D object by a distance along the given axis in local space.
  9460. *
  9461. * @param {Vector3} axis - The (normalized) axis vector.
  9462. * @param {number} distance - The distance in world units.
  9463. * @return {Object3D} A reference to this instance.
  9464. */
  9465. translateOnAxis( axis, distance ) {
  9466. // translate object by distance along axis in object space
  9467. // axis is assumed to be normalized
  9468. _v1$6.copy( axis ).applyQuaternion( this.quaternion );
  9469. this.position.add( _v1$6.multiplyScalar( distance ) );
  9470. return this;
  9471. }
  9472. /**
  9473. * Translate the 3D object by a distance along its X-axis in local space.
  9474. *
  9475. * @param {number} distance - The distance in world units.
  9476. * @return {Object3D} A reference to this instance.
  9477. */
  9478. translateX( distance ) {
  9479. return this.translateOnAxis( _xAxis, distance );
  9480. }
  9481. /**
  9482. * Translate the 3D object by a distance along its Y-axis in local space.
  9483. *
  9484. * @param {number} distance - The distance in world units.
  9485. * @return {Object3D} A reference to this instance.
  9486. */
  9487. translateY( distance ) {
  9488. return this.translateOnAxis( _yAxis, distance );
  9489. }
  9490. /**
  9491. * Translate the 3D object by a distance along its Z-axis in local space.
  9492. *
  9493. * @param {number} distance - The distance in world units.
  9494. * @return {Object3D} A reference to this instance.
  9495. */
  9496. translateZ( distance ) {
  9497. return this.translateOnAxis( _zAxis, distance );
  9498. }
  9499. /**
  9500. * Converts the given vector from this 3D object's local space to world space.
  9501. *
  9502. * @param {Vector3} vector - The vector to convert.
  9503. * @return {Vector3} The converted vector.
  9504. */
  9505. localToWorld( vector ) {
  9506. this.updateWorldMatrix( true, false );
  9507. return vector.applyMatrix4( this.matrixWorld );
  9508. }
  9509. /**
  9510. * Converts the given vector from this 3D object's world space to local space.
  9511. *
  9512. * @param {Vector3} vector - The vector to convert.
  9513. * @return {Vector3} The converted vector.
  9514. */
  9515. worldToLocal( vector ) {
  9516. this.updateWorldMatrix( true, false );
  9517. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  9518. }
  9519. /**
  9520. * Rotates the object to face a point in world space.
  9521. *
  9522. * This method does not support objects having non-uniformly-scaled parent(s).
  9523. *
  9524. * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
  9525. * @param {number} [y] - The y coordinate in world space.
  9526. * @param {number} [z] - The z coordinate in world space.
  9527. */
  9528. lookAt( x, y, z ) {
  9529. // This method does not support objects having non-uniformly-scaled parent(s)
  9530. if ( x.isVector3 ) {
  9531. _target.copy( x );
  9532. } else {
  9533. _target.set( x, y, z );
  9534. }
  9535. const parent = this.parent;
  9536. this.updateWorldMatrix( true, false );
  9537. _position$4.setFromMatrixPosition( this.matrixWorld );
  9538. if ( this.isCamera || this.isLight ) {
  9539. _m1$1.lookAt( _position$4, _target, this.up );
  9540. } else {
  9541. _m1$1.lookAt( _target, _position$4, this.up );
  9542. }
  9543. this.quaternion.setFromRotationMatrix( _m1$1 );
  9544. if ( parent ) {
  9545. _m1$1.extractRotation( parent.matrixWorld );
  9546. _q1.setFromRotationMatrix( _m1$1 );
  9547. this.quaternion.premultiply( _q1.invert() );
  9548. }
  9549. }
  9550. /**
  9551. * Adds the given 3D object as a child to this 3D object. An arbitrary number of
  9552. * objects may be added. Any current parent on an object passed in here will be
  9553. * removed, since an object can have at most one parent.
  9554. *
  9555. * @fires Object3D#added
  9556. * @fires Object3D#childadded
  9557. * @param {Object3D} object - The 3D object to add.
  9558. * @return {Object3D} A reference to this instance.
  9559. */
  9560. add( object ) {
  9561. if ( arguments.length > 1 ) {
  9562. for ( let i = 0; i < arguments.length; i ++ ) {
  9563. this.add( arguments[ i ] );
  9564. }
  9565. return this;
  9566. }
  9567. if ( object === this ) {
  9568. error( 'Object3D.add: object can\'t be added as a child of itself.', object );
  9569. return this;
  9570. }
  9571. if ( object && object.isObject3D ) {
  9572. object.removeFromParent();
  9573. object.parent = this;
  9574. this.children.push( object );
  9575. object.dispatchEvent( _addedEvent );
  9576. _childaddedEvent.child = object;
  9577. this.dispatchEvent( _childaddedEvent );
  9578. _childaddedEvent.child = null;
  9579. } else {
  9580. error( 'Object3D.add: object not an instance of THREE.Object3D.', object );
  9581. }
  9582. return this;
  9583. }
  9584. /**
  9585. * Removes the given 3D object as child from this 3D object.
  9586. * An arbitrary number of objects may be removed.
  9587. *
  9588. * @fires Object3D#removed
  9589. * @fires Object3D#childremoved
  9590. * @param {Object3D} object - The 3D object to remove.
  9591. * @return {Object3D} A reference to this instance.
  9592. */
  9593. remove( object ) {
  9594. if ( arguments.length > 1 ) {
  9595. for ( let i = 0; i < arguments.length; i ++ ) {
  9596. this.remove( arguments[ i ] );
  9597. }
  9598. return this;
  9599. }
  9600. const index = this.children.indexOf( object );
  9601. if ( index !== -1 ) {
  9602. object.parent = null;
  9603. this.children.splice( index, 1 );
  9604. object.dispatchEvent( _removedEvent );
  9605. _childremovedEvent.child = object;
  9606. this.dispatchEvent( _childremovedEvent );
  9607. _childremovedEvent.child = null;
  9608. }
  9609. return this;
  9610. }
  9611. /**
  9612. * Removes this 3D object from its current parent.
  9613. *
  9614. * @fires Object3D#removed
  9615. * @fires Object3D#childremoved
  9616. * @return {Object3D} A reference to this instance.
  9617. */
  9618. removeFromParent() {
  9619. const parent = this.parent;
  9620. if ( parent !== null ) {
  9621. parent.remove( this );
  9622. }
  9623. return this;
  9624. }
  9625. /**
  9626. * Removes all child objects.
  9627. *
  9628. * @fires Object3D#removed
  9629. * @fires Object3D#childremoved
  9630. * @return {Object3D} A reference to this instance.
  9631. */
  9632. clear() {
  9633. return this.remove( ... this.children );
  9634. }
  9635. /**
  9636. * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
  9637. * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
  9638. *
  9639. * @fires Object3D#added
  9640. * @fires Object3D#childadded
  9641. * @param {Object3D} object - The 3D object to attach.
  9642. * @return {Object3D} A reference to this instance.
  9643. */
  9644. attach( object ) {
  9645. // adds object as a child of this, while maintaining the object's world transform
  9646. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  9647. this.updateWorldMatrix( true, false );
  9648. _m1$1.copy( this.matrixWorld ).invert();
  9649. if ( object.parent !== null ) {
  9650. object.parent.updateWorldMatrix( true, false );
  9651. _m1$1.multiply( object.parent.matrixWorld );
  9652. }
  9653. object.applyMatrix4( _m1$1 );
  9654. object.removeFromParent();
  9655. object.parent = this;
  9656. this.children.push( object );
  9657. object.updateWorldMatrix( false, true );
  9658. object.dispatchEvent( _addedEvent );
  9659. _childaddedEvent.child = object;
  9660. this.dispatchEvent( _childaddedEvent );
  9661. _childaddedEvent.child = null;
  9662. return this;
  9663. }
  9664. /**
  9665. * Searches through the 3D object and its children, starting with the 3D object
  9666. * itself, and returns the first with a matching ID.
  9667. *
  9668. * @param {number} id - The id.
  9669. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  9670. */
  9671. getObjectById( id ) {
  9672. return this.getObjectByProperty( 'id', id );
  9673. }
  9674. /**
  9675. * Searches through the 3D object and its children, starting with the 3D object
  9676. * itself, and returns the first with a matching name.
  9677. *
  9678. * @param {string} name - The name.
  9679. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  9680. */
  9681. getObjectByName( name ) {
  9682. return this.getObjectByProperty( 'name', name );
  9683. }
  9684. /**
  9685. * Searches through the 3D object and its children, starting with the 3D object
  9686. * itself, and returns the first with a matching property value.
  9687. *
  9688. * @param {string} name - The name of the property.
  9689. * @param {any} value - The value.
  9690. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  9691. */
  9692. getObjectByProperty( name, value ) {
  9693. if ( this[ name ] === value ) return this;
  9694. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  9695. const child = this.children[ i ];
  9696. const object = child.getObjectByProperty( name, value );
  9697. if ( object !== undefined ) {
  9698. return object;
  9699. }
  9700. }
  9701. return undefined;
  9702. }
  9703. /**
  9704. * Searches through the 3D object and its children, starting with the 3D object
  9705. * itself, and returns all 3D objects with a matching property value.
  9706. *
  9707. * @param {string} name - The name of the property.
  9708. * @param {any} value - The value.
  9709. * @param {Array<Object3D>} result - The method stores the result in this array.
  9710. * @return {Array<Object3D>} The found 3D objects.
  9711. */
  9712. getObjectsByProperty( name, value, result = [] ) {
  9713. if ( this[ name ] === value ) result.push( this );
  9714. const children = this.children;
  9715. for ( let i = 0, l = children.length; i < l; i ++ ) {
  9716. children[ i ].getObjectsByProperty( name, value, result );
  9717. }
  9718. return result;
  9719. }
  9720. /**
  9721. * Returns a vector representing the position of the 3D object in world space.
  9722. *
  9723. * @param {Vector3} target - The target vector the result is stored to.
  9724. * @return {Vector3} The 3D object's position in world space.
  9725. */
  9726. getWorldPosition( target ) {
  9727. this.updateWorldMatrix( true, false );
  9728. return target.setFromMatrixPosition( this.matrixWorld );
  9729. }
  9730. /**
  9731. * Returns a Quaternion representing the position of the 3D object in world space.
  9732. *
  9733. * @param {Quaternion} target - The target Quaternion the result is stored to.
  9734. * @return {Quaternion} The 3D object's rotation in world space.
  9735. */
  9736. getWorldQuaternion( target ) {
  9737. this.updateWorldMatrix( true, false );
  9738. this.matrixWorld.decompose( _position$4, target, _scale$3 );
  9739. return target;
  9740. }
  9741. /**
  9742. * Returns a vector representing the scale of the 3D object in world space.
  9743. *
  9744. * @param {Vector3} target - The target vector the result is stored to.
  9745. * @return {Vector3} The 3D object's scale in world space.
  9746. */
  9747. getWorldScale( target ) {
  9748. this.updateWorldMatrix( true, false );
  9749. this.matrixWorld.decompose( _position$4, _quaternion$3, target );
  9750. return target;
  9751. }
  9752. /**
  9753. * Returns a vector representing the ("look") direction of the 3D object in world space.
  9754. *
  9755. * @param {Vector3} target - The target vector the result is stored to.
  9756. * @return {Vector3} The 3D object's direction in world space.
  9757. */
  9758. getWorldDirection( target ) {
  9759. this.updateWorldMatrix( true, false );
  9760. const e = this.matrixWorld.elements;
  9761. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  9762. }
  9763. /**
  9764. * Abstract method to get intersections between a casted ray and this
  9765. * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
  9766. * implement this method in order to use raycasting.
  9767. *
  9768. * @abstract
  9769. * @param {Raycaster} raycaster - The raycaster.
  9770. * @param {Array<Object>} intersects - An array holding the result of the method.
  9771. */
  9772. raycast( /* raycaster, intersects */ ) {}
  9773. /**
  9774. * Executes the callback on this 3D object and all descendants.
  9775. *
  9776. * Note: Modifying the scene graph inside the callback is discouraged.
  9777. *
  9778. * @param {Function} callback - A callback function that allows to process the current 3D object.
  9779. */
  9780. traverse( callback ) {
  9781. callback( this );
  9782. const children = this.children;
  9783. for ( let i = 0, l = children.length; i < l; i ++ ) {
  9784. children[ i ].traverse( callback );
  9785. }
  9786. }
  9787. /**
  9788. * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
  9789. * Descendants of invisible 3D objects are not traversed.
  9790. *
  9791. * Note: Modifying the scene graph inside the callback is discouraged.
  9792. *
  9793. * @param {Function} callback - A callback function that allows to process the current 3D object.
  9794. */
  9795. traverseVisible( callback ) {
  9796. if ( this.visible === false ) return;
  9797. callback( this );
  9798. const children = this.children;
  9799. for ( let i = 0, l = children.length; i < l; i ++ ) {
  9800. children[ i ].traverseVisible( callback );
  9801. }
  9802. }
  9803. /**
  9804. * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
  9805. *
  9806. * Note: Modifying the scene graph inside the callback is discouraged.
  9807. *
  9808. * @param {Function} callback - A callback function that allows to process the current 3D object.
  9809. */
  9810. traverseAncestors( callback ) {
  9811. const parent = this.parent;
  9812. if ( parent !== null ) {
  9813. callback( parent );
  9814. parent.traverseAncestors( callback );
  9815. }
  9816. }
  9817. /**
  9818. * Updates the transformation matrix in local space by computing it from the current
  9819. * position, rotation and scale values.
  9820. */
  9821. updateMatrix() {
  9822. this.matrix.compose( this.position, this.quaternion, this.scale );
  9823. const pivot = this.pivot;
  9824. if ( pivot !== null ) {
  9825. const px = pivot.x, py = pivot.y, pz = pivot.z;
  9826. const te = this.matrix.elements;
  9827. te[ 12 ] += px - te[ 0 ] * px - te[ 4 ] * py - te[ 8 ] * pz;
  9828. te[ 13 ] += py - te[ 1 ] * px - te[ 5 ] * py - te[ 9 ] * pz;
  9829. te[ 14 ] += pz - te[ 2 ] * px - te[ 6 ] * py - te[ 10 ] * pz;
  9830. }
  9831. this.matrixWorldNeedsUpdate = true;
  9832. }
  9833. /**
  9834. * Updates the transformation matrix in world space of this 3D objects and its descendants.
  9835. *
  9836. * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
  9837. * local space. The computation of the local and world matrix can be controlled with the
  9838. * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
  9839. * `true` by default. Set these flags to `false` if you need more control over the update matrix process.
  9840. *
  9841. * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
  9842. * when {@link Object3D#matrixWorldNeedsUpdate} is `false`.
  9843. */
  9844. updateMatrixWorld( force ) {
  9845. if ( this.matrixAutoUpdate ) this.updateMatrix();
  9846. if ( this.matrixWorldNeedsUpdate || force ) {
  9847. if ( this.matrixWorldAutoUpdate === true ) {
  9848. if ( this.parent === null ) {
  9849. this.matrixWorld.copy( this.matrix );
  9850. } else {
  9851. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  9852. }
  9853. }
  9854. this.matrixWorldNeedsUpdate = false;
  9855. force = true;
  9856. }
  9857. // make sure descendants are updated if required
  9858. const children = this.children;
  9859. for ( let i = 0, l = children.length; i < l; i ++ ) {
  9860. const child = children[ i ];
  9861. child.updateMatrixWorld( force );
  9862. }
  9863. }
  9864. /**
  9865. * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
  9866. * update of ancestor and descendant nodes.
  9867. *
  9868. * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
  9869. * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
  9870. */
  9871. updateWorldMatrix( updateParents, updateChildren ) {
  9872. const parent = this.parent;
  9873. if ( updateParents === true && parent !== null ) {
  9874. parent.updateWorldMatrix( true, false );
  9875. }
  9876. if ( this.matrixAutoUpdate ) this.updateMatrix();
  9877. if ( this.matrixWorldAutoUpdate === true ) {
  9878. if ( this.parent === null ) {
  9879. this.matrixWorld.copy( this.matrix );
  9880. } else {
  9881. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  9882. }
  9883. }
  9884. // make sure descendants are updated
  9885. if ( updateChildren === true ) {
  9886. const children = this.children;
  9887. for ( let i = 0, l = children.length; i < l; i ++ ) {
  9888. const child = children[ i ];
  9889. child.updateWorldMatrix( false, true );
  9890. }
  9891. }
  9892. }
  9893. /**
  9894. * Serializes the 3D object into JSON.
  9895. *
  9896. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  9897. * @return {Object} A JSON object representing the serialized 3D object.
  9898. * @see {@link ObjectLoader#parse}
  9899. */
  9900. toJSON( meta ) {
  9901. // meta is a string when called from JSON.stringify
  9902. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  9903. const output = {};
  9904. // meta is a hash used to collect geometries, materials.
  9905. // not providing it implies that this is the root object
  9906. // being serialized.
  9907. if ( isRootObject ) {
  9908. // initialize meta obj
  9909. meta = {
  9910. geometries: {},
  9911. materials: {},
  9912. textures: {},
  9913. images: {},
  9914. shapes: {},
  9915. skeletons: {},
  9916. animations: {},
  9917. nodes: {}
  9918. };
  9919. output.metadata = {
  9920. version: 4.7,
  9921. type: 'Object',
  9922. generator: 'Object3D.toJSON'
  9923. };
  9924. }
  9925. // standard Object3D serialization
  9926. const object = {};
  9927. object.uuid = this.uuid;
  9928. object.type = this.type;
  9929. if ( this.name !== '' ) object.name = this.name;
  9930. if ( this.castShadow === true ) object.castShadow = true;
  9931. if ( this.receiveShadow === true ) object.receiveShadow = true;
  9932. if ( this.visible === false ) object.visible = false;
  9933. if ( this.frustumCulled === false ) object.frustumCulled = false;
  9934. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  9935. if ( this.static !== false ) object.static = this.static;
  9936. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  9937. object.layers = this.layers.mask;
  9938. object.matrix = this.matrix.toArray();
  9939. object.up = this.up.toArray();
  9940. if ( this.pivot !== null ) object.pivot = this.pivot.toArray();
  9941. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  9942. if ( this.morphTargetDictionary !== undefined ) object.morphTargetDictionary = Object.assign( {}, this.morphTargetDictionary );
  9943. if ( this.morphTargetInfluences !== undefined ) object.morphTargetInfluences = this.morphTargetInfluences.slice();
  9944. // object specific properties
  9945. if ( this.isInstancedMesh ) {
  9946. object.type = 'InstancedMesh';
  9947. object.count = this.count;
  9948. object.instanceMatrix = this.instanceMatrix.toJSON();
  9949. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  9950. }
  9951. if ( this.isBatchedMesh ) {
  9952. object.type = 'BatchedMesh';
  9953. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  9954. object.sortObjects = this.sortObjects;
  9955. object.drawRanges = this._drawRanges;
  9956. object.reservedRanges = this._reservedRanges;
  9957. object.geometryInfo = this._geometryInfo.map( info => ( {
  9958. ...info,
  9959. boundingBox: info.boundingBox ? info.boundingBox.toJSON() : undefined,
  9960. boundingSphere: info.boundingSphere ? info.boundingSphere.toJSON() : undefined
  9961. } ) );
  9962. object.instanceInfo = this._instanceInfo.map( info => ( { ...info } ) );
  9963. object.availableInstanceIds = this._availableInstanceIds.slice();
  9964. object.availableGeometryIds = this._availableGeometryIds.slice();
  9965. object.nextIndexStart = this._nextIndexStart;
  9966. object.nextVertexStart = this._nextVertexStart;
  9967. object.geometryCount = this._geometryCount;
  9968. object.maxInstanceCount = this._maxInstanceCount;
  9969. object.maxVertexCount = this._maxVertexCount;
  9970. object.maxIndexCount = this._maxIndexCount;
  9971. object.geometryInitialized = this._geometryInitialized;
  9972. object.matricesTexture = this._matricesTexture.toJSON( meta );
  9973. object.indirectTexture = this._indirectTexture.toJSON( meta );
  9974. if ( this._colorsTexture !== null ) {
  9975. object.colorsTexture = this._colorsTexture.toJSON( meta );
  9976. }
  9977. if ( this.boundingSphere !== null ) {
  9978. object.boundingSphere = this.boundingSphere.toJSON();
  9979. }
  9980. if ( this.boundingBox !== null ) {
  9981. object.boundingBox = this.boundingBox.toJSON();
  9982. }
  9983. }
  9984. //
  9985. function serialize( library, element ) {
  9986. if ( library[ element.uuid ] === undefined ) {
  9987. library[ element.uuid ] = element.toJSON( meta );
  9988. }
  9989. return element.uuid;
  9990. }
  9991. if ( this.isScene ) {
  9992. if ( this.background ) {
  9993. if ( this.background.isColor ) {
  9994. object.background = this.background.toJSON();
  9995. } else if ( this.background.isTexture ) {
  9996. object.background = this.background.toJSON( meta ).uuid;
  9997. }
  9998. }
  9999. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  10000. object.environment = this.environment.toJSON( meta ).uuid;
  10001. }
  10002. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  10003. object.geometry = serialize( meta.geometries, this.geometry );
  10004. const parameters = this.geometry.parameters;
  10005. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  10006. const shapes = parameters.shapes;
  10007. if ( Array.isArray( shapes ) ) {
  10008. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  10009. const shape = shapes[ i ];
  10010. serialize( meta.shapes, shape );
  10011. }
  10012. } else {
  10013. serialize( meta.shapes, shapes );
  10014. }
  10015. }
  10016. }
  10017. if ( this.isSkinnedMesh ) {
  10018. object.bindMode = this.bindMode;
  10019. object.bindMatrix = this.bindMatrix.toArray();
  10020. if ( this.skeleton !== undefined ) {
  10021. serialize( meta.skeletons, this.skeleton );
  10022. object.skeleton = this.skeleton.uuid;
  10023. }
  10024. }
  10025. if ( this.material !== undefined ) {
  10026. if ( Array.isArray( this.material ) ) {
  10027. const uuids = [];
  10028. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  10029. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  10030. }
  10031. object.material = uuids;
  10032. } else {
  10033. object.material = serialize( meta.materials, this.material );
  10034. }
  10035. }
  10036. //
  10037. if ( this.children.length > 0 ) {
  10038. object.children = [];
  10039. for ( let i = 0; i < this.children.length; i ++ ) {
  10040. object.children.push( this.children[ i ].toJSON( meta ).object );
  10041. }
  10042. }
  10043. //
  10044. if ( this.animations.length > 0 ) {
  10045. object.animations = [];
  10046. for ( let i = 0; i < this.animations.length; i ++ ) {
  10047. const animation = this.animations[ i ];
  10048. object.animations.push( serialize( meta.animations, animation ) );
  10049. }
  10050. }
  10051. if ( isRootObject ) {
  10052. const geometries = extractFromCache( meta.geometries );
  10053. const materials = extractFromCache( meta.materials );
  10054. const textures = extractFromCache( meta.textures );
  10055. const images = extractFromCache( meta.images );
  10056. const shapes = extractFromCache( meta.shapes );
  10057. const skeletons = extractFromCache( meta.skeletons );
  10058. const animations = extractFromCache( meta.animations );
  10059. const nodes = extractFromCache( meta.nodes );
  10060. if ( geometries.length > 0 ) output.geometries = geometries;
  10061. if ( materials.length > 0 ) output.materials = materials;
  10062. if ( textures.length > 0 ) output.textures = textures;
  10063. if ( images.length > 0 ) output.images = images;
  10064. if ( shapes.length > 0 ) output.shapes = shapes;
  10065. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  10066. if ( animations.length > 0 ) output.animations = animations;
  10067. if ( nodes.length > 0 ) output.nodes = nodes;
  10068. }
  10069. output.object = object;
  10070. return output;
  10071. // extract data from the cache hash
  10072. // remove metadata on each item
  10073. // and return as array
  10074. function extractFromCache( cache ) {
  10075. const values = [];
  10076. for ( const key in cache ) {
  10077. const data = cache[ key ];
  10078. delete data.metadata;
  10079. values.push( data );
  10080. }
  10081. return values;
  10082. }
  10083. }
  10084. /**
  10085. * Returns a new 3D object with copied values from this instance.
  10086. *
  10087. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
  10088. * @return {Object3D} A clone of this instance.
  10089. */
  10090. clone( recursive ) {
  10091. return new this.constructor().copy( this, recursive );
  10092. }
  10093. /**
  10094. * Copies the values of the given 3D object to this instance.
  10095. *
  10096. * @param {Object3D} source - The 3D object to copy.
  10097. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
  10098. * @return {Object3D} A reference to this instance.
  10099. */
  10100. copy( source, recursive = true ) {
  10101. this.name = source.name;
  10102. this.up.copy( source.up );
  10103. this.position.copy( source.position );
  10104. this.rotation.order = source.rotation.order;
  10105. this.quaternion.copy( source.quaternion );
  10106. this.scale.copy( source.scale );
  10107. this.pivot = ( source.pivot !== null ) ? source.pivot.clone() : null;
  10108. this.matrix.copy( source.matrix );
  10109. this.matrixWorld.copy( source.matrixWorld );
  10110. this.matrixAutoUpdate = source.matrixAutoUpdate;
  10111. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  10112. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  10113. this.layers.mask = source.layers.mask;
  10114. this.visible = source.visible;
  10115. this.castShadow = source.castShadow;
  10116. this.receiveShadow = source.receiveShadow;
  10117. this.frustumCulled = source.frustumCulled;
  10118. this.renderOrder = source.renderOrder;
  10119. this.static = source.static;
  10120. this.animations = source.animations.slice();
  10121. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  10122. if ( recursive === true ) {
  10123. for ( let i = 0; i < source.children.length; i ++ ) {
  10124. const child = source.children[ i ];
  10125. this.add( child.clone() );
  10126. }
  10127. }
  10128. return this;
  10129. }
  10130. }
  10131. /**
  10132. * The default up direction for objects, also used as the default
  10133. * position for {@link DirectionalLight} and {@link HemisphereLight}.
  10134. *
  10135. * @static
  10136. * @type {Vector3}
  10137. * @default (0,1,0)
  10138. */
  10139. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  10140. /**
  10141. * The default setting for {@link Object3D#matrixAutoUpdate} for
  10142. * newly created 3D objects.
  10143. *
  10144. * @static
  10145. * @type {boolean}
  10146. * @default true
  10147. */
  10148. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  10149. /**
  10150. * The default setting for {@link Object3D#matrixWorldAutoUpdate} for
  10151. * newly created 3D objects.
  10152. *
  10153. * @static
  10154. * @type {boolean}
  10155. * @default true
  10156. */
  10157. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  10158. /**
  10159. * This is almost identical to an {@link Object3D}. Its purpose is to
  10160. * make working with groups of objects syntactically clearer.
  10161. *
  10162. * ```js
  10163. * // Create a group and add the two cubes.
  10164. * // These cubes can now be rotated / scaled etc as a group.
  10165. * const group = new THREE.Group();
  10166. *
  10167. * group.add( meshA );
  10168. * group.add( meshB );
  10169. *
  10170. * scene.add( group );
  10171. * ```
  10172. *
  10173. * @augments Object3D
  10174. */
  10175. class Group extends Object3D {
  10176. constructor() {
  10177. super();
  10178. /**
  10179. * This flag can be used for type testing.
  10180. *
  10181. * @type {boolean}
  10182. * @readonly
  10183. * @default true
  10184. */
  10185. this.isGroup = true;
  10186. this.type = 'Group';
  10187. }
  10188. }
  10189. const _moveEvent = { type: 'move' };
  10190. /**
  10191. * Class for representing a XR controller with its
  10192. * different coordinate systems.
  10193. *
  10194. * @private
  10195. */
  10196. class WebXRController {
  10197. /**
  10198. * Constructs a new XR controller.
  10199. */
  10200. constructor() {
  10201. /**
  10202. * A group representing the target ray space
  10203. * of the XR controller.
  10204. *
  10205. * @private
  10206. * @type {?Group}
  10207. * @default null
  10208. */
  10209. this._targetRay = null;
  10210. /**
  10211. * A group representing the grip space
  10212. * of the XR controller.
  10213. *
  10214. * @private
  10215. * @type {?Group}
  10216. * @default null
  10217. */
  10218. this._grip = null;
  10219. /**
  10220. * A group representing the hand space
  10221. * of the XR controller.
  10222. *
  10223. * @private
  10224. * @type {?Group}
  10225. * @default null
  10226. */
  10227. this._hand = null;
  10228. }
  10229. /**
  10230. * Returns a group representing the hand space of the XR controller.
  10231. *
  10232. * @return {Group} A group representing the hand space of the XR controller.
  10233. */
  10234. getHandSpace() {
  10235. if ( this._hand === null ) {
  10236. this._hand = new Group();
  10237. this._hand.matrixAutoUpdate = false;
  10238. this._hand.visible = false;
  10239. this._hand.joints = {};
  10240. this._hand.inputState = { pinching: false };
  10241. }
  10242. return this._hand;
  10243. }
  10244. /**
  10245. * Returns a group representing the target ray space of the XR controller.
  10246. *
  10247. * @return {Group} A group representing the target ray space of the XR controller.
  10248. */
  10249. getTargetRaySpace() {
  10250. if ( this._targetRay === null ) {
  10251. this._targetRay = new Group();
  10252. this._targetRay.matrixAutoUpdate = false;
  10253. this._targetRay.visible = false;
  10254. this._targetRay.hasLinearVelocity = false;
  10255. this._targetRay.linearVelocity = new Vector3();
  10256. this._targetRay.hasAngularVelocity = false;
  10257. this._targetRay.angularVelocity = new Vector3();
  10258. }
  10259. return this._targetRay;
  10260. }
  10261. /**
  10262. * Returns a group representing the grip space of the XR controller.
  10263. *
  10264. * @return {Group} A group representing the grip space of the XR controller.
  10265. */
  10266. getGripSpace() {
  10267. if ( this._grip === null ) {
  10268. this._grip = new Group();
  10269. this._grip.matrixAutoUpdate = false;
  10270. this._grip.visible = false;
  10271. this._grip.hasLinearVelocity = false;
  10272. this._grip.linearVelocity = new Vector3();
  10273. this._grip.hasAngularVelocity = false;
  10274. this._grip.angularVelocity = new Vector3();
  10275. this._grip.eventsEnabled = false;
  10276. }
  10277. return this._grip;
  10278. }
  10279. /**
  10280. * Dispatches the given event to the groups representing
  10281. * the different coordinate spaces of the XR controller.
  10282. *
  10283. * @param {Object} event - The event to dispatch.
  10284. * @return {WebXRController} A reference to this instance.
  10285. */
  10286. dispatchEvent( event ) {
  10287. if ( this._targetRay !== null ) {
  10288. this._targetRay.dispatchEvent( event );
  10289. }
  10290. if ( this._grip !== null ) {
  10291. this._grip.dispatchEvent( event );
  10292. }
  10293. if ( this._hand !== null ) {
  10294. this._hand.dispatchEvent( event );
  10295. }
  10296. return this;
  10297. }
  10298. /**
  10299. * Connects the controller with the given XR input source.
  10300. *
  10301. * @param {XRInputSource} inputSource - The input source.
  10302. * @return {WebXRController} A reference to this instance.
  10303. */
  10304. connect( inputSource ) {
  10305. if ( inputSource && inputSource.hand ) {
  10306. const hand = this._hand;
  10307. if ( hand ) {
  10308. for ( const inputjoint of inputSource.hand.values() ) {
  10309. // Initialize hand with joints when connected
  10310. this._getHandJoint( hand, inputjoint );
  10311. }
  10312. }
  10313. }
  10314. this.dispatchEvent( { type: 'connected', data: inputSource } );
  10315. return this;
  10316. }
  10317. /**
  10318. * Disconnects the controller from the given XR input source.
  10319. *
  10320. * @param {XRInputSource} inputSource - The input source.
  10321. * @return {WebXRController} A reference to this instance.
  10322. */
  10323. disconnect( inputSource ) {
  10324. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  10325. if ( this._targetRay !== null ) {
  10326. this._targetRay.visible = false;
  10327. }
  10328. if ( this._grip !== null ) {
  10329. this._grip.visible = false;
  10330. }
  10331. if ( this._hand !== null ) {
  10332. this._hand.visible = false;
  10333. }
  10334. return this;
  10335. }
  10336. /**
  10337. * Updates the controller with the given input source, XR frame and reference space.
  10338. * This updates the transformations of the groups that represent the different
  10339. * coordinate systems of the controller.
  10340. *
  10341. * @param {XRInputSource} inputSource - The input source.
  10342. * @param {XRFrame} frame - The XR frame.
  10343. * @param {XRReferenceSpace} referenceSpace - The reference space.
  10344. * @return {WebXRController} A reference to this instance.
  10345. */
  10346. update( inputSource, frame, referenceSpace ) {
  10347. let inputPose = null;
  10348. let gripPose = null;
  10349. let handPose = null;
  10350. const targetRay = this._targetRay;
  10351. const grip = this._grip;
  10352. const hand = this._hand;
  10353. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  10354. if ( hand && inputSource.hand ) {
  10355. handPose = true;
  10356. for ( const inputjoint of inputSource.hand.values() ) {
  10357. // Update the joints groups with the XRJoint poses
  10358. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  10359. // The transform of this joint will be updated with the joint pose on each frame
  10360. const joint = this._getHandJoint( hand, inputjoint );
  10361. if ( jointPose !== null ) {
  10362. joint.matrix.fromArray( jointPose.transform.matrix );
  10363. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  10364. joint.matrixWorldNeedsUpdate = true;
  10365. joint.jointRadius = jointPose.radius;
  10366. }
  10367. joint.visible = jointPose !== null;
  10368. }
  10369. // Custom events
  10370. // Check pinchz
  10371. const indexTip = hand.joints[ 'index-finger-tip' ];
  10372. const thumbTip = hand.joints[ 'thumb-tip' ];
  10373. const distance = indexTip.position.distanceTo( thumbTip.position );
  10374. const distanceToPinch = 0.02;
  10375. const threshold = 0.005;
  10376. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  10377. hand.inputState.pinching = false;
  10378. this.dispatchEvent( {
  10379. type: 'pinchend',
  10380. handedness: inputSource.handedness,
  10381. target: this
  10382. } );
  10383. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  10384. hand.inputState.pinching = true;
  10385. this.dispatchEvent( {
  10386. type: 'pinchstart',
  10387. handedness: inputSource.handedness,
  10388. target: this
  10389. } );
  10390. }
  10391. } else {
  10392. if ( grip !== null && inputSource.gripSpace ) {
  10393. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  10394. if ( gripPose !== null ) {
  10395. grip.matrix.fromArray( gripPose.transform.matrix );
  10396. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  10397. grip.matrixWorldNeedsUpdate = true;
  10398. if ( gripPose.linearVelocity ) {
  10399. grip.hasLinearVelocity = true;
  10400. grip.linearVelocity.copy( gripPose.linearVelocity );
  10401. } else {
  10402. grip.hasLinearVelocity = false;
  10403. }
  10404. if ( gripPose.angularVelocity ) {
  10405. grip.hasAngularVelocity = true;
  10406. grip.angularVelocity.copy( gripPose.angularVelocity );
  10407. } else {
  10408. grip.hasAngularVelocity = false;
  10409. }
  10410. // grip update event if enabled
  10411. if ( grip.eventsEnabled ) {
  10412. grip.dispatchEvent( {
  10413. type: 'gripUpdated',
  10414. data: inputSource,
  10415. target: this
  10416. } );
  10417. }
  10418. }
  10419. }
  10420. }
  10421. if ( targetRay !== null ) {
  10422. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  10423. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  10424. if ( inputPose === null && gripPose !== null ) {
  10425. inputPose = gripPose;
  10426. }
  10427. if ( inputPose !== null ) {
  10428. targetRay.matrix.fromArray( inputPose.transform.matrix );
  10429. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  10430. targetRay.matrixWorldNeedsUpdate = true;
  10431. if ( inputPose.linearVelocity ) {
  10432. targetRay.hasLinearVelocity = true;
  10433. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  10434. } else {
  10435. targetRay.hasLinearVelocity = false;
  10436. }
  10437. if ( inputPose.angularVelocity ) {
  10438. targetRay.hasAngularVelocity = true;
  10439. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  10440. } else {
  10441. targetRay.hasAngularVelocity = false;
  10442. }
  10443. this.dispatchEvent( _moveEvent );
  10444. }
  10445. }
  10446. }
  10447. if ( targetRay !== null ) {
  10448. targetRay.visible = ( inputPose !== null );
  10449. }
  10450. if ( grip !== null ) {
  10451. grip.visible = ( gripPose !== null );
  10452. }
  10453. if ( hand !== null ) {
  10454. hand.visible = ( handPose !== null );
  10455. }
  10456. return this;
  10457. }
  10458. /**
  10459. * Returns a group representing the hand joint for the given input joint.
  10460. *
  10461. * @private
  10462. * @param {Group} hand - The group representing the hand space.
  10463. * @param {XRJointSpace} inputjoint - The hand joint data.
  10464. * @return {Group} A group representing the hand joint for the given input joint.
  10465. */
  10466. _getHandJoint( hand, inputjoint ) {
  10467. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  10468. const joint = new Group();
  10469. joint.matrixAutoUpdate = false;
  10470. joint.visible = false;
  10471. hand.joints[ inputjoint.jointName ] = joint;
  10472. hand.add( joint );
  10473. }
  10474. return hand.joints[ inputjoint.jointName ];
  10475. }
  10476. }
  10477. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  10478. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  10479. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  10480. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  10481. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  10482. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  10483. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  10484. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  10485. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  10486. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  10487. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  10488. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  10489. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  10490. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  10491. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  10492. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  10493. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  10494. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  10495. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  10496. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  10497. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  10498. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  10499. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  10500. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  10501. const _hslA = { h: 0, s: 0, l: 0 };
  10502. const _hslB = { h: 0, s: 0, l: 0 };
  10503. function hue2rgb( p, q, t ) {
  10504. if ( t < 0 ) t += 1;
  10505. if ( t > 1 ) t -= 1;
  10506. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  10507. if ( t < 1 / 2 ) return q;
  10508. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  10509. return p;
  10510. }
  10511. /**
  10512. * A Color instance is represented by RGB components in the linear <i>working
  10513. * color space</i>, which defaults to `LinearSRGBColorSpace`. Inputs
  10514. * conventionally using `SRGBColorSpace` (such as hexadecimals and CSS
  10515. * strings) are converted to the working color space automatically.
  10516. *
  10517. * ```js
  10518. * // converted automatically from SRGBColorSpace to LinearSRGBColorSpace
  10519. * const color = new THREE.Color().setHex( 0x112233 );
  10520. * ```
  10521. * Source color spaces may be specified explicitly, to ensure correct conversions.
  10522. * ```js
  10523. * // assumed already LinearSRGBColorSpace; no conversion
  10524. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5 );
  10525. *
  10526. * // converted explicitly from SRGBColorSpace to LinearSRGBColorSpace
  10527. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5, SRGBColorSpace );
  10528. * ```
  10529. * If THREE.ColorManagement is disabled, no conversions occur. For details,
  10530. * see <i>Color management</i>. Iterating through a Color instance will yield
  10531. * its components (r, g, b) in the corresponding order. A Color can be initialised
  10532. * in any of the following ways:
  10533. * ```js
  10534. * //empty constructor - will default white
  10535. * const color1 = new THREE.Color();
  10536. *
  10537. * //Hexadecimal color (recommended)
  10538. * const color2 = new THREE.Color( 0xff0000 );
  10539. *
  10540. * //RGB string
  10541. * const color3 = new THREE.Color("rgb(255, 0, 0)");
  10542. * const color4 = new THREE.Color("rgb(100%, 0%, 0%)");
  10543. *
  10544. * //X11 color name - all 140 color names are supported.
  10545. * //Note the lack of CamelCase in the name
  10546. * const color5 = new THREE.Color( 'skyblue' );
  10547. * //HSL string
  10548. * const color6 = new THREE.Color("hsl(0, 100%, 50%)");
  10549. *
  10550. * //Separate RGB values between 0 and 1
  10551. * const color7 = new THREE.Color( 1, 0, 0 );
  10552. * ```
  10553. */
  10554. class Color {
  10555. /**
  10556. * Constructs a new color.
  10557. *
  10558. * Note that standard method of specifying color in three.js is with a hexadecimal triplet,
  10559. * and that method is used throughout the rest of the documentation.
  10560. *
  10561. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  10562. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  10563. * @param {number} [g] - The green component.
  10564. * @param {number} [b] - The blue component.
  10565. */
  10566. constructor( r, g, b ) {
  10567. /**
  10568. * This flag can be used for type testing.
  10569. *
  10570. * @type {boolean}
  10571. * @readonly
  10572. * @default true
  10573. */
  10574. this.isColor = true;
  10575. /**
  10576. * The red component.
  10577. *
  10578. * @type {number}
  10579. * @default 1
  10580. */
  10581. this.r = 1;
  10582. /**
  10583. * The green component.
  10584. *
  10585. * @type {number}
  10586. * @default 1
  10587. */
  10588. this.g = 1;
  10589. /**
  10590. * The blue component.
  10591. *
  10592. * @type {number}
  10593. * @default 1
  10594. */
  10595. this.b = 1;
  10596. return this.set( r, g, b );
  10597. }
  10598. /**
  10599. * Sets the colors's components from the given values.
  10600. *
  10601. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  10602. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  10603. * @param {number} [g] - The green component.
  10604. * @param {number} [b] - The blue component.
  10605. * @return {Color} A reference to this color.
  10606. */
  10607. set( r, g, b ) {
  10608. if ( g === undefined && b === undefined ) {
  10609. // r is THREE.Color, hex or string
  10610. const value = r;
  10611. if ( value && value.isColor ) {
  10612. this.copy( value );
  10613. } else if ( typeof value === 'number' ) {
  10614. this.setHex( value );
  10615. } else if ( typeof value === 'string' ) {
  10616. this.setStyle( value );
  10617. }
  10618. } else {
  10619. this.setRGB( r, g, b );
  10620. }
  10621. return this;
  10622. }
  10623. /**
  10624. * Sets the colors's components to the given scalar value.
  10625. *
  10626. * @param {number} scalar - The scalar value.
  10627. * @return {Color} A reference to this color.
  10628. */
  10629. setScalar( scalar ) {
  10630. this.r = scalar;
  10631. this.g = scalar;
  10632. this.b = scalar;
  10633. return this;
  10634. }
  10635. /**
  10636. * Sets this color from a hexadecimal value.
  10637. *
  10638. * @param {number} hex - The hexadecimal value.
  10639. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10640. * @return {Color} A reference to this color.
  10641. */
  10642. setHex( hex, colorSpace = SRGBColorSpace ) {
  10643. hex = Math.floor( hex );
  10644. this.r = ( hex >> 16 & 255 ) / 255;
  10645. this.g = ( hex >> 8 & 255 ) / 255;
  10646. this.b = ( hex & 255 ) / 255;
  10647. ColorManagement.colorSpaceToWorking( this, colorSpace );
  10648. return this;
  10649. }
  10650. /**
  10651. * Sets this color from RGB values.
  10652. *
  10653. * @param {number} r - Red channel value between `0.0` and `1.0`.
  10654. * @param {number} g - Green channel value between `0.0` and `1.0`.
  10655. * @param {number} b - Blue channel value between `0.0` and `1.0`.
  10656. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  10657. * @return {Color} A reference to this color.
  10658. */
  10659. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  10660. this.r = r;
  10661. this.g = g;
  10662. this.b = b;
  10663. ColorManagement.colorSpaceToWorking( this, colorSpace );
  10664. return this;
  10665. }
  10666. /**
  10667. * Sets this color from RGB values.
  10668. *
  10669. * @param {number} h - Hue value between `0.0` and `1.0`.
  10670. * @param {number} s - Saturation value between `0.0` and `1.0`.
  10671. * @param {number} l - Lightness value between `0.0` and `1.0`.
  10672. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  10673. * @return {Color} A reference to this color.
  10674. */
  10675. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  10676. // h,s,l ranges are in 0.0 - 1.0
  10677. h = euclideanModulo( h, 1 );
  10678. s = clamp( s, 0, 1 );
  10679. l = clamp( l, 0, 1 );
  10680. if ( s === 0 ) {
  10681. this.r = this.g = this.b = l;
  10682. } else {
  10683. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  10684. const q = ( 2 * l ) - p;
  10685. this.r = hue2rgb( q, p, h + 1 / 3 );
  10686. this.g = hue2rgb( q, p, h );
  10687. this.b = hue2rgb( q, p, h - 1 / 3 );
  10688. }
  10689. ColorManagement.colorSpaceToWorking( this, colorSpace );
  10690. return this;
  10691. }
  10692. /**
  10693. * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`,
  10694. * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or
  10695. * any [X11 color name](https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart) -
  10696. * all 140 color names are supported).
  10697. *
  10698. * @param {string} style - Color as a CSS-style string.
  10699. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10700. * @return {Color} A reference to this color.
  10701. */
  10702. setStyle( style, colorSpace = SRGBColorSpace ) {
  10703. function handleAlpha( string ) {
  10704. if ( string === undefined ) return;
  10705. if ( parseFloat( string ) < 1 ) {
  10706. warn( 'Color: Alpha component of ' + style + ' will be ignored.' );
  10707. }
  10708. }
  10709. let m;
  10710. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  10711. // rgb / hsl
  10712. let color;
  10713. const name = m[ 1 ];
  10714. const components = m[ 2 ];
  10715. switch ( name ) {
  10716. case 'rgb':
  10717. case 'rgba':
  10718. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  10719. // rgb(255,0,0) rgba(255,0,0,0.5)
  10720. handleAlpha( color[ 4 ] );
  10721. return this.setRGB(
  10722. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  10723. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  10724. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  10725. colorSpace
  10726. );
  10727. }
  10728. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  10729. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  10730. handleAlpha( color[ 4 ] );
  10731. return this.setRGB(
  10732. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  10733. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  10734. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  10735. colorSpace
  10736. );
  10737. }
  10738. break;
  10739. case 'hsl':
  10740. case 'hsla':
  10741. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  10742. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  10743. handleAlpha( color[ 4 ] );
  10744. return this.setHSL(
  10745. parseFloat( color[ 1 ] ) / 360,
  10746. parseFloat( color[ 2 ] ) / 100,
  10747. parseFloat( color[ 3 ] ) / 100,
  10748. colorSpace
  10749. );
  10750. }
  10751. break;
  10752. default:
  10753. warn( 'Color: Unknown color model ' + style );
  10754. }
  10755. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  10756. // hex color
  10757. const hex = m[ 1 ];
  10758. const size = hex.length;
  10759. if ( size === 3 ) {
  10760. // #ff0
  10761. return this.setRGB(
  10762. parseInt( hex.charAt( 0 ), 16 ) / 15,
  10763. parseInt( hex.charAt( 1 ), 16 ) / 15,
  10764. parseInt( hex.charAt( 2 ), 16 ) / 15,
  10765. colorSpace
  10766. );
  10767. } else if ( size === 6 ) {
  10768. // #ff0000
  10769. return this.setHex( parseInt( hex, 16 ), colorSpace );
  10770. } else {
  10771. warn( 'Color: Invalid hex color ' + style );
  10772. }
  10773. } else if ( style && style.length > 0 ) {
  10774. return this.setColorName( style, colorSpace );
  10775. }
  10776. return this;
  10777. }
  10778. /**
  10779. * Sets this color from a color name. Faster than {@link Color#setStyle} if
  10780. * you don't need the other CSS-style formats.
  10781. *
  10782. * For convenience, the list of names is exposed in `Color.NAMES` as a hash.
  10783. * ```js
  10784. * Color.NAMES.aliceblue // returns 0xF0F8FF
  10785. * ```
  10786. *
  10787. * @param {string} style - The color name.
  10788. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10789. * @return {Color} A reference to this color.
  10790. */
  10791. setColorName( style, colorSpace = SRGBColorSpace ) {
  10792. // color keywords
  10793. const hex = _colorKeywords[ style.toLowerCase() ];
  10794. if ( hex !== undefined ) {
  10795. // red
  10796. this.setHex( hex, colorSpace );
  10797. } else {
  10798. // unknown color
  10799. warn( 'Color: Unknown color ' + style );
  10800. }
  10801. return this;
  10802. }
  10803. /**
  10804. * Returns a new color with copied values from this instance.
  10805. *
  10806. * @return {Color} A clone of this instance.
  10807. */
  10808. clone() {
  10809. return new this.constructor( this.r, this.g, this.b );
  10810. }
  10811. /**
  10812. * Copies the values of the given color to this instance.
  10813. *
  10814. * @param {Color} color - The color to copy.
  10815. * @return {Color} A reference to this color.
  10816. */
  10817. copy( color ) {
  10818. this.r = color.r;
  10819. this.g = color.g;
  10820. this.b = color.b;
  10821. return this;
  10822. }
  10823. /**
  10824. * Copies the given color into this color, and then converts this color from
  10825. * `SRGBColorSpace` to `LinearSRGBColorSpace`.
  10826. *
  10827. * @param {Color} color - The color to copy/convert.
  10828. * @return {Color} A reference to this color.
  10829. */
  10830. copySRGBToLinear( color ) {
  10831. this.r = SRGBToLinear( color.r );
  10832. this.g = SRGBToLinear( color.g );
  10833. this.b = SRGBToLinear( color.b );
  10834. return this;
  10835. }
  10836. /**
  10837. * Copies the given color into this color, and then converts this color from
  10838. * `LinearSRGBColorSpace` to `SRGBColorSpace`.
  10839. *
  10840. * @param {Color} color - The color to copy/convert.
  10841. * @return {Color} A reference to this color.
  10842. */
  10843. copyLinearToSRGB( color ) {
  10844. this.r = LinearToSRGB( color.r );
  10845. this.g = LinearToSRGB( color.g );
  10846. this.b = LinearToSRGB( color.b );
  10847. return this;
  10848. }
  10849. /**
  10850. * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`.
  10851. *
  10852. * @return {Color} A reference to this color.
  10853. */
  10854. convertSRGBToLinear() {
  10855. this.copySRGBToLinear( this );
  10856. return this;
  10857. }
  10858. /**
  10859. * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`.
  10860. *
  10861. * @return {Color} A reference to this color.
  10862. */
  10863. convertLinearToSRGB() {
  10864. this.copyLinearToSRGB( this );
  10865. return this;
  10866. }
  10867. /**
  10868. * Returns the hexadecimal value of this color.
  10869. *
  10870. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10871. * @return {number} The hexadecimal value.
  10872. */
  10873. getHex( colorSpace = SRGBColorSpace ) {
  10874. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  10875. 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 ) );
  10876. }
  10877. /**
  10878. * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').
  10879. *
  10880. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10881. * @return {string} The hexadecimal value as a string.
  10882. */
  10883. getHexString( colorSpace = SRGBColorSpace ) {
  10884. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( -6 );
  10885. }
  10886. /**
  10887. * Converts the colors RGB values into the HSL format and stores them into the
  10888. * given target object.
  10889. *
  10890. * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result.
  10891. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  10892. * @return {{h:number,s:number,l:number}} The HSL representation of this color.
  10893. */
  10894. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  10895. // h,s,l ranges are in 0.0 - 1.0
  10896. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  10897. const r = _color.r, g = _color.g, b = _color.b;
  10898. const max = Math.max( r, g, b );
  10899. const min = Math.min( r, g, b );
  10900. let hue, saturation;
  10901. const lightness = ( min + max ) / 2.0;
  10902. if ( min === max ) {
  10903. hue = 0;
  10904. saturation = 0;
  10905. } else {
  10906. const delta = max - min;
  10907. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  10908. switch ( max ) {
  10909. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  10910. case g: hue = ( b - r ) / delta + 2; break;
  10911. case b: hue = ( r - g ) / delta + 4; break;
  10912. }
  10913. hue /= 6;
  10914. }
  10915. target.h = hue;
  10916. target.s = saturation;
  10917. target.l = lightness;
  10918. return target;
  10919. }
  10920. /**
  10921. * Returns the RGB values of this color and stores them into the given target object.
  10922. *
  10923. * @param {Color} target - The target color that is used to store the method's result.
  10924. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  10925. * @return {Color} The RGB representation of this color.
  10926. */
  10927. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  10928. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  10929. target.r = _color.r;
  10930. target.g = _color.g;
  10931. target.b = _color.b;
  10932. return target;
  10933. }
  10934. /**
  10935. * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`.
  10936. *
  10937. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10938. * @return {string} The CSS representation of this color.
  10939. */
  10940. getStyle( colorSpace = SRGBColorSpace ) {
  10941. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  10942. const r = _color.r, g = _color.g, b = _color.b;
  10943. if ( colorSpace !== SRGBColorSpace ) {
  10944. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  10945. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  10946. }
  10947. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  10948. }
  10949. /**
  10950. * Adds the given HSL values to this color's values.
  10951. * Internally, this converts the color's RGB values to HSL, adds HSL
  10952. * and then converts the color back to RGB.
  10953. *
  10954. * @param {number} h - Hue value between `0.0` and `1.0`.
  10955. * @param {number} s - Saturation value between `0.0` and `1.0`.
  10956. * @param {number} l - Lightness value between `0.0` and `1.0`.
  10957. * @return {Color} A reference to this color.
  10958. */
  10959. offsetHSL( h, s, l ) {
  10960. this.getHSL( _hslA );
  10961. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  10962. }
  10963. /**
  10964. * Adds the RGB values of the given color to the RGB values of this color.
  10965. *
  10966. * @param {Color} color - The color to add.
  10967. * @return {Color} A reference to this color.
  10968. */
  10969. add( color ) {
  10970. this.r += color.r;
  10971. this.g += color.g;
  10972. this.b += color.b;
  10973. return this;
  10974. }
  10975. /**
  10976. * Adds the RGB values of the given colors and stores the result in this instance.
  10977. *
  10978. * @param {Color} color1 - The first color.
  10979. * @param {Color} color2 - The second color.
  10980. * @return {Color} A reference to this color.
  10981. */
  10982. addColors( color1, color2 ) {
  10983. this.r = color1.r + color2.r;
  10984. this.g = color1.g + color2.g;
  10985. this.b = color1.b + color2.b;
  10986. return this;
  10987. }
  10988. /**
  10989. * Adds the given scalar value to the RGB values of this color.
  10990. *
  10991. * @param {number} s - The scalar to add.
  10992. * @return {Color} A reference to this color.
  10993. */
  10994. addScalar( s ) {
  10995. this.r += s;
  10996. this.g += s;
  10997. this.b += s;
  10998. return this;
  10999. }
  11000. /**
  11001. * Subtracts the RGB values of the given color from the RGB values of this color.
  11002. *
  11003. * @param {Color} color - The color to subtract.
  11004. * @return {Color} A reference to this color.
  11005. */
  11006. sub( color ) {
  11007. this.r = Math.max( 0, this.r - color.r );
  11008. this.g = Math.max( 0, this.g - color.g );
  11009. this.b = Math.max( 0, this.b - color.b );
  11010. return this;
  11011. }
  11012. /**
  11013. * Multiplies the RGB values of the given color with the RGB values of this color.
  11014. *
  11015. * @param {Color} color - The color to multiply.
  11016. * @return {Color} A reference to this color.
  11017. */
  11018. multiply( color ) {
  11019. this.r *= color.r;
  11020. this.g *= color.g;
  11021. this.b *= color.b;
  11022. return this;
  11023. }
  11024. /**
  11025. * Multiplies the given scalar value with the RGB values of this color.
  11026. *
  11027. * @param {number} s - The scalar to multiply.
  11028. * @return {Color} A reference to this color.
  11029. */
  11030. multiplyScalar( s ) {
  11031. this.r *= s;
  11032. this.g *= s;
  11033. this.b *= s;
  11034. return this;
  11035. }
  11036. /**
  11037. * Linearly interpolates this color's RGB values toward the RGB values of the
  11038. * given color. The alpha argument can be thought of as the ratio between
  11039. * the two colors, where `0.0` is this color and `1.0` is the first argument.
  11040. *
  11041. * @param {Color} color - The color to converge on.
  11042. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  11043. * @return {Color} A reference to this color.
  11044. */
  11045. lerp( color, alpha ) {
  11046. this.r += ( color.r - this.r ) * alpha;
  11047. this.g += ( color.g - this.g ) * alpha;
  11048. this.b += ( color.b - this.b ) * alpha;
  11049. return this;
  11050. }
  11051. /**
  11052. * Linearly interpolates between the given colors and stores the result in this instance.
  11053. * The alpha argument can be thought of as the ratio between the two colors, where `0.0`
  11054. * is the first and `1.0` is the second color.
  11055. *
  11056. * @param {Color} color1 - The first color.
  11057. * @param {Color} color2 - The second color.
  11058. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  11059. * @return {Color} A reference to this color.
  11060. */
  11061. lerpColors( color1, color2, alpha ) {
  11062. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  11063. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  11064. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  11065. return this;
  11066. }
  11067. /**
  11068. * Linearly interpolates this color's HSL values toward the HSL values of the
  11069. * given color. It differs from {@link Color#lerp} by not interpolating straight
  11070. * from one color to the other, but instead going through all the hues in between
  11071. * those two colors. The alpha argument can be thought of as the ratio between
  11072. * the two colors, where 0.0 is this color and 1.0 is the first argument.
  11073. *
  11074. * @param {Color} color - The color to converge on.
  11075. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  11076. * @return {Color} A reference to this color.
  11077. */
  11078. lerpHSL( color, alpha ) {
  11079. this.getHSL( _hslA );
  11080. color.getHSL( _hslB );
  11081. const h = lerp( _hslA.h, _hslB.h, alpha );
  11082. const s = lerp( _hslA.s, _hslB.s, alpha );
  11083. const l = lerp( _hslA.l, _hslB.l, alpha );
  11084. this.setHSL( h, s, l );
  11085. return this;
  11086. }
  11087. /**
  11088. * Sets the color's RGB components from the given 3D vector.
  11089. *
  11090. * @param {Vector3} v - The vector to set.
  11091. * @return {Color} A reference to this color.
  11092. */
  11093. setFromVector3( v ) {
  11094. this.r = v.x;
  11095. this.g = v.y;
  11096. this.b = v.z;
  11097. return this;
  11098. }
  11099. /**
  11100. * Transforms this color with the given 3x3 matrix.
  11101. *
  11102. * @param {Matrix3} m - The matrix.
  11103. * @return {Color} A reference to this color.
  11104. */
  11105. applyMatrix3( m ) {
  11106. const r = this.r, g = this.g, b = this.b;
  11107. const e = m.elements;
  11108. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  11109. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  11110. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  11111. return this;
  11112. }
  11113. /**
  11114. * Returns `true` if this color is equal with the given one.
  11115. *
  11116. * @param {Color} c - The color to test for equality.
  11117. * @return {boolean} Whether this bounding color is equal with the given one.
  11118. */
  11119. equals( c ) {
  11120. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  11121. }
  11122. /**
  11123. * Sets this color's RGB components from the given array.
  11124. *
  11125. * @param {Array<number>} array - An array holding the RGB values.
  11126. * @param {number} [offset=0] - The offset into the array.
  11127. * @return {Color} A reference to this color.
  11128. */
  11129. fromArray( array, offset = 0 ) {
  11130. this.r = array[ offset ];
  11131. this.g = array[ offset + 1 ];
  11132. this.b = array[ offset + 2 ];
  11133. return this;
  11134. }
  11135. /**
  11136. * Writes the RGB components of this color to the given array. If no array is provided,
  11137. * the method returns a new instance.
  11138. *
  11139. * @param {Array<number>} [array=[]] - The target array holding the color components.
  11140. * @param {number} [offset=0] - Index of the first element in the array.
  11141. * @return {Array<number>} The color components.
  11142. */
  11143. toArray( array = [], offset = 0 ) {
  11144. array[ offset ] = this.r;
  11145. array[ offset + 1 ] = this.g;
  11146. array[ offset + 2 ] = this.b;
  11147. return array;
  11148. }
  11149. /**
  11150. * Sets the components of this color from the given buffer attribute.
  11151. *
  11152. * @param {BufferAttribute} attribute - The buffer attribute holding color data.
  11153. * @param {number} index - The index into the attribute.
  11154. * @return {Color} A reference to this color.
  11155. */
  11156. fromBufferAttribute( attribute, index ) {
  11157. this.r = attribute.getX( index );
  11158. this.g = attribute.getY( index );
  11159. this.b = attribute.getZ( index );
  11160. return this;
  11161. }
  11162. /**
  11163. * This methods defines the serialization result of this class. Returns the color
  11164. * as a hexadecimal value.
  11165. *
  11166. * @return {number} The hexadecimal value.
  11167. */
  11168. toJSON() {
  11169. return this.getHex();
  11170. }
  11171. *[ Symbol.iterator ]() {
  11172. yield this.r;
  11173. yield this.g;
  11174. yield this.b;
  11175. }
  11176. }
  11177. const _color = /*@__PURE__*/ new Color();
  11178. /**
  11179. * A dictionary with X11 color names.
  11180. *
  11181. * Note that multiple words such as Dark Orange become the string 'darkorange'.
  11182. *
  11183. * @static
  11184. * @type {Object}
  11185. */
  11186. Color.NAMES = _colorKeywords;
  11187. /**
  11188. * This class can be used to define an exponential squared fog,
  11189. * which gives a clear view near the camera and a faster than exponentially
  11190. * densening fog farther from the camera.
  11191. *
  11192. * ```js
  11193. * const scene = new THREE.Scene();
  11194. * scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );
  11195. * ```
  11196. */
  11197. class FogExp2 {
  11198. /**
  11199. * Constructs a new fog.
  11200. *
  11201. * @param {number|Color} color - The fog's color.
  11202. * @param {number} [density=0.00025] - Defines how fast the fog will grow dense.
  11203. */
  11204. constructor( color, density = 0.00025 ) {
  11205. /**
  11206. * This flag can be used for type testing.
  11207. *
  11208. * @type {boolean}
  11209. * @readonly
  11210. * @default true
  11211. */
  11212. this.isFogExp2 = true;
  11213. /**
  11214. * The name of the fog.
  11215. *
  11216. * @type {string}
  11217. */
  11218. this.name = '';
  11219. /**
  11220. * The fog's color.
  11221. *
  11222. * @type {Color}
  11223. */
  11224. this.color = new Color( color );
  11225. /**
  11226. * Defines how fast the fog will grow dense.
  11227. *
  11228. * @type {number}
  11229. * @default 0.00025
  11230. */
  11231. this.density = density;
  11232. }
  11233. /**
  11234. * Returns a new fog with copied values from this instance.
  11235. *
  11236. * @return {FogExp2} A clone of this instance.
  11237. */
  11238. clone() {
  11239. return new FogExp2( this.color, this.density );
  11240. }
  11241. /**
  11242. * Serializes the fog into JSON.
  11243. *
  11244. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  11245. * @return {Object} A JSON object representing the serialized fog
  11246. */
  11247. toJSON( /* meta */ ) {
  11248. return {
  11249. type: 'FogExp2',
  11250. name: this.name,
  11251. color: this.color.getHex(),
  11252. density: this.density
  11253. };
  11254. }
  11255. }
  11256. /**
  11257. * This class can be used to define a linear fog that grows linearly denser
  11258. * with the distance.
  11259. *
  11260. * ```js
  11261. * const scene = new THREE.Scene();
  11262. * scene.fog = new THREE.Fog( 0xcccccc, 10, 15 );
  11263. * ```
  11264. */
  11265. class Fog {
  11266. /**
  11267. * Constructs a new fog.
  11268. *
  11269. * @param {number|Color} color - The fog's color.
  11270. * @param {number} [near=1] - The minimum distance to start applying fog.
  11271. * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied.
  11272. */
  11273. constructor( color, near = 1, far = 1000 ) {
  11274. /**
  11275. * This flag can be used for type testing.
  11276. *
  11277. * @type {boolean}
  11278. * @readonly
  11279. * @default true
  11280. */
  11281. this.isFog = true;
  11282. /**
  11283. * The name of the fog.
  11284. *
  11285. * @type {string}
  11286. */
  11287. this.name = '';
  11288. /**
  11289. * The fog's color.
  11290. *
  11291. * @type {Color}
  11292. */
  11293. this.color = new Color( color );
  11294. /**
  11295. * The minimum distance to start applying fog. Objects that are less than
  11296. * `near` units from the active camera won't be affected by fog.
  11297. *
  11298. * @type {number}
  11299. * @default 1
  11300. */
  11301. this.near = near;
  11302. /**
  11303. * The maximum distance at which fog stops being calculated and applied.
  11304. * Objects that are more than `far` units away from the active camera won't
  11305. * be affected by fog.
  11306. *
  11307. * @type {number}
  11308. * @default 1000
  11309. */
  11310. this.far = far;
  11311. }
  11312. /**
  11313. * Returns a new fog with copied values from this instance.
  11314. *
  11315. * @return {Fog} A clone of this instance.
  11316. */
  11317. clone() {
  11318. return new Fog( this.color, this.near, this.far );
  11319. }
  11320. /**
  11321. * Serializes the fog into JSON.
  11322. *
  11323. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  11324. * @return {Object} A JSON object representing the serialized fog
  11325. */
  11326. toJSON( /* meta */ ) {
  11327. return {
  11328. type: 'Fog',
  11329. name: this.name,
  11330. color: this.color.getHex(),
  11331. near: this.near,
  11332. far: this.far
  11333. };
  11334. }
  11335. }
  11336. /**
  11337. * Scenes allow you to set up what is to be rendered and where by three.js.
  11338. * This is where you place 3D objects like meshes, lines or lights.
  11339. *
  11340. * @augments Object3D
  11341. */
  11342. class Scene extends Object3D {
  11343. /**
  11344. * Constructs a new scene.
  11345. */
  11346. constructor() {
  11347. super();
  11348. /**
  11349. * This flag can be used for type testing.
  11350. *
  11351. * @type {boolean}
  11352. * @readonly
  11353. * @default true
  11354. */
  11355. this.isScene = true;
  11356. this.type = 'Scene';
  11357. /**
  11358. * Defines the background of the scene. Valid inputs are:
  11359. *
  11360. * - A color for defining a uniform colored background.
  11361. * - A texture for defining a (flat) textured background.
  11362. * - Cube textures or equirectangular textures for defining a skybox.
  11363. *
  11364. * @type {?(Color|Texture)}
  11365. * @default null
  11366. */
  11367. this.background = null;
  11368. /**
  11369. * Sets the environment map for all physical materials in the scene. However,
  11370. * it's not possible to overwrite an existing texture assigned to the `envMap`
  11371. * material property.
  11372. *
  11373. * @type {?Texture}
  11374. * @default null
  11375. */
  11376. this.environment = null;
  11377. /**
  11378. * A fog instance defining the type of fog that affects everything
  11379. * rendered in the scene.
  11380. *
  11381. * @type {?(Fog|FogExp2)}
  11382. * @default null
  11383. */
  11384. this.fog = null;
  11385. /**
  11386. * Sets the blurriness of the background. Only influences environment maps
  11387. * assigned to {@link Scene#background}. Valid input is a float between `0`
  11388. * and `1`.
  11389. *
  11390. * @type {number}
  11391. * @default 0
  11392. */
  11393. this.backgroundBlurriness = 0;
  11394. /**
  11395. * Attenuates the color of the background. Only applies to background textures.
  11396. *
  11397. * @type {number}
  11398. * @default 1
  11399. */
  11400. this.backgroundIntensity = 1;
  11401. /**
  11402. * The rotation of the background in radians. Only influences environment maps
  11403. * assigned to {@link Scene#background}.
  11404. *
  11405. * @type {Euler}
  11406. * @default (0,0,0)
  11407. */
  11408. this.backgroundRotation = new Euler();
  11409. /**
  11410. * Attenuates the color of the environment. Only influences environment maps
  11411. * assigned to {@link Scene#environment}.
  11412. *
  11413. * @type {number}
  11414. * @default 1
  11415. */
  11416. this.environmentIntensity = 1;
  11417. /**
  11418. * The rotation of the environment map in radians. Only influences physical materials
  11419. * in the scene when {@link Scene#environment} is used.
  11420. *
  11421. * @type {Euler}
  11422. * @default (0,0,0)
  11423. */
  11424. this.environmentRotation = new Euler();
  11425. /**
  11426. * Forces everything in the scene to be rendered with the defined material. It is possible
  11427. * to exclude materials from override by setting {@link Material#allowOverride} to `false`.
  11428. *
  11429. * @type {?Material}
  11430. * @default null
  11431. */
  11432. this.overrideMaterial = null;
  11433. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  11434. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  11435. }
  11436. }
  11437. copy( source, recursive ) {
  11438. super.copy( source, recursive );
  11439. if ( source.background !== null ) this.background = source.background.clone();
  11440. if ( source.environment !== null ) this.environment = source.environment.clone();
  11441. if ( source.fog !== null ) this.fog = source.fog.clone();
  11442. this.backgroundBlurriness = source.backgroundBlurriness;
  11443. this.backgroundIntensity = source.backgroundIntensity;
  11444. this.backgroundRotation.copy( source.backgroundRotation );
  11445. this.environmentIntensity = source.environmentIntensity;
  11446. this.environmentRotation.copy( source.environmentRotation );
  11447. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  11448. this.matrixAutoUpdate = source.matrixAutoUpdate;
  11449. return this;
  11450. }
  11451. toJSON( meta ) {
  11452. const data = super.toJSON( meta );
  11453. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  11454. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  11455. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  11456. data.object.backgroundRotation = this.backgroundRotation.toArray();
  11457. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  11458. data.object.environmentRotation = this.environmentRotation.toArray();
  11459. return data;
  11460. }
  11461. }
  11462. const _v0$2 = /*@__PURE__*/ new Vector3();
  11463. const _v1$5 = /*@__PURE__*/ new Vector3();
  11464. const _v2$4 = /*@__PURE__*/ new Vector3();
  11465. const _v3$2 = /*@__PURE__*/ new Vector3();
  11466. const _vab = /*@__PURE__*/ new Vector3();
  11467. const _vac = /*@__PURE__*/ new Vector3();
  11468. const _vbc = /*@__PURE__*/ new Vector3();
  11469. const _vap = /*@__PURE__*/ new Vector3();
  11470. const _vbp = /*@__PURE__*/ new Vector3();
  11471. const _vcp = /*@__PURE__*/ new Vector3();
  11472. const _v40 = /*@__PURE__*/ new Vector4();
  11473. const _v41 = /*@__PURE__*/ new Vector4();
  11474. const _v42 = /*@__PURE__*/ new Vector4();
  11475. /**
  11476. * A geometric triangle as defined by three vectors representing its three corners.
  11477. */
  11478. class Triangle {
  11479. /**
  11480. * Constructs a new triangle.
  11481. *
  11482. * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle.
  11483. * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle.
  11484. * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle.
  11485. */
  11486. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  11487. /**
  11488. * The first corner of the triangle.
  11489. *
  11490. * @type {Vector3}
  11491. */
  11492. this.a = a;
  11493. /**
  11494. * The second corner of the triangle.
  11495. *
  11496. * @type {Vector3}
  11497. */
  11498. this.b = b;
  11499. /**
  11500. * The third corner of the triangle.
  11501. *
  11502. * @type {Vector3}
  11503. */
  11504. this.c = c;
  11505. }
  11506. /**
  11507. * Computes the normal vector of a triangle.
  11508. *
  11509. * @param {Vector3} a - The first corner of the triangle.
  11510. * @param {Vector3} b - The second corner of the triangle.
  11511. * @param {Vector3} c - The third corner of the triangle.
  11512. * @param {Vector3} target - The target vector that is used to store the method's result.
  11513. * @return {Vector3} The triangle's normal.
  11514. */
  11515. static getNormal( a, b, c, target ) {
  11516. target.subVectors( c, b );
  11517. _v0$2.subVectors( a, b );
  11518. target.cross( _v0$2 );
  11519. const targetLengthSq = target.lengthSq();
  11520. if ( targetLengthSq > 0 ) {
  11521. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  11522. }
  11523. return target.set( 0, 0, 0 );
  11524. }
  11525. /**
  11526. * Computes a barycentric coordinates from the given vector.
  11527. * Returns `null` if the triangle is degenerate.
  11528. *
  11529. * @param {Vector3} point - A point in 3D space.
  11530. * @param {Vector3} a - The first corner of the triangle.
  11531. * @param {Vector3} b - The second corner of the triangle.
  11532. * @param {Vector3} c - The third corner of the triangle.
  11533. * @param {Vector3} target - The target vector that is used to store the method's result.
  11534. * @return {?Vector3} The barycentric coordinates for the given point
  11535. */
  11536. static getBarycoord( point, a, b, c, target ) {
  11537. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  11538. _v0$2.subVectors( c, a );
  11539. _v1$5.subVectors( b, a );
  11540. _v2$4.subVectors( point, a );
  11541. const dot00 = _v0$2.dot( _v0$2 );
  11542. const dot01 = _v0$2.dot( _v1$5 );
  11543. const dot02 = _v0$2.dot( _v2$4 );
  11544. const dot11 = _v1$5.dot( _v1$5 );
  11545. const dot12 = _v1$5.dot( _v2$4 );
  11546. const denom = ( dot00 * dot11 - dot01 * dot01 );
  11547. // collinear or singular triangle
  11548. if ( denom === 0 ) {
  11549. target.set( 0, 0, 0 );
  11550. return null;
  11551. }
  11552. const invDenom = 1 / denom;
  11553. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  11554. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  11555. // barycentric coordinates must always sum to 1
  11556. return target.set( 1 - u - v, v, u );
  11557. }
  11558. /**
  11559. * Returns `true` if the given point, when projected onto the plane of the
  11560. * triangle, lies within the triangle.
  11561. *
  11562. * @param {Vector3} point - The point in 3D space to test.
  11563. * @param {Vector3} a - The first corner of the triangle.
  11564. * @param {Vector3} b - The second corner of the triangle.
  11565. * @param {Vector3} c - The third corner of the triangle.
  11566. * @return {boolean} Whether the given point, when projected onto the plane of the
  11567. * triangle, lies within the triangle or not.
  11568. */
  11569. static containsPoint( point, a, b, c ) {
  11570. // if the triangle is degenerate then we can't contain a point
  11571. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  11572. return false;
  11573. }
  11574. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  11575. }
  11576. /**
  11577. * Computes the value barycentrically interpolated for the given point on the
  11578. * triangle. Returns `null` if the triangle is degenerate.
  11579. *
  11580. * @param {Vector3} point - Position of interpolated point.
  11581. * @param {Vector3} p1 - The first corner of the triangle.
  11582. * @param {Vector3} p2 - The second corner of the triangle.
  11583. * @param {Vector3} p3 - The third corner of the triangle.
  11584. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11585. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11586. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11587. * @param {Vector3} target - The target vector that is used to store the method's result.
  11588. * @return {?Vector3} The interpolated value.
  11589. */
  11590. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  11591. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  11592. target.x = 0;
  11593. target.y = 0;
  11594. if ( 'z' in target ) target.z = 0;
  11595. if ( 'w' in target ) target.w = 0;
  11596. return null;
  11597. }
  11598. target.setScalar( 0 );
  11599. target.addScaledVector( v1, _v3$2.x );
  11600. target.addScaledVector( v2, _v3$2.y );
  11601. target.addScaledVector( v3, _v3$2.z );
  11602. return target;
  11603. }
  11604. /**
  11605. * Computes the value barycentrically interpolated for the given attribute and indices.
  11606. *
  11607. * @param {BufferAttribute} attr - The attribute to interpolate.
  11608. * @param {number} i1 - Index of first vertex.
  11609. * @param {number} i2 - Index of second vertex.
  11610. * @param {number} i3 - Index of third vertex.
  11611. * @param {Vector3} barycoord - The barycoordinate value to use to interpolate.
  11612. * @param {Vector3} target - The target vector that is used to store the method's result.
  11613. * @return {Vector3} The interpolated attribute value.
  11614. */
  11615. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  11616. _v40.setScalar( 0 );
  11617. _v41.setScalar( 0 );
  11618. _v42.setScalar( 0 );
  11619. _v40.fromBufferAttribute( attr, i1 );
  11620. _v41.fromBufferAttribute( attr, i2 );
  11621. _v42.fromBufferAttribute( attr, i3 );
  11622. target.setScalar( 0 );
  11623. target.addScaledVector( _v40, barycoord.x );
  11624. target.addScaledVector( _v41, barycoord.y );
  11625. target.addScaledVector( _v42, barycoord.z );
  11626. return target;
  11627. }
  11628. /**
  11629. * Returns `true` if the triangle is oriented towards the given direction.
  11630. *
  11631. * @param {Vector3} a - The first corner of the triangle.
  11632. * @param {Vector3} b - The second corner of the triangle.
  11633. * @param {Vector3} c - The third corner of the triangle.
  11634. * @param {Vector3} direction - The (normalized) direction vector.
  11635. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11636. */
  11637. static isFrontFacing( a, b, c, direction ) {
  11638. _v0$2.subVectors( c, b );
  11639. _v1$5.subVectors( a, b );
  11640. // strictly front facing
  11641. return _v0$2.cross( _v1$5 ).dot( direction ) < 0;
  11642. }
  11643. /**
  11644. * Sets the triangle's vertices by copying the given values.
  11645. *
  11646. * @param {Vector3} a - The first corner of the triangle.
  11647. * @param {Vector3} b - The second corner of the triangle.
  11648. * @param {Vector3} c - The third corner of the triangle.
  11649. * @return {Triangle} A reference to this triangle.
  11650. */
  11651. set( a, b, c ) {
  11652. this.a.copy( a );
  11653. this.b.copy( b );
  11654. this.c.copy( c );
  11655. return this;
  11656. }
  11657. /**
  11658. * Sets the triangle's vertices by copying the given array values.
  11659. *
  11660. * @param {Array<Vector3>} points - An array with 3D points.
  11661. * @param {number} i0 - The array index representing the first corner of the triangle.
  11662. * @param {number} i1 - The array index representing the second corner of the triangle.
  11663. * @param {number} i2 - The array index representing the third corner of the triangle.
  11664. * @return {Triangle} A reference to this triangle.
  11665. */
  11666. setFromPointsAndIndices( points, i0, i1, i2 ) {
  11667. this.a.copy( points[ i0 ] );
  11668. this.b.copy( points[ i1 ] );
  11669. this.c.copy( points[ i2 ] );
  11670. return this;
  11671. }
  11672. /**
  11673. * Sets the triangle's vertices by copying the given attribute values.
  11674. *
  11675. * @param {BufferAttribute} attribute - A buffer attribute with 3D points data.
  11676. * @param {number} i0 - The attribute index representing the first corner of the triangle.
  11677. * @param {number} i1 - The attribute index representing the second corner of the triangle.
  11678. * @param {number} i2 - The attribute index representing the third corner of the triangle.
  11679. * @return {Triangle} A reference to this triangle.
  11680. */
  11681. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  11682. this.a.fromBufferAttribute( attribute, i0 );
  11683. this.b.fromBufferAttribute( attribute, i1 );
  11684. this.c.fromBufferAttribute( attribute, i2 );
  11685. return this;
  11686. }
  11687. /**
  11688. * Returns a new triangle with copied values from this instance.
  11689. *
  11690. * @return {Triangle} A clone of this instance.
  11691. */
  11692. clone() {
  11693. return new this.constructor().copy( this );
  11694. }
  11695. /**
  11696. * Copies the values of the given triangle to this instance.
  11697. *
  11698. * @param {Triangle} triangle - The triangle to copy.
  11699. * @return {Triangle} A reference to this triangle.
  11700. */
  11701. copy( triangle ) {
  11702. this.a.copy( triangle.a );
  11703. this.b.copy( triangle.b );
  11704. this.c.copy( triangle.c );
  11705. return this;
  11706. }
  11707. /**
  11708. * Computes the area of the triangle.
  11709. *
  11710. * @return {number} The triangle's area.
  11711. */
  11712. getArea() {
  11713. _v0$2.subVectors( this.c, this.b );
  11714. _v1$5.subVectors( this.a, this.b );
  11715. return _v0$2.cross( _v1$5 ).length() * 0.5;
  11716. }
  11717. /**
  11718. * Computes the midpoint of the triangle.
  11719. *
  11720. * @param {Vector3} target - The target vector that is used to store the method's result.
  11721. * @return {Vector3} The triangle's midpoint.
  11722. */
  11723. getMidpoint( target ) {
  11724. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  11725. }
  11726. /**
  11727. * Computes the normal of the triangle.
  11728. *
  11729. * @param {Vector3} target - The target vector that is used to store the method's result.
  11730. * @return {Vector3} The triangle's normal.
  11731. */
  11732. getNormal( target ) {
  11733. return Triangle.getNormal( this.a, this.b, this.c, target );
  11734. }
  11735. /**
  11736. * Computes a plane the triangle lies within.
  11737. *
  11738. * @param {Plane} target - The target vector that is used to store the method's result.
  11739. * @return {Plane} The plane the triangle lies within.
  11740. */
  11741. getPlane( target ) {
  11742. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  11743. }
  11744. /**
  11745. * Computes a barycentric coordinates from the given vector.
  11746. * Returns `null` if the triangle is degenerate.
  11747. *
  11748. * @param {Vector3} point - A point in 3D space.
  11749. * @param {Vector3} target - The target vector that is used to store the method's result.
  11750. * @return {?Vector3} The barycentric coordinates for the given point
  11751. */
  11752. getBarycoord( point, target ) {
  11753. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  11754. }
  11755. /**
  11756. * Computes the value barycentrically interpolated for the given point on the
  11757. * triangle. Returns `null` if the triangle is degenerate.
  11758. *
  11759. * @param {Vector3} point - Position of interpolated point.
  11760. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11761. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11762. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11763. * @param {Vector3} target - The target vector that is used to store the method's result.
  11764. * @return {?Vector3} The interpolated value.
  11765. */
  11766. getInterpolation( point, v1, v2, v3, target ) {
  11767. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  11768. }
  11769. /**
  11770. * Returns `true` if the given point, when projected onto the plane of the
  11771. * triangle, lies within the triangle.
  11772. *
  11773. * @param {Vector3} point - The point in 3D space to test.
  11774. * @return {boolean} Whether the given point, when projected onto the plane of the
  11775. * triangle, lies within the triangle or not.
  11776. */
  11777. containsPoint( point ) {
  11778. return Triangle.containsPoint( point, this.a, this.b, this.c );
  11779. }
  11780. /**
  11781. * Returns `true` if the triangle is oriented towards the given direction.
  11782. *
  11783. * @param {Vector3} direction - The (normalized) direction vector.
  11784. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11785. */
  11786. isFrontFacing( direction ) {
  11787. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  11788. }
  11789. /**
  11790. * Returns `true` if this triangle intersects with the given box.
  11791. *
  11792. * @param {Box3} box - The box to intersect.
  11793. * @return {boolean} Whether this triangle intersects with the given box or not.
  11794. */
  11795. intersectsBox( box ) {
  11796. return box.intersectsTriangle( this );
  11797. }
  11798. /**
  11799. * Returns the closest point on the triangle to the given point.
  11800. *
  11801. * @param {Vector3} p - The point to compute the closest point for.
  11802. * @param {Vector3} target - The target vector that is used to store the method's result.
  11803. * @return {Vector3} The closest point on the triangle.
  11804. */
  11805. closestPointToPoint( p, target ) {
  11806. const a = this.a, b = this.b, c = this.c;
  11807. let v, w;
  11808. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  11809. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  11810. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  11811. // basically, we're distinguishing which of the voronoi regions of the triangle
  11812. // the point lies in with the minimum amount of redundant computation.
  11813. _vab.subVectors( b, a );
  11814. _vac.subVectors( c, a );
  11815. _vap.subVectors( p, a );
  11816. const d1 = _vab.dot( _vap );
  11817. const d2 = _vac.dot( _vap );
  11818. if ( d1 <= 0 && d2 <= 0 ) {
  11819. // vertex region of A; barycentric coords (1, 0, 0)
  11820. return target.copy( a );
  11821. }
  11822. _vbp.subVectors( p, b );
  11823. const d3 = _vab.dot( _vbp );
  11824. const d4 = _vac.dot( _vbp );
  11825. if ( d3 >= 0 && d4 <= d3 ) {
  11826. // vertex region of B; barycentric coords (0, 1, 0)
  11827. return target.copy( b );
  11828. }
  11829. const vc = d1 * d4 - d3 * d2;
  11830. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  11831. v = d1 / ( d1 - d3 );
  11832. // edge region of AB; barycentric coords (1-v, v, 0)
  11833. return target.copy( a ).addScaledVector( _vab, v );
  11834. }
  11835. _vcp.subVectors( p, c );
  11836. const d5 = _vab.dot( _vcp );
  11837. const d6 = _vac.dot( _vcp );
  11838. if ( d6 >= 0 && d5 <= d6 ) {
  11839. // vertex region of C; barycentric coords (0, 0, 1)
  11840. return target.copy( c );
  11841. }
  11842. const vb = d5 * d2 - d1 * d6;
  11843. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  11844. w = d2 / ( d2 - d6 );
  11845. // edge region of AC; barycentric coords (1-w, 0, w)
  11846. return target.copy( a ).addScaledVector( _vac, w );
  11847. }
  11848. const va = d3 * d6 - d5 * d4;
  11849. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  11850. _vbc.subVectors( c, b );
  11851. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  11852. // edge region of BC; barycentric coords (0, 1-w, w)
  11853. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  11854. }
  11855. // face region
  11856. const denom = 1 / ( va + vb + vc );
  11857. // u = va * denom
  11858. v = vb * denom;
  11859. w = vc * denom;
  11860. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  11861. }
  11862. /**
  11863. * Returns `true` if this triangle is equal with the given one.
  11864. *
  11865. * @param {Triangle} triangle - The triangle to test for equality.
  11866. * @return {boolean} Whether this triangle is equal with the given one.
  11867. */
  11868. equals( triangle ) {
  11869. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  11870. }
  11871. }
  11872. /**
  11873. * Represents an axis-aligned bounding box (AABB) in 3D space.
  11874. */
  11875. class Box3 {
  11876. /**
  11877. * Constructs a new bounding box.
  11878. *
  11879. * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box.
  11880. * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  11881. */
  11882. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  11883. /**
  11884. * This flag can be used for type testing.
  11885. *
  11886. * @type {boolean}
  11887. * @readonly
  11888. * @default true
  11889. */
  11890. this.isBox3 = true;
  11891. /**
  11892. * The lower boundary of the box.
  11893. *
  11894. * @type {Vector3}
  11895. */
  11896. this.min = min;
  11897. /**
  11898. * The upper boundary of the box.
  11899. *
  11900. * @type {Vector3}
  11901. */
  11902. this.max = max;
  11903. }
  11904. /**
  11905. * Sets the lower and upper boundaries of this box.
  11906. * Please note that this method only copies the values from the given objects.
  11907. *
  11908. * @param {Vector3} min - The lower boundary of the box.
  11909. * @param {Vector3} max - The upper boundary of the box.
  11910. * @return {Box3} A reference to this bounding box.
  11911. */
  11912. set( min, max ) {
  11913. this.min.copy( min );
  11914. this.max.copy( max );
  11915. return this;
  11916. }
  11917. /**
  11918. * Sets the upper and lower bounds of this box so it encloses the position data
  11919. * in the given array.
  11920. *
  11921. * @param {Array<number>} array - An array holding 3D position data.
  11922. * @return {Box3} A reference to this bounding box.
  11923. */
  11924. setFromArray( array ) {
  11925. this.makeEmpty();
  11926. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  11927. this.expandByPoint( _vector$b.fromArray( array, i ) );
  11928. }
  11929. return this;
  11930. }
  11931. /**
  11932. * Sets the upper and lower bounds of this box so it encloses the position data
  11933. * in the given buffer attribute.
  11934. *
  11935. * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data.
  11936. * @return {Box3} A reference to this bounding box.
  11937. */
  11938. setFromBufferAttribute( attribute ) {
  11939. this.makeEmpty();
  11940. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  11941. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  11942. }
  11943. return this;
  11944. }
  11945. /**
  11946. * Sets the upper and lower bounds of this box so it encloses the position data
  11947. * in the given array.
  11948. *
  11949. * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}.
  11950. * @return {Box3} A reference to this bounding box.
  11951. */
  11952. setFromPoints( points ) {
  11953. this.makeEmpty();
  11954. for ( let i = 0, il = points.length; i < il; i ++ ) {
  11955. this.expandByPoint( points[ i ] );
  11956. }
  11957. return this;
  11958. }
  11959. /**
  11960. * Centers this box on the given center vector and sets this box's width, height and
  11961. * depth to the given size values.
  11962. *
  11963. * @param {Vector3} center - The center of the box.
  11964. * @param {Vector3} size - The x, y and z dimensions of the box.
  11965. * @return {Box3} A reference to this bounding box.
  11966. */
  11967. setFromCenterAndSize( center, size ) {
  11968. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  11969. this.min.copy( center ).sub( halfSize );
  11970. this.max.copy( center ).add( halfSize );
  11971. return this;
  11972. }
  11973. /**
  11974. * Computes the world-axis-aligned bounding box for the given 3D object
  11975. * (including its children), accounting for the object's, and children's,
  11976. * world transforms. The function may result in a larger box than strictly necessary.
  11977. *
  11978. * @param {Object3D} object - The 3D object to compute the bounding box for.
  11979. * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest
  11980. * world-axis-aligned bounding box at the expense of more computation.
  11981. * @return {Box3} A reference to this bounding box.
  11982. */
  11983. setFromObject( object, precise = false ) {
  11984. this.makeEmpty();
  11985. return this.expandByObject( object, precise );
  11986. }
  11987. /**
  11988. * Returns a new box with copied values from this instance.
  11989. *
  11990. * @return {Box3} A clone of this instance.
  11991. */
  11992. clone() {
  11993. return new this.constructor().copy( this );
  11994. }
  11995. /**
  11996. * Copies the values of the given box to this instance.
  11997. *
  11998. * @param {Box3} box - The box to copy.
  11999. * @return {Box3} A reference to this bounding box.
  12000. */
  12001. copy( box ) {
  12002. this.min.copy( box.min );
  12003. this.max.copy( box.max );
  12004. return this;
  12005. }
  12006. /**
  12007. * Makes this box empty which means in encloses a zero space in 3D.
  12008. *
  12009. * @return {Box3} A reference to this bounding box.
  12010. */
  12011. makeEmpty() {
  12012. this.min.x = this.min.y = this.min.z = + Infinity;
  12013. this.max.x = this.max.y = this.max.z = - Infinity;
  12014. return this;
  12015. }
  12016. /**
  12017. * Returns true if this box includes zero points within its bounds.
  12018. * Note that a box with equal lower and upper bounds still includes one
  12019. * point, the one both bounds share.
  12020. *
  12021. * @return {boolean} Whether this box is empty or not.
  12022. */
  12023. isEmpty() {
  12024. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  12025. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  12026. }
  12027. /**
  12028. * Returns the center point of this box.
  12029. *
  12030. * @param {Vector3} target - The target vector that is used to store the method's result.
  12031. * @return {Vector3} The center point.
  12032. */
  12033. getCenter( target ) {
  12034. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  12035. }
  12036. /**
  12037. * Returns the dimensions of this box.
  12038. *
  12039. * @param {Vector3} target - The target vector that is used to store the method's result.
  12040. * @return {Vector3} The size.
  12041. */
  12042. getSize( target ) {
  12043. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  12044. }
  12045. /**
  12046. * Expands the boundaries of this box to include the given point.
  12047. *
  12048. * @param {Vector3} point - The point that should be included by the bounding box.
  12049. * @return {Box3} A reference to this bounding box.
  12050. */
  12051. expandByPoint( point ) {
  12052. this.min.min( point );
  12053. this.max.max( point );
  12054. return this;
  12055. }
  12056. /**
  12057. * Expands this box equilaterally by the given vector. The width of this
  12058. * box will be expanded by the x component of the vector in both
  12059. * directions. The height of this box will be expanded by the y component of
  12060. * the vector in both directions. The depth of this box will be
  12061. * expanded by the z component of the vector in both directions.
  12062. *
  12063. * @param {Vector3} vector - The vector that should expand the bounding box.
  12064. * @return {Box3} A reference to this bounding box.
  12065. */
  12066. expandByVector( vector ) {
  12067. this.min.sub( vector );
  12068. this.max.add( vector );
  12069. return this;
  12070. }
  12071. /**
  12072. * Expands each dimension of the box by the given scalar. If negative, the
  12073. * dimensions of the box will be contracted.
  12074. *
  12075. * @param {number} scalar - The scalar value that should expand the bounding box.
  12076. * @return {Box3} A reference to this bounding box.
  12077. */
  12078. expandByScalar( scalar ) {
  12079. this.min.addScalar( - scalar );
  12080. this.max.addScalar( scalar );
  12081. return this;
  12082. }
  12083. /**
  12084. * Expands the boundaries of this box to include the given 3D object and
  12085. * its children, accounting for the object's, and children's, world
  12086. * transforms. The function may result in a larger box than strictly
  12087. * necessary (unless the precise parameter is set to true).
  12088. *
  12089. * @param {Object3D} object - The 3D object that should expand the bounding box.
  12090. * @param {boolean} precise - If set to `true`, the method expands the bounding box
  12091. * as little as necessary at the expense of more computation.
  12092. * @return {Box3} A reference to this bounding box.
  12093. */
  12094. expandByObject( object, precise = false ) {
  12095. // Computes the world-axis-aligned bounding box of an object (including its children),
  12096. // accounting for both the object's, and children's, world transforms
  12097. object.updateWorldMatrix( false, false );
  12098. const geometry = object.geometry;
  12099. if ( geometry !== undefined ) {
  12100. const positionAttribute = geometry.getAttribute( 'position' );
  12101. // precise AABB computation based on vertex data requires at least a position attribute.
  12102. // instancing isn't supported so far and uses the normal (conservative) code path.
  12103. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  12104. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  12105. if ( object.isMesh === true ) {
  12106. object.getVertexPosition( i, _vector$b );
  12107. } else {
  12108. _vector$b.fromBufferAttribute( positionAttribute, i );
  12109. }
  12110. _vector$b.applyMatrix4( object.matrixWorld );
  12111. this.expandByPoint( _vector$b );
  12112. }
  12113. } else {
  12114. if ( object.boundingBox !== undefined ) {
  12115. // object-level bounding box
  12116. if ( object.boundingBox === null ) {
  12117. object.computeBoundingBox();
  12118. }
  12119. _box$4.copy( object.boundingBox );
  12120. } else {
  12121. // geometry-level bounding box
  12122. if ( geometry.boundingBox === null ) {
  12123. geometry.computeBoundingBox();
  12124. }
  12125. _box$4.copy( geometry.boundingBox );
  12126. }
  12127. _box$4.applyMatrix4( object.matrixWorld );
  12128. this.union( _box$4 );
  12129. }
  12130. }
  12131. const children = object.children;
  12132. for ( let i = 0, l = children.length; i < l; i ++ ) {
  12133. this.expandByObject( children[ i ], precise );
  12134. }
  12135. return this;
  12136. }
  12137. /**
  12138. * Returns `true` if the given point lies within or on the boundaries of this box.
  12139. *
  12140. * @param {Vector3} point - The point to test.
  12141. * @return {boolean} Whether the bounding box contains the given point or not.
  12142. */
  12143. containsPoint( point ) {
  12144. return point.x >= this.min.x && point.x <= this.max.x &&
  12145. point.y >= this.min.y && point.y <= this.max.y &&
  12146. point.z >= this.min.z && point.z <= this.max.z;
  12147. }
  12148. /**
  12149. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  12150. * If this box and the given one are identical, this function also returns `true`.
  12151. *
  12152. * @param {Box3} box - The bounding box to test.
  12153. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  12154. */
  12155. containsBox( box ) {
  12156. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  12157. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  12158. this.min.z <= box.min.z && box.max.z <= this.max.z;
  12159. }
  12160. /**
  12161. * Returns a point as a proportion of this box's width, height and depth.
  12162. *
  12163. * @param {Vector3} point - A point in 3D space.
  12164. * @param {Vector3} target - The target vector that is used to store the method's result.
  12165. * @return {Vector3} A point as a proportion of this box's width, height and depth.
  12166. */
  12167. getParameter( point, target ) {
  12168. // This can potentially have a divide by zero if the box
  12169. // has a size dimension of 0.
  12170. return target.set(
  12171. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  12172. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  12173. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  12174. );
  12175. }
  12176. /**
  12177. * Returns `true` if the given bounding box intersects with this bounding box.
  12178. *
  12179. * @param {Box3} box - The bounding box to test.
  12180. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  12181. */
  12182. intersectsBox( box ) {
  12183. // using 6 splitting planes to rule out intersections.
  12184. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  12185. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  12186. box.max.z >= this.min.z && box.min.z <= this.max.z;
  12187. }
  12188. /**
  12189. * Returns `true` if the given bounding sphere intersects with this bounding box.
  12190. *
  12191. * @param {Sphere} sphere - The bounding sphere to test.
  12192. * @return {boolean} Whether the given bounding sphere intersects with this bounding box.
  12193. */
  12194. intersectsSphere( sphere ) {
  12195. // Find the point on the AABB closest to the sphere center.
  12196. this.clampPoint( sphere.center, _vector$b );
  12197. // If that point is inside the sphere, the AABB and sphere intersect.
  12198. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  12199. }
  12200. /**
  12201. * Returns `true` if the given plane intersects with this bounding box.
  12202. *
  12203. * @param {Plane} plane - The plane to test.
  12204. * @return {boolean} Whether the given plane intersects with this bounding box.
  12205. */
  12206. intersectsPlane( plane ) {
  12207. // We compute the minimum and maximum dot product values. If those values
  12208. // are on the same side (back or front) of the plane, then there is no intersection.
  12209. let min, max;
  12210. if ( plane.normal.x > 0 ) {
  12211. min = plane.normal.x * this.min.x;
  12212. max = plane.normal.x * this.max.x;
  12213. } else {
  12214. min = plane.normal.x * this.max.x;
  12215. max = plane.normal.x * this.min.x;
  12216. }
  12217. if ( plane.normal.y > 0 ) {
  12218. min += plane.normal.y * this.min.y;
  12219. max += plane.normal.y * this.max.y;
  12220. } else {
  12221. min += plane.normal.y * this.max.y;
  12222. max += plane.normal.y * this.min.y;
  12223. }
  12224. if ( plane.normal.z > 0 ) {
  12225. min += plane.normal.z * this.min.z;
  12226. max += plane.normal.z * this.max.z;
  12227. } else {
  12228. min += plane.normal.z * this.max.z;
  12229. max += plane.normal.z * this.min.z;
  12230. }
  12231. return ( min <= - plane.constant && max >= - plane.constant );
  12232. }
  12233. /**
  12234. * Returns `true` if the given triangle intersects with this bounding box.
  12235. *
  12236. * @param {Triangle} triangle - The triangle to test.
  12237. * @return {boolean} Whether the given triangle intersects with this bounding box.
  12238. */
  12239. intersectsTriangle( triangle ) {
  12240. if ( this.isEmpty() ) {
  12241. return false;
  12242. }
  12243. // compute box center and extents
  12244. this.getCenter( _center );
  12245. _extents.subVectors( this.max, _center );
  12246. // translate triangle to aabb origin
  12247. _v0$1.subVectors( triangle.a, _center );
  12248. _v1$4.subVectors( triangle.b, _center );
  12249. _v2$3.subVectors( triangle.c, _center );
  12250. // compute edge vectors for triangle
  12251. _f0.subVectors( _v1$4, _v0$1 );
  12252. _f1.subVectors( _v2$3, _v1$4 );
  12253. _f2.subVectors( _v0$1, _v2$3 );
  12254. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  12255. // 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
  12256. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  12257. let axes = [
  12258. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  12259. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  12260. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  12261. ];
  12262. if ( ! satForAxes( axes, _v0$1, _v1$4, _v2$3, _extents ) ) {
  12263. return false;
  12264. }
  12265. // test 3 face normals from the aabb
  12266. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  12267. if ( ! satForAxes( axes, _v0$1, _v1$4, _v2$3, _extents ) ) {
  12268. return false;
  12269. }
  12270. // finally testing the face normal of the triangle
  12271. // use already existing triangle edge vectors here
  12272. _triangleNormal.crossVectors( _f0, _f1 );
  12273. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  12274. return satForAxes( axes, _v0$1, _v1$4, _v2$3, _extents );
  12275. }
  12276. /**
  12277. * Clamps the given point within the bounds of this box.
  12278. *
  12279. * @param {Vector3} point - The point to clamp.
  12280. * @param {Vector3} target - The target vector that is used to store the method's result.
  12281. * @return {Vector3} The clamped point.
  12282. */
  12283. clampPoint( point, target ) {
  12284. return target.copy( point ).clamp( this.min, this.max );
  12285. }
  12286. /**
  12287. * Returns the euclidean distance from any edge of this box to the specified point. If
  12288. * the given point lies inside of this box, the distance will be `0`.
  12289. *
  12290. * @param {Vector3} point - The point to compute the distance to.
  12291. * @return {number} The euclidean distance.
  12292. */
  12293. distanceToPoint( point ) {
  12294. return this.clampPoint( point, _vector$b ).distanceTo( point );
  12295. }
  12296. /**
  12297. * Returns a bounding sphere that encloses this bounding box.
  12298. *
  12299. * @param {Sphere} target - The target sphere that is used to store the method's result.
  12300. * @return {Sphere} The bounding sphere that encloses this bounding box.
  12301. */
  12302. getBoundingSphere( target ) {
  12303. if ( this.isEmpty() ) {
  12304. target.makeEmpty();
  12305. } else {
  12306. this.getCenter( target.center );
  12307. target.radius = this.getSize( _vector$b ).length() * 0.5;
  12308. }
  12309. return target;
  12310. }
  12311. /**
  12312. * Computes the intersection of this bounding box and the given one, setting the upper
  12313. * bound of this box to the lesser of the two boxes' upper bounds and the
  12314. * lower bound of this box to the greater of the two boxes' lower bounds. If
  12315. * there's no overlap, makes this box empty.
  12316. *
  12317. * @param {Box3} box - The bounding box to intersect with.
  12318. * @return {Box3} A reference to this bounding box.
  12319. */
  12320. intersect( box ) {
  12321. this.min.max( box.min );
  12322. this.max.min( box.max );
  12323. // 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.
  12324. if ( this.isEmpty() ) this.makeEmpty();
  12325. return this;
  12326. }
  12327. /**
  12328. * Computes the union of this box and another and the given one, setting the upper
  12329. * bound of this box to the greater of the two boxes' upper bounds and the
  12330. * lower bound of this box to the lesser of the two boxes' lower bounds.
  12331. *
  12332. * @param {Box3} box - The bounding box that will be unioned with this instance.
  12333. * @return {Box3} A reference to this bounding box.
  12334. */
  12335. union( box ) {
  12336. this.min.min( box.min );
  12337. this.max.max( box.max );
  12338. return this;
  12339. }
  12340. /**
  12341. * Transforms this bounding box by the given 4x4 transformation matrix.
  12342. *
  12343. * @param {Matrix4} matrix - The transformation matrix.
  12344. * @return {Box3} A reference to this bounding box.
  12345. */
  12346. applyMatrix4( matrix ) {
  12347. // transform of empty box is an empty box.
  12348. if ( this.isEmpty() ) return this;
  12349. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  12350. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  12351. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  12352. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  12353. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  12354. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  12355. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  12356. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  12357. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  12358. this.setFromPoints( _points );
  12359. return this;
  12360. }
  12361. /**
  12362. * Adds the given offset to both the upper and lower bounds of this bounding box,
  12363. * effectively moving it in 3D space.
  12364. *
  12365. * @param {Vector3} offset - The offset that should be used to translate the bounding box.
  12366. * @return {Box3} A reference to this bounding box.
  12367. */
  12368. translate( offset ) {
  12369. this.min.add( offset );
  12370. this.max.add( offset );
  12371. return this;
  12372. }
  12373. /**
  12374. * Returns `true` if this bounding box is equal with the given one.
  12375. *
  12376. * @param {Box3} box - The box to test for equality.
  12377. * @return {boolean} Whether this bounding box is equal with the given one.
  12378. */
  12379. equals( box ) {
  12380. return box.min.equals( this.min ) && box.max.equals( this.max );
  12381. }
  12382. /**
  12383. * Returns a serialized structure of the bounding box.
  12384. *
  12385. * @return {Object} Serialized structure with fields representing the object state.
  12386. */
  12387. toJSON() {
  12388. return {
  12389. min: this.min.toArray(),
  12390. max: this.max.toArray()
  12391. };
  12392. }
  12393. /**
  12394. * Returns a serialized structure of the bounding box.
  12395. *
  12396. * @param {Object} json - The serialized json to set the box from.
  12397. * @return {Box3} A reference to this bounding box.
  12398. */
  12399. fromJSON( json ) {
  12400. this.min.fromArray( json.min );
  12401. this.max.fromArray( json.max );
  12402. return this;
  12403. }
  12404. }
  12405. const _points = [
  12406. /*@__PURE__*/ new Vector3(),
  12407. /*@__PURE__*/ new Vector3(),
  12408. /*@__PURE__*/ new Vector3(),
  12409. /*@__PURE__*/ new Vector3(),
  12410. /*@__PURE__*/ new Vector3(),
  12411. /*@__PURE__*/ new Vector3(),
  12412. /*@__PURE__*/ new Vector3(),
  12413. /*@__PURE__*/ new Vector3()
  12414. ];
  12415. const _vector$b = /*@__PURE__*/ new Vector3();
  12416. const _box$4 = /*@__PURE__*/ new Box3();
  12417. // triangle centered vertices
  12418. const _v0$1 = /*@__PURE__*/ new Vector3();
  12419. const _v1$4 = /*@__PURE__*/ new Vector3();
  12420. const _v2$3 = /*@__PURE__*/ new Vector3();
  12421. // triangle edge vectors
  12422. const _f0 = /*@__PURE__*/ new Vector3();
  12423. const _f1 = /*@__PURE__*/ new Vector3();
  12424. const _f2 = /*@__PURE__*/ new Vector3();
  12425. const _center = /*@__PURE__*/ new Vector3();
  12426. const _extents = /*@__PURE__*/ new Vector3();
  12427. const _triangleNormal = /*@__PURE__*/ new Vector3();
  12428. const _testAxis = /*@__PURE__*/ new Vector3();
  12429. function satForAxes( axes, v0, v1, v2, extents ) {
  12430. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  12431. _testAxis.fromArray( axes, i );
  12432. // project the aabb onto the separating axis
  12433. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  12434. // project all 3 vertices of the triangle onto the separating axis
  12435. const p0 = v0.dot( _testAxis );
  12436. const p1 = v1.dot( _testAxis );
  12437. const p2 = v2.dot( _testAxis );
  12438. // actual test, basically see if either of the most extreme of the triangle points intersects r
  12439. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  12440. // points of the projected triangle are outside the projected half-length of the aabb
  12441. // the axis is separating and we can exit
  12442. return false;
  12443. }
  12444. }
  12445. return true;
  12446. }
  12447. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  12448. const _tables = /*@__PURE__*/ _generateTables();
  12449. function _generateTables() {
  12450. // float32 to float16 helpers
  12451. const buffer = new ArrayBuffer( 4 );
  12452. const floatView = new Float32Array( buffer );
  12453. const uint32View = new Uint32Array( buffer );
  12454. const baseTable = new Uint32Array( 512 );
  12455. const shiftTable = new Uint32Array( 512 );
  12456. for ( let i = 0; i < 256; ++ i ) {
  12457. const e = i - 127;
  12458. // very small number (0, -0)
  12459. if ( e < -27 ) {
  12460. baseTable[ i ] = 0x0000;
  12461. baseTable[ i | 0x100 ] = 0x8000;
  12462. shiftTable[ i ] = 24;
  12463. shiftTable[ i | 0x100 ] = 24;
  12464. // small number (denorm)
  12465. } else if ( e < -14 ) {
  12466. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  12467. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  12468. shiftTable[ i ] = - e - 1;
  12469. shiftTable[ i | 0x100 ] = - e - 1;
  12470. // normal number
  12471. } else if ( e <= 15 ) {
  12472. baseTable[ i ] = ( e + 15 ) << 10;
  12473. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  12474. shiftTable[ i ] = 13;
  12475. shiftTable[ i | 0x100 ] = 13;
  12476. // large number (Infinity, -Infinity)
  12477. } else if ( e < 128 ) {
  12478. baseTable[ i ] = 0x7c00;
  12479. baseTable[ i | 0x100 ] = 0xfc00;
  12480. shiftTable[ i ] = 24;
  12481. shiftTable[ i | 0x100 ] = 24;
  12482. // stay (NaN, Infinity, -Infinity)
  12483. } else {
  12484. baseTable[ i ] = 0x7c00;
  12485. baseTable[ i | 0x100 ] = 0xfc00;
  12486. shiftTable[ i ] = 13;
  12487. shiftTable[ i | 0x100 ] = 13;
  12488. }
  12489. }
  12490. // float16 to float32 helpers
  12491. const mantissaTable = new Uint32Array( 2048 );
  12492. const exponentTable = new Uint32Array( 64 );
  12493. const offsetTable = new Uint32Array( 64 );
  12494. for ( let i = 1; i < 1024; ++ i ) {
  12495. let m = i << 13; // zero pad mantissa bits
  12496. let e = 0; // zero exponent
  12497. // normalized
  12498. while ( ( m & 0x00800000 ) === 0 ) {
  12499. m <<= 1;
  12500. e -= 0x00800000; // decrement exponent
  12501. }
  12502. m &= -8388609; // clear leading 1 bit
  12503. e += 0x38800000; // adjust bias
  12504. mantissaTable[ i ] = m | e;
  12505. }
  12506. for ( let i = 1024; i < 2048; ++ i ) {
  12507. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  12508. }
  12509. for ( let i = 1; i < 31; ++ i ) {
  12510. exponentTable[ i ] = i << 23;
  12511. }
  12512. exponentTable[ 31 ] = 0x47800000;
  12513. exponentTable[ 32 ] = 0x80000000;
  12514. for ( let i = 33; i < 63; ++ i ) {
  12515. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  12516. }
  12517. exponentTable[ 63 ] = 0xc7800000;
  12518. for ( let i = 1; i < 64; ++ i ) {
  12519. if ( i !== 32 ) {
  12520. offsetTable[ i ] = 1024;
  12521. }
  12522. }
  12523. return {
  12524. floatView: floatView,
  12525. uint32View: uint32View,
  12526. baseTable: baseTable,
  12527. shiftTable: shiftTable,
  12528. mantissaTable: mantissaTable,
  12529. exponentTable: exponentTable,
  12530. offsetTable: offsetTable
  12531. };
  12532. }
  12533. /**
  12534. * Returns a half precision floating point value (FP16) from the given single
  12535. * precision floating point value (FP32).
  12536. *
  12537. * @param {number} val - A single precision floating point value.
  12538. * @return {number} The FP16 value.
  12539. */
  12540. function toHalfFloat( val ) {
  12541. if ( Math.abs( val ) > 65504 ) warn( 'DataUtils.toHalfFloat(): Value out of range.' );
  12542. val = clamp( val, -65504, 65504 );
  12543. _tables.floatView[ 0 ] = val;
  12544. const f = _tables.uint32View[ 0 ];
  12545. const e = ( f >> 23 ) & 0x1ff;
  12546. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  12547. }
  12548. /**
  12549. * Returns a single precision floating point value (FP32) from the given half
  12550. * precision floating point value (FP16).
  12551. *
  12552. * @param {number} val - A half precision floating point value.
  12553. * @return {number} The FP32 value.
  12554. */
  12555. function fromHalfFloat( val ) {
  12556. const m = val >> 10;
  12557. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  12558. return _tables.floatView[ 0 ];
  12559. }
  12560. /**
  12561. * A class containing utility functions for data.
  12562. *
  12563. * @hideconstructor
  12564. */
  12565. class DataUtils {
  12566. /**
  12567. * Returns a half precision floating point value (FP16) from the given single
  12568. * precision floating point value (FP32).
  12569. *
  12570. * @param {number} val - A single precision floating point value.
  12571. * @return {number} The FP16 value.
  12572. */
  12573. static toHalfFloat( val ) {
  12574. return toHalfFloat( val );
  12575. }
  12576. /**
  12577. * Returns a single precision floating point value (FP32) from the given half
  12578. * precision floating point value (FP16).
  12579. *
  12580. * @param {number} val - A half precision floating point value.
  12581. * @return {number} The FP32 value.
  12582. */
  12583. static fromHalfFloat( val ) {
  12584. return fromHalfFloat( val );
  12585. }
  12586. }
  12587. const _vector$a = /*@__PURE__*/ new Vector3();
  12588. const _vector2$1 = /*@__PURE__*/ new Vector2();
  12589. let _id$2 = 0;
  12590. /**
  12591. * This class stores data for an attribute (such as vertex positions, face
  12592. * indices, normals, colors, UVs, and any custom attributes ) associated with
  12593. * a geometry, which allows for more efficient passing of data to the GPU.
  12594. *
  12595. * When working with vector-like data, the `fromBufferAttribute( attribute, index )`
  12596. * helper methods on vector and color class might be helpful. E.g. {@link Vector3#fromBufferAttribute}.
  12597. */
  12598. class BufferAttribute {
  12599. /**
  12600. * Constructs a new buffer attribute.
  12601. *
  12602. * @param {TypedArray} array - The array holding the attribute data.
  12603. * @param {number} itemSize - The item size.
  12604. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  12605. */
  12606. constructor( array, itemSize, normalized = false ) {
  12607. if ( Array.isArray( array ) ) {
  12608. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  12609. }
  12610. /**
  12611. * This flag can be used for type testing.
  12612. *
  12613. * @type {boolean}
  12614. * @readonly
  12615. * @default true
  12616. */
  12617. this.isBufferAttribute = true;
  12618. /**
  12619. * The ID of the buffer attribute.
  12620. *
  12621. * @name BufferAttribute#id
  12622. * @type {number}
  12623. * @readonly
  12624. */
  12625. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  12626. /**
  12627. * The name of the buffer attribute.
  12628. *
  12629. * @type {string}
  12630. */
  12631. this.name = '';
  12632. /**
  12633. * The array holding the attribute data. It should have `itemSize * numVertices`
  12634. * elements, where `numVertices` is the number of vertices in the associated geometry.
  12635. *
  12636. * @type {TypedArray}
  12637. */
  12638. this.array = array;
  12639. /**
  12640. * The number of values of the array that should be associated with a particular vertex.
  12641. * For instance, if this attribute is storing a 3-component vector (such as a position,
  12642. * normal, or color), then the value should be `3`.
  12643. *
  12644. * @type {number}
  12645. */
  12646. this.itemSize = itemSize;
  12647. /**
  12648. * Represents the number of items this buffer attribute stores. It is internally computed
  12649. * by dividing the `array` length by the `itemSize`.
  12650. *
  12651. * @type {number}
  12652. * @readonly
  12653. */
  12654. this.count = array !== undefined ? array.length / itemSize : 0;
  12655. /**
  12656. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  12657. * the values in the GLSL code. For instance, if `array` is an instance of `UInt16Array`,
  12658. * and `normalized` is `true`, the values `0 - +65535` in the array data will be mapped to
  12659. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  12660. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  12661. *
  12662. * @type {boolean}
  12663. */
  12664. this.normalized = normalized;
  12665. /**
  12666. * Defines the intended usage pattern of the data store for optimization purposes.
  12667. *
  12668. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  12669. * instantiate a new one and set the desired usage before the next render.
  12670. *
  12671. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  12672. * @default StaticDrawUsage
  12673. */
  12674. this.usage = StaticDrawUsage;
  12675. /**
  12676. * This can be used to only update some components of stored vectors (for example, just the
  12677. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  12678. *
  12679. * @type {Array<Object>}
  12680. */
  12681. this.updateRanges = [];
  12682. /**
  12683. * Configures the bound GPU type for use in shaders.
  12684. *
  12685. * Note: this only has an effect for integer arrays and is not configurable for float arrays.
  12686. * For lower precision float types, use `Float16BufferAttribute`.
  12687. *
  12688. * @type {(FloatType|IntType)}
  12689. * @default FloatType
  12690. */
  12691. this.gpuType = FloatType;
  12692. /**
  12693. * A version number, incremented every time the `needsUpdate` is set to `true`.
  12694. *
  12695. * @type {number}
  12696. */
  12697. this.version = 0;
  12698. }
  12699. /**
  12700. * A callback function that is executed after the renderer has transferred the attribute
  12701. * array data to the GPU.
  12702. */
  12703. onUploadCallback() {}
  12704. /**
  12705. * Flag to indicate that this attribute has changed and should be re-sent to
  12706. * the GPU. Set this to `true` when you modify the value of the array.
  12707. *
  12708. * @type {number}
  12709. * @default false
  12710. * @param {boolean} value
  12711. */
  12712. set needsUpdate( value ) {
  12713. if ( value === true ) this.version ++;
  12714. }
  12715. /**
  12716. * Sets the usage of this buffer attribute.
  12717. *
  12718. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  12719. * @return {BufferAttribute} A reference to this buffer attribute.
  12720. */
  12721. setUsage( value ) {
  12722. this.usage = value;
  12723. return this;
  12724. }
  12725. /**
  12726. * Adds a range of data in the data array to be updated on the GPU.
  12727. *
  12728. * @param {number} start - Position at which to start update.
  12729. * @param {number} count - The number of components to update.
  12730. */
  12731. addUpdateRange( start, count ) {
  12732. this.updateRanges.push( { start, count } );
  12733. }
  12734. /**
  12735. * Clears the update ranges.
  12736. */
  12737. clearUpdateRanges() {
  12738. this.updateRanges.length = 0;
  12739. }
  12740. /**
  12741. * Copies the values of the given buffer attribute to this instance.
  12742. *
  12743. * @param {BufferAttribute} source - The buffer attribute to copy.
  12744. * @return {BufferAttribute} A reference to this instance.
  12745. */
  12746. copy( source ) {
  12747. this.name = source.name;
  12748. this.array = new source.array.constructor( source.array );
  12749. this.itemSize = source.itemSize;
  12750. this.count = source.count;
  12751. this.normalized = source.normalized;
  12752. this.usage = source.usage;
  12753. this.gpuType = source.gpuType;
  12754. return this;
  12755. }
  12756. /**
  12757. * Copies a vector from the given buffer attribute to this one. The start
  12758. * and destination position in the attribute buffers are represented by the
  12759. * given indices.
  12760. *
  12761. * @param {number} index1 - The destination index into this buffer attribute.
  12762. * @param {BufferAttribute} attribute - The buffer attribute to copy from.
  12763. * @param {number} index2 - The source index into the given buffer attribute.
  12764. * @return {BufferAttribute} A reference to this instance.
  12765. */
  12766. copyAt( index1, attribute, index2 ) {
  12767. index1 *= this.itemSize;
  12768. index2 *= attribute.itemSize;
  12769. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  12770. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  12771. }
  12772. return this;
  12773. }
  12774. /**
  12775. * Copies the given array data into this buffer attribute.
  12776. *
  12777. * @param {(TypedArray|Array)} array - The array to copy.
  12778. * @return {BufferAttribute} A reference to this instance.
  12779. */
  12780. copyArray( array ) {
  12781. this.array.set( array );
  12782. return this;
  12783. }
  12784. /**
  12785. * Applies the given 3x3 matrix to the given attribute. Works with
  12786. * item size `2` and `3`.
  12787. *
  12788. * @param {Matrix3} m - The matrix to apply.
  12789. * @return {BufferAttribute} A reference to this instance.
  12790. */
  12791. applyMatrix3( m ) {
  12792. if ( this.itemSize === 2 ) {
  12793. for ( let i = 0, l = this.count; i < l; i ++ ) {
  12794. _vector2$1.fromBufferAttribute( this, i );
  12795. _vector2$1.applyMatrix3( m );
  12796. this.setXY( i, _vector2$1.x, _vector2$1.y );
  12797. }
  12798. } else if ( this.itemSize === 3 ) {
  12799. for ( let i = 0, l = this.count; i < l; i ++ ) {
  12800. _vector$a.fromBufferAttribute( this, i );
  12801. _vector$a.applyMatrix3( m );
  12802. this.setXYZ( i, _vector$a.x, _vector$a.y, _vector$a.z );
  12803. }
  12804. }
  12805. return this;
  12806. }
  12807. /**
  12808. * Applies the given 4x4 matrix to the given attribute. Only works with
  12809. * item size `3`.
  12810. *
  12811. * @param {Matrix4} m - The matrix to apply.
  12812. * @return {BufferAttribute} A reference to this instance.
  12813. */
  12814. applyMatrix4( m ) {
  12815. for ( let i = 0, l = this.count; i < l; i ++ ) {
  12816. _vector$a.fromBufferAttribute( this, i );
  12817. _vector$a.applyMatrix4( m );
  12818. this.setXYZ( i, _vector$a.x, _vector$a.y, _vector$a.z );
  12819. }
  12820. return this;
  12821. }
  12822. /**
  12823. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  12824. * item size `3`.
  12825. *
  12826. * @param {Matrix3} m - The normal matrix to apply.
  12827. * @return {BufferAttribute} A reference to this instance.
  12828. */
  12829. applyNormalMatrix( m ) {
  12830. for ( let i = 0, l = this.count; i < l; i ++ ) {
  12831. _vector$a.fromBufferAttribute( this, i );
  12832. _vector$a.applyNormalMatrix( m );
  12833. this.setXYZ( i, _vector$a.x, _vector$a.y, _vector$a.z );
  12834. }
  12835. return this;
  12836. }
  12837. /**
  12838. * Applies the given 4x4 matrix to the given attribute. Only works with
  12839. * item size `3` and with direction vectors.
  12840. *
  12841. * @param {Matrix4} m - The matrix to apply.
  12842. * @return {BufferAttribute} A reference to this instance.
  12843. */
  12844. transformDirection( m ) {
  12845. for ( let i = 0, l = this.count; i < l; i ++ ) {
  12846. _vector$a.fromBufferAttribute( this, i );
  12847. _vector$a.transformDirection( m );
  12848. this.setXYZ( i, _vector$a.x, _vector$a.y, _vector$a.z );
  12849. }
  12850. return this;
  12851. }
  12852. /**
  12853. * Sets the given array data in the buffer attribute.
  12854. *
  12855. * @param {(TypedArray|Array)} value - The array data to set.
  12856. * @param {number} [offset=0] - The offset in this buffer attribute's array.
  12857. * @return {BufferAttribute} A reference to this instance.
  12858. */
  12859. set( value, offset = 0 ) {
  12860. // Matching BufferAttribute constructor, do not normalize the array.
  12861. this.array.set( value, offset );
  12862. return this;
  12863. }
  12864. /**
  12865. * Returns the given component of the vector at the given index.
  12866. *
  12867. * @param {number} index - The index into the buffer attribute.
  12868. * @param {number} component - The component index.
  12869. * @return {number} The returned value.
  12870. */
  12871. getComponent( index, component ) {
  12872. let value = this.array[ index * this.itemSize + component ];
  12873. if ( this.normalized ) value = denormalize( value, this.array );
  12874. return value;
  12875. }
  12876. /**
  12877. * Sets the given value to the given component of the vector at the given index.
  12878. *
  12879. * @param {number} index - The index into the buffer attribute.
  12880. * @param {number} component - The component index.
  12881. * @param {number} value - The value to set.
  12882. * @return {BufferAttribute} A reference to this instance.
  12883. */
  12884. setComponent( index, component, value ) {
  12885. if ( this.normalized ) value = normalize( value, this.array );
  12886. this.array[ index * this.itemSize + component ] = value;
  12887. return this;
  12888. }
  12889. /**
  12890. * Returns the x component of the vector at the given index.
  12891. *
  12892. * @param {number} index - The index into the buffer attribute.
  12893. * @return {number} The x component.
  12894. */
  12895. getX( index ) {
  12896. let x = this.array[ index * this.itemSize ];
  12897. if ( this.normalized ) x = denormalize( x, this.array );
  12898. return x;
  12899. }
  12900. /**
  12901. * Sets the x component of the vector at the given index.
  12902. *
  12903. * @param {number} index - The index into the buffer attribute.
  12904. * @param {number} x - The value to set.
  12905. * @return {BufferAttribute} A reference to this instance.
  12906. */
  12907. setX( index, x ) {
  12908. if ( this.normalized ) x = normalize( x, this.array );
  12909. this.array[ index * this.itemSize ] = x;
  12910. return this;
  12911. }
  12912. /**
  12913. * Returns the y component of the vector at the given index.
  12914. *
  12915. * @param {number} index - The index into the buffer attribute.
  12916. * @return {number} The y component.
  12917. */
  12918. getY( index ) {
  12919. let y = this.array[ index * this.itemSize + 1 ];
  12920. if ( this.normalized ) y = denormalize( y, this.array );
  12921. return y;
  12922. }
  12923. /**
  12924. * Sets the y component of the vector at the given index.
  12925. *
  12926. * @param {number} index - The index into the buffer attribute.
  12927. * @param {number} y - The value to set.
  12928. * @return {BufferAttribute} A reference to this instance.
  12929. */
  12930. setY( index, y ) {
  12931. if ( this.normalized ) y = normalize( y, this.array );
  12932. this.array[ index * this.itemSize + 1 ] = y;
  12933. return this;
  12934. }
  12935. /**
  12936. * Returns the z component of the vector at the given index.
  12937. *
  12938. * @param {number} index - The index into the buffer attribute.
  12939. * @return {number} The z component.
  12940. */
  12941. getZ( index ) {
  12942. let z = this.array[ index * this.itemSize + 2 ];
  12943. if ( this.normalized ) z = denormalize( z, this.array );
  12944. return z;
  12945. }
  12946. /**
  12947. * Sets the z component of the vector at the given index.
  12948. *
  12949. * @param {number} index - The index into the buffer attribute.
  12950. * @param {number} z - The value to set.
  12951. * @return {BufferAttribute} A reference to this instance.
  12952. */
  12953. setZ( index, z ) {
  12954. if ( this.normalized ) z = normalize( z, this.array );
  12955. this.array[ index * this.itemSize + 2 ] = z;
  12956. return this;
  12957. }
  12958. /**
  12959. * Returns the w component of the vector at the given index.
  12960. *
  12961. * @param {number} index - The index into the buffer attribute.
  12962. * @return {number} The w component.
  12963. */
  12964. getW( index ) {
  12965. let w = this.array[ index * this.itemSize + 3 ];
  12966. if ( this.normalized ) w = denormalize( w, this.array );
  12967. return w;
  12968. }
  12969. /**
  12970. * Sets the w component of the vector at the given index.
  12971. *
  12972. * @param {number} index - The index into the buffer attribute.
  12973. * @param {number} w - The value to set.
  12974. * @return {BufferAttribute} A reference to this instance.
  12975. */
  12976. setW( index, w ) {
  12977. if ( this.normalized ) w = normalize( w, this.array );
  12978. this.array[ index * this.itemSize + 3 ] = w;
  12979. return this;
  12980. }
  12981. /**
  12982. * Sets the x and y component of the vector at the given index.
  12983. *
  12984. * @param {number} index - The index into the buffer attribute.
  12985. * @param {number} x - The value for the x component to set.
  12986. * @param {number} y - The value for the y component to set.
  12987. * @return {BufferAttribute} A reference to this instance.
  12988. */
  12989. setXY( index, x, y ) {
  12990. index *= this.itemSize;
  12991. if ( this.normalized ) {
  12992. x = normalize( x, this.array );
  12993. y = normalize( y, this.array );
  12994. }
  12995. this.array[ index + 0 ] = x;
  12996. this.array[ index + 1 ] = y;
  12997. return this;
  12998. }
  12999. /**
  13000. * Sets the x, y and z component of the vector at the given index.
  13001. *
  13002. * @param {number} index - The index into the buffer attribute.
  13003. * @param {number} x - The value for the x component to set.
  13004. * @param {number} y - The value for the y component to set.
  13005. * @param {number} z - The value for the z component to set.
  13006. * @return {BufferAttribute} A reference to this instance.
  13007. */
  13008. setXYZ( index, x, y, z ) {
  13009. index *= this.itemSize;
  13010. if ( this.normalized ) {
  13011. x = normalize( x, this.array );
  13012. y = normalize( y, this.array );
  13013. z = normalize( z, this.array );
  13014. }
  13015. this.array[ index + 0 ] = x;
  13016. this.array[ index + 1 ] = y;
  13017. this.array[ index + 2 ] = z;
  13018. return this;
  13019. }
  13020. /**
  13021. * Sets the x, y, z and w component of the vector at the given index.
  13022. *
  13023. * @param {number} index - The index into the buffer attribute.
  13024. * @param {number} x - The value for the x component to set.
  13025. * @param {number} y - The value for the y component to set.
  13026. * @param {number} z - The value for the z component to set.
  13027. * @param {number} w - The value for the w component to set.
  13028. * @return {BufferAttribute} A reference to this instance.
  13029. */
  13030. setXYZW( index, x, y, z, w ) {
  13031. index *= this.itemSize;
  13032. if ( this.normalized ) {
  13033. x = normalize( x, this.array );
  13034. y = normalize( y, this.array );
  13035. z = normalize( z, this.array );
  13036. w = normalize( w, this.array );
  13037. }
  13038. this.array[ index + 0 ] = x;
  13039. this.array[ index + 1 ] = y;
  13040. this.array[ index + 2 ] = z;
  13041. this.array[ index + 3 ] = w;
  13042. return this;
  13043. }
  13044. /**
  13045. * Sets the given callback function that is executed after the Renderer has transferred
  13046. * the attribute array data to the GPU. Can be used to perform clean-up operations after
  13047. * the upload when attribute data are not needed anymore on the CPU side.
  13048. *
  13049. * @param {Function} callback - The `onUpload()` callback.
  13050. * @return {BufferAttribute} A reference to this instance.
  13051. */
  13052. onUpload( callback ) {
  13053. this.onUploadCallback = callback;
  13054. return this;
  13055. }
  13056. /**
  13057. * Returns a new buffer attribute with copied values from this instance.
  13058. *
  13059. * @return {BufferAttribute} A clone of this instance.
  13060. */
  13061. clone() {
  13062. return new this.constructor( this.array, this.itemSize ).copy( this );
  13063. }
  13064. /**
  13065. * Serializes the buffer attribute into JSON.
  13066. *
  13067. * @return {Object} A JSON object representing the serialized buffer attribute.
  13068. */
  13069. toJSON() {
  13070. const data = {
  13071. itemSize: this.itemSize,
  13072. type: this.array.constructor.name,
  13073. array: Array.from( this.array ),
  13074. normalized: this.normalized
  13075. };
  13076. if ( this.name !== '' ) data.name = this.name;
  13077. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  13078. return data;
  13079. }
  13080. }
  13081. /**
  13082. * Convenient class that can be used when creating a `Int8` buffer attribute with
  13083. * a plain `Array` instance.
  13084. *
  13085. * @augments BufferAttribute
  13086. */
  13087. class Int8BufferAttribute extends BufferAttribute {
  13088. /**
  13089. * Constructs a new buffer attribute.
  13090. *
  13091. * @param {(Array<number>|Int8Array)} array - The array holding the attribute data.
  13092. * @param {number} itemSize - The item size.
  13093. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13094. */
  13095. constructor( array, itemSize, normalized ) {
  13096. super( new Int8Array( array ), itemSize, normalized );
  13097. }
  13098. }
  13099. /**
  13100. * Convenient class that can be used when creating a `UInt8` buffer attribute with
  13101. * a plain `Array` instance.
  13102. *
  13103. * @augments BufferAttribute
  13104. */
  13105. class Uint8BufferAttribute extends BufferAttribute {
  13106. /**
  13107. * Constructs a new buffer attribute.
  13108. *
  13109. * @param {(Array<number>|Uint8Array)} array - The array holding the attribute data.
  13110. * @param {number} itemSize - The item size.
  13111. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13112. */
  13113. constructor( array, itemSize, normalized ) {
  13114. super( new Uint8Array( array ), itemSize, normalized );
  13115. }
  13116. }
  13117. /**
  13118. * Convenient class that can be used when creating a `UInt8Clamped` buffer attribute with
  13119. * a plain `Array` instance.
  13120. *
  13121. * @augments BufferAttribute
  13122. */
  13123. class Uint8ClampedBufferAttribute extends BufferAttribute {
  13124. /**
  13125. * Constructs a new buffer attribute.
  13126. *
  13127. * @param {(Array<number>|Uint8ClampedArray)} array - The array holding the attribute data.
  13128. * @param {number} itemSize - The item size.
  13129. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13130. */
  13131. constructor( array, itemSize, normalized ) {
  13132. super( new Uint8ClampedArray( array ), itemSize, normalized );
  13133. }
  13134. }
  13135. /**
  13136. * Convenient class that can be used when creating a `Int16` buffer attribute with
  13137. * a plain `Array` instance.
  13138. *
  13139. * @augments BufferAttribute
  13140. */
  13141. class Int16BufferAttribute extends BufferAttribute {
  13142. /**
  13143. * Constructs a new buffer attribute.
  13144. *
  13145. * @param {(Array<number>|Int16Array)} array - The array holding the attribute data.
  13146. * @param {number} itemSize - The item size.
  13147. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13148. */
  13149. constructor( array, itemSize, normalized ) {
  13150. super( new Int16Array( array ), itemSize, normalized );
  13151. }
  13152. }
  13153. /**
  13154. * Convenient class that can be used when creating a `UInt16` buffer attribute with
  13155. * a plain `Array` instance.
  13156. *
  13157. * @augments BufferAttribute
  13158. */
  13159. class Uint16BufferAttribute extends BufferAttribute {
  13160. /**
  13161. * Constructs a new buffer attribute.
  13162. *
  13163. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  13164. * @param {number} itemSize - The item size.
  13165. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13166. */
  13167. constructor( array, itemSize, normalized ) {
  13168. super( new Uint16Array( array ), itemSize, normalized );
  13169. }
  13170. }
  13171. /**
  13172. * Convenient class that can be used when creating a `Int32` buffer attribute with
  13173. * a plain `Array` instance.
  13174. *
  13175. * @augments BufferAttribute
  13176. */
  13177. class Int32BufferAttribute extends BufferAttribute {
  13178. /**
  13179. * Constructs a new buffer attribute.
  13180. *
  13181. * @param {(Array<number>|Int32Array)} array - The array holding the attribute data.
  13182. * @param {number} itemSize - The item size.
  13183. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13184. */
  13185. constructor( array, itemSize, normalized ) {
  13186. super( new Int32Array( array ), itemSize, normalized );
  13187. }
  13188. }
  13189. /**
  13190. * Convenient class that can be used when creating a `UInt32` buffer attribute with
  13191. * a plain `Array` instance.
  13192. *
  13193. * @augments BufferAttribute
  13194. */
  13195. class Uint32BufferAttribute extends BufferAttribute {
  13196. /**
  13197. * Constructs a new buffer attribute.
  13198. *
  13199. * @param {(Array<number>|Uint32Array)} array - The array holding the attribute data.
  13200. * @param {number} itemSize - The item size.
  13201. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13202. */
  13203. constructor( array, itemSize, normalized ) {
  13204. super( new Uint32Array( array ), itemSize, normalized );
  13205. }
  13206. }
  13207. /**
  13208. * Convenient class that can be used when creating a `Float16` buffer attribute with
  13209. * a plain `Array` instance.
  13210. *
  13211. * This class automatically converts to and from FP16 via `Uint16Array` since `Float16Array`
  13212. * browser support is still problematic.
  13213. *
  13214. * @augments BufferAttribute
  13215. */
  13216. class Float16BufferAttribute extends BufferAttribute {
  13217. /**
  13218. * Constructs a new buffer attribute.
  13219. *
  13220. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  13221. * @param {number} itemSize - The item size.
  13222. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13223. */
  13224. constructor( array, itemSize, normalized ) {
  13225. super( new Uint16Array( array ), itemSize, normalized );
  13226. this.isFloat16BufferAttribute = true;
  13227. }
  13228. getX( index ) {
  13229. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  13230. if ( this.normalized ) x = denormalize( x, this.array );
  13231. return x;
  13232. }
  13233. setX( index, x ) {
  13234. if ( this.normalized ) x = normalize( x, this.array );
  13235. this.array[ index * this.itemSize ] = toHalfFloat( x );
  13236. return this;
  13237. }
  13238. getY( index ) {
  13239. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  13240. if ( this.normalized ) y = denormalize( y, this.array );
  13241. return y;
  13242. }
  13243. setY( index, y ) {
  13244. if ( this.normalized ) y = normalize( y, this.array );
  13245. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  13246. return this;
  13247. }
  13248. getZ( index ) {
  13249. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  13250. if ( this.normalized ) z = denormalize( z, this.array );
  13251. return z;
  13252. }
  13253. setZ( index, z ) {
  13254. if ( this.normalized ) z = normalize( z, this.array );
  13255. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  13256. return this;
  13257. }
  13258. getW( index ) {
  13259. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  13260. if ( this.normalized ) w = denormalize( w, this.array );
  13261. return w;
  13262. }
  13263. setW( index, w ) {
  13264. if ( this.normalized ) w = normalize( w, this.array );
  13265. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  13266. return this;
  13267. }
  13268. setXY( index, x, y ) {
  13269. index *= this.itemSize;
  13270. if ( this.normalized ) {
  13271. x = normalize( x, this.array );
  13272. y = normalize( y, this.array );
  13273. }
  13274. this.array[ index + 0 ] = toHalfFloat( x );
  13275. this.array[ index + 1 ] = toHalfFloat( y );
  13276. return this;
  13277. }
  13278. setXYZ( index, x, y, z ) {
  13279. index *= this.itemSize;
  13280. if ( this.normalized ) {
  13281. x = normalize( x, this.array );
  13282. y = normalize( y, this.array );
  13283. z = normalize( z, this.array );
  13284. }
  13285. this.array[ index + 0 ] = toHalfFloat( x );
  13286. this.array[ index + 1 ] = toHalfFloat( y );
  13287. this.array[ index + 2 ] = toHalfFloat( z );
  13288. return this;
  13289. }
  13290. setXYZW( index, x, y, z, w ) {
  13291. index *= this.itemSize;
  13292. if ( this.normalized ) {
  13293. x = normalize( x, this.array );
  13294. y = normalize( y, this.array );
  13295. z = normalize( z, this.array );
  13296. w = normalize( w, this.array );
  13297. }
  13298. this.array[ index + 0 ] = toHalfFloat( x );
  13299. this.array[ index + 1 ] = toHalfFloat( y );
  13300. this.array[ index + 2 ] = toHalfFloat( z );
  13301. this.array[ index + 3 ] = toHalfFloat( w );
  13302. return this;
  13303. }
  13304. }
  13305. /**
  13306. * Convenient class that can be used when creating a `Float32` buffer attribute with
  13307. * a plain `Array` instance.
  13308. *
  13309. * @augments BufferAttribute
  13310. */
  13311. class Float32BufferAttribute extends BufferAttribute {
  13312. /**
  13313. * Constructs a new buffer attribute.
  13314. *
  13315. * @param {(Array<number>|Float32Array)} array - The array holding the attribute data.
  13316. * @param {number} itemSize - The item size.
  13317. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13318. */
  13319. constructor( array, itemSize, normalized ) {
  13320. super( new Float32Array( array ), itemSize, normalized );
  13321. }
  13322. }
  13323. const _box$3 = /*@__PURE__*/ new Box3();
  13324. const _v1$3 = /*@__PURE__*/ new Vector3();
  13325. const _v2$2 = /*@__PURE__*/ new Vector3();
  13326. /**
  13327. * An analytical 3D sphere defined by a center and radius. This class is mainly
  13328. * used as a Bounding Sphere for 3D objects.
  13329. */
  13330. class Sphere {
  13331. /**
  13332. * Constructs a new sphere.
  13333. *
  13334. * @param {Vector3} [center=(0,0,0)] - The center of the sphere
  13335. * @param {number} [radius=-1] - The radius of the sphere.
  13336. */
  13337. constructor( center = new Vector3(), radius = -1 ) {
  13338. /**
  13339. * This flag can be used for type testing.
  13340. *
  13341. * @type {boolean}
  13342. * @readonly
  13343. * @default true
  13344. */
  13345. this.isSphere = true;
  13346. /**
  13347. * The center of the sphere
  13348. *
  13349. * @type {Vector3}
  13350. */
  13351. this.center = center;
  13352. /**
  13353. * The radius of the sphere.
  13354. *
  13355. * @type {number}
  13356. */
  13357. this.radius = radius;
  13358. }
  13359. /**
  13360. * Sets the sphere's components by copying the given values.
  13361. *
  13362. * @param {Vector3} center - The center.
  13363. * @param {number} radius - The radius.
  13364. * @return {Sphere} A reference to this sphere.
  13365. */
  13366. set( center, radius ) {
  13367. this.center.copy( center );
  13368. this.radius = radius;
  13369. return this;
  13370. }
  13371. /**
  13372. * Computes the minimum bounding sphere for list of points.
  13373. * If the optional center point is given, it is used as the sphere's
  13374. * center. Otherwise, the center of the axis-aligned bounding box
  13375. * encompassing the points is calculated.
  13376. *
  13377. * @param {Array<Vector3>} points - A list of points in 3D space.
  13378. * @param {Vector3} [optionalCenter] - The center of the sphere.
  13379. * @return {Sphere} A reference to this sphere.
  13380. */
  13381. setFromPoints( points, optionalCenter ) {
  13382. const center = this.center;
  13383. if ( optionalCenter !== undefined ) {
  13384. center.copy( optionalCenter );
  13385. } else {
  13386. _box$3.setFromPoints( points ).getCenter( center );
  13387. }
  13388. let maxRadiusSq = 0;
  13389. for ( let i = 0, il = points.length; i < il; i ++ ) {
  13390. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  13391. }
  13392. this.radius = Math.sqrt( maxRadiusSq );
  13393. return this;
  13394. }
  13395. /**
  13396. * Copies the values of the given sphere to this instance.
  13397. *
  13398. * @param {Sphere} sphere - The sphere to copy.
  13399. * @return {Sphere} A reference to this sphere.
  13400. */
  13401. copy( sphere ) {
  13402. this.center.copy( sphere.center );
  13403. this.radius = sphere.radius;
  13404. return this;
  13405. }
  13406. /**
  13407. * Returns `true` if the sphere is empty (the radius set to a negative number).
  13408. *
  13409. * Spheres with a radius of `0` contain only their center point and are not
  13410. * considered to be empty.
  13411. *
  13412. * @return {boolean} Whether this sphere is empty or not.
  13413. */
  13414. isEmpty() {
  13415. return ( this.radius < 0 );
  13416. }
  13417. /**
  13418. * Makes this sphere empty which means in encloses a zero space in 3D.
  13419. *
  13420. * @return {Sphere} A reference to this sphere.
  13421. */
  13422. makeEmpty() {
  13423. this.center.set( 0, 0, 0 );
  13424. this.radius = -1;
  13425. return this;
  13426. }
  13427. /**
  13428. * Returns `true` if this sphere contains the given point inclusive of
  13429. * the surface of the sphere.
  13430. *
  13431. * @param {Vector3} point - The point to check.
  13432. * @return {boolean} Whether this sphere contains the given point or not.
  13433. */
  13434. containsPoint( point ) {
  13435. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  13436. }
  13437. /**
  13438. * Returns the closest distance from the boundary of the sphere to the
  13439. * given point. If the sphere contains the point, the distance will
  13440. * be negative.
  13441. *
  13442. * @param {Vector3} point - The point to compute the distance to.
  13443. * @return {number} The distance to the point.
  13444. */
  13445. distanceToPoint( point ) {
  13446. return ( point.distanceTo( this.center ) - this.radius );
  13447. }
  13448. /**
  13449. * Returns `true` if this sphere intersects with the given one.
  13450. *
  13451. * @param {Sphere} sphere - The sphere to test.
  13452. * @return {boolean} Whether this sphere intersects with the given one or not.
  13453. */
  13454. intersectsSphere( sphere ) {
  13455. const radiusSum = this.radius + sphere.radius;
  13456. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  13457. }
  13458. /**
  13459. * Returns `true` if this sphere intersects with the given box.
  13460. *
  13461. * @param {Box3} box - The box to test.
  13462. * @return {boolean} Whether this sphere intersects with the given box or not.
  13463. */
  13464. intersectsBox( box ) {
  13465. return box.intersectsSphere( this );
  13466. }
  13467. /**
  13468. * Returns `true` if this sphere intersects with the given plane.
  13469. *
  13470. * @param {Plane} plane - The plane to test.
  13471. * @return {boolean} Whether this sphere intersects with the given plane or not.
  13472. */
  13473. intersectsPlane( plane ) {
  13474. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  13475. }
  13476. /**
  13477. * Clamps a point within the sphere. If the point is outside the sphere, it
  13478. * will clamp it to the closest point on the edge of the sphere. Points
  13479. * already inside the sphere will not be affected.
  13480. *
  13481. * @param {Vector3} point - The plane to clamp.
  13482. * @param {Vector3} target - The target vector that is used to store the method's result.
  13483. * @return {Vector3} The clamped point.
  13484. */
  13485. clampPoint( point, target ) {
  13486. const deltaLengthSq = this.center.distanceToSquared( point );
  13487. target.copy( point );
  13488. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  13489. target.sub( this.center ).normalize();
  13490. target.multiplyScalar( this.radius ).add( this.center );
  13491. }
  13492. return target;
  13493. }
  13494. /**
  13495. * Returns a bounding box that encloses this sphere.
  13496. *
  13497. * @param {Box3} target - The target box that is used to store the method's result.
  13498. * @return {Box3} The bounding box that encloses this sphere.
  13499. */
  13500. getBoundingBox( target ) {
  13501. if ( this.isEmpty() ) {
  13502. // Empty sphere produces empty bounding box
  13503. target.makeEmpty();
  13504. return target;
  13505. }
  13506. target.set( this.center, this.center );
  13507. target.expandByScalar( this.radius );
  13508. return target;
  13509. }
  13510. /**
  13511. * Transforms this sphere with the given 4x4 transformation matrix.
  13512. *
  13513. * @param {Matrix4} matrix - The transformation matrix.
  13514. * @return {Sphere} A reference to this sphere.
  13515. */
  13516. applyMatrix4( matrix ) {
  13517. this.center.applyMatrix4( matrix );
  13518. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  13519. return this;
  13520. }
  13521. /**
  13522. * Translates the sphere's center by the given offset.
  13523. *
  13524. * @param {Vector3} offset - The offset.
  13525. * @return {Sphere} A reference to this sphere.
  13526. */
  13527. translate( offset ) {
  13528. this.center.add( offset );
  13529. return this;
  13530. }
  13531. /**
  13532. * Expands the boundaries of this sphere to include the given point.
  13533. *
  13534. * @param {Vector3} point - The point to include.
  13535. * @return {Sphere} A reference to this sphere.
  13536. */
  13537. expandByPoint( point ) {
  13538. if ( this.isEmpty() ) {
  13539. this.center.copy( point );
  13540. this.radius = 0;
  13541. return this;
  13542. }
  13543. _v1$3.subVectors( point, this.center );
  13544. const lengthSq = _v1$3.lengthSq();
  13545. if ( lengthSq > ( this.radius * this.radius ) ) {
  13546. // calculate the minimal sphere
  13547. const length = Math.sqrt( lengthSq );
  13548. const delta = ( length - this.radius ) * 0.5;
  13549. this.center.addScaledVector( _v1$3, delta / length );
  13550. this.radius += delta;
  13551. }
  13552. return this;
  13553. }
  13554. /**
  13555. * Expands this sphere to enclose both the original sphere and the given sphere.
  13556. *
  13557. * @param {Sphere} sphere - The sphere to include.
  13558. * @return {Sphere} A reference to this sphere.
  13559. */
  13560. union( sphere ) {
  13561. if ( sphere.isEmpty() ) {
  13562. return this;
  13563. }
  13564. if ( this.isEmpty() ) {
  13565. this.copy( sphere );
  13566. return this;
  13567. }
  13568. if ( this.center.equals( sphere.center ) === true ) {
  13569. this.radius = Math.max( this.radius, sphere.radius );
  13570. } else {
  13571. _v2$2.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  13572. this.expandByPoint( _v1$3.copy( sphere.center ).add( _v2$2 ) );
  13573. this.expandByPoint( _v1$3.copy( sphere.center ).sub( _v2$2 ) );
  13574. }
  13575. return this;
  13576. }
  13577. /**
  13578. * Returns `true` if this sphere is equal with the given one.
  13579. *
  13580. * @param {Sphere} sphere - The sphere to test for equality.
  13581. * @return {boolean} Whether this bounding sphere is equal with the given one.
  13582. */
  13583. equals( sphere ) {
  13584. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  13585. }
  13586. /**
  13587. * Returns a new sphere with copied values from this instance.
  13588. *
  13589. * @return {Sphere} A clone of this instance.
  13590. */
  13591. clone() {
  13592. return new this.constructor().copy( this );
  13593. }
  13594. /**
  13595. * Returns a serialized structure of the bounding sphere.
  13596. *
  13597. * @return {Object} Serialized structure with fields representing the object state.
  13598. */
  13599. toJSON() {
  13600. return {
  13601. radius: this.radius,
  13602. center: this.center.toArray()
  13603. };
  13604. }
  13605. /**
  13606. * Returns a serialized structure of the bounding sphere.
  13607. *
  13608. * @param {Object} json - The serialized json to set the sphere from.
  13609. * @return {Sphere} A reference to this bounding sphere.
  13610. */
  13611. fromJSON( json ) {
  13612. this.radius = json.radius;
  13613. this.center.fromArray( json.center );
  13614. return this;
  13615. }
  13616. }
  13617. let _id$1 = 0;
  13618. const _m1 = /*@__PURE__*/ new Matrix4();
  13619. const _obj = /*@__PURE__*/ new Object3D();
  13620. const _offset = /*@__PURE__*/ new Vector3();
  13621. const _box$2 = /*@__PURE__*/ new Box3();
  13622. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  13623. const _vector$9 = /*@__PURE__*/ new Vector3();
  13624. /**
  13625. * A representation of mesh, line, or point geometry. Includes vertex
  13626. * positions, face indices, normals, colors, UVs, and custom attributes
  13627. * within buffers, reducing the cost of passing all this data to the GPU.
  13628. *
  13629. * ```js
  13630. * const geometry = new THREE.BufferGeometry();
  13631. * // create a simple square shape. We duplicate the top left and bottom right
  13632. * // vertices because each vertex needs to appear once per triangle.
  13633. * const vertices = new Float32Array( [
  13634. * -1.0, -1.0, 1.0, // v0
  13635. * 1.0, -1.0, 1.0, // v1
  13636. * 1.0, 1.0, 1.0, // v2
  13637. *
  13638. * 1.0, 1.0, 1.0, // v3
  13639. * -1.0, 1.0, 1.0, // v4
  13640. * -1.0, -1.0, 1.0 // v5
  13641. * ] );
  13642. * // itemSize = 3 because there are 3 values (components) per vertex
  13643. * geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  13644. * const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
  13645. * const mesh = new THREE.Mesh( geometry, material );
  13646. * ```
  13647. *
  13648. * @augments EventDispatcher
  13649. */
  13650. class BufferGeometry extends EventDispatcher {
  13651. /**
  13652. * Constructs a new geometry.
  13653. */
  13654. constructor() {
  13655. super();
  13656. /**
  13657. * This flag can be used for type testing.
  13658. *
  13659. * @type {boolean}
  13660. * @readonly
  13661. * @default true
  13662. */
  13663. this.isBufferGeometry = true;
  13664. /**
  13665. * The ID of the geometry.
  13666. *
  13667. * @name BufferGeometry#id
  13668. * @type {number}
  13669. * @readonly
  13670. */
  13671. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  13672. /**
  13673. * The UUID of the geometry.
  13674. *
  13675. * @type {string}
  13676. * @readonly
  13677. */
  13678. this.uuid = generateUUID();
  13679. /**
  13680. * The name of the geometry.
  13681. *
  13682. * @type {string}
  13683. */
  13684. this.name = '';
  13685. this.type = 'BufferGeometry';
  13686. /**
  13687. * Allows for vertices to be re-used across multiple triangles; this is
  13688. * called using "indexed triangles". Each triangle is associated with the
  13689. * indices of three vertices. This attribute therefore stores the index of
  13690. * each vertex for each triangular face. If this attribute is not set, the
  13691. * renderer assumes that each three contiguous positions represent a single triangle.
  13692. *
  13693. * @type {?BufferAttribute}
  13694. * @default null
  13695. */
  13696. this.index = null;
  13697. /**
  13698. * A (storage) buffer attribute which was generated with a compute shader and
  13699. * now defines indirect draw calls.
  13700. *
  13701. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  13702. *
  13703. * @type {?BufferAttribute}
  13704. * @default null
  13705. */
  13706. this.indirect = null;
  13707. /**
  13708. * The offset, in bytes, into the indirect drawing buffer where the value data begins. If an array is provided, multiple indirect draw calls will be made for each offset.
  13709. *
  13710. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  13711. *
  13712. * @type {number|Array<number>}
  13713. * @default 0
  13714. */
  13715. this.indirectOffset = 0;
  13716. /**
  13717. * This dictionary has as id the name of the attribute to be set and as value
  13718. * the buffer attribute to set it to. Rather than accessing this property directly,
  13719. * use `setAttribute()` and `getAttribute()` to access attributes of this geometry.
  13720. *
  13721. * @type {Object<string,(BufferAttribute|InterleavedBufferAttribute)>}
  13722. */
  13723. this.attributes = {};
  13724. /**
  13725. * This dictionary holds the morph targets of the geometry.
  13726. *
  13727. * Note: Once the geometry has been rendered, the morph attribute data cannot
  13728. * be changed. You will have to call `dispose()`, and create a new geometry instance.
  13729. *
  13730. * @type {Object}
  13731. */
  13732. this.morphAttributes = {};
  13733. /**
  13734. * Used to control the morph target behavior; when set to `true`, the morph
  13735. * target data is treated as relative offsets, rather than as absolute
  13736. * positions/normals.
  13737. *
  13738. * @type {boolean}
  13739. * @default false
  13740. */
  13741. this.morphTargetsRelative = false;
  13742. /**
  13743. * Split the geometry into groups, each of which will be rendered in a
  13744. * separate draw call. This allows an array of materials to be used with the geometry.
  13745. *
  13746. * Use `addGroup()` and `clearGroups()` to edit groups, rather than modifying this array directly.
  13747. *
  13748. * Every vertex and index must belong to exactly one group — groups must not share vertices or
  13749. * indices, and must not leave vertices or indices unused.
  13750. *
  13751. * @type {Array<Object>}
  13752. */
  13753. this.groups = [];
  13754. /**
  13755. * Bounding box for the geometry which can be calculated with `computeBoundingBox()`.
  13756. *
  13757. * @type {?Box3}
  13758. * @default null
  13759. */
  13760. this.boundingBox = null;
  13761. /**
  13762. * Bounding sphere for the geometry which can be calculated with `computeBoundingSphere()`.
  13763. *
  13764. * @type {?Sphere}
  13765. * @default null
  13766. */
  13767. this.boundingSphere = null;
  13768. /**
  13769. * Determines the part of the geometry to render. This should not be set directly,
  13770. * instead use `setDrawRange()`.
  13771. *
  13772. * @type {{start:number,count:number}}
  13773. */
  13774. this.drawRange = { start: 0, count: Infinity };
  13775. /**
  13776. * An object that can be used to store custom data about the geometry.
  13777. * It should not hold references to functions as these will not be cloned.
  13778. *
  13779. * @type {Object}
  13780. */
  13781. this.userData = {};
  13782. }
  13783. /**
  13784. * Returns the index of this geometry.
  13785. *
  13786. * @return {?BufferAttribute} The index. Returns `null` if no index is defined.
  13787. */
  13788. getIndex() {
  13789. return this.index;
  13790. }
  13791. /**
  13792. * Sets the given index to this geometry.
  13793. *
  13794. * @param {Array<number>|BufferAttribute} index - The index to set.
  13795. * @return {BufferGeometry} A reference to this instance.
  13796. */
  13797. setIndex( index ) {
  13798. if ( Array.isArray( index ) ) {
  13799. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  13800. } else {
  13801. this.index = index;
  13802. }
  13803. return this;
  13804. }
  13805. /**
  13806. * Sets the given indirect attribute to this geometry.
  13807. *
  13808. * @param {BufferAttribute} indirect - The attribute holding indirect draw calls.
  13809. * @param {number|Array<number>} [indirectOffset=0] - The offset, in bytes, into the indirect drawing buffer where the value data begins. If an array is provided, multiple indirect draw calls will be made for each offset.
  13810. * @return {BufferGeometry} A reference to this instance.
  13811. */
  13812. setIndirect( indirect, indirectOffset = 0 ) {
  13813. this.indirect = indirect;
  13814. this.indirectOffset = indirectOffset;
  13815. return this;
  13816. }
  13817. /**
  13818. * Returns the indirect attribute of this geometry.
  13819. *
  13820. * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined.
  13821. */
  13822. getIndirect() {
  13823. return this.indirect;
  13824. }
  13825. /**
  13826. * Returns the buffer attribute for the given name.
  13827. *
  13828. * @param {string} name - The attribute name.
  13829. * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute.
  13830. * Returns `undefined` if not attribute has been found.
  13831. */
  13832. getAttribute( name ) {
  13833. return this.attributes[ name ];
  13834. }
  13835. /**
  13836. * Sets the given attribute for the given name.
  13837. *
  13838. * @param {string} name - The attribute name.
  13839. * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set.
  13840. * @return {BufferGeometry} A reference to this instance.
  13841. */
  13842. setAttribute( name, attribute ) {
  13843. this.attributes[ name ] = attribute;
  13844. return this;
  13845. }
  13846. /**
  13847. * Deletes the attribute for the given name.
  13848. *
  13849. * @param {string} name - The attribute name to delete.
  13850. * @return {BufferGeometry} A reference to this instance.
  13851. */
  13852. deleteAttribute( name ) {
  13853. delete this.attributes[ name ];
  13854. return this;
  13855. }
  13856. /**
  13857. * Returns `true` if this geometry has an attribute for the given name.
  13858. *
  13859. * @param {string} name - The attribute name.
  13860. * @return {boolean} Whether this geometry has an attribute for the given name or not.
  13861. */
  13862. hasAttribute( name ) {
  13863. return this.attributes[ name ] !== undefined;
  13864. }
  13865. /**
  13866. * Adds a group to this geometry.
  13867. *
  13868. * @param {number} start - The first element in this draw call. That is the first
  13869. * vertex for non-indexed geometry, otherwise the first triangle index.
  13870. * @param {number} count - Specifies how many vertices (or indices) are part of this group.
  13871. * @param {number} [materialIndex=0] - The material array index to use.
  13872. */
  13873. addGroup( start, count, materialIndex = 0 ) {
  13874. this.groups.push( {
  13875. start: start,
  13876. count: count,
  13877. materialIndex: materialIndex
  13878. } );
  13879. }
  13880. /**
  13881. * Clears all groups.
  13882. */
  13883. clearGroups() {
  13884. this.groups = [];
  13885. }
  13886. /**
  13887. * Sets the draw range for this geometry.
  13888. *
  13889. * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index.
  13890. * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render.
  13891. * For indexed BufferGeometry, `count` is the number of indices to render.
  13892. */
  13893. setDrawRange( start, count ) {
  13894. this.drawRange.start = start;
  13895. this.drawRange.count = count;
  13896. }
  13897. /**
  13898. * Applies the given 4x4 transformation matrix to the geometry.
  13899. *
  13900. * @param {Matrix4} matrix - The matrix to apply.
  13901. * @return {BufferGeometry} A reference to this instance.
  13902. */
  13903. applyMatrix4( matrix ) {
  13904. const position = this.attributes.position;
  13905. if ( position !== undefined ) {
  13906. position.applyMatrix4( matrix );
  13907. position.needsUpdate = true;
  13908. }
  13909. const normal = this.attributes.normal;
  13910. if ( normal !== undefined ) {
  13911. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  13912. normal.applyNormalMatrix( normalMatrix );
  13913. normal.needsUpdate = true;
  13914. }
  13915. const tangent = this.attributes.tangent;
  13916. if ( tangent !== undefined ) {
  13917. tangent.transformDirection( matrix );
  13918. tangent.needsUpdate = true;
  13919. }
  13920. if ( this.boundingBox !== null ) {
  13921. this.computeBoundingBox();
  13922. }
  13923. if ( this.boundingSphere !== null ) {
  13924. this.computeBoundingSphere();
  13925. }
  13926. return this;
  13927. }
  13928. /**
  13929. * Applies the rotation represented by the Quaternion to the geometry.
  13930. *
  13931. * @param {Quaternion} q - The Quaternion to apply.
  13932. * @return {BufferGeometry} A reference to this instance.
  13933. */
  13934. applyQuaternion( q ) {
  13935. _m1.makeRotationFromQuaternion( q );
  13936. this.applyMatrix4( _m1 );
  13937. return this;
  13938. }
  13939. /**
  13940. * Rotates the geometry about the X axis. This is typically done as a one time
  13941. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  13942. * real-time mesh rotation.
  13943. *
  13944. * @param {number} angle - The angle in radians.
  13945. * @return {BufferGeometry} A reference to this instance.
  13946. */
  13947. rotateX( angle ) {
  13948. // rotate geometry around world x-axis
  13949. _m1.makeRotationX( angle );
  13950. this.applyMatrix4( _m1 );
  13951. return this;
  13952. }
  13953. /**
  13954. * Rotates the geometry about the Y axis. This is typically done as a one time
  13955. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  13956. * real-time mesh rotation.
  13957. *
  13958. * @param {number} angle - The angle in radians.
  13959. * @return {BufferGeometry} A reference to this instance.
  13960. */
  13961. rotateY( angle ) {
  13962. // rotate geometry around world y-axis
  13963. _m1.makeRotationY( angle );
  13964. this.applyMatrix4( _m1 );
  13965. return this;
  13966. }
  13967. /**
  13968. * Rotates the geometry about the Z axis. This is typically done as a one time
  13969. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  13970. * real-time mesh rotation.
  13971. *
  13972. * @param {number} angle - The angle in radians.
  13973. * @return {BufferGeometry} A reference to this instance.
  13974. */
  13975. rotateZ( angle ) {
  13976. // rotate geometry around world z-axis
  13977. _m1.makeRotationZ( angle );
  13978. this.applyMatrix4( _m1 );
  13979. return this;
  13980. }
  13981. /**
  13982. * Translates the geometry. This is typically done as a one time
  13983. * operation, and not during a loop. Use {@link Object3D#position} for typical
  13984. * real-time mesh rotation.
  13985. *
  13986. * @param {number} x - The x offset.
  13987. * @param {number} y - The y offset.
  13988. * @param {number} z - The z offset.
  13989. * @return {BufferGeometry} A reference to this instance.
  13990. */
  13991. translate( x, y, z ) {
  13992. // translate geometry
  13993. _m1.makeTranslation( x, y, z );
  13994. this.applyMatrix4( _m1 );
  13995. return this;
  13996. }
  13997. /**
  13998. * Scales the geometry. This is typically done as a one time
  13999. * operation, and not during a loop. Use {@link Object3D#scale} for typical
  14000. * real-time mesh rotation.
  14001. *
  14002. * @param {number} x - The x scale.
  14003. * @param {number} y - The y scale.
  14004. * @param {number} z - The z scale.
  14005. * @return {BufferGeometry} A reference to this instance.
  14006. */
  14007. scale( x, y, z ) {
  14008. // scale geometry
  14009. _m1.makeScale( x, y, z );
  14010. this.applyMatrix4( _m1 );
  14011. return this;
  14012. }
  14013. /**
  14014. * Rotates the geometry to face a point in 3D space. This is typically done as a one time
  14015. * operation, and not during a loop. Use {@link Object3D#lookAt} for typical
  14016. * real-time mesh rotation.
  14017. *
  14018. * @param {Vector3} vector - The target point.
  14019. * @return {BufferGeometry} A reference to this instance.
  14020. */
  14021. lookAt( vector ) {
  14022. _obj.lookAt( vector );
  14023. _obj.updateMatrix();
  14024. this.applyMatrix4( _obj.matrix );
  14025. return this;
  14026. }
  14027. /**
  14028. * Center the geometry based on its bounding box.
  14029. *
  14030. * @return {BufferGeometry} A reference to this instance.
  14031. */
  14032. center() {
  14033. this.computeBoundingBox();
  14034. this.boundingBox.getCenter( _offset ).negate();
  14035. this.translate( _offset.x, _offset.y, _offset.z );
  14036. return this;
  14037. }
  14038. /**
  14039. * Defines a geometry by creating a `position` attribute based on the given array of points. The array
  14040. * can hold 2D or 3D vectors. When using two-dimensional data, the `z` coordinate for all vertices is
  14041. * set to `0`.
  14042. *
  14043. * If the method is used with an existing `position` attribute, the vertex data are overwritten with the
  14044. * data from the array. The length of the array must match the vertex count.
  14045. *
  14046. * @param {Array<Vector2>|Array<Vector3>} points - The points.
  14047. * @return {BufferGeometry} A reference to this instance.
  14048. */
  14049. setFromPoints( points ) {
  14050. const positionAttribute = this.getAttribute( 'position' );
  14051. if ( positionAttribute === undefined ) {
  14052. const position = [];
  14053. for ( let i = 0, l = points.length; i < l; i ++ ) {
  14054. const point = points[ i ];
  14055. position.push( point.x, point.y, point.z || 0 );
  14056. }
  14057. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  14058. } else {
  14059. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  14060. for ( let i = 0; i < l; i ++ ) {
  14061. const point = points[ i ];
  14062. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  14063. }
  14064. if ( points.length > positionAttribute.count ) {
  14065. warn( 'BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  14066. }
  14067. positionAttribute.needsUpdate = true;
  14068. }
  14069. return this;
  14070. }
  14071. /**
  14072. * Computes the bounding box of the geometry, and updates the `boundingBox` member.
  14073. * The bounding box is not computed by the engine; it must be computed by your app.
  14074. * You may need to recompute the bounding box if the geometry vertices are modified.
  14075. */
  14076. computeBoundingBox() {
  14077. if ( this.boundingBox === null ) {
  14078. this.boundingBox = new Box3();
  14079. }
  14080. const position = this.attributes.position;
  14081. const morphAttributesPosition = this.morphAttributes.position;
  14082. if ( position && position.isGLBufferAttribute ) {
  14083. error( 'BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  14084. this.boundingBox.set(
  14085. new Vector3( - Infinity, - Infinity, - Infinity ),
  14086. new Vector3( + Infinity, + Infinity, + Infinity )
  14087. );
  14088. return;
  14089. }
  14090. if ( position !== undefined ) {
  14091. this.boundingBox.setFromBufferAttribute( position );
  14092. // process morph attributes if present
  14093. if ( morphAttributesPosition ) {
  14094. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14095. const morphAttribute = morphAttributesPosition[ i ];
  14096. _box$2.setFromBufferAttribute( morphAttribute );
  14097. if ( this.morphTargetsRelative ) {
  14098. _vector$9.addVectors( this.boundingBox.min, _box$2.min );
  14099. this.boundingBox.expandByPoint( _vector$9 );
  14100. _vector$9.addVectors( this.boundingBox.max, _box$2.max );
  14101. this.boundingBox.expandByPoint( _vector$9 );
  14102. } else {
  14103. this.boundingBox.expandByPoint( _box$2.min );
  14104. this.boundingBox.expandByPoint( _box$2.max );
  14105. }
  14106. }
  14107. }
  14108. } else {
  14109. this.boundingBox.makeEmpty();
  14110. }
  14111. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  14112. error( 'BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  14113. }
  14114. }
  14115. /**
  14116. * Computes the bounding sphere of the geometry, and updates the `boundingSphere` member.
  14117. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  14118. * You may need to recompute the bounding sphere if the geometry vertices are modified.
  14119. */
  14120. computeBoundingSphere() {
  14121. if ( this.boundingSphere === null ) {
  14122. this.boundingSphere = new Sphere();
  14123. }
  14124. const position = this.attributes.position;
  14125. const morphAttributesPosition = this.morphAttributes.position;
  14126. if ( position && position.isGLBufferAttribute ) {
  14127. error( 'BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  14128. this.boundingSphere.set( new Vector3(), Infinity );
  14129. return;
  14130. }
  14131. if ( position ) {
  14132. // first, find the center of the bounding sphere
  14133. const center = this.boundingSphere.center;
  14134. _box$2.setFromBufferAttribute( position );
  14135. // process morph attributes if present
  14136. if ( morphAttributesPosition ) {
  14137. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14138. const morphAttribute = morphAttributesPosition[ i ];
  14139. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  14140. if ( this.morphTargetsRelative ) {
  14141. _vector$9.addVectors( _box$2.min, _boxMorphTargets.min );
  14142. _box$2.expandByPoint( _vector$9 );
  14143. _vector$9.addVectors( _box$2.max, _boxMorphTargets.max );
  14144. _box$2.expandByPoint( _vector$9 );
  14145. } else {
  14146. _box$2.expandByPoint( _boxMorphTargets.min );
  14147. _box$2.expandByPoint( _boxMorphTargets.max );
  14148. }
  14149. }
  14150. }
  14151. _box$2.getCenter( center );
  14152. // second, try to find a boundingSphere with a radius smaller than the
  14153. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  14154. let maxRadiusSq = 0;
  14155. for ( let i = 0, il = position.count; i < il; i ++ ) {
  14156. _vector$9.fromBufferAttribute( position, i );
  14157. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$9 ) );
  14158. }
  14159. // process morph attributes if present
  14160. if ( morphAttributesPosition ) {
  14161. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14162. const morphAttribute = morphAttributesPosition[ i ];
  14163. const morphTargetsRelative = this.morphTargetsRelative;
  14164. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  14165. _vector$9.fromBufferAttribute( morphAttribute, j );
  14166. if ( morphTargetsRelative ) {
  14167. _offset.fromBufferAttribute( position, j );
  14168. _vector$9.add( _offset );
  14169. }
  14170. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$9 ) );
  14171. }
  14172. }
  14173. }
  14174. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  14175. if ( isNaN( this.boundingSphere.radius ) ) {
  14176. error( 'BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  14177. }
  14178. }
  14179. }
  14180. /**
  14181. * Calculates and adds a tangent attribute to this geometry.
  14182. *
  14183. * The computation is only supported for indexed geometries and if position, normal, and uv attributes
  14184. * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by
  14185. * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead.
  14186. */
  14187. computeTangents() {
  14188. const index = this.index;
  14189. const attributes = this.attributes;
  14190. // based on http://www.terathon.com/code/tangent.html
  14191. // (per vertex tangents)
  14192. if ( index === null ||
  14193. attributes.position === undefined ||
  14194. attributes.normal === undefined ||
  14195. attributes.uv === undefined ) {
  14196. error( 'BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  14197. return;
  14198. }
  14199. const positionAttribute = attributes.position;
  14200. const normalAttribute = attributes.normal;
  14201. const uvAttribute = attributes.uv;
  14202. if ( this.hasAttribute( 'tangent' ) === false ) {
  14203. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  14204. }
  14205. const tangentAttribute = this.getAttribute( 'tangent' );
  14206. const tan1 = [], tan2 = [];
  14207. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14208. tan1[ i ] = new Vector3();
  14209. tan2[ i ] = new Vector3();
  14210. }
  14211. const vA = new Vector3(),
  14212. vB = new Vector3(),
  14213. vC = new Vector3(),
  14214. uvA = new Vector2(),
  14215. uvB = new Vector2(),
  14216. uvC = new Vector2(),
  14217. sdir = new Vector3(),
  14218. tdir = new Vector3();
  14219. function handleTriangle( a, b, c ) {
  14220. vA.fromBufferAttribute( positionAttribute, a );
  14221. vB.fromBufferAttribute( positionAttribute, b );
  14222. vC.fromBufferAttribute( positionAttribute, c );
  14223. uvA.fromBufferAttribute( uvAttribute, a );
  14224. uvB.fromBufferAttribute( uvAttribute, b );
  14225. uvC.fromBufferAttribute( uvAttribute, c );
  14226. vB.sub( vA );
  14227. vC.sub( vA );
  14228. uvB.sub( uvA );
  14229. uvC.sub( uvA );
  14230. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  14231. // silently ignore degenerate uv triangles having coincident or colinear vertices
  14232. if ( ! isFinite( r ) ) return;
  14233. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  14234. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  14235. tan1[ a ].add( sdir );
  14236. tan1[ b ].add( sdir );
  14237. tan1[ c ].add( sdir );
  14238. tan2[ a ].add( tdir );
  14239. tan2[ b ].add( tdir );
  14240. tan2[ c ].add( tdir );
  14241. }
  14242. let groups = this.groups;
  14243. if ( groups.length === 0 ) {
  14244. groups = [ {
  14245. start: 0,
  14246. count: index.count
  14247. } ];
  14248. }
  14249. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14250. const group = groups[ i ];
  14251. const start = group.start;
  14252. const count = group.count;
  14253. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14254. handleTriangle(
  14255. index.getX( j + 0 ),
  14256. index.getX( j + 1 ),
  14257. index.getX( j + 2 )
  14258. );
  14259. }
  14260. }
  14261. const tmp = new Vector3(), tmp2 = new Vector3();
  14262. const n = new Vector3(), n2 = new Vector3();
  14263. function handleVertex( v ) {
  14264. n.fromBufferAttribute( normalAttribute, v );
  14265. n2.copy( n );
  14266. const t = tan1[ v ];
  14267. // Gram-Schmidt orthogonalize
  14268. tmp.copy( t );
  14269. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  14270. // Calculate handedness
  14271. tmp2.crossVectors( n2, t );
  14272. const test = tmp2.dot( tan2[ v ] );
  14273. const w = ( test < 0.0 ) ? -1 : 1.0;
  14274. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  14275. }
  14276. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14277. const group = groups[ i ];
  14278. const start = group.start;
  14279. const count = group.count;
  14280. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14281. handleVertex( index.getX( j + 0 ) );
  14282. handleVertex( index.getX( j + 1 ) );
  14283. handleVertex( index.getX( j + 2 ) );
  14284. }
  14285. }
  14286. }
  14287. /**
  14288. * Computes vertex normals for the given vertex data. For indexed geometries, the method sets
  14289. * each vertex normal to be the average of the face normals of the faces that share that vertex.
  14290. * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal
  14291. * to be the same as the face normal.
  14292. */
  14293. computeVertexNormals() {
  14294. const index = this.index;
  14295. const positionAttribute = this.getAttribute( 'position' );
  14296. if ( positionAttribute !== undefined ) {
  14297. let normalAttribute = this.getAttribute( 'normal' );
  14298. if ( normalAttribute === undefined ) {
  14299. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  14300. this.setAttribute( 'normal', normalAttribute );
  14301. } else {
  14302. // reset existing normals to zero
  14303. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  14304. normalAttribute.setXYZ( i, 0, 0, 0 );
  14305. }
  14306. }
  14307. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  14308. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  14309. const cb = new Vector3(), ab = new Vector3();
  14310. // indexed elements
  14311. if ( index ) {
  14312. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  14313. const vA = index.getX( i + 0 );
  14314. const vB = index.getX( i + 1 );
  14315. const vC = index.getX( i + 2 );
  14316. pA.fromBufferAttribute( positionAttribute, vA );
  14317. pB.fromBufferAttribute( positionAttribute, vB );
  14318. pC.fromBufferAttribute( positionAttribute, vC );
  14319. cb.subVectors( pC, pB );
  14320. ab.subVectors( pA, pB );
  14321. cb.cross( ab );
  14322. nA.fromBufferAttribute( normalAttribute, vA );
  14323. nB.fromBufferAttribute( normalAttribute, vB );
  14324. nC.fromBufferAttribute( normalAttribute, vC );
  14325. nA.add( cb );
  14326. nB.add( cb );
  14327. nC.add( cb );
  14328. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  14329. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  14330. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  14331. }
  14332. } else {
  14333. // non-indexed elements (unconnected triangle soup)
  14334. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  14335. pA.fromBufferAttribute( positionAttribute, i + 0 );
  14336. pB.fromBufferAttribute( positionAttribute, i + 1 );
  14337. pC.fromBufferAttribute( positionAttribute, i + 2 );
  14338. cb.subVectors( pC, pB );
  14339. ab.subVectors( pA, pB );
  14340. cb.cross( ab );
  14341. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  14342. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  14343. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  14344. }
  14345. }
  14346. this.normalizeNormals();
  14347. normalAttribute.needsUpdate = true;
  14348. }
  14349. }
  14350. /**
  14351. * Ensures every normal vector in a geometry will have a magnitude of `1`. This will
  14352. * correct lighting on the geometry surfaces.
  14353. */
  14354. normalizeNormals() {
  14355. const normals = this.attributes.normal;
  14356. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  14357. _vector$9.fromBufferAttribute( normals, i );
  14358. _vector$9.normalize();
  14359. normals.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  14360. }
  14361. }
  14362. /**
  14363. * Return a new non-index version of this indexed geometry. If the geometry
  14364. * is already non-indexed, the method is a NOOP.
  14365. *
  14366. * @return {BufferGeometry} The non-indexed version of this indexed geometry.
  14367. */
  14368. toNonIndexed() {
  14369. function convertBufferAttribute( attribute, indices ) {
  14370. const array = attribute.array;
  14371. const itemSize = attribute.itemSize;
  14372. const normalized = attribute.normalized;
  14373. const array2 = new array.constructor( indices.length * itemSize );
  14374. let index = 0, index2 = 0;
  14375. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  14376. if ( attribute.isInterleavedBufferAttribute ) {
  14377. index = indices[ i ] * attribute.data.stride + attribute.offset;
  14378. } else {
  14379. index = indices[ i ] * itemSize;
  14380. }
  14381. for ( let j = 0; j < itemSize; j ++ ) {
  14382. array2[ index2 ++ ] = array[ index ++ ];
  14383. }
  14384. }
  14385. return new BufferAttribute( array2, itemSize, normalized );
  14386. }
  14387. //
  14388. if ( this.index === null ) {
  14389. warn( 'BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  14390. return this;
  14391. }
  14392. const geometry2 = new BufferGeometry();
  14393. const indices = this.index.array;
  14394. const attributes = this.attributes;
  14395. // attributes
  14396. for ( const name in attributes ) {
  14397. const attribute = attributes[ name ];
  14398. const newAttribute = convertBufferAttribute( attribute, indices );
  14399. geometry2.setAttribute( name, newAttribute );
  14400. }
  14401. // morph attributes
  14402. const morphAttributes = this.morphAttributes;
  14403. for ( const name in morphAttributes ) {
  14404. const morphArray = [];
  14405. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  14406. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  14407. const attribute = morphAttribute[ i ];
  14408. const newAttribute = convertBufferAttribute( attribute, indices );
  14409. morphArray.push( newAttribute );
  14410. }
  14411. geometry2.morphAttributes[ name ] = morphArray;
  14412. }
  14413. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  14414. // groups
  14415. const groups = this.groups;
  14416. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  14417. const group = groups[ i ];
  14418. geometry2.addGroup( group.start, group.count, group.materialIndex );
  14419. }
  14420. return geometry2;
  14421. }
  14422. /**
  14423. * Serializes the geometry into JSON.
  14424. *
  14425. * @return {Object} A JSON object representing the serialized geometry.
  14426. */
  14427. toJSON() {
  14428. const data = {
  14429. metadata: {
  14430. version: 4.7,
  14431. type: 'BufferGeometry',
  14432. generator: 'BufferGeometry.toJSON'
  14433. }
  14434. };
  14435. // standard BufferGeometry serialization
  14436. data.uuid = this.uuid;
  14437. data.type = this.type;
  14438. if ( this.name !== '' ) data.name = this.name;
  14439. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  14440. if ( this.parameters !== undefined ) {
  14441. const parameters = this.parameters;
  14442. for ( const key in parameters ) {
  14443. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  14444. }
  14445. return data;
  14446. }
  14447. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  14448. data.data = { attributes: {} };
  14449. const index = this.index;
  14450. if ( index !== null ) {
  14451. data.data.index = {
  14452. type: index.array.constructor.name,
  14453. array: Array.prototype.slice.call( index.array )
  14454. };
  14455. }
  14456. const attributes = this.attributes;
  14457. for ( const key in attributes ) {
  14458. const attribute = attributes[ key ];
  14459. data.data.attributes[ key ] = attribute.toJSON( data.data );
  14460. }
  14461. const morphAttributes = {};
  14462. let hasMorphAttributes = false;
  14463. for ( const key in this.morphAttributes ) {
  14464. const attributeArray = this.morphAttributes[ key ];
  14465. const array = [];
  14466. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  14467. const attribute = attributeArray[ i ];
  14468. array.push( attribute.toJSON( data.data ) );
  14469. }
  14470. if ( array.length > 0 ) {
  14471. morphAttributes[ key ] = array;
  14472. hasMorphAttributes = true;
  14473. }
  14474. }
  14475. if ( hasMorphAttributes ) {
  14476. data.data.morphAttributes = morphAttributes;
  14477. data.data.morphTargetsRelative = this.morphTargetsRelative;
  14478. }
  14479. const groups = this.groups;
  14480. if ( groups.length > 0 ) {
  14481. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  14482. }
  14483. const boundingSphere = this.boundingSphere;
  14484. if ( boundingSphere !== null ) {
  14485. data.data.boundingSphere = boundingSphere.toJSON();
  14486. }
  14487. return data;
  14488. }
  14489. /**
  14490. * Returns a new geometry with copied values from this instance.
  14491. *
  14492. * @return {BufferGeometry} A clone of this instance.
  14493. */
  14494. clone() {
  14495. return new this.constructor().copy( this );
  14496. }
  14497. /**
  14498. * Copies the values of the given geometry to this instance.
  14499. *
  14500. * @param {BufferGeometry} source - The geometry to copy.
  14501. * @return {BufferGeometry} A reference to this instance.
  14502. */
  14503. copy( source ) {
  14504. // reset
  14505. this.index = null;
  14506. this.attributes = {};
  14507. this.morphAttributes = {};
  14508. this.groups = [];
  14509. this.boundingBox = null;
  14510. this.boundingSphere = null;
  14511. // used for storing cloned, shared data
  14512. const data = {};
  14513. // name
  14514. this.name = source.name;
  14515. // index
  14516. const index = source.index;
  14517. if ( index !== null ) {
  14518. this.setIndex( index.clone() );
  14519. }
  14520. // attributes
  14521. const attributes = source.attributes;
  14522. for ( const name in attributes ) {
  14523. const attribute = attributes[ name ];
  14524. this.setAttribute( name, attribute.clone( data ) );
  14525. }
  14526. // morph attributes
  14527. const morphAttributes = source.morphAttributes;
  14528. for ( const name in morphAttributes ) {
  14529. const array = [];
  14530. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  14531. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  14532. array.push( morphAttribute[ i ].clone( data ) );
  14533. }
  14534. this.morphAttributes[ name ] = array;
  14535. }
  14536. this.morphTargetsRelative = source.morphTargetsRelative;
  14537. // groups
  14538. const groups = source.groups;
  14539. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  14540. const group = groups[ i ];
  14541. this.addGroup( group.start, group.count, group.materialIndex );
  14542. }
  14543. // bounding box
  14544. const boundingBox = source.boundingBox;
  14545. if ( boundingBox !== null ) {
  14546. this.boundingBox = boundingBox.clone();
  14547. }
  14548. // bounding sphere
  14549. const boundingSphere = source.boundingSphere;
  14550. if ( boundingSphere !== null ) {
  14551. this.boundingSphere = boundingSphere.clone();
  14552. }
  14553. // draw range
  14554. this.drawRange.start = source.drawRange.start;
  14555. this.drawRange.count = source.drawRange.count;
  14556. // user data
  14557. this.userData = source.userData;
  14558. return this;
  14559. }
  14560. /**
  14561. * Frees the GPU-related resources allocated by this instance. Call this
  14562. * method whenever this instance is no longer used in your app.
  14563. *
  14564. * @fires BufferGeometry#dispose
  14565. */
  14566. dispose() {
  14567. this.dispatchEvent( { type: 'dispose' } );
  14568. }
  14569. }
  14570. /**
  14571. * "Interleaved" means that multiple attributes, possibly of different types,
  14572. * (e.g., position, normal, uv, color) are packed into a single array buffer.
  14573. *
  14574. * An introduction into interleaved arrays can be found here: [Interleaved array basics](https://blog.tojicode.com/2011/05/interleaved-array-basics.html)
  14575. */
  14576. class InterleavedBuffer {
  14577. /**
  14578. * Constructs a new interleaved buffer.
  14579. *
  14580. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  14581. * @param {number} stride - The number of typed-array elements per vertex.
  14582. */
  14583. constructor( array, stride ) {
  14584. /**
  14585. * This flag can be used for type testing.
  14586. *
  14587. * @type {boolean}
  14588. * @readonly
  14589. * @default true
  14590. */
  14591. this.isInterleavedBuffer = true;
  14592. /**
  14593. * A typed array with a shared buffer storing attribute data.
  14594. *
  14595. * @type {TypedArray}
  14596. */
  14597. this.array = array;
  14598. /**
  14599. * The number of typed-array elements per vertex.
  14600. *
  14601. * @type {number}
  14602. */
  14603. this.stride = stride;
  14604. /**
  14605. * The total number of elements in the array
  14606. *
  14607. * @type {number}
  14608. * @readonly
  14609. */
  14610. this.count = array !== undefined ? array.length / stride : 0;
  14611. /**
  14612. * Defines the intended usage pattern of the data store for optimization purposes.
  14613. *
  14614. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  14615. * instantiate a new one and set the desired usage before the next render.
  14616. *
  14617. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  14618. * @default StaticDrawUsage
  14619. */
  14620. this.usage = StaticDrawUsage;
  14621. /**
  14622. * This can be used to only update some components of stored vectors (for example, just the
  14623. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  14624. *
  14625. * @type {Array<Object>}
  14626. */
  14627. this.updateRanges = [];
  14628. /**
  14629. * A version number, incremented every time the `needsUpdate` is set to `true`.
  14630. *
  14631. * @type {number}
  14632. */
  14633. this.version = 0;
  14634. /**
  14635. * The UUID of the interleaved buffer.
  14636. *
  14637. * @type {string}
  14638. * @readonly
  14639. */
  14640. this.uuid = generateUUID();
  14641. }
  14642. /**
  14643. * A callback function that is executed after the renderer has transferred the attribute array
  14644. * data to the GPU.
  14645. */
  14646. onUploadCallback() {}
  14647. /**
  14648. * Flag to indicate that this attribute has changed and should be re-sent to
  14649. * the GPU. Set this to `true` when you modify the value of the array.
  14650. *
  14651. * @type {number}
  14652. * @default false
  14653. * @param {boolean} value
  14654. */
  14655. set needsUpdate( value ) {
  14656. if ( value === true ) this.version ++;
  14657. }
  14658. /**
  14659. * Sets the usage of this interleaved buffer.
  14660. *
  14661. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  14662. * @return {InterleavedBuffer} A reference to this interleaved buffer.
  14663. */
  14664. setUsage( value ) {
  14665. this.usage = value;
  14666. return this;
  14667. }
  14668. /**
  14669. * Adds a range of data in the data array to be updated on the GPU.
  14670. *
  14671. * @param {number} start - Position at which to start update.
  14672. * @param {number} count - The number of components to update.
  14673. */
  14674. addUpdateRange( start, count ) {
  14675. this.updateRanges.push( { start, count } );
  14676. }
  14677. /**
  14678. * Clears the update ranges.
  14679. */
  14680. clearUpdateRanges() {
  14681. this.updateRanges.length = 0;
  14682. }
  14683. /**
  14684. * Copies the values of the given interleaved buffer to this instance.
  14685. *
  14686. * @param {InterleavedBuffer} source - The interleaved buffer to copy.
  14687. * @return {InterleavedBuffer} A reference to this instance.
  14688. */
  14689. copy( source ) {
  14690. this.array = new source.array.constructor( source.array );
  14691. this.count = source.count;
  14692. this.stride = source.stride;
  14693. this.usage = source.usage;
  14694. return this;
  14695. }
  14696. /**
  14697. * Copies a vector from the given interleaved buffer to this one. The start
  14698. * and destination position in the attribute buffers are represented by the
  14699. * given indices.
  14700. *
  14701. * @param {number} index1 - The destination index into this interleaved buffer.
  14702. * @param {InterleavedBuffer} interleavedBuffer - The interleaved buffer to copy from.
  14703. * @param {number} index2 - The source index into the given interleaved buffer.
  14704. * @return {InterleavedBuffer} A reference to this instance.
  14705. */
  14706. copyAt( index1, interleavedBuffer, index2 ) {
  14707. index1 *= this.stride;
  14708. index2 *= interleavedBuffer.stride;
  14709. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  14710. this.array[ index1 + i ] = interleavedBuffer.array[ index2 + i ];
  14711. }
  14712. return this;
  14713. }
  14714. /**
  14715. * Sets the given array data in the interleaved buffer.
  14716. *
  14717. * @param {(TypedArray|Array)} value - The array data to set.
  14718. * @param {number} [offset=0] - The offset in this interleaved buffer's array.
  14719. * @return {InterleavedBuffer} A reference to this instance.
  14720. */
  14721. set( value, offset = 0 ) {
  14722. this.array.set( value, offset );
  14723. return this;
  14724. }
  14725. /**
  14726. * Returns a new interleaved buffer with copied values from this instance.
  14727. *
  14728. * @param {Object} [data] - An object with shared array buffers that allows to retain shared structures.
  14729. * @return {InterleavedBuffer} A clone of this instance.
  14730. */
  14731. clone( data ) {
  14732. if ( data.arrayBuffers === undefined ) {
  14733. data.arrayBuffers = {};
  14734. }
  14735. if ( this.array.buffer._uuid === undefined ) {
  14736. this.array.buffer._uuid = generateUUID();
  14737. }
  14738. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  14739. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  14740. }
  14741. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  14742. const ib = new this.constructor( array, this.stride );
  14743. ib.setUsage( this.usage );
  14744. return ib;
  14745. }
  14746. /**
  14747. * Sets the given callback function that is executed after the Renderer has transferred
  14748. * the array data to the GPU. Can be used to perform clean-up operations after
  14749. * the upload when data are not needed anymore on the CPU side.
  14750. *
  14751. * @param {Function} callback - The `onUpload()` callback.
  14752. * @return {InterleavedBuffer} A reference to this instance.
  14753. */
  14754. onUpload( callback ) {
  14755. this.onUploadCallback = callback;
  14756. return this;
  14757. }
  14758. /**
  14759. * Serializes the interleaved buffer into JSON.
  14760. *
  14761. * @param {Object} [data] - An optional value holding meta information about the serialization.
  14762. * @return {Object} A JSON object representing the serialized interleaved buffer.
  14763. */
  14764. toJSON( data ) {
  14765. if ( data.arrayBuffers === undefined ) {
  14766. data.arrayBuffers = {};
  14767. }
  14768. // generate UUID for array buffer if necessary
  14769. if ( this.array.buffer._uuid === undefined ) {
  14770. this.array.buffer._uuid = generateUUID();
  14771. }
  14772. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  14773. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  14774. }
  14775. //
  14776. return {
  14777. uuid: this.uuid,
  14778. buffer: this.array.buffer._uuid,
  14779. type: this.array.constructor.name,
  14780. stride: this.stride
  14781. };
  14782. }
  14783. }
  14784. const _vector$8 = /*@__PURE__*/ new Vector3();
  14785. /**
  14786. * An alternative version of a buffer attribute with interleaved data. Interleaved
  14787. * attributes share a common interleaved data storage ({@link InterleavedBuffer}) and refer with
  14788. * different offsets into the buffer.
  14789. */
  14790. class InterleavedBufferAttribute {
  14791. /**
  14792. * Constructs a new interleaved buffer attribute.
  14793. *
  14794. * @param {InterleavedBuffer} interleavedBuffer - The buffer holding the interleaved data.
  14795. * @param {number} itemSize - The item size.
  14796. * @param {number} offset - The attribute offset into the buffer.
  14797. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14798. */
  14799. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  14800. /**
  14801. * This flag can be used for type testing.
  14802. *
  14803. * @type {boolean}
  14804. * @readonly
  14805. * @default true
  14806. */
  14807. this.isInterleavedBufferAttribute = true;
  14808. /**
  14809. * The name of the buffer attribute.
  14810. *
  14811. * @type {string}
  14812. */
  14813. this.name = '';
  14814. /**
  14815. * The buffer holding the interleaved data.
  14816. *
  14817. * @type {InterleavedBuffer}
  14818. */
  14819. this.data = interleavedBuffer;
  14820. /**
  14821. * The item size, see {@link BufferAttribute#itemSize}.
  14822. *
  14823. * @type {number}
  14824. */
  14825. this.itemSize = itemSize;
  14826. /**
  14827. * The attribute offset into the buffer.
  14828. *
  14829. * @type {number}
  14830. */
  14831. this.offset = offset;
  14832. /**
  14833. * Whether the data are normalized or not, see {@link BufferAttribute#normalized}
  14834. *
  14835. * @type {InterleavedBuffer}
  14836. */
  14837. this.normalized = normalized;
  14838. }
  14839. /**
  14840. * The item count of this buffer attribute.
  14841. *
  14842. * @type {number}
  14843. * @readonly
  14844. */
  14845. get count() {
  14846. return this.data.count;
  14847. }
  14848. /**
  14849. * The array holding the interleaved buffer attribute data.
  14850. *
  14851. * @type {TypedArray}
  14852. */
  14853. get array() {
  14854. return this.data.array;
  14855. }
  14856. /**
  14857. * Flag to indicate that this attribute has changed and should be re-sent to
  14858. * the GPU. Set this to `true` when you modify the value of the array.
  14859. *
  14860. * @type {number}
  14861. * @default false
  14862. * @param {boolean} value
  14863. */
  14864. set needsUpdate( value ) {
  14865. this.data.needsUpdate = value;
  14866. }
  14867. /**
  14868. * Applies the given 4x4 matrix to the given attribute. Only works with
  14869. * item size `3`.
  14870. *
  14871. * @param {Matrix4} m - The matrix to apply.
  14872. * @return {InterleavedBufferAttribute} A reference to this instance.
  14873. */
  14874. applyMatrix4( m ) {
  14875. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  14876. _vector$8.fromBufferAttribute( this, i );
  14877. _vector$8.applyMatrix4( m );
  14878. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14879. }
  14880. return this;
  14881. }
  14882. /**
  14883. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  14884. * item size `3`.
  14885. *
  14886. * @param {Matrix3} m - The normal matrix to apply.
  14887. * @return {InterleavedBufferAttribute} A reference to this instance.
  14888. */
  14889. applyNormalMatrix( m ) {
  14890. for ( let i = 0, l = this.count; i < l; i ++ ) {
  14891. _vector$8.fromBufferAttribute( this, i );
  14892. _vector$8.applyNormalMatrix( m );
  14893. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14894. }
  14895. return this;
  14896. }
  14897. /**
  14898. * Applies the given 4x4 matrix to the given attribute. Only works with
  14899. * item size `3` and with direction vectors.
  14900. *
  14901. * @param {Matrix4} m - The matrix to apply.
  14902. * @return {InterleavedBufferAttribute} A reference to this instance.
  14903. */
  14904. transformDirection( m ) {
  14905. for ( let i = 0, l = this.count; i < l; i ++ ) {
  14906. _vector$8.fromBufferAttribute( this, i );
  14907. _vector$8.transformDirection( m );
  14908. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14909. }
  14910. return this;
  14911. }
  14912. /**
  14913. * Returns the given component of the vector at the given index.
  14914. *
  14915. * @param {number} index - The index into the buffer attribute.
  14916. * @param {number} component - The component index.
  14917. * @return {number} The returned value.
  14918. */
  14919. getComponent( index, component ) {
  14920. let value = this.array[ index * this.data.stride + this.offset + component ];
  14921. if ( this.normalized ) value = denormalize( value, this.array );
  14922. return value;
  14923. }
  14924. /**
  14925. * Sets the given value to the given component of the vector at the given index.
  14926. *
  14927. * @param {number} index - The index into the buffer attribute.
  14928. * @param {number} component - The component index.
  14929. * @param {number} value - The value to set.
  14930. * @return {InterleavedBufferAttribute} A reference to this instance.
  14931. */
  14932. setComponent( index, component, value ) {
  14933. if ( this.normalized ) value = normalize( value, this.array );
  14934. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  14935. return this;
  14936. }
  14937. /**
  14938. * Sets the x component of the vector at the given index.
  14939. *
  14940. * @param {number} index - The index into the buffer attribute.
  14941. * @param {number} x - The value to set.
  14942. * @return {InterleavedBufferAttribute} A reference to this instance.
  14943. */
  14944. setX( index, x ) {
  14945. if ( this.normalized ) x = normalize( x, this.array );
  14946. this.data.array[ index * this.data.stride + this.offset ] = x;
  14947. return this;
  14948. }
  14949. /**
  14950. * Sets the y component of the vector at the given index.
  14951. *
  14952. * @param {number} index - The index into the buffer attribute.
  14953. * @param {number} y - The value to set.
  14954. * @return {InterleavedBufferAttribute} A reference to this instance.
  14955. */
  14956. setY( index, y ) {
  14957. if ( this.normalized ) y = normalize( y, this.array );
  14958. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  14959. return this;
  14960. }
  14961. /**
  14962. * Sets the z component of the vector at the given index.
  14963. *
  14964. * @param {number} index - The index into the buffer attribute.
  14965. * @param {number} z - The value to set.
  14966. * @return {InterleavedBufferAttribute} A reference to this instance.
  14967. */
  14968. setZ( index, z ) {
  14969. if ( this.normalized ) z = normalize( z, this.array );
  14970. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  14971. return this;
  14972. }
  14973. /**
  14974. * Sets the w component of the vector at the given index.
  14975. *
  14976. * @param {number} index - The index into the buffer attribute.
  14977. * @param {number} w - The value to set.
  14978. * @return {InterleavedBufferAttribute} A reference to this instance.
  14979. */
  14980. setW( index, w ) {
  14981. if ( this.normalized ) w = normalize( w, this.array );
  14982. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  14983. return this;
  14984. }
  14985. /**
  14986. * Returns the x component of the vector at the given index.
  14987. *
  14988. * @param {number} index - The index into the buffer attribute.
  14989. * @return {number} The x component.
  14990. */
  14991. getX( index ) {
  14992. let x = this.data.array[ index * this.data.stride + this.offset ];
  14993. if ( this.normalized ) x = denormalize( x, this.array );
  14994. return x;
  14995. }
  14996. /**
  14997. * Returns the y component of the vector at the given index.
  14998. *
  14999. * @param {number} index - The index into the buffer attribute.
  15000. * @return {number} The y component.
  15001. */
  15002. getY( index ) {
  15003. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  15004. if ( this.normalized ) y = denormalize( y, this.array );
  15005. return y;
  15006. }
  15007. /**
  15008. * Returns the z component of the vector at the given index.
  15009. *
  15010. * @param {number} index - The index into the buffer attribute.
  15011. * @return {number} The z component.
  15012. */
  15013. getZ( index ) {
  15014. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  15015. if ( this.normalized ) z = denormalize( z, this.array );
  15016. return z;
  15017. }
  15018. /**
  15019. * Returns the w component of the vector at the given index.
  15020. *
  15021. * @param {number} index - The index into the buffer attribute.
  15022. * @return {number} The w component.
  15023. */
  15024. getW( index ) {
  15025. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  15026. if ( this.normalized ) w = denormalize( w, this.array );
  15027. return w;
  15028. }
  15029. /**
  15030. * Sets the x and y component of the vector at the given index.
  15031. *
  15032. * @param {number} index - The index into the buffer attribute.
  15033. * @param {number} x - The value for the x component to set.
  15034. * @param {number} y - The value for the y component to set.
  15035. * @return {InterleavedBufferAttribute} A reference to this instance.
  15036. */
  15037. setXY( index, x, y ) {
  15038. index = index * this.data.stride + this.offset;
  15039. if ( this.normalized ) {
  15040. x = normalize( x, this.array );
  15041. y = normalize( y, this.array );
  15042. }
  15043. this.data.array[ index + 0 ] = x;
  15044. this.data.array[ index + 1 ] = y;
  15045. return this;
  15046. }
  15047. /**
  15048. * Sets the x, y and z component of the vector at the given index.
  15049. *
  15050. * @param {number} index - The index into the buffer attribute.
  15051. * @param {number} x - The value for the x component to set.
  15052. * @param {number} y - The value for the y component to set.
  15053. * @param {number} z - The value for the z component to set.
  15054. * @return {InterleavedBufferAttribute} A reference to this instance.
  15055. */
  15056. setXYZ( index, x, y, z ) {
  15057. index = index * this.data.stride + this.offset;
  15058. if ( this.normalized ) {
  15059. x = normalize( x, this.array );
  15060. y = normalize( y, this.array );
  15061. z = normalize( z, this.array );
  15062. }
  15063. this.data.array[ index + 0 ] = x;
  15064. this.data.array[ index + 1 ] = y;
  15065. this.data.array[ index + 2 ] = z;
  15066. return this;
  15067. }
  15068. /**
  15069. * Sets the x, y, z and w component of the vector at the given index.
  15070. *
  15071. * @param {number} index - The index into the buffer attribute.
  15072. * @param {number} x - The value for the x component to set.
  15073. * @param {number} y - The value for the y component to set.
  15074. * @param {number} z - The value for the z component to set.
  15075. * @param {number} w - The value for the w component to set.
  15076. * @return {InterleavedBufferAttribute} A reference to this instance.
  15077. */
  15078. setXYZW( index, x, y, z, w ) {
  15079. index = index * this.data.stride + this.offset;
  15080. if ( this.normalized ) {
  15081. x = normalize( x, this.array );
  15082. y = normalize( y, this.array );
  15083. z = normalize( z, this.array );
  15084. w = normalize( w, this.array );
  15085. }
  15086. this.data.array[ index + 0 ] = x;
  15087. this.data.array[ index + 1 ] = y;
  15088. this.data.array[ index + 2 ] = z;
  15089. this.data.array[ index + 3 ] = w;
  15090. return this;
  15091. }
  15092. /**
  15093. * Returns a new buffer attribute with copied values from this instance.
  15094. *
  15095. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  15096. *
  15097. * @param {Object} [data] - An object with interleaved buffers that allows to retain the interleaved property.
  15098. * @return {BufferAttribute|InterleavedBufferAttribute} A clone of this instance.
  15099. */
  15100. clone( data ) {
  15101. if ( data === undefined ) {
  15102. log( 'InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  15103. const array = [];
  15104. for ( let i = 0; i < this.count; i ++ ) {
  15105. const index = i * this.data.stride + this.offset;
  15106. for ( let j = 0; j < this.itemSize; j ++ ) {
  15107. array.push( this.data.array[ index + j ] );
  15108. }
  15109. }
  15110. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  15111. } else {
  15112. if ( data.interleavedBuffers === undefined ) {
  15113. data.interleavedBuffers = {};
  15114. }
  15115. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  15116. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  15117. }
  15118. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  15119. }
  15120. }
  15121. /**
  15122. * Serializes the buffer attribute into JSON.
  15123. *
  15124. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  15125. *
  15126. * @param {Object} [data] - An optional value holding meta information about the serialization.
  15127. * @return {Object} A JSON object representing the serialized buffer attribute.
  15128. */
  15129. toJSON( data ) {
  15130. if ( data === undefined ) {
  15131. log( 'InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  15132. const array = [];
  15133. for ( let i = 0; i < this.count; i ++ ) {
  15134. const index = i * this.data.stride + this.offset;
  15135. for ( let j = 0; j < this.itemSize; j ++ ) {
  15136. array.push( this.data.array[ index + j ] );
  15137. }
  15138. }
  15139. // de-interleave data and save it as an ordinary buffer attribute for now
  15140. return {
  15141. itemSize: this.itemSize,
  15142. type: this.array.constructor.name,
  15143. array: array,
  15144. normalized: this.normalized
  15145. };
  15146. } else {
  15147. // save as true interleaved attribute
  15148. if ( data.interleavedBuffers === undefined ) {
  15149. data.interleavedBuffers = {};
  15150. }
  15151. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  15152. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  15153. }
  15154. return {
  15155. isInterleavedBufferAttribute: true,
  15156. itemSize: this.itemSize,
  15157. data: this.data.uuid,
  15158. offset: this.offset,
  15159. normalized: this.normalized
  15160. };
  15161. }
  15162. }
  15163. }
  15164. let _materialId = 0;
  15165. /**
  15166. * Abstract base class for materials.
  15167. *
  15168. * Materials define the appearance of renderable 3D objects.
  15169. *
  15170. * @abstract
  15171. * @augments EventDispatcher
  15172. */
  15173. class Material extends EventDispatcher {
  15174. /**
  15175. * Constructs a new material.
  15176. */
  15177. constructor() {
  15178. super();
  15179. /**
  15180. * This flag can be used for type testing.
  15181. *
  15182. * @type {boolean}
  15183. * @readonly
  15184. * @default true
  15185. */
  15186. this.isMaterial = true;
  15187. /**
  15188. * The ID of the material.
  15189. *
  15190. * @name Material#id
  15191. * @type {number}
  15192. * @readonly
  15193. */
  15194. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  15195. /**
  15196. * The UUID of the material.
  15197. *
  15198. * @type {string}
  15199. * @readonly
  15200. */
  15201. this.uuid = generateUUID();
  15202. /**
  15203. * The name of the material.
  15204. *
  15205. * @type {string}
  15206. */
  15207. this.name = '';
  15208. /**
  15209. * The type property is used for detecting the object type
  15210. * in context of serialization/deserialization.
  15211. *
  15212. * @type {string}
  15213. * @readonly
  15214. */
  15215. this.type = 'Material';
  15216. /**
  15217. * Defines the blending type of the material.
  15218. *
  15219. * It must be set to `CustomBlending` if custom blending properties like
  15220. * {@link Material#blendSrc}, {@link Material#blendDst} or {@link Material#blendEquation}
  15221. * should have any effect.
  15222. *
  15223. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending)}
  15224. * @default NormalBlending
  15225. */
  15226. this.blending = NormalBlending;
  15227. /**
  15228. * Defines which side of faces will be rendered - front, back or both.
  15229. *
  15230. * @type {(FrontSide|BackSide|DoubleSide)}
  15231. * @default FrontSide
  15232. */
  15233. this.side = FrontSide;
  15234. /**
  15235. * If set to `true`, vertex colors should be used.
  15236. *
  15237. * The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or
  15238. * four (RGBA) component color buffer attribute is used.
  15239. *
  15240. * @type {boolean}
  15241. * @default false
  15242. */
  15243. this.vertexColors = false;
  15244. /**
  15245. * Defines how transparent the material is.
  15246. * A value of `0.0` indicates fully transparent, `1.0` is fully opaque.
  15247. *
  15248. * If the {@link Material#transparent} is not set to `true`,
  15249. * the material will remain fully opaque and this value will only affect its color.
  15250. *
  15251. * @type {number}
  15252. * @default 1
  15253. */
  15254. this.opacity = 1;
  15255. /**
  15256. * Defines whether this material is transparent. This has an effect on
  15257. * rendering as transparent objects need special treatment and are rendered
  15258. * after non-transparent objects.
  15259. *
  15260. * When set to true, the extent to which the material is transparent is
  15261. * controlled by {@link Material#opacity}.
  15262. *
  15263. * @type {boolean}
  15264. * @default false
  15265. */
  15266. this.transparent = false;
  15267. /**
  15268. * Enables alpha hashed transparency, an alternative to {@link Material#transparent} or
  15269. * {@link Material#alphaTest}. The material will not be rendered if opacity is lower than
  15270. * a random threshold. Randomization introduces some grain or noise, but approximates alpha
  15271. * blending without the associated problems of sorting. Using TAA can reduce the resulting noise.
  15272. *
  15273. * @type {boolean}
  15274. * @default false
  15275. */
  15276. this.alphaHash = false;
  15277. /**
  15278. * Defines the blending source factor.
  15279. *
  15280. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  15281. * @default SrcAlphaFactor
  15282. */
  15283. this.blendSrc = SrcAlphaFactor;
  15284. /**
  15285. * Defines the blending destination factor.
  15286. *
  15287. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  15288. * @default OneMinusSrcAlphaFactor
  15289. */
  15290. this.blendDst = OneMinusSrcAlphaFactor;
  15291. /**
  15292. * Defines the blending equation.
  15293. *
  15294. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  15295. * @default AddEquation
  15296. */
  15297. this.blendEquation = AddEquation;
  15298. /**
  15299. * Defines the blending source alpha factor.
  15300. *
  15301. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  15302. * @default null
  15303. */
  15304. this.blendSrcAlpha = null;
  15305. /**
  15306. * Defines the blending destination alpha factor.
  15307. *
  15308. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  15309. * @default null
  15310. */
  15311. this.blendDstAlpha = null;
  15312. /**
  15313. * Defines the blending equation of the alpha channel.
  15314. *
  15315. * @type {?(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  15316. * @default null
  15317. */
  15318. this.blendEquationAlpha = null;
  15319. /**
  15320. * Represents the RGB values of the constant blend color.
  15321. *
  15322. * This property has only an effect when using custom blending with `ConstantColor` or `OneMinusConstantColor`.
  15323. *
  15324. * @type {Color}
  15325. * @default (0,0,0)
  15326. */
  15327. this.blendColor = new Color( 0, 0, 0 );
  15328. /**
  15329. * Represents the alpha value of the constant blend color.
  15330. *
  15331. * This property has only an effect when using custom blending with `ConstantAlpha` or `OneMinusConstantAlpha`.
  15332. *
  15333. * @type {number}
  15334. * @default 0
  15335. */
  15336. this.blendAlpha = 0;
  15337. /**
  15338. * Defines the depth function.
  15339. *
  15340. * @type {(NeverDepth|AlwaysDepth|LessDepth|LessEqualDepth|EqualDepth|GreaterEqualDepth|GreaterDepth|NotEqualDepth)}
  15341. * @default LessEqualDepth
  15342. */
  15343. this.depthFunc = LessEqualDepth;
  15344. /**
  15345. * Whether to have depth test enabled when rendering this material.
  15346. * When the depth test is disabled, the depth write will also be implicitly disabled.
  15347. *
  15348. * @type {boolean}
  15349. * @default true
  15350. */
  15351. this.depthTest = true;
  15352. /**
  15353. * Whether rendering this material has any effect on the depth buffer.
  15354. *
  15355. * When drawing 2D overlays it can be useful to disable the depth writing in
  15356. * order to layer several things together without creating z-index artifacts.
  15357. *
  15358. * @type {boolean}
  15359. * @default true
  15360. */
  15361. this.depthWrite = true;
  15362. /**
  15363. * The bit mask to use when writing to the stencil buffer.
  15364. *
  15365. * @type {number}
  15366. * @default 0xff
  15367. */
  15368. this.stencilWriteMask = 0xff;
  15369. /**
  15370. * The stencil comparison function to use.
  15371. *
  15372. * @type {NeverStencilFunc|LessStencilFunc|EqualStencilFunc|LessEqualStencilFunc|GreaterStencilFunc|NotEqualStencilFunc|GreaterEqualStencilFunc|AlwaysStencilFunc}
  15373. * @default AlwaysStencilFunc
  15374. */
  15375. this.stencilFunc = AlwaysStencilFunc;
  15376. /**
  15377. * The value to use when performing stencil comparisons or stencil operations.
  15378. *
  15379. * @type {number}
  15380. * @default 0
  15381. */
  15382. this.stencilRef = 0;
  15383. /**
  15384. * The bit mask to use when comparing against the stencil buffer.
  15385. *
  15386. * @type {number}
  15387. * @default 0xff
  15388. */
  15389. this.stencilFuncMask = 0xff;
  15390. /**
  15391. * Which stencil operation to perform when the comparison function returns `false`.
  15392. *
  15393. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  15394. * @default KeepStencilOp
  15395. */
  15396. this.stencilFail = KeepStencilOp;
  15397. /**
  15398. * Which stencil operation to perform when the comparison function returns
  15399. * `true` but the depth test fails.
  15400. *
  15401. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  15402. * @default KeepStencilOp
  15403. */
  15404. this.stencilZFail = KeepStencilOp;
  15405. /**
  15406. * Which stencil operation to perform when the comparison function returns
  15407. * `true` and the depth test passes.
  15408. *
  15409. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  15410. * @default KeepStencilOp
  15411. */
  15412. this.stencilZPass = KeepStencilOp;
  15413. /**
  15414. * Whether stencil operations are performed against the stencil buffer. In
  15415. * order to perform writes or comparisons against the stencil buffer this
  15416. * value must be `true`.
  15417. *
  15418. * @type {boolean}
  15419. * @default false
  15420. */
  15421. this.stencilWrite = false;
  15422. /**
  15423. * User-defined clipping planes specified as THREE.Plane objects in world
  15424. * space. These planes apply to the objects this material is attached to.
  15425. * Points in space whose signed distance to the plane is negative are clipped
  15426. * (not rendered). This requires {@link WebGLRenderer#localClippingEnabled} to
  15427. * be `true`.
  15428. *
  15429. * @type {?Array<Plane>}
  15430. * @default null
  15431. */
  15432. this.clippingPlanes = null;
  15433. /**
  15434. * Changes the behavior of clipping planes so that only their intersection is
  15435. * clipped, rather than their union.
  15436. *
  15437. * @type {boolean}
  15438. * @default false
  15439. */
  15440. this.clipIntersection = false;
  15441. /**
  15442. * Defines whether to clip shadows according to the clipping planes specified
  15443. * on this material.
  15444. *
  15445. * @type {boolean}
  15446. * @default false
  15447. */
  15448. this.clipShadows = false;
  15449. /**
  15450. * Defines which side of faces cast shadows. If `null`, the side casting shadows
  15451. * is determined as follows:
  15452. *
  15453. * - When {@link Material#side} is set to `FrontSide`, the back side cast shadows.
  15454. * - When {@link Material#side} is set to `BackSide`, the front side cast shadows.
  15455. * - When {@link Material#side} is set to `DoubleSide`, both sides cast shadows.
  15456. *
  15457. * @type {?(FrontSide|BackSide|DoubleSide)}
  15458. * @default null
  15459. */
  15460. this.shadowSide = null;
  15461. /**
  15462. * Whether to render the material's color.
  15463. *
  15464. * This can be used in conjunction with {@link Object3D#renderOder} to create invisible
  15465. * objects that occlude other objects.
  15466. *
  15467. * @type {boolean}
  15468. * @default true
  15469. */
  15470. this.colorWrite = true;
  15471. /**
  15472. * Override the renderer's default precision for this material.
  15473. *
  15474. * @type {?('highp'|'mediump'|'lowp')}
  15475. * @default null
  15476. */
  15477. this.precision = null;
  15478. /**
  15479. * Whether to use polygon offset or not. When enabled, each fragment's depth value will
  15480. * be offset after it is interpolated from the depth values of the appropriate vertices.
  15481. * The offset is added before the depth test is performed and before the value is written
  15482. * into the depth buffer.
  15483. *
  15484. * Can be useful for rendering hidden-line images, for applying decals to surfaces, and for
  15485. * rendering solids with highlighted edges.
  15486. *
  15487. * @type {boolean}
  15488. * @default false
  15489. */
  15490. this.polygonOffset = false;
  15491. /**
  15492. * Specifies a scale factor that is used to create a variable depth offset for each polygon.
  15493. *
  15494. * @type {number}
  15495. * @default 0
  15496. */
  15497. this.polygonOffsetFactor = 0;
  15498. /**
  15499. * Is multiplied by an implementation-specific value to create a constant depth offset.
  15500. *
  15501. * @type {number}
  15502. * @default 0
  15503. */
  15504. this.polygonOffsetUnits = 0;
  15505. /**
  15506. * Whether to apply dithering to the color to remove the appearance of banding.
  15507. *
  15508. * @type {boolean}
  15509. * @default false
  15510. */
  15511. this.dithering = false;
  15512. /**
  15513. * Whether alpha to coverage should be enabled or not. Can only be used with MSAA-enabled contexts
  15514. * (meaning when the renderer was created with *antialias* parameter set to `true`). Enabling this
  15515. * will smooth aliasing on clip plane edges and alphaTest-clipped edges.
  15516. *
  15517. * @type {boolean}
  15518. * @default false
  15519. */
  15520. this.alphaToCoverage = false;
  15521. /**
  15522. * Whether to premultiply the alpha (transparency) value.
  15523. *
  15524. * @type {boolean}
  15525. * @default false
  15526. */
  15527. this.premultipliedAlpha = false;
  15528. /**
  15529. * Whether double-sided, transparent objects should be rendered with a single pass or not.
  15530. *
  15531. * The engine renders double-sided, transparent objects with two draw calls (back faces first,
  15532. * then front faces) to mitigate transparency artifacts. There are scenarios however where this
  15533. * approach produces no quality gains but still doubles draw calls e.g. when rendering flat
  15534. * vegetation like grass sprites. In these cases, set the `forceSinglePass` flag to `true` to
  15535. * disable the two pass rendering to avoid performance issues.
  15536. *
  15537. * @type {boolean}
  15538. * @default false
  15539. */
  15540. this.forceSinglePass = false;
  15541. /**
  15542. * Whether it's possible to override the material with {@link Scene#overrideMaterial} or not.
  15543. *
  15544. * @type {boolean}
  15545. * @default true
  15546. */
  15547. this.allowOverride = true;
  15548. /**
  15549. * Defines whether 3D objects using this material are visible.
  15550. *
  15551. * @type {boolean}
  15552. * @default true
  15553. */
  15554. this.visible = true;
  15555. /**
  15556. * Defines whether this material is tone mapped according to the renderer's tone mapping setting.
  15557. *
  15558. * It is ignored when rendering to a render target or using post processing or when using
  15559. * `WebGPURenderer`. In all these cases, all materials are honored by tone mapping.
  15560. *
  15561. * @type {boolean}
  15562. * @default true
  15563. */
  15564. this.toneMapped = true;
  15565. /**
  15566. * An object that can be used to store custom data about the Material. It
  15567. * should not hold references to functions as these will not be cloned.
  15568. *
  15569. * @type {Object}
  15570. */
  15571. this.userData = {};
  15572. /**
  15573. * This starts at `0` and counts how many times {@link Material#needsUpdate} is set to `true`.
  15574. *
  15575. * @type {number}
  15576. * @readonly
  15577. * @default 0
  15578. */
  15579. this.version = 0;
  15580. this._alphaTest = 0;
  15581. }
  15582. /**
  15583. * Sets the alpha value to be used when running an alpha test. The material
  15584. * will not be rendered if the opacity is lower than this value.
  15585. *
  15586. * @type {number}
  15587. * @readonly
  15588. * @default 0
  15589. */
  15590. get alphaTest() {
  15591. return this._alphaTest;
  15592. }
  15593. set alphaTest( value ) {
  15594. if ( this._alphaTest > 0 !== value > 0 ) {
  15595. this.version ++;
  15596. }
  15597. this._alphaTest = value;
  15598. }
  15599. /**
  15600. * An optional callback that is executed immediately before the material is used to render a 3D object.
  15601. *
  15602. * This method can only be used when rendering with {@link WebGLRenderer}.
  15603. *
  15604. * @param {WebGLRenderer} renderer - The renderer.
  15605. * @param {Scene} scene - The scene.
  15606. * @param {Camera} camera - The camera that is used to render the scene.
  15607. * @param {BufferGeometry} geometry - The 3D object's geometry.
  15608. * @param {Object3D} object - The 3D object.
  15609. * @param {Object} group - The geometry group data.
  15610. */
  15611. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  15612. /**
  15613. * An optional callback that is executed immediately before the shader
  15614. * program is compiled. This function is called with the shader source code
  15615. * as a parameter. Useful for the modification of built-in materials.
  15616. *
  15617. * This method can only be used when rendering with {@link WebGLRenderer}. The
  15618. * recommended approach when customizing materials is to use `WebGPURenderer` with the new
  15619. * Node Material system and [TSL](https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language).
  15620. *
  15621. * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
  15622. * @param {WebGLRenderer} renderer - A reference to the renderer.
  15623. */
  15624. onBeforeCompile( /* shaderobject, renderer */ ) {}
  15625. /**
  15626. * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
  15627. * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
  15628. * shader or recompile the shader for this material as needed.
  15629. *
  15630. * This method can only be used when rendering with {@link WebGLRenderer}.
  15631. *
  15632. * @return {string} The custom program cache key.
  15633. */
  15634. customProgramCacheKey() {
  15635. return this.onBeforeCompile.toString();
  15636. }
  15637. /**
  15638. * This method can be used to set default values from parameter objects.
  15639. * It is a generic implementation so it can be used with different types
  15640. * of materials.
  15641. *
  15642. * @param {Object} [values] - The material values to set.
  15643. */
  15644. setValues( values ) {
  15645. if ( values === undefined ) return;
  15646. for ( const key in values ) {
  15647. const newValue = values[ key ];
  15648. if ( newValue === undefined ) {
  15649. warn( `Material: parameter '${ key }' has value of undefined.` );
  15650. continue;
  15651. }
  15652. const currentValue = this[ key ];
  15653. if ( currentValue === undefined ) {
  15654. warn( `Material: '${ key }' is not a property of THREE.${ this.type }.` );
  15655. continue;
  15656. }
  15657. if ( currentValue && currentValue.isColor ) {
  15658. currentValue.set( newValue );
  15659. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  15660. currentValue.copy( newValue );
  15661. } else {
  15662. this[ key ] = newValue;
  15663. }
  15664. }
  15665. }
  15666. /**
  15667. * Serializes the material into JSON.
  15668. *
  15669. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  15670. * @return {Object} A JSON object representing the serialized material.
  15671. * @see {@link ObjectLoader#parse}
  15672. */
  15673. toJSON( meta ) {
  15674. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  15675. if ( isRootObject ) {
  15676. meta = {
  15677. textures: {},
  15678. images: {}
  15679. };
  15680. }
  15681. const data = {
  15682. metadata: {
  15683. version: 4.7,
  15684. type: 'Material',
  15685. generator: 'Material.toJSON'
  15686. }
  15687. };
  15688. // standard Material serialization
  15689. data.uuid = this.uuid;
  15690. data.type = this.type;
  15691. if ( this.name !== '' ) data.name = this.name;
  15692. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  15693. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  15694. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  15695. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  15696. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  15697. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  15698. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  15699. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  15700. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  15701. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  15702. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  15703. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  15704. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  15705. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  15706. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  15707. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  15708. }
  15709. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  15710. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  15711. }
  15712. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  15713. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  15714. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  15715. }
  15716. if ( this.sheenColorMap && this.sheenColorMap.isTexture ) {
  15717. data.sheenColorMap = this.sheenColorMap.toJSON( meta ).uuid;
  15718. }
  15719. if ( this.sheenRoughnessMap && this.sheenRoughnessMap.isTexture ) {
  15720. data.sheenRoughnessMap = this.sheenRoughnessMap.toJSON( meta ).uuid;
  15721. }
  15722. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  15723. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  15724. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  15725. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  15726. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  15727. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  15728. }
  15729. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  15730. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  15731. }
  15732. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  15733. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  15734. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  15735. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  15736. }
  15737. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  15738. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  15739. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  15740. if ( this.lightMap && this.lightMap.isTexture ) {
  15741. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  15742. data.lightMapIntensity = this.lightMapIntensity;
  15743. }
  15744. if ( this.aoMap && this.aoMap.isTexture ) {
  15745. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  15746. data.aoMapIntensity = this.aoMapIntensity;
  15747. }
  15748. if ( this.bumpMap && this.bumpMap.isTexture ) {
  15749. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  15750. data.bumpScale = this.bumpScale;
  15751. }
  15752. if ( this.normalMap && this.normalMap.isTexture ) {
  15753. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  15754. data.normalMapType = this.normalMapType;
  15755. data.normalScale = this.normalScale.toArray();
  15756. }
  15757. if ( this.displacementMap && this.displacementMap.isTexture ) {
  15758. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  15759. data.displacementScale = this.displacementScale;
  15760. data.displacementBias = this.displacementBias;
  15761. }
  15762. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  15763. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  15764. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  15765. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  15766. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  15767. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  15768. if ( this.envMap && this.envMap.isTexture ) {
  15769. data.envMap = this.envMap.toJSON( meta ).uuid;
  15770. if ( this.combine !== undefined ) data.combine = this.combine;
  15771. }
  15772. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  15773. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  15774. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  15775. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  15776. if ( this.gradientMap && this.gradientMap.isTexture ) {
  15777. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  15778. }
  15779. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  15780. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  15781. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  15782. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  15783. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  15784. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  15785. if ( this.size !== undefined ) data.size = this.size;
  15786. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  15787. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  15788. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  15789. if ( this.side !== FrontSide ) data.side = this.side;
  15790. if ( this.vertexColors === true ) data.vertexColors = true;
  15791. if ( this.opacity < 1 ) data.opacity = this.opacity;
  15792. if ( this.transparent === true ) data.transparent = true;
  15793. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  15794. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  15795. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  15796. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  15797. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  15798. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  15799. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  15800. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  15801. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  15802. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  15803. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  15804. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  15805. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  15806. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  15807. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  15808. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  15809. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  15810. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  15811. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  15812. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  15813. // rotation (SpriteMaterial)
  15814. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  15815. if ( this.polygonOffset === true ) data.polygonOffset = true;
  15816. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  15817. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  15818. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  15819. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  15820. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  15821. if ( this.scale !== undefined ) data.scale = this.scale;
  15822. if ( this.dithering === true ) data.dithering = true;
  15823. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  15824. if ( this.alphaHash === true ) data.alphaHash = true;
  15825. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  15826. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  15827. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  15828. if ( this.allowOverride === false ) data.allowOverride = false;
  15829. if ( this.wireframe === true ) data.wireframe = true;
  15830. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  15831. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  15832. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  15833. if ( this.flatShading === true ) data.flatShading = true;
  15834. if ( this.visible === false ) data.visible = false;
  15835. if ( this.toneMapped === false ) data.toneMapped = false;
  15836. if ( this.fog === false ) data.fog = false;
  15837. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  15838. // TODO: Copied from Object3D.toJSON
  15839. function extractFromCache( cache ) {
  15840. const values = [];
  15841. for ( const key in cache ) {
  15842. const data = cache[ key ];
  15843. delete data.metadata;
  15844. values.push( data );
  15845. }
  15846. return values;
  15847. }
  15848. if ( isRootObject ) {
  15849. const textures = extractFromCache( meta.textures );
  15850. const images = extractFromCache( meta.images );
  15851. if ( textures.length > 0 ) data.textures = textures;
  15852. if ( images.length > 0 ) data.images = images;
  15853. }
  15854. return data;
  15855. }
  15856. /**
  15857. * Returns a new material with copied values from this instance.
  15858. *
  15859. * @return {Material} A clone of this instance.
  15860. */
  15861. clone() {
  15862. return new this.constructor().copy( this );
  15863. }
  15864. /**
  15865. * Copies the values of the given material to this instance.
  15866. *
  15867. * @param {Material} source - The material to copy.
  15868. * @return {Material} A reference to this instance.
  15869. */
  15870. copy( source ) {
  15871. this.name = source.name;
  15872. this.blending = source.blending;
  15873. this.side = source.side;
  15874. this.vertexColors = source.vertexColors;
  15875. this.opacity = source.opacity;
  15876. this.transparent = source.transparent;
  15877. this.blendSrc = source.blendSrc;
  15878. this.blendDst = source.blendDst;
  15879. this.blendEquation = source.blendEquation;
  15880. this.blendSrcAlpha = source.blendSrcAlpha;
  15881. this.blendDstAlpha = source.blendDstAlpha;
  15882. this.blendEquationAlpha = source.blendEquationAlpha;
  15883. this.blendColor.copy( source.blendColor );
  15884. this.blendAlpha = source.blendAlpha;
  15885. this.depthFunc = source.depthFunc;
  15886. this.depthTest = source.depthTest;
  15887. this.depthWrite = source.depthWrite;
  15888. this.stencilWriteMask = source.stencilWriteMask;
  15889. this.stencilFunc = source.stencilFunc;
  15890. this.stencilRef = source.stencilRef;
  15891. this.stencilFuncMask = source.stencilFuncMask;
  15892. this.stencilFail = source.stencilFail;
  15893. this.stencilZFail = source.stencilZFail;
  15894. this.stencilZPass = source.stencilZPass;
  15895. this.stencilWrite = source.stencilWrite;
  15896. const srcPlanes = source.clippingPlanes;
  15897. let dstPlanes = null;
  15898. if ( srcPlanes !== null ) {
  15899. const n = srcPlanes.length;
  15900. dstPlanes = new Array( n );
  15901. for ( let i = 0; i !== n; ++ i ) {
  15902. dstPlanes[ i ] = srcPlanes[ i ].clone();
  15903. }
  15904. }
  15905. this.clippingPlanes = dstPlanes;
  15906. this.clipIntersection = source.clipIntersection;
  15907. this.clipShadows = source.clipShadows;
  15908. this.shadowSide = source.shadowSide;
  15909. this.colorWrite = source.colorWrite;
  15910. this.precision = source.precision;
  15911. this.polygonOffset = source.polygonOffset;
  15912. this.polygonOffsetFactor = source.polygonOffsetFactor;
  15913. this.polygonOffsetUnits = source.polygonOffsetUnits;
  15914. this.dithering = source.dithering;
  15915. this.alphaTest = source.alphaTest;
  15916. this.alphaHash = source.alphaHash;
  15917. this.alphaToCoverage = source.alphaToCoverage;
  15918. this.premultipliedAlpha = source.premultipliedAlpha;
  15919. this.forceSinglePass = source.forceSinglePass;
  15920. this.allowOverride = source.allowOverride;
  15921. this.visible = source.visible;
  15922. this.toneMapped = source.toneMapped;
  15923. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  15924. return this;
  15925. }
  15926. /**
  15927. * Frees the GPU-related resources allocated by this instance. Call this
  15928. * method whenever this instance is no longer used in your app.
  15929. *
  15930. * @fires Material#dispose
  15931. */
  15932. dispose() {
  15933. /**
  15934. * Fires when the material has been disposed of.
  15935. *
  15936. * @event Material#dispose
  15937. * @type {Object}
  15938. */
  15939. this.dispatchEvent( { type: 'dispose' } );
  15940. }
  15941. /**
  15942. * Setting this property to `true` indicates the engine the material
  15943. * needs to be recompiled.
  15944. *
  15945. * @type {boolean}
  15946. * @default false
  15947. * @param {boolean} value
  15948. */
  15949. set needsUpdate( value ) {
  15950. if ( value === true ) this.version ++;
  15951. }
  15952. }
  15953. /**
  15954. * A material for rendering instances of {@link Sprite}.
  15955. *
  15956. * ```js
  15957. * const map = new THREE.TextureLoader().load( 'textures/sprite.png' );
  15958. * const material = new THREE.SpriteMaterial( { map: map, color: 0xffffff } );
  15959. *
  15960. * const sprite = new THREE.Sprite( material );
  15961. * sprite.scale.set(200, 200, 1)
  15962. * scene.add( sprite );
  15963. * ```
  15964. *
  15965. * @augments Material
  15966. */
  15967. class SpriteMaterial extends Material {
  15968. /**
  15969. * Constructs a new sprite material.
  15970. *
  15971. * @param {Object} [parameters] - An object with one or more properties
  15972. * defining the material's appearance. Any property of the material
  15973. * (including any property from inherited materials) can be passed
  15974. * in here. Color values can be passed any type of value accepted
  15975. * by {@link Color#set}.
  15976. */
  15977. constructor( parameters ) {
  15978. super();
  15979. /**
  15980. * This flag can be used for type testing.
  15981. *
  15982. * @type {boolean}
  15983. * @readonly
  15984. * @default true
  15985. */
  15986. this.isSpriteMaterial = true;
  15987. this.type = 'SpriteMaterial';
  15988. /**
  15989. * Color of the material.
  15990. *
  15991. * @type {Color}
  15992. * @default (1,1,1)
  15993. */
  15994. this.color = new Color( 0xffffff );
  15995. /**
  15996. * The color map. May optionally include an alpha channel, typically combined
  15997. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  15998. * color is modulated by the diffuse `color`.
  15999. *
  16000. * @type {?Texture}
  16001. * @default null
  16002. */
  16003. this.map = null;
  16004. /**
  16005. * The alpha map is a grayscale texture that controls the opacity across the
  16006. * surface (black: fully transparent; white: fully opaque).
  16007. *
  16008. * Only the color of the texture is used, ignoring the alpha channel if one
  16009. * exists. For RGB and RGBA textures, the renderer will use the green channel
  16010. * when sampling this texture due to the extra bit of precision provided for
  16011. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  16012. * luminance/alpha textures will also still work as expected.
  16013. *
  16014. * @type {?Texture}
  16015. * @default null
  16016. */
  16017. this.alphaMap = null;
  16018. /**
  16019. * The rotation of the sprite in radians.
  16020. *
  16021. * @type {number}
  16022. * @default 0
  16023. */
  16024. this.rotation = 0;
  16025. /**
  16026. * Specifies whether size of the sprite is attenuated by the camera depth (perspective camera only).
  16027. *
  16028. * @type {boolean}
  16029. * @default true
  16030. */
  16031. this.sizeAttenuation = true;
  16032. /**
  16033. * Overwritten since sprite materials are transparent
  16034. * by default.
  16035. *
  16036. * @type {boolean}
  16037. * @default true
  16038. */
  16039. this.transparent = true;
  16040. /**
  16041. * Whether the material is affected by fog or not.
  16042. *
  16043. * @type {boolean}
  16044. * @default true
  16045. */
  16046. this.fog = true;
  16047. this.setValues( parameters );
  16048. }
  16049. copy( source ) {
  16050. super.copy( source );
  16051. this.color.copy( source.color );
  16052. this.map = source.map;
  16053. this.alphaMap = source.alphaMap;
  16054. this.rotation = source.rotation;
  16055. this.sizeAttenuation = source.sizeAttenuation;
  16056. this.fog = source.fog;
  16057. return this;
  16058. }
  16059. }
  16060. let _geometry;
  16061. const _intersectPoint = /*@__PURE__*/ new Vector3();
  16062. const _worldScale = /*@__PURE__*/ new Vector3();
  16063. const _mvPosition = /*@__PURE__*/ new Vector3();
  16064. const _alignedPosition = /*@__PURE__*/ new Vector2();
  16065. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  16066. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  16067. const _vA$1 = /*@__PURE__*/ new Vector3();
  16068. const _vB$1 = /*@__PURE__*/ new Vector3();
  16069. const _vC$1 = /*@__PURE__*/ new Vector3();
  16070. const _uvA = /*@__PURE__*/ new Vector2();
  16071. const _uvB = /*@__PURE__*/ new Vector2();
  16072. const _uvC = /*@__PURE__*/ new Vector2();
  16073. /**
  16074. * A sprite is a plane that always faces towards the camera, generally with a
  16075. * partially transparent texture applied.
  16076. *
  16077. * Sprites do not cast shadows, setting {@link Object3D#castShadow} to `true` will
  16078. * have no effect.
  16079. *
  16080. * ```js
  16081. * const map = new THREE.TextureLoader().load( 'sprite.png' );
  16082. * const material = new THREE.SpriteMaterial( { map: map } );
  16083. *
  16084. * const sprite = new THREE.Sprite( material );
  16085. * scene.add( sprite );
  16086. * ```
  16087. *
  16088. * @augments Object3D
  16089. */
  16090. class Sprite extends Object3D {
  16091. /**
  16092. * Constructs a new sprite.
  16093. *
  16094. * @param {(SpriteMaterial|SpriteNodeMaterial)} [material] - The sprite material.
  16095. */
  16096. constructor( material = new SpriteMaterial() ) {
  16097. super();
  16098. /**
  16099. * This flag can be used for type testing.
  16100. *
  16101. * @type {boolean}
  16102. * @readonly
  16103. * @default true
  16104. */
  16105. this.isSprite = true;
  16106. this.type = 'Sprite';
  16107. if ( _geometry === undefined ) {
  16108. _geometry = new BufferGeometry();
  16109. const float32Array = new Float32Array( [
  16110. -0.5, -0.5, 0, 0, 0,
  16111. 0.5, -0.5, 0, 1, 0,
  16112. 0.5, 0.5, 0, 1, 1,
  16113. -0.5, 0.5, 0, 0, 1
  16114. ] );
  16115. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  16116. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  16117. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  16118. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  16119. }
  16120. /**
  16121. * The sprite geometry.
  16122. *
  16123. * @type {BufferGeometry}
  16124. */
  16125. this.geometry = _geometry;
  16126. /**
  16127. * The sprite material.
  16128. *
  16129. * @type {(SpriteMaterial|SpriteNodeMaterial)}
  16130. */
  16131. this.material = material;
  16132. /**
  16133. * The sprite's anchor point, and the point around which the sprite rotates.
  16134. * A value of `(0.5, 0.5)` corresponds to the midpoint of the sprite. A value
  16135. * of `(0, 0)` corresponds to the lower left corner of the sprite.
  16136. *
  16137. * @type {Vector2}
  16138. * @default (0.5,0.5)
  16139. */
  16140. this.center = new Vector2( 0.5, 0.5 );
  16141. /**
  16142. * The number of instances of this sprite.
  16143. * Can only be used with {@link WebGPURenderer}.
  16144. *
  16145. * @type {number}
  16146. * @default 1
  16147. */
  16148. this.count = 1;
  16149. }
  16150. /**
  16151. * Computes intersection points between a casted ray and this sprite.
  16152. *
  16153. * @param {Raycaster} raycaster - The raycaster.
  16154. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  16155. */
  16156. raycast( raycaster, intersects ) {
  16157. if ( raycaster.camera === null ) {
  16158. error( 'Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  16159. }
  16160. _worldScale.setFromMatrixScale( this.matrixWorld );
  16161. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  16162. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  16163. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  16164. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  16165. _worldScale.multiplyScalar( - _mvPosition.z );
  16166. }
  16167. const rotation = this.material.rotation;
  16168. let sin, cos;
  16169. if ( rotation !== 0 ) {
  16170. cos = Math.cos( rotation );
  16171. sin = Math.sin( rotation );
  16172. }
  16173. const center = this.center;
  16174. transformVertex( _vA$1.set( -0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16175. transformVertex( _vB$1.set( 0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16176. transformVertex( _vC$1.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16177. _uvA.set( 0, 0 );
  16178. _uvB.set( 1, 0 );
  16179. _uvC.set( 1, 1 );
  16180. // check first triangle
  16181. let intersect = raycaster.ray.intersectTriangle( _vA$1, _vB$1, _vC$1, false, _intersectPoint );
  16182. if ( intersect === null ) {
  16183. // check second triangle
  16184. transformVertex( _vB$1.set( -0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16185. _uvB.set( 0, 1 );
  16186. intersect = raycaster.ray.intersectTriangle( _vA$1, _vC$1, _vB$1, false, _intersectPoint );
  16187. if ( intersect === null ) {
  16188. return;
  16189. }
  16190. }
  16191. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  16192. if ( distance < raycaster.near || distance > raycaster.far ) return;
  16193. intersects.push( {
  16194. distance: distance,
  16195. point: _intersectPoint.clone(),
  16196. uv: Triangle.getInterpolation( _intersectPoint, _vA$1, _vB$1, _vC$1, _uvA, _uvB, _uvC, new Vector2() ),
  16197. face: null,
  16198. object: this
  16199. } );
  16200. }
  16201. copy( source, recursive ) {
  16202. super.copy( source, recursive );
  16203. if ( source.center !== undefined ) this.center.copy( source.center );
  16204. this.material = source.material;
  16205. return this;
  16206. }
  16207. }
  16208. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  16209. // compute position in camera space
  16210. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  16211. // to check if rotation is not zero
  16212. if ( sin !== undefined ) {
  16213. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  16214. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  16215. } else {
  16216. _rotatedPosition.copy( _alignedPosition );
  16217. }
  16218. vertexPosition.copy( mvPosition );
  16219. vertexPosition.x += _rotatedPosition.x;
  16220. vertexPosition.y += _rotatedPosition.y;
  16221. // transform to world space
  16222. vertexPosition.applyMatrix4( _viewWorldMatrix );
  16223. }
  16224. const _v1$2 = /*@__PURE__*/ new Vector3();
  16225. const _v2$1 = /*@__PURE__*/ new Vector3();
  16226. /**
  16227. * A component for providing a basic Level of Detail (LOD) mechanism.
  16228. *
  16229. * Every LOD level is associated with an object, and rendering can be switched
  16230. * between them at the distances specified. Typically you would create, say,
  16231. * three meshes, one for far away (low detail), one for mid range (medium
  16232. * detail) and one for close up (high detail).
  16233. *
  16234. * ```js
  16235. * const lod = new THREE.LOD();
  16236. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  16237. *
  16238. * //Create spheres with 3 levels of detail and create new LOD levels for them
  16239. * for( let i = 0; i < 3; i++ ) {
  16240. *
  16241. * const geometry = new THREE.IcosahedronGeometry( 10, 3 - i );
  16242. * const mesh = new THREE.Mesh( geometry, material );
  16243. * lod.addLevel( mesh, i * 75 );
  16244. *
  16245. * }
  16246. *
  16247. * scene.add( lod );
  16248. * ```
  16249. *
  16250. * @augments Object3D
  16251. */
  16252. class LOD extends Object3D {
  16253. /**
  16254. * Constructs a new LOD.
  16255. */
  16256. constructor() {
  16257. super();
  16258. /**
  16259. * This flag can be used for type testing.
  16260. *
  16261. * @type {boolean}
  16262. * @readonly
  16263. * @default true
  16264. */
  16265. this.isLOD = true;
  16266. /**
  16267. * The current LOD index.
  16268. *
  16269. * @private
  16270. * @type {number}
  16271. * @default 0
  16272. */
  16273. this._currentLevel = 0;
  16274. this.type = 'LOD';
  16275. Object.defineProperties( this, {
  16276. /**
  16277. * This array holds the LOD levels.
  16278. *
  16279. * @name LOD#levels
  16280. * @type {Array<{object:Object3D,distance:number,hysteresis:number}>}
  16281. */
  16282. levels: {
  16283. enumerable: true,
  16284. value: []
  16285. }
  16286. } );
  16287. /**
  16288. * Whether the LOD object is updated automatically by the renderer per frame
  16289. * or not. If set to `false`, you have to call {@link LOD#update} in the
  16290. * render loop by yourself.
  16291. *
  16292. * @type {boolean}
  16293. * @default true
  16294. */
  16295. this.autoUpdate = true;
  16296. }
  16297. copy( source ) {
  16298. super.copy( source, false );
  16299. const levels = source.levels;
  16300. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  16301. const level = levels[ i ];
  16302. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  16303. }
  16304. this.autoUpdate = source.autoUpdate;
  16305. return this;
  16306. }
  16307. /**
  16308. * Adds a mesh that will display at a certain distance and greater. Typically
  16309. * the further away the distance, the lower the detail on the mesh.
  16310. *
  16311. * @param {Object3D} object - The 3D object to display at this level.
  16312. * @param {number} [distance=0] - The distance at which to display this level of detail.
  16313. * @param {number} [hysteresis=0] - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance.
  16314. * @return {LOD} A reference to this instance.
  16315. */
  16316. addLevel( object, distance = 0, hysteresis = 0 ) {
  16317. distance = Math.abs( distance );
  16318. const levels = this.levels;
  16319. let l;
  16320. for ( l = 0; l < levels.length; l ++ ) {
  16321. if ( distance < levels[ l ].distance ) {
  16322. break;
  16323. }
  16324. }
  16325. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  16326. this.add( object );
  16327. return this;
  16328. }
  16329. /**
  16330. * Removes an existing level, based on the distance from the camera.
  16331. * Returns `true` when the level has been removed. Otherwise `false`.
  16332. *
  16333. * @param {number} distance - Distance of the level to remove.
  16334. * @return {boolean} Whether the level has been removed or not.
  16335. */
  16336. removeLevel( distance ) {
  16337. const levels = this.levels;
  16338. for ( let i = 0; i < levels.length; i ++ ) {
  16339. if ( levels[ i ].distance === distance ) {
  16340. const removedElements = levels.splice( i, 1 );
  16341. this.remove( removedElements[ 0 ].object );
  16342. return true;
  16343. }
  16344. }
  16345. return false;
  16346. }
  16347. /**
  16348. * Returns the currently active LOD level index.
  16349. *
  16350. * @return {number} The current active LOD level index.
  16351. */
  16352. getCurrentLevel() {
  16353. return this._currentLevel;
  16354. }
  16355. /**
  16356. * Returns a reference to the first 3D object that is greater than
  16357. * the given distance.
  16358. *
  16359. * @param {number} distance - The LOD distance.
  16360. * @return {?Object3D} The found 3D object. `null` if no 3D object has been found.
  16361. */
  16362. getObjectForDistance( distance ) {
  16363. const levels = this.levels;
  16364. if ( levels.length > 0 ) {
  16365. let i, l;
  16366. for ( i = 1, l = levels.length; i < l; i ++ ) {
  16367. let levelDistance = levels[ i ].distance;
  16368. if ( levels[ i ].object.visible ) {
  16369. levelDistance -= levelDistance * levels[ i ].hysteresis;
  16370. }
  16371. if ( distance < levelDistance ) {
  16372. break;
  16373. }
  16374. }
  16375. return levels[ i - 1 ].object;
  16376. }
  16377. return null;
  16378. }
  16379. /**
  16380. * Computes intersection points between a casted ray and this LOD.
  16381. *
  16382. * @param {Raycaster} raycaster - The raycaster.
  16383. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  16384. */
  16385. raycast( raycaster, intersects ) {
  16386. const levels = this.levels;
  16387. if ( levels.length > 0 ) {
  16388. _v1$2.setFromMatrixPosition( this.matrixWorld );
  16389. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  16390. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  16391. }
  16392. }
  16393. /**
  16394. * Updates the LOD by computing which LOD level should be visible according
  16395. * to the current distance of the given camera.
  16396. *
  16397. * @param {Camera} camera - The camera the scene is rendered with.
  16398. */
  16399. update( camera ) {
  16400. const levels = this.levels;
  16401. if ( levels.length > 1 ) {
  16402. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  16403. _v2$1.setFromMatrixPosition( this.matrixWorld );
  16404. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  16405. levels[ 0 ].object.visible = true;
  16406. let i, l;
  16407. for ( i = 1, l = levels.length; i < l; i ++ ) {
  16408. let levelDistance = levels[ i ].distance;
  16409. if ( levels[ i ].object.visible ) {
  16410. levelDistance -= levelDistance * levels[ i ].hysteresis;
  16411. }
  16412. if ( distance >= levelDistance ) {
  16413. levels[ i - 1 ].object.visible = false;
  16414. levels[ i ].object.visible = true;
  16415. } else {
  16416. break;
  16417. }
  16418. }
  16419. this._currentLevel = i - 1;
  16420. for ( ; i < l; i ++ ) {
  16421. levels[ i ].object.visible = false;
  16422. }
  16423. }
  16424. }
  16425. toJSON( meta ) {
  16426. const data = super.toJSON( meta );
  16427. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  16428. data.object.levels = [];
  16429. const levels = this.levels;
  16430. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  16431. const level = levels[ i ];
  16432. data.object.levels.push( {
  16433. object: level.object.uuid,
  16434. distance: level.distance,
  16435. hysteresis: level.hysteresis
  16436. } );
  16437. }
  16438. return data;
  16439. }
  16440. }
  16441. const _vector$7 = /*@__PURE__*/ new Vector3();
  16442. const _segCenter = /*@__PURE__*/ new Vector3();
  16443. const _segDir = /*@__PURE__*/ new Vector3();
  16444. const _diff = /*@__PURE__*/ new Vector3();
  16445. const _edge1 = /*@__PURE__*/ new Vector3();
  16446. const _edge2 = /*@__PURE__*/ new Vector3();
  16447. const _normal$1 = /*@__PURE__*/ new Vector3();
  16448. /**
  16449. * A ray that emits from an origin in a certain direction. The class is used by
  16450. * {@link Raycaster} to assist with raycasting. Raycasting is used for
  16451. * mouse picking (working out what objects in the 3D space the mouse is over)
  16452. * amongst other things.
  16453. */
  16454. class Ray {
  16455. /**
  16456. * Constructs a new ray.
  16457. *
  16458. * @param {Vector3} [origin=(0,0,0)] - The origin of the ray.
  16459. * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray.
  16460. */
  16461. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, -1 ) ) {
  16462. /**
  16463. * The origin of the ray.
  16464. *
  16465. * @type {Vector3}
  16466. */
  16467. this.origin = origin;
  16468. /**
  16469. * The (normalized) direction of the ray.
  16470. *
  16471. * @type {Vector3}
  16472. */
  16473. this.direction = direction;
  16474. }
  16475. /**
  16476. * Sets the ray's components by copying the given values.
  16477. *
  16478. * @param {Vector3} origin - The origin.
  16479. * @param {Vector3} direction - The direction.
  16480. * @return {Ray} A reference to this ray.
  16481. */
  16482. set( origin, direction ) {
  16483. this.origin.copy( origin );
  16484. this.direction.copy( direction );
  16485. return this;
  16486. }
  16487. /**
  16488. * Copies the values of the given ray to this instance.
  16489. *
  16490. * @param {Ray} ray - The ray to copy.
  16491. * @return {Ray} A reference to this ray.
  16492. */
  16493. copy( ray ) {
  16494. this.origin.copy( ray.origin );
  16495. this.direction.copy( ray.direction );
  16496. return this;
  16497. }
  16498. /**
  16499. * Returns a vector that is located at a given distance along this ray.
  16500. *
  16501. * @param {number} t - The distance along the ray to retrieve a position for.
  16502. * @param {Vector3} target - The target vector that is used to store the method's result.
  16503. * @return {Vector3} A position on the ray.
  16504. */
  16505. at( t, target ) {
  16506. return target.copy( this.origin ).addScaledVector( this.direction, t );
  16507. }
  16508. /**
  16509. * Adjusts the direction of the ray to point at the given vector in world space.
  16510. *
  16511. * @param {Vector3} v - The target position.
  16512. * @return {Ray} A reference to this ray.
  16513. */
  16514. lookAt( v ) {
  16515. this.direction.copy( v ).sub( this.origin ).normalize();
  16516. return this;
  16517. }
  16518. /**
  16519. * Shift the origin of this ray along its direction by the given distance.
  16520. *
  16521. * @param {number} t - The distance along the ray to interpolate.
  16522. * @return {Ray} A reference to this ray.
  16523. */
  16524. recast( t ) {
  16525. this.origin.copy( this.at( t, _vector$7 ) );
  16526. return this;
  16527. }
  16528. /**
  16529. * Returns the point along this ray that is closest to the given point.
  16530. *
  16531. * @param {Vector3} point - A point in 3D space to get the closet location on the ray for.
  16532. * @param {Vector3} target - The target vector that is used to store the method's result.
  16533. * @return {Vector3} The closest point on this ray.
  16534. */
  16535. closestPointToPoint( point, target ) {
  16536. target.subVectors( point, this.origin );
  16537. const directionDistance = target.dot( this.direction );
  16538. if ( directionDistance < 0 ) {
  16539. return target.copy( this.origin );
  16540. }
  16541. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  16542. }
  16543. /**
  16544. * Returns the distance of the closest approach between this ray and the given point.
  16545. *
  16546. * @param {Vector3} point - A point in 3D space to compute the distance to.
  16547. * @return {number} The distance.
  16548. */
  16549. distanceToPoint( point ) {
  16550. return Math.sqrt( this.distanceSqToPoint( point ) );
  16551. }
  16552. /**
  16553. * Returns the squared distance of the closest approach between this ray and the given point.
  16554. *
  16555. * @param {Vector3} point - A point in 3D space to compute the distance to.
  16556. * @return {number} The squared distance.
  16557. */
  16558. distanceSqToPoint( point ) {
  16559. const directionDistance = _vector$7.subVectors( point, this.origin ).dot( this.direction );
  16560. // point behind the ray
  16561. if ( directionDistance < 0 ) {
  16562. return this.origin.distanceToSquared( point );
  16563. }
  16564. _vector$7.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  16565. return _vector$7.distanceToSquared( point );
  16566. }
  16567. /**
  16568. * Returns the squared distance between this ray and the given line segment.
  16569. *
  16570. * @param {Vector3} v0 - The start point of the line segment.
  16571. * @param {Vector3} v1 - The end point of the line segment.
  16572. * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment.
  16573. * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray.
  16574. * @return {number} The squared distance.
  16575. */
  16576. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  16577. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  16578. // It returns the min distance between the ray and the segment
  16579. // defined by v0 and v1
  16580. // It can also set two optional targets :
  16581. // - The closest point on the ray
  16582. // - The closest point on the segment
  16583. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  16584. _segDir.copy( v1 ).sub( v0 ).normalize();
  16585. _diff.copy( this.origin ).sub( _segCenter );
  16586. const segExtent = v0.distanceTo( v1 ) * 0.5;
  16587. const a01 = - this.direction.dot( _segDir );
  16588. const b0 = _diff.dot( this.direction );
  16589. const b1 = - _diff.dot( _segDir );
  16590. const c = _diff.lengthSq();
  16591. const det = Math.abs( 1 - a01 * a01 );
  16592. let s0, s1, sqrDist, extDet;
  16593. if ( det > 0 ) {
  16594. // The ray and segment are not parallel.
  16595. s0 = a01 * b1 - b0;
  16596. s1 = a01 * b0 - b1;
  16597. extDet = segExtent * det;
  16598. if ( s0 >= 0 ) {
  16599. if ( s1 >= - extDet ) {
  16600. if ( s1 <= extDet ) {
  16601. // region 0
  16602. // Minimum at interior points of ray and segment.
  16603. const invDet = 1 / det;
  16604. s0 *= invDet;
  16605. s1 *= invDet;
  16606. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  16607. } else {
  16608. // region 1
  16609. s1 = segExtent;
  16610. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  16611. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16612. }
  16613. } else {
  16614. // region 5
  16615. s1 = - segExtent;
  16616. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  16617. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16618. }
  16619. } else {
  16620. if ( s1 <= - extDet ) {
  16621. // region 4
  16622. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  16623. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  16624. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16625. } else if ( s1 <= extDet ) {
  16626. // region 3
  16627. s0 = 0;
  16628. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  16629. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  16630. } else {
  16631. // region 2
  16632. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  16633. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  16634. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16635. }
  16636. }
  16637. } else {
  16638. // Ray and segment are parallel.
  16639. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  16640. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  16641. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16642. }
  16643. if ( optionalPointOnRay ) {
  16644. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  16645. }
  16646. if ( optionalPointOnSegment ) {
  16647. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  16648. }
  16649. return sqrDist;
  16650. }
  16651. /**
  16652. * Intersects this ray with the given sphere, returning the intersection
  16653. * point or `null` if there is no intersection.
  16654. *
  16655. * @param {Sphere} sphere - The sphere to intersect.
  16656. * @param {Vector3} target - The target vector that is used to store the method's result.
  16657. * @return {?Vector3} The intersection point.
  16658. */
  16659. intersectSphere( sphere, target ) {
  16660. _vector$7.subVectors( sphere.center, this.origin );
  16661. const tca = _vector$7.dot( this.direction );
  16662. const d2 = _vector$7.dot( _vector$7 ) - tca * tca;
  16663. const radius2 = sphere.radius * sphere.radius;
  16664. if ( d2 > radius2 ) return null;
  16665. const thc = Math.sqrt( radius2 - d2 );
  16666. // t0 = first intersect point - entrance on front of sphere
  16667. const t0 = tca - thc;
  16668. // t1 = second intersect point - exit point on back of sphere
  16669. const t1 = tca + thc;
  16670. // test to see if t1 is behind the ray - if so, return null
  16671. if ( t1 < 0 ) return null;
  16672. // test to see if t0 is behind the ray:
  16673. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  16674. // in order to always return an intersect point that is in front of the ray.
  16675. if ( t0 < 0 ) return this.at( t1, target );
  16676. // else t0 is in front of the ray, so return the first collision point scaled by t0
  16677. return this.at( t0, target );
  16678. }
  16679. /**
  16680. * Returns `true` if this ray intersects with the given sphere.
  16681. *
  16682. * @param {Sphere} sphere - The sphere to intersect.
  16683. * @return {boolean} Whether this ray intersects with the given sphere or not.
  16684. */
  16685. intersectsSphere( sphere ) {
  16686. if ( sphere.radius < 0 ) return false; // handle empty spheres, see #31187
  16687. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  16688. }
  16689. /**
  16690. * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray
  16691. * does not intersect with the plane.
  16692. *
  16693. * @param {Plane} plane - The plane to compute the distance to.
  16694. * @return {?number} Whether this ray intersects with the given sphere or not.
  16695. */
  16696. distanceToPlane( plane ) {
  16697. const denominator = plane.normal.dot( this.direction );
  16698. if ( denominator === 0 ) {
  16699. // line is coplanar, return origin
  16700. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  16701. return 0;
  16702. }
  16703. // Null is preferable to undefined since undefined means.... it is undefined
  16704. return null;
  16705. }
  16706. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  16707. // Return if the ray never intersects the plane
  16708. return t >= 0 ? t : null;
  16709. }
  16710. /**
  16711. * Intersects this ray with the given plane, returning the intersection
  16712. * point or `null` if there is no intersection.
  16713. *
  16714. * @param {Plane} plane - The plane to intersect.
  16715. * @param {Vector3} target - The target vector that is used to store the method's result.
  16716. * @return {?Vector3} The intersection point.
  16717. */
  16718. intersectPlane( plane, target ) {
  16719. const t = this.distanceToPlane( plane );
  16720. if ( t === null ) {
  16721. return null;
  16722. }
  16723. return this.at( t, target );
  16724. }
  16725. /**
  16726. * Returns `true` if this ray intersects with the given plane.
  16727. *
  16728. * @param {Plane} plane - The plane to intersect.
  16729. * @return {boolean} Whether this ray intersects with the given plane or not.
  16730. */
  16731. intersectsPlane( plane ) {
  16732. // check if the ray lies on the plane first
  16733. const distToPoint = plane.distanceToPoint( this.origin );
  16734. if ( distToPoint === 0 ) {
  16735. return true;
  16736. }
  16737. const denominator = plane.normal.dot( this.direction );
  16738. if ( denominator * distToPoint < 0 ) {
  16739. return true;
  16740. }
  16741. // ray origin is behind the plane (and is pointing behind it)
  16742. return false;
  16743. }
  16744. /**
  16745. * Intersects this ray with the given bounding box, returning the intersection
  16746. * point or `null` if there is no intersection.
  16747. *
  16748. * @param {Box3} box - The box to intersect.
  16749. * @param {Vector3} target - The target vector that is used to store the method's result.
  16750. * @return {?Vector3} The intersection point.
  16751. */
  16752. intersectBox( box, target ) {
  16753. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  16754. const invdirx = 1 / this.direction.x,
  16755. invdiry = 1 / this.direction.y,
  16756. invdirz = 1 / this.direction.z;
  16757. const origin = this.origin;
  16758. if ( invdirx >= 0 ) {
  16759. tmin = ( box.min.x - origin.x ) * invdirx;
  16760. tmax = ( box.max.x - origin.x ) * invdirx;
  16761. } else {
  16762. tmin = ( box.max.x - origin.x ) * invdirx;
  16763. tmax = ( box.min.x - origin.x ) * invdirx;
  16764. }
  16765. if ( invdiry >= 0 ) {
  16766. tymin = ( box.min.y - origin.y ) * invdiry;
  16767. tymax = ( box.max.y - origin.y ) * invdiry;
  16768. } else {
  16769. tymin = ( box.max.y - origin.y ) * invdiry;
  16770. tymax = ( box.min.y - origin.y ) * invdiry;
  16771. }
  16772. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  16773. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  16774. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  16775. if ( invdirz >= 0 ) {
  16776. tzmin = ( box.min.z - origin.z ) * invdirz;
  16777. tzmax = ( box.max.z - origin.z ) * invdirz;
  16778. } else {
  16779. tzmin = ( box.max.z - origin.z ) * invdirz;
  16780. tzmax = ( box.min.z - origin.z ) * invdirz;
  16781. }
  16782. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  16783. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  16784. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  16785. //return point closest to the ray (positive side)
  16786. if ( tmax < 0 ) return null;
  16787. return this.at( tmin >= 0 ? tmin : tmax, target );
  16788. }
  16789. /**
  16790. * Returns `true` if this ray intersects with the given box.
  16791. *
  16792. * @param {Box3} box - The box to intersect.
  16793. * @return {boolean} Whether this ray intersects with the given box or not.
  16794. */
  16795. intersectsBox( box ) {
  16796. return this.intersectBox( box, _vector$7 ) !== null;
  16797. }
  16798. /**
  16799. * Intersects this ray with the given triangle, returning the intersection
  16800. * point or `null` if there is no intersection.
  16801. *
  16802. * @param {Vector3} a - The first vertex of the triangle.
  16803. * @param {Vector3} b - The second vertex of the triangle.
  16804. * @param {Vector3} c - The third vertex of the triangle.
  16805. * @param {boolean} backfaceCulling - Whether to use backface culling or not.
  16806. * @param {Vector3} target - The target vector that is used to store the method's result.
  16807. * @return {?Vector3} The intersection point.
  16808. */
  16809. intersectTriangle( a, b, c, backfaceCulling, target ) {
  16810. // Compute the offset origin, edges, and normal.
  16811. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  16812. _edge1.subVectors( b, a );
  16813. _edge2.subVectors( c, a );
  16814. _normal$1.crossVectors( _edge1, _edge2 );
  16815. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  16816. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  16817. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  16818. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  16819. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  16820. let DdN = this.direction.dot( _normal$1 );
  16821. let sign;
  16822. if ( DdN > 0 ) {
  16823. if ( backfaceCulling ) return null;
  16824. sign = 1;
  16825. } else if ( DdN < 0 ) {
  16826. sign = -1;
  16827. DdN = - DdN;
  16828. } else {
  16829. return null;
  16830. }
  16831. _diff.subVectors( this.origin, a );
  16832. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  16833. // b1 < 0, no intersection
  16834. if ( DdQxE2 < 0 ) {
  16835. return null;
  16836. }
  16837. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  16838. // b2 < 0, no intersection
  16839. if ( DdE1xQ < 0 ) {
  16840. return null;
  16841. }
  16842. // b1+b2 > 1, no intersection
  16843. if ( DdQxE2 + DdE1xQ > DdN ) {
  16844. return null;
  16845. }
  16846. // Line intersects triangle, check if ray does.
  16847. const QdN = - sign * _diff.dot( _normal$1 );
  16848. // t < 0, no intersection
  16849. if ( QdN < 0 ) {
  16850. return null;
  16851. }
  16852. // Ray intersects triangle.
  16853. return this.at( QdN / DdN, target );
  16854. }
  16855. /**
  16856. * Transforms this ray with the given 4x4 transformation matrix.
  16857. *
  16858. * @param {Matrix4} matrix4 - The transformation matrix.
  16859. * @return {Ray} A reference to this ray.
  16860. */
  16861. applyMatrix4( matrix4 ) {
  16862. this.origin.applyMatrix4( matrix4 );
  16863. this.direction.transformDirection( matrix4 );
  16864. return this;
  16865. }
  16866. /**
  16867. * Returns `true` if this ray is equal with the given one.
  16868. *
  16869. * @param {Ray} ray - The ray to test for equality.
  16870. * @return {boolean} Whether this ray is equal with the given one.
  16871. */
  16872. equals( ray ) {
  16873. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  16874. }
  16875. /**
  16876. * Returns a new ray with copied values from this instance.
  16877. *
  16878. * @return {Ray} A clone of this instance.
  16879. */
  16880. clone() {
  16881. return new this.constructor().copy( this );
  16882. }
  16883. }
  16884. /**
  16885. * A material for drawing geometries in a simple shaded (flat or wireframe) way.
  16886. *
  16887. * This material is not affected by lights.
  16888. *
  16889. * @augments Material
  16890. * @demo scenes/material-browser.html#MeshBasicMaterial
  16891. */
  16892. class MeshBasicMaterial extends Material {
  16893. /**
  16894. * Constructs a new mesh basic material.
  16895. *
  16896. * @param {Object} [parameters] - An object with one or more properties
  16897. * defining the material's appearance. Any property of the material
  16898. * (including any property from inherited materials) can be passed
  16899. * in here. Color values can be passed any type of value accepted
  16900. * by {@link Color#set}.
  16901. */
  16902. constructor( parameters ) {
  16903. super();
  16904. /**
  16905. * This flag can be used for type testing.
  16906. *
  16907. * @type {boolean}
  16908. * @readonly
  16909. * @default true
  16910. */
  16911. this.isMeshBasicMaterial = true;
  16912. this.type = 'MeshBasicMaterial';
  16913. /**
  16914. * Color of the material.
  16915. *
  16916. * @type {Color}
  16917. * @default (1,1,1)
  16918. */
  16919. this.color = new Color( 0xffffff ); // diffuse
  16920. /**
  16921. * The color map. May optionally include an alpha channel, typically combined
  16922. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  16923. * color is modulated by the diffuse `color`.
  16924. *
  16925. * @type {?Texture}
  16926. * @default null
  16927. */
  16928. this.map = null;
  16929. /**
  16930. * The light map. Requires a second set of UVs.
  16931. *
  16932. * @type {?Texture}
  16933. * @default null
  16934. */
  16935. this.lightMap = null;
  16936. /**
  16937. * Intensity of the baked light.
  16938. *
  16939. * @type {number}
  16940. * @default 1
  16941. */
  16942. this.lightMapIntensity = 1.0;
  16943. /**
  16944. * The red channel of this texture is used as the ambient occlusion map.
  16945. * Requires a second set of UVs.
  16946. *
  16947. * @type {?Texture}
  16948. * @default null
  16949. */
  16950. this.aoMap = null;
  16951. /**
  16952. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  16953. * disables ambient occlusion. Where intensity is `1` and the AO map's
  16954. * red channel is also `1`, ambient light is fully occluded on a surface.
  16955. *
  16956. * @type {number}
  16957. * @default 1
  16958. */
  16959. this.aoMapIntensity = 1.0;
  16960. /**
  16961. * Specular map used by the material.
  16962. *
  16963. * @type {?Texture}
  16964. * @default null
  16965. */
  16966. this.specularMap = null;
  16967. /**
  16968. * The alpha map is a grayscale texture that controls the opacity across the
  16969. * surface (black: fully transparent; white: fully opaque).
  16970. *
  16971. * Only the color of the texture is used, ignoring the alpha channel if one
  16972. * exists. For RGB and RGBA textures, the renderer will use the green channel
  16973. * when sampling this texture due to the extra bit of precision provided for
  16974. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  16975. * luminance/alpha textures will also still work as expected.
  16976. *
  16977. * @type {?Texture}
  16978. * @default null
  16979. */
  16980. this.alphaMap = null;
  16981. /**
  16982. * The environment map.
  16983. *
  16984. * @type {?Texture}
  16985. * @default null
  16986. */
  16987. this.envMap = null;
  16988. /**
  16989. * The rotation of the environment map in radians.
  16990. *
  16991. * @type {Euler}
  16992. * @default (0,0,0)
  16993. */
  16994. this.envMapRotation = new Euler();
  16995. /**
  16996. * How to combine the result of the surface's color with the environment map, if any.
  16997. *
  16998. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  16999. * blend between the two colors.
  17000. *
  17001. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  17002. * @default MultiplyOperation
  17003. */
  17004. this.combine = MultiplyOperation;
  17005. /**
  17006. * How much the environment map affects the surface.
  17007. * The valid range is between `0` (no reflections) and `1` (full reflections).
  17008. *
  17009. * @type {number}
  17010. * @default 1
  17011. */
  17012. this.reflectivity = 1;
  17013. /**
  17014. * The index of refraction (IOR) of air (approximately 1) divided by the
  17015. * index of refraction of the material. It is used with environment mapping
  17016. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  17017. * The refraction ratio should not exceed `1`.
  17018. *
  17019. * @type {number}
  17020. * @default 0.98
  17021. */
  17022. this.refractionRatio = 0.98;
  17023. /**
  17024. * Renders the geometry as a wireframe.
  17025. *
  17026. * @type {boolean}
  17027. * @default false
  17028. */
  17029. this.wireframe = false;
  17030. /**
  17031. * Controls the thickness of the wireframe.
  17032. *
  17033. * Can only be used with {@link SVGRenderer}.
  17034. *
  17035. * @type {number}
  17036. * @default 1
  17037. */
  17038. this.wireframeLinewidth = 1;
  17039. /**
  17040. * Defines appearance of wireframe ends.
  17041. *
  17042. * Can only be used with {@link SVGRenderer}.
  17043. *
  17044. * @type {('round'|'bevel'|'miter')}
  17045. * @default 'round'
  17046. */
  17047. this.wireframeLinecap = 'round';
  17048. /**
  17049. * Defines appearance of wireframe joints.
  17050. *
  17051. * Can only be used with {@link SVGRenderer}.
  17052. *
  17053. * @type {('round'|'bevel'|'miter')}
  17054. * @default 'round'
  17055. */
  17056. this.wireframeLinejoin = 'round';
  17057. /**
  17058. * Whether the material is affected by fog or not.
  17059. *
  17060. * @type {boolean}
  17061. * @default true
  17062. */
  17063. this.fog = true;
  17064. this.setValues( parameters );
  17065. }
  17066. copy( source ) {
  17067. super.copy( source );
  17068. this.color.copy( source.color );
  17069. this.map = source.map;
  17070. this.lightMap = source.lightMap;
  17071. this.lightMapIntensity = source.lightMapIntensity;
  17072. this.aoMap = source.aoMap;
  17073. this.aoMapIntensity = source.aoMapIntensity;
  17074. this.specularMap = source.specularMap;
  17075. this.alphaMap = source.alphaMap;
  17076. this.envMap = source.envMap;
  17077. this.envMapRotation.copy( source.envMapRotation );
  17078. this.combine = source.combine;
  17079. this.reflectivity = source.reflectivity;
  17080. this.refractionRatio = source.refractionRatio;
  17081. this.wireframe = source.wireframe;
  17082. this.wireframeLinewidth = source.wireframeLinewidth;
  17083. this.wireframeLinecap = source.wireframeLinecap;
  17084. this.wireframeLinejoin = source.wireframeLinejoin;
  17085. this.fog = source.fog;
  17086. return this;
  17087. }
  17088. }
  17089. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  17090. const _ray$3 = /*@__PURE__*/ new Ray();
  17091. const _sphere$6 = /*@__PURE__*/ new Sphere();
  17092. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  17093. const _vA = /*@__PURE__*/ new Vector3();
  17094. const _vB = /*@__PURE__*/ new Vector3();
  17095. const _vC = /*@__PURE__*/ new Vector3();
  17096. const _tempA = /*@__PURE__*/ new Vector3();
  17097. const _morphA = /*@__PURE__*/ new Vector3();
  17098. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  17099. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  17100. /**
  17101. * Class representing triangular polygon mesh based objects.
  17102. *
  17103. * ```js
  17104. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  17105. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  17106. * const mesh = new THREE.Mesh( geometry, material );
  17107. * scene.add( mesh );
  17108. * ```
  17109. *
  17110. * @augments Object3D
  17111. */
  17112. class Mesh extends Object3D {
  17113. /**
  17114. * Constructs a new mesh.
  17115. *
  17116. * @param {BufferGeometry} [geometry] - The mesh geometry.
  17117. * @param {Material|Array<Material>} [material] - The mesh material.
  17118. */
  17119. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  17120. super();
  17121. /**
  17122. * This flag can be used for type testing.
  17123. *
  17124. * @type {boolean}
  17125. * @readonly
  17126. * @default true
  17127. */
  17128. this.isMesh = true;
  17129. this.type = 'Mesh';
  17130. /**
  17131. * The mesh geometry.
  17132. *
  17133. * @type {BufferGeometry}
  17134. */
  17135. this.geometry = geometry;
  17136. /**
  17137. * The mesh material.
  17138. *
  17139. * @type {Material|Array<Material>}
  17140. * @default MeshBasicMaterial
  17141. */
  17142. this.material = material;
  17143. /**
  17144. * A dictionary representing the morph targets in the geometry. The key is the
  17145. * morph targets name, the value its attribute index. This member is `undefined`
  17146. * by default and only set when morph targets are detected in the geometry.
  17147. *
  17148. * @type {Object<string,number>|undefined}
  17149. * @default undefined
  17150. */
  17151. this.morphTargetDictionary = undefined;
  17152. /**
  17153. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  17154. * is applied. This member is `undefined` by default and only set when morph targets are
  17155. * detected in the geometry.
  17156. *
  17157. * @type {Array<number>|undefined}
  17158. * @default undefined
  17159. */
  17160. this.morphTargetInfluences = undefined;
  17161. /**
  17162. * The number of instances of this mesh.
  17163. * Can only be used with {@link WebGPURenderer}.
  17164. *
  17165. * @type {number}
  17166. * @default 1
  17167. */
  17168. this.count = 1;
  17169. this.updateMorphTargets();
  17170. }
  17171. copy( source, recursive ) {
  17172. super.copy( source, recursive );
  17173. if ( source.morphTargetInfluences !== undefined ) {
  17174. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  17175. }
  17176. if ( source.morphTargetDictionary !== undefined ) {
  17177. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  17178. }
  17179. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  17180. this.geometry = source.geometry;
  17181. return this;
  17182. }
  17183. /**
  17184. * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences}
  17185. * to make sure existing morph targets can influence this 3D object.
  17186. */
  17187. updateMorphTargets() {
  17188. const geometry = this.geometry;
  17189. const morphAttributes = geometry.morphAttributes;
  17190. const keys = Object.keys( morphAttributes );
  17191. if ( keys.length > 0 ) {
  17192. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  17193. if ( morphAttribute !== undefined ) {
  17194. this.morphTargetInfluences = [];
  17195. this.morphTargetDictionary = {};
  17196. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  17197. const name = morphAttribute[ m ].name || String( m );
  17198. this.morphTargetInfluences.push( 0 );
  17199. this.morphTargetDictionary[ name ] = m;
  17200. }
  17201. }
  17202. }
  17203. }
  17204. /**
  17205. * Returns the local-space position of the vertex at the given index, taking into
  17206. * account the current animation state of both morph targets and skinning.
  17207. *
  17208. * @param {number} index - The vertex index.
  17209. * @param {Vector3} target - The target object that is used to store the method's result.
  17210. * @return {Vector3} The vertex position in local space.
  17211. */
  17212. getVertexPosition( index, target ) {
  17213. const geometry = this.geometry;
  17214. const position = geometry.attributes.position;
  17215. const morphPosition = geometry.morphAttributes.position;
  17216. const morphTargetsRelative = geometry.morphTargetsRelative;
  17217. target.fromBufferAttribute( position, index );
  17218. const morphInfluences = this.morphTargetInfluences;
  17219. if ( morphPosition && morphInfluences ) {
  17220. _morphA.set( 0, 0, 0 );
  17221. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  17222. const influence = morphInfluences[ i ];
  17223. const morphAttribute = morphPosition[ i ];
  17224. if ( influence === 0 ) continue;
  17225. _tempA.fromBufferAttribute( morphAttribute, index );
  17226. if ( morphTargetsRelative ) {
  17227. _morphA.addScaledVector( _tempA, influence );
  17228. } else {
  17229. _morphA.addScaledVector( _tempA.sub( target ), influence );
  17230. }
  17231. }
  17232. target.add( _morphA );
  17233. }
  17234. return target;
  17235. }
  17236. /**
  17237. * Computes intersection points between a casted ray and this line.
  17238. *
  17239. * @param {Raycaster} raycaster - The raycaster.
  17240. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  17241. */
  17242. raycast( raycaster, intersects ) {
  17243. const geometry = this.geometry;
  17244. const material = this.material;
  17245. const matrixWorld = this.matrixWorld;
  17246. if ( material === undefined ) return;
  17247. // test with bounding sphere in world space
  17248. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17249. _sphere$6.copy( geometry.boundingSphere );
  17250. _sphere$6.applyMatrix4( matrixWorld );
  17251. // check distance from ray origin to bounding sphere
  17252. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  17253. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  17254. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  17255. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  17256. }
  17257. // convert ray to local space of mesh
  17258. _inverseMatrix$3.copy( matrixWorld ).invert();
  17259. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  17260. // test with bounding box in local space
  17261. if ( geometry.boundingBox !== null ) {
  17262. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  17263. }
  17264. // test for intersections with geometry
  17265. this._computeIntersections( raycaster, intersects, _ray$3 );
  17266. }
  17267. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  17268. let intersection;
  17269. const geometry = this.geometry;
  17270. const material = this.material;
  17271. const index = geometry.index;
  17272. const position = geometry.attributes.position;
  17273. const uv = geometry.attributes.uv;
  17274. const uv1 = geometry.attributes.uv1;
  17275. const normal = geometry.attributes.normal;
  17276. const groups = geometry.groups;
  17277. const drawRange = geometry.drawRange;
  17278. if ( index !== null ) {
  17279. // indexed buffer geometry
  17280. if ( Array.isArray( material ) ) {
  17281. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  17282. const group = groups[ i ];
  17283. const groupMaterial = material[ group.materialIndex ];
  17284. const start = Math.max( group.start, drawRange.start );
  17285. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  17286. for ( let j = start, jl = end; j < jl; j += 3 ) {
  17287. const a = index.getX( j );
  17288. const b = index.getX( j + 1 );
  17289. const c = index.getX( j + 2 );
  17290. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  17291. if ( intersection ) {
  17292. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  17293. intersection.face.materialIndex = group.materialIndex;
  17294. intersects.push( intersection );
  17295. }
  17296. }
  17297. }
  17298. } else {
  17299. const start = Math.max( 0, drawRange.start );
  17300. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  17301. for ( let i = start, il = end; i < il; i += 3 ) {
  17302. const a = index.getX( i );
  17303. const b = index.getX( i + 1 );
  17304. const c = index.getX( i + 2 );
  17305. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  17306. if ( intersection ) {
  17307. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  17308. intersects.push( intersection );
  17309. }
  17310. }
  17311. }
  17312. } else if ( position !== undefined ) {
  17313. // non-indexed buffer geometry
  17314. if ( Array.isArray( material ) ) {
  17315. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  17316. const group = groups[ i ];
  17317. const groupMaterial = material[ group.materialIndex ];
  17318. const start = Math.max( group.start, drawRange.start );
  17319. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  17320. for ( let j = start, jl = end; j < jl; j += 3 ) {
  17321. const a = j;
  17322. const b = j + 1;
  17323. const c = j + 2;
  17324. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  17325. if ( intersection ) {
  17326. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  17327. intersection.face.materialIndex = group.materialIndex;
  17328. intersects.push( intersection );
  17329. }
  17330. }
  17331. }
  17332. } else {
  17333. const start = Math.max( 0, drawRange.start );
  17334. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  17335. for ( let i = start, il = end; i < il; i += 3 ) {
  17336. const a = i;
  17337. const b = i + 1;
  17338. const c = i + 2;
  17339. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  17340. if ( intersection ) {
  17341. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  17342. intersects.push( intersection );
  17343. }
  17344. }
  17345. }
  17346. }
  17347. }
  17348. }
  17349. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  17350. let intersect;
  17351. if ( material.side === BackSide ) {
  17352. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  17353. } else {
  17354. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  17355. }
  17356. if ( intersect === null ) return null;
  17357. _intersectionPointWorld.copy( point );
  17358. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  17359. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  17360. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  17361. return {
  17362. distance: distance,
  17363. point: _intersectionPointWorld.clone(),
  17364. object: object
  17365. };
  17366. }
  17367. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  17368. object.getVertexPosition( a, _vA );
  17369. object.getVertexPosition( b, _vB );
  17370. object.getVertexPosition( c, _vC );
  17371. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint );
  17372. if ( intersection ) {
  17373. const barycoord = new Vector3();
  17374. Triangle.getBarycoord( _intersectionPoint, _vA, _vB, _vC, barycoord );
  17375. if ( uv ) {
  17376. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  17377. }
  17378. if ( uv1 ) {
  17379. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  17380. }
  17381. if ( normal ) {
  17382. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  17383. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  17384. intersection.normal.multiplyScalar( -1 );
  17385. }
  17386. }
  17387. const face = {
  17388. a: a,
  17389. b: b,
  17390. c: c,
  17391. normal: new Vector3(),
  17392. materialIndex: 0
  17393. };
  17394. Triangle.getNormal( _vA, _vB, _vC, face.normal );
  17395. intersection.face = face;
  17396. intersection.barycoord = barycoord;
  17397. }
  17398. return intersection;
  17399. }
  17400. const _baseVector = /*@__PURE__*/ new Vector4();
  17401. const _skinIndex = /*@__PURE__*/ new Vector4();
  17402. const _skinWeight = /*@__PURE__*/ new Vector4();
  17403. const _vector4 = /*@__PURE__*/ new Vector4();
  17404. const _matrix4 = /*@__PURE__*/ new Matrix4();
  17405. const _vertex = /*@__PURE__*/ new Vector3();
  17406. const _sphere$5 = /*@__PURE__*/ new Sphere();
  17407. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  17408. const _ray$2 = /*@__PURE__*/ new Ray();
  17409. /**
  17410. * A mesh that has a {@link Skeleton} that can then be used to animate the
  17411. * vertices of the geometry with skinning/skeleton animation.
  17412. *
  17413. * Next to a valid skeleton, the skinned mesh requires skin indices and weights
  17414. * as buffer attributes in its geometry. These attribute define which bones affect a single
  17415. * vertex to a certain extend.
  17416. *
  17417. * Typically skinned meshes are not created manually but loaders like {@link GLTFLoader}
  17418. * or {@link FBXLoader } import respective models.
  17419. *
  17420. * @augments Mesh
  17421. * @demo scenes/bones-browser.html
  17422. */
  17423. class SkinnedMesh extends Mesh {
  17424. /**
  17425. * Constructs a new skinned mesh.
  17426. *
  17427. * @param {BufferGeometry} [geometry] - The mesh geometry.
  17428. * @param {Material|Array<Material>} [material] - The mesh material.
  17429. */
  17430. constructor( geometry, material ) {
  17431. super( geometry, material );
  17432. /**
  17433. * This flag can be used for type testing.
  17434. *
  17435. * @type {boolean}
  17436. * @readonly
  17437. * @default true
  17438. */
  17439. this.isSkinnedMesh = true;
  17440. this.type = 'SkinnedMesh';
  17441. /**
  17442. * `AttachedBindMode` means the skinned mesh shares the same world space as the skeleton.
  17443. * This is not true when using `DetachedBindMode` which is useful when sharing a skeleton
  17444. * across multiple skinned meshes.
  17445. *
  17446. * @type {(AttachedBindMode|DetachedBindMode)}
  17447. * @default AttachedBindMode
  17448. */
  17449. this.bindMode = AttachedBindMode;
  17450. /**
  17451. * The base matrix that is used for the bound bone transforms.
  17452. *
  17453. * @type {Matrix4}
  17454. */
  17455. this.bindMatrix = new Matrix4();
  17456. /**
  17457. * The base matrix that is used for resetting the bound bone transforms.
  17458. *
  17459. * @type {Matrix4}
  17460. */
  17461. this.bindMatrixInverse = new Matrix4();
  17462. /**
  17463. * The bounding box of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingBox}.
  17464. *
  17465. * @type {?Box3}
  17466. * @default null
  17467. */
  17468. this.boundingBox = null;
  17469. /**
  17470. * The bounding sphere of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingSphere}.
  17471. *
  17472. * @type {?Sphere}
  17473. * @default null
  17474. */
  17475. this.boundingSphere = null;
  17476. }
  17477. /**
  17478. * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}.
  17479. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  17480. * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect
  17481. * the current animation state.
  17482. */
  17483. computeBoundingBox() {
  17484. const geometry = this.geometry;
  17485. if ( this.boundingBox === null ) {
  17486. this.boundingBox = new Box3();
  17487. }
  17488. this.boundingBox.makeEmpty();
  17489. const positionAttribute = geometry.getAttribute( 'position' );
  17490. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  17491. this.getVertexPosition( i, _vertex );
  17492. this.boundingBox.expandByPoint( _vertex );
  17493. }
  17494. }
  17495. /**
  17496. * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}.
  17497. * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting
  17498. * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed
  17499. * per frame in order to reflect the current animation state.
  17500. */
  17501. computeBoundingSphere() {
  17502. const geometry = this.geometry;
  17503. if ( this.boundingSphere === null ) {
  17504. this.boundingSphere = new Sphere();
  17505. }
  17506. this.boundingSphere.makeEmpty();
  17507. const positionAttribute = geometry.getAttribute( 'position' );
  17508. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  17509. this.getVertexPosition( i, _vertex );
  17510. this.boundingSphere.expandByPoint( _vertex );
  17511. }
  17512. }
  17513. copy( source, recursive ) {
  17514. super.copy( source, recursive );
  17515. this.bindMode = source.bindMode;
  17516. this.bindMatrix.copy( source.bindMatrix );
  17517. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  17518. this.skeleton = source.skeleton;
  17519. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  17520. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  17521. return this;
  17522. }
  17523. raycast( raycaster, intersects ) {
  17524. const material = this.material;
  17525. const matrixWorld = this.matrixWorld;
  17526. if ( material === undefined ) return;
  17527. // test with bounding sphere in world space
  17528. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  17529. _sphere$5.copy( this.boundingSphere );
  17530. _sphere$5.applyMatrix4( matrixWorld );
  17531. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  17532. // convert ray to local space of skinned mesh
  17533. _inverseMatrix$2.copy( matrixWorld ).invert();
  17534. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  17535. // test with bounding box in local space
  17536. if ( this.boundingBox !== null ) {
  17537. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  17538. }
  17539. // test for intersections with geometry
  17540. this._computeIntersections( raycaster, intersects, _ray$2 );
  17541. }
  17542. getVertexPosition( index, target ) {
  17543. super.getVertexPosition( index, target );
  17544. this.applyBoneTransform( index, target );
  17545. return target;
  17546. }
  17547. /**
  17548. * Binds the given skeleton to the skinned mesh.
  17549. *
  17550. * @param {Skeleton} skeleton - The skeleton to bind.
  17551. * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided,
  17552. * the skinned mesh's world matrix will be used instead.
  17553. */
  17554. bind( skeleton, bindMatrix ) {
  17555. this.skeleton = skeleton;
  17556. if ( bindMatrix === undefined ) {
  17557. this.updateMatrixWorld( true );
  17558. this.skeleton.calculateInverses();
  17559. bindMatrix = this.matrixWorld;
  17560. }
  17561. this.bindMatrix.copy( bindMatrix );
  17562. this.bindMatrixInverse.copy( bindMatrix ).invert();
  17563. }
  17564. /**
  17565. * This method sets the skinned mesh in the rest pose).
  17566. */
  17567. pose() {
  17568. this.skeleton.pose();
  17569. }
  17570. /**
  17571. * Normalizes the skin weights which are defined as a buffer attribute
  17572. * in the skinned mesh's geometry.
  17573. */
  17574. normalizeSkinWeights() {
  17575. const vector = new Vector4();
  17576. const skinWeight = this.geometry.attributes.skinWeight;
  17577. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  17578. vector.fromBufferAttribute( skinWeight, i );
  17579. const scale = 1.0 / vector.manhattanLength();
  17580. if ( scale !== Infinity ) {
  17581. vector.multiplyScalar( scale );
  17582. } else {
  17583. vector.set( 1, 0, 0, 0 ); // do something reasonable
  17584. }
  17585. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  17586. }
  17587. }
  17588. updateMatrixWorld( force ) {
  17589. super.updateMatrixWorld( force );
  17590. if ( this.bindMode === AttachedBindMode ) {
  17591. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  17592. } else if ( this.bindMode === DetachedBindMode ) {
  17593. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  17594. } else {
  17595. warn( 'SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  17596. }
  17597. }
  17598. /**
  17599. * Applies the bone transform associated with the given index to the given
  17600. * vector. Can be used to transform positions or direction vectors by providing
  17601. * a Vector4 with 1 or 0 in the w component respectively. Returns the updated vector.
  17602. *
  17603. * @param {number} index - The vertex index.
  17604. * @param {Vector3|Vector4} target - The target object that is used to store the method's result.
  17605. * @return {Vector3|Vector4} The updated vertex attribute data.
  17606. */
  17607. applyBoneTransform( index, target ) {
  17608. const skeleton = this.skeleton;
  17609. const geometry = this.geometry;
  17610. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  17611. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  17612. if ( target.isVector4 ) {
  17613. _baseVector.copy( target );
  17614. target.set( 0, 0, 0, 0 );
  17615. } else {
  17616. _baseVector.set( ...target, 1 );
  17617. target.set( 0, 0, 0 );
  17618. }
  17619. _baseVector.applyMatrix4( this.bindMatrix );
  17620. for ( let i = 0; i < 4; i ++ ) {
  17621. const weight = _skinWeight.getComponent( i );
  17622. if ( weight !== 0 ) {
  17623. const boneIndex = _skinIndex.getComponent( i );
  17624. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  17625. target.addScaledVector( _vector4.copy( _baseVector ).applyMatrix4( _matrix4 ), weight );
  17626. }
  17627. }
  17628. if ( target.isVector4 ) {
  17629. // ensure the homogenous coordinate remains unchanged after vector operations
  17630. target.w = _baseVector.w;
  17631. }
  17632. return target.applyMatrix4( this.bindMatrixInverse );
  17633. }
  17634. }
  17635. /**
  17636. * A bone which is part of a {@link Skeleton}. The skeleton in turn is used by
  17637. * the {@link SkinnedMesh}.
  17638. *
  17639. * ```js
  17640. * const root = new THREE.Bone();
  17641. * const child = new THREE.Bone();
  17642. *
  17643. * root.add( child );
  17644. * child.position.y = 5;
  17645. * ```
  17646. *
  17647. * @augments Object3D
  17648. */
  17649. class Bone extends Object3D {
  17650. /**
  17651. * Constructs a new bone.
  17652. */
  17653. constructor() {
  17654. super();
  17655. /**
  17656. * This flag can be used for type testing.
  17657. *
  17658. * @type {boolean}
  17659. * @readonly
  17660. * @default true
  17661. */
  17662. this.isBone = true;
  17663. this.type = 'Bone';
  17664. }
  17665. }
  17666. /**
  17667. * Creates a texture directly from raw buffer data.
  17668. *
  17669. * The interpretation of the data depends on type and format: If the type is
  17670. * `UnsignedByteType`, a `Uint8Array` will be useful for addressing the
  17671. * texel data. If the format is `RGBAFormat`, data needs four values for
  17672. * one texel; Red, Green, Blue and Alpha (typically the opacity).
  17673. *
  17674. * @augments Texture
  17675. */
  17676. class DataTexture extends Texture {
  17677. /**
  17678. * Constructs a new data texture.
  17679. *
  17680. * @param {?TypedArray} [data=null] - The buffer data.
  17681. * @param {number} [width=1] - The width of the texture.
  17682. * @param {number} [height=1] - The height of the texture.
  17683. * @param {number} [format=RGBAFormat] - The texture format.
  17684. * @param {number} [type=UnsignedByteType] - The texture type.
  17685. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  17686. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  17687. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  17688. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  17689. * @param {number} [minFilter=NearestFilter] - The min filter value.
  17690. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  17691. * @param {string} [colorSpace=NoColorSpace] - The color space.
  17692. */
  17693. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  17694. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  17695. /**
  17696. * This flag can be used for type testing.
  17697. *
  17698. * @type {boolean}
  17699. * @readonly
  17700. * @default true
  17701. */
  17702. this.isDataTexture = true;
  17703. /**
  17704. * The image definition of a data texture.
  17705. *
  17706. * @type {{data:TypedArray,width:number,height:number}}
  17707. */
  17708. this.image = { data: data, width: width, height: height };
  17709. /**
  17710. * Whether to generate mipmaps (if possible) for a texture.
  17711. *
  17712. * Overwritten and set to `false` by default.
  17713. *
  17714. * @type {boolean}
  17715. * @default false
  17716. */
  17717. this.generateMipmaps = false;
  17718. /**
  17719. * If set to `true`, the texture is flipped along the vertical axis when
  17720. * uploaded to the GPU.
  17721. *
  17722. * Overwritten and set to `false` by default.
  17723. *
  17724. * @type {boolean}
  17725. * @default false
  17726. */
  17727. this.flipY = false;
  17728. /**
  17729. * Specifies the alignment requirements for the start of each pixel row in memory.
  17730. *
  17731. * Overwritten and set to `1` by default.
  17732. *
  17733. * @type {boolean}
  17734. * @default 1
  17735. */
  17736. this.unpackAlignment = 1;
  17737. }
  17738. }
  17739. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  17740. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  17741. /**
  17742. * Class for representing the armatures in `three.js`. The skeleton
  17743. * is defined by a hierarchy of bones.
  17744. *
  17745. * ```js
  17746. * const bones = [];
  17747. *
  17748. * const shoulder = new THREE.Bone();
  17749. * const elbow = new THREE.Bone();
  17750. * const hand = new THREE.Bone();
  17751. *
  17752. * shoulder.add( elbow );
  17753. * elbow.add( hand );
  17754. *
  17755. * bones.push( shoulder , elbow, hand);
  17756. *
  17757. * shoulder.position.y = -5;
  17758. * elbow.position.y = 0;
  17759. * hand.position.y = 5;
  17760. *
  17761. * const armSkeleton = new THREE.Skeleton( bones );
  17762. * ```
  17763. */
  17764. class Skeleton {
  17765. /**
  17766. * Constructs a new skeleton.
  17767. *
  17768. * @param {Array<Bone>} [bones] - An array of bones.
  17769. * @param {Array<Matrix4>} [boneInverses] - An array of bone inverse matrices.
  17770. * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}.
  17771. */
  17772. constructor( bones = [], boneInverses = [] ) {
  17773. this.uuid = generateUUID();
  17774. /**
  17775. * An array of bones defining the skeleton.
  17776. *
  17777. * @type {Array<Bone>}
  17778. */
  17779. this.bones = bones.slice( 0 );
  17780. /**
  17781. * An array of bone inverse matrices.
  17782. *
  17783. * @type {Array<Matrix4>}
  17784. */
  17785. this.boneInverses = boneInverses;
  17786. /**
  17787. * An array buffer holding the bone data.
  17788. * Input data for {@link Skeleton#boneTexture}.
  17789. *
  17790. * @type {?Float32Array}
  17791. * @default null
  17792. */
  17793. this.boneMatrices = null;
  17794. /**
  17795. * An array buffer holding the bone data of the previous frame.
  17796. * Required for computing velocity. Maintained in {@link SkinningNode}.
  17797. *
  17798. * @type {?Float32Array}
  17799. * @default null
  17800. */
  17801. this.previousBoneMatrices = null;
  17802. /**
  17803. * A texture holding the bone data for use
  17804. * in the vertex shader.
  17805. *
  17806. * @type {?DataTexture}
  17807. * @default null
  17808. */
  17809. this.boneTexture = null;
  17810. this.init();
  17811. }
  17812. /**
  17813. * Initializes the skeleton. This method gets automatically called by the constructor
  17814. * but depending on how the skeleton is created it might be necessary to call this method
  17815. * manually.
  17816. */
  17817. init() {
  17818. const bones = this.bones;
  17819. const boneInverses = this.boneInverses;
  17820. this.boneMatrices = new Float32Array( bones.length * 16 );
  17821. // calculate inverse bone matrices if necessary
  17822. if ( boneInverses.length === 0 ) {
  17823. this.calculateInverses();
  17824. } else {
  17825. // handle special case
  17826. if ( bones.length !== boneInverses.length ) {
  17827. warn( 'Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  17828. this.boneInverses = [];
  17829. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17830. this.boneInverses.push( new Matrix4() );
  17831. }
  17832. }
  17833. }
  17834. }
  17835. /**
  17836. * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses}
  17837. * and fills it with new matrices.
  17838. */
  17839. calculateInverses() {
  17840. this.boneInverses.length = 0;
  17841. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17842. const inverse = new Matrix4();
  17843. if ( this.bones[ i ] ) {
  17844. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  17845. }
  17846. this.boneInverses.push( inverse );
  17847. }
  17848. }
  17849. /**
  17850. * Resets the skeleton to the base pose.
  17851. */
  17852. pose() {
  17853. // recover the bind-time world matrices
  17854. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17855. const bone = this.bones[ i ];
  17856. if ( bone ) {
  17857. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  17858. }
  17859. }
  17860. // compute the local matrices, positions, rotations and scales
  17861. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17862. const bone = this.bones[ i ];
  17863. if ( bone ) {
  17864. if ( bone.parent && bone.parent.isBone ) {
  17865. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  17866. bone.matrix.multiply( bone.matrixWorld );
  17867. } else {
  17868. bone.matrix.copy( bone.matrixWorld );
  17869. }
  17870. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  17871. }
  17872. }
  17873. }
  17874. /**
  17875. * Resets the skeleton to the base pose.
  17876. */
  17877. update() {
  17878. const bones = this.bones;
  17879. const boneInverses = this.boneInverses;
  17880. const boneMatrices = this.boneMatrices;
  17881. const boneTexture = this.boneTexture;
  17882. // flatten bone matrices to array
  17883. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  17884. // compute the offset between the current and the original transform
  17885. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  17886. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  17887. _offsetMatrix.toArray( boneMatrices, i * 16 );
  17888. }
  17889. if ( boneTexture !== null ) {
  17890. boneTexture.needsUpdate = true;
  17891. }
  17892. }
  17893. /**
  17894. * Returns a new skeleton with copied values from this instance.
  17895. *
  17896. * @return {Skeleton} A clone of this instance.
  17897. */
  17898. clone() {
  17899. return new Skeleton( this.bones, this.boneInverses );
  17900. }
  17901. /**
  17902. * Computes a data texture for passing bone data to the vertex shader.
  17903. *
  17904. * @return {Skeleton} A reference of this instance.
  17905. */
  17906. computeBoneTexture() {
  17907. // layout (1 matrix = 4 pixels)
  17908. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  17909. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  17910. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  17911. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  17912. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  17913. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  17914. size = Math.ceil( size / 4 ) * 4;
  17915. size = Math.max( size, 4 );
  17916. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  17917. boneMatrices.set( this.boneMatrices ); // copy current values
  17918. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  17919. boneTexture.needsUpdate = true;
  17920. this.boneMatrices = boneMatrices;
  17921. this.boneTexture = boneTexture;
  17922. return this;
  17923. }
  17924. /**
  17925. * Searches through the skeleton's bone array and returns the first with a
  17926. * matching name.
  17927. *
  17928. * @param {string} name - The name of the bone.
  17929. * @return {Bone|undefined} The found bone. `undefined` if no bone has been found.
  17930. */
  17931. getBoneByName( name ) {
  17932. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17933. const bone = this.bones[ i ];
  17934. if ( bone.name === name ) {
  17935. return bone;
  17936. }
  17937. }
  17938. return undefined;
  17939. }
  17940. /**
  17941. * Frees the GPU-related resources allocated by this instance. Call this
  17942. * method whenever this instance is no longer used in your app.
  17943. */
  17944. dispose( ) {
  17945. if ( this.boneTexture !== null ) {
  17946. this.boneTexture.dispose();
  17947. this.boneTexture = null;
  17948. }
  17949. }
  17950. /**
  17951. * Setups the skeleton by the given JSON and bones.
  17952. *
  17953. * @param {Object} json - The skeleton as serialized JSON.
  17954. * @param {Object<string, Bone>} bones - An array of bones.
  17955. * @return {Skeleton} A reference of this instance.
  17956. */
  17957. fromJSON( json, bones ) {
  17958. this.uuid = json.uuid;
  17959. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  17960. const uuid = json.bones[ i ];
  17961. let bone = bones[ uuid ];
  17962. if ( bone === undefined ) {
  17963. warn( 'Skeleton: No bone found with UUID:', uuid );
  17964. bone = new Bone();
  17965. }
  17966. this.bones.push( bone );
  17967. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  17968. }
  17969. this.init();
  17970. return this;
  17971. }
  17972. /**
  17973. * Serializes the skeleton into JSON.
  17974. *
  17975. * @return {Object} A JSON object representing the serialized skeleton.
  17976. * @see {@link ObjectLoader#parse}
  17977. */
  17978. toJSON() {
  17979. const data = {
  17980. metadata: {
  17981. version: 4.7,
  17982. type: 'Skeleton',
  17983. generator: 'Skeleton.toJSON'
  17984. },
  17985. bones: [],
  17986. boneInverses: []
  17987. };
  17988. data.uuid = this.uuid;
  17989. const bones = this.bones;
  17990. const boneInverses = this.boneInverses;
  17991. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  17992. const bone = bones[ i ];
  17993. data.bones.push( bone.uuid );
  17994. const boneInverse = boneInverses[ i ];
  17995. data.boneInverses.push( boneInverse.toArray() );
  17996. }
  17997. return data;
  17998. }
  17999. }
  18000. /**
  18001. * An instanced version of a buffer attribute.
  18002. *
  18003. * @augments BufferAttribute
  18004. */
  18005. class InstancedBufferAttribute extends BufferAttribute {
  18006. /**
  18007. * Constructs a new instanced buffer attribute.
  18008. *
  18009. * @param {TypedArray} array - The array holding the attribute data.
  18010. * @param {number} itemSize - The item size.
  18011. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  18012. * @param {number} [meshPerAttribute=1] - How often a value of this buffer attribute should be repeated.
  18013. */
  18014. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  18015. super( array, itemSize, normalized );
  18016. /**
  18017. * This flag can be used for type testing.
  18018. *
  18019. * @type {boolean}
  18020. * @readonly
  18021. * @default true
  18022. */
  18023. this.isInstancedBufferAttribute = true;
  18024. /**
  18025. * Defines how often a value of this buffer attribute should be repeated. A
  18026. * value of one means that each value of the instanced attribute is used for
  18027. * a single instance. A value of two means that each value is used for two
  18028. * consecutive instances (and so on).
  18029. *
  18030. * @type {number}
  18031. * @default 1
  18032. */
  18033. this.meshPerAttribute = meshPerAttribute;
  18034. }
  18035. copy( source ) {
  18036. super.copy( source );
  18037. this.meshPerAttribute = source.meshPerAttribute;
  18038. return this;
  18039. }
  18040. toJSON() {
  18041. const data = super.toJSON();
  18042. data.meshPerAttribute = this.meshPerAttribute;
  18043. data.isInstancedBufferAttribute = true;
  18044. return data;
  18045. }
  18046. }
  18047. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  18048. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  18049. const _instanceIntersects = [];
  18050. const _box3 = /*@__PURE__*/ new Box3();
  18051. const _identity = /*@__PURE__*/ new Matrix4();
  18052. const _mesh$1 = /*@__PURE__*/ new Mesh();
  18053. const _sphere$4 = /*@__PURE__*/ new Sphere();
  18054. /**
  18055. * A special version of a mesh with instanced rendering support. Use
  18056. * this class if you have to render a large number of objects with the same
  18057. * geometry and material(s) but with different world transformations. The usage
  18058. * of 'InstancedMesh' will help you to reduce the number of draw calls and thus
  18059. * improve the overall rendering performance in your application.
  18060. *
  18061. * @augments Mesh
  18062. */
  18063. class InstancedMesh extends Mesh {
  18064. /**
  18065. * Constructs a new instanced mesh.
  18066. *
  18067. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18068. * @param {Material|Array<Material>} [material] - The mesh material.
  18069. * @param {number} count - The number of instances.
  18070. */
  18071. constructor( geometry, material, count ) {
  18072. super( geometry, material );
  18073. /**
  18074. * This flag can be used for type testing.
  18075. *
  18076. * @type {boolean}
  18077. * @readonly
  18078. * @default true
  18079. */
  18080. this.isInstancedMesh = true;
  18081. /**
  18082. * Represents the local transformation of all instances. You have to set its
  18083. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18084. * via {@link InstancedMesh#setMatrixAt}.
  18085. *
  18086. * @type {InstancedBufferAttribute}
  18087. */
  18088. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  18089. /**
  18090. * Represents the local transformation of all instances of the previous frame.
  18091. * Required for computing velocity. Maintained in {@link InstanceNode}.
  18092. *
  18093. * @type {?InstancedBufferAttribute}
  18094. * @default null
  18095. */
  18096. this.previousInstanceMatrix = null;
  18097. /**
  18098. * Represents the color of all instances. You have to set its
  18099. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18100. * via {@link InstancedMesh#setColorAt}.
  18101. *
  18102. * @type {?InstancedBufferAttribute}
  18103. * @default null
  18104. */
  18105. this.instanceColor = null;
  18106. /**
  18107. * Represents the morph target weights of all instances. You have to set its
  18108. * {@link Texture#needsUpdate} flag to true if you modify instanced data
  18109. * via {@link InstancedMesh#setMorphAt}.
  18110. *
  18111. * @type {?DataTexture}
  18112. * @default null
  18113. */
  18114. this.morphTexture = null;
  18115. /**
  18116. * The number of instances.
  18117. *
  18118. * @type {number}
  18119. */
  18120. this.count = count;
  18121. /**
  18122. * The bounding box of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingBox}.
  18123. *
  18124. * @type {?Box3}
  18125. * @default null
  18126. */
  18127. this.boundingBox = null;
  18128. /**
  18129. * The bounding sphere of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingSphere}.
  18130. *
  18131. * @type {?Sphere}
  18132. * @default null
  18133. */
  18134. this.boundingSphere = null;
  18135. for ( let i = 0; i < count; i ++ ) {
  18136. this.setMatrixAt( i, _identity );
  18137. }
  18138. }
  18139. /**
  18140. * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}.
  18141. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  18142. * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  18143. */
  18144. computeBoundingBox() {
  18145. const geometry = this.geometry;
  18146. const count = this.count;
  18147. if ( this.boundingBox === null ) {
  18148. this.boundingBox = new Box3();
  18149. }
  18150. if ( geometry.boundingBox === null ) {
  18151. geometry.computeBoundingBox();
  18152. }
  18153. this.boundingBox.makeEmpty();
  18154. for ( let i = 0; i < count; i ++ ) {
  18155. this.getMatrixAt( i, _instanceLocalMatrix );
  18156. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  18157. this.boundingBox.union( _box3 );
  18158. }
  18159. }
  18160. /**
  18161. * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere}
  18162. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  18163. * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  18164. */
  18165. computeBoundingSphere() {
  18166. const geometry = this.geometry;
  18167. const count = this.count;
  18168. if ( this.boundingSphere === null ) {
  18169. this.boundingSphere = new Sphere();
  18170. }
  18171. if ( geometry.boundingSphere === null ) {
  18172. geometry.computeBoundingSphere();
  18173. }
  18174. this.boundingSphere.makeEmpty();
  18175. for ( let i = 0; i < count; i ++ ) {
  18176. this.getMatrixAt( i, _instanceLocalMatrix );
  18177. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  18178. this.boundingSphere.union( _sphere$4 );
  18179. }
  18180. }
  18181. copy( source, recursive ) {
  18182. super.copy( source, recursive );
  18183. this.instanceMatrix.copy( source.instanceMatrix );
  18184. if ( source.previousInstanceMatrix !== null ) this.previousInstanceMatrix = source.previousInstanceMatrix.clone();
  18185. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  18186. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  18187. this.count = source.count;
  18188. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18189. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18190. return this;
  18191. }
  18192. /**
  18193. * Gets the color of the defined instance.
  18194. *
  18195. * @param {number} index - The instance index.
  18196. * @param {Color} color - The target object that is used to store the method's result.
  18197. * @return {Color} A reference to the target color.
  18198. */
  18199. getColorAt( index, color ) {
  18200. if ( this.instanceColor === null ) {
  18201. return color.setRGB( 1, 1, 1 );
  18202. } else {
  18203. return color.fromArray( this.instanceColor.array, index * 3 );
  18204. }
  18205. }
  18206. /**
  18207. * Gets the local transformation matrix of the defined instance.
  18208. *
  18209. * @param {number} index - The instance index.
  18210. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  18211. * @return {Matrix4} A reference to the target matrix.
  18212. */
  18213. getMatrixAt( index, matrix ) {
  18214. return matrix.fromArray( this.instanceMatrix.array, index * 16 );
  18215. }
  18216. /**
  18217. * Gets the morph target weights of the defined instance.
  18218. *
  18219. * @param {number} index - The instance index.
  18220. * @param {Mesh} object - The target object that is used to store the method's result.
  18221. */
  18222. getMorphAt( index, object ) {
  18223. const objectInfluences = object.morphTargetInfluences;
  18224. const array = this.morphTexture.source.data.data;
  18225. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  18226. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  18227. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  18228. objectInfluences[ i ] = array[ dataIndex + i ];
  18229. }
  18230. }
  18231. raycast( raycaster, intersects ) {
  18232. const matrixWorld = this.matrixWorld;
  18233. const raycastTimes = this.count;
  18234. _mesh$1.geometry = this.geometry;
  18235. _mesh$1.material = this.material;
  18236. if ( _mesh$1.material === undefined ) return;
  18237. // test with bounding sphere first
  18238. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18239. _sphere$4.copy( this.boundingSphere );
  18240. _sphere$4.applyMatrix4( matrixWorld );
  18241. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  18242. // now test each instance
  18243. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  18244. // calculate the world matrix for each instance
  18245. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  18246. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  18247. // the mesh represents this single instance
  18248. _mesh$1.matrixWorld = _instanceWorldMatrix;
  18249. _mesh$1.raycast( raycaster, _instanceIntersects );
  18250. // process the result of raycast
  18251. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  18252. const intersect = _instanceIntersects[ i ];
  18253. intersect.instanceId = instanceId;
  18254. intersect.object = this;
  18255. intersects.push( intersect );
  18256. }
  18257. _instanceIntersects.length = 0;
  18258. }
  18259. }
  18260. /**
  18261. * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of
  18262. * {@link InstancedMesh#instanceColor} to `true` after updating all the colors.
  18263. *
  18264. * @param {number} index - The instance index.
  18265. * @param {Color} color - The instance color.
  18266. * @return {InstancedMesh} A reference to this instanced mesh.
  18267. */
  18268. setColorAt( index, color ) {
  18269. if ( this.instanceColor === null ) {
  18270. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  18271. }
  18272. color.toArray( this.instanceColor.array, index * 3 );
  18273. return this;
  18274. }
  18275. /**
  18276. * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of
  18277. * {@link InstancedMesh#instanceMatrix} to `true` after updating all the colors.
  18278. *
  18279. * @param {number} index - The instance index.
  18280. * @param {Matrix4} matrix - The local transformation.
  18281. * @return {InstancedMesh} A reference to this instanced mesh.
  18282. */
  18283. setMatrixAt( index, matrix ) {
  18284. matrix.toArray( this.instanceMatrix.array, index * 16 );
  18285. return this;
  18286. }
  18287. /**
  18288. * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of
  18289. * {@link InstancedMesh#morphTexture} to `true` after updating all the influences.
  18290. *
  18291. * @param {number} index - The instance index.
  18292. * @param {Mesh} object - A mesh which `morphTargetInfluences` property containing the morph target weights
  18293. * of a single instance.
  18294. * @return {InstancedMesh} A reference to this instanced mesh.
  18295. */
  18296. setMorphAt( index, object ) {
  18297. const objectInfluences = object.morphTargetInfluences;
  18298. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  18299. if ( this.morphTexture === null ) {
  18300. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  18301. }
  18302. const array = this.morphTexture.source.data.data;
  18303. let morphInfluencesSum = 0;
  18304. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  18305. morphInfluencesSum += objectInfluences[ i ];
  18306. }
  18307. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  18308. const dataIndex = len * index;
  18309. array[ dataIndex ] = morphBaseInfluence;
  18310. array.set( objectInfluences, dataIndex + 1 );
  18311. return this;
  18312. }
  18313. updateMorphTargets() {
  18314. }
  18315. /**
  18316. * Frees the GPU-related resources allocated by this instance. Call this
  18317. * method whenever this instance is no longer used in your app.
  18318. */
  18319. dispose() {
  18320. this.dispatchEvent( { type: 'dispose' } );
  18321. if ( this.morphTexture !== null ) {
  18322. this.morphTexture.dispose();
  18323. this.morphTexture = null;
  18324. }
  18325. }
  18326. }
  18327. const _vector1 = /*@__PURE__*/ new Vector3();
  18328. const _vector2 = /*@__PURE__*/ new Vector3();
  18329. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  18330. /**
  18331. * A two dimensional surface that extends infinitely in 3D space, represented
  18332. * in [Hessian normal form](http://mathworld.wolfram.com/HessianNormalForm.html)
  18333. * by a unit length normal vector and a constant.
  18334. */
  18335. class Plane {
  18336. /**
  18337. * Constructs a new plane.
  18338. *
  18339. * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane.
  18340. * @param {number} [constant=0] - The signed distance from the origin to the plane.
  18341. */
  18342. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  18343. /**
  18344. * This flag can be used for type testing.
  18345. *
  18346. * @type {boolean}
  18347. * @readonly
  18348. * @default true
  18349. */
  18350. this.isPlane = true;
  18351. /**
  18352. * A unit length vector defining the normal of the plane.
  18353. *
  18354. * @type {Vector3}
  18355. */
  18356. this.normal = normal;
  18357. /**
  18358. * The signed distance from the origin to the plane.
  18359. *
  18360. * @type {number}
  18361. * @default 0
  18362. */
  18363. this.constant = constant;
  18364. }
  18365. /**
  18366. * Sets the plane components by copying the given values.
  18367. *
  18368. * @param {Vector3} normal - The normal.
  18369. * @param {number} constant - The constant.
  18370. * @return {Plane} A reference to this plane.
  18371. */
  18372. set( normal, constant ) {
  18373. this.normal.copy( normal );
  18374. this.constant = constant;
  18375. return this;
  18376. }
  18377. /**
  18378. * Sets the plane components by defining `x`, `y`, `z` as the
  18379. * plane normal and `w` as the constant.
  18380. *
  18381. * @param {number} x - The value for the normal's x component.
  18382. * @param {number} y - The value for the normal's y component.
  18383. * @param {number} z - The value for the normal's z component.
  18384. * @param {number} w - The constant value.
  18385. * @return {Plane} A reference to this plane.
  18386. */
  18387. setComponents( x, y, z, w ) {
  18388. this.normal.set( x, y, z );
  18389. this.constant = w;
  18390. return this;
  18391. }
  18392. /**
  18393. * Sets the plane from the given normal and coplanar point (that is a point
  18394. * that lies onto the plane).
  18395. *
  18396. * @param {Vector3} normal - The normal.
  18397. * @param {Vector3} point - A coplanar point.
  18398. * @return {Plane} A reference to this plane.
  18399. */
  18400. setFromNormalAndCoplanarPoint( normal, point ) {
  18401. this.normal.copy( normal );
  18402. this.constant = - point.dot( this.normal );
  18403. return this;
  18404. }
  18405. /**
  18406. * Sets the plane from three coplanar points. The winding order is
  18407. * assumed to be counter-clockwise, and determines the direction of
  18408. * the plane normal.
  18409. *
  18410. * @param {Vector3} a - The first coplanar point.
  18411. * @param {Vector3} b - The second coplanar point.
  18412. * @param {Vector3} c - The third coplanar point.
  18413. * @return {Plane} A reference to this plane.
  18414. */
  18415. setFromCoplanarPoints( a, b, c ) {
  18416. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  18417. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  18418. this.setFromNormalAndCoplanarPoint( normal, a );
  18419. return this;
  18420. }
  18421. /**
  18422. * Copies the values of the given plane to this instance.
  18423. *
  18424. * @param {Plane} plane - The plane to copy.
  18425. * @return {Plane} A reference to this plane.
  18426. */
  18427. copy( plane ) {
  18428. this.normal.copy( plane.normal );
  18429. this.constant = plane.constant;
  18430. return this;
  18431. }
  18432. /**
  18433. * Normalizes the plane normal and adjusts the constant accordingly.
  18434. *
  18435. * @return {Plane} A reference to this plane.
  18436. */
  18437. normalize() {
  18438. // Note: will lead to a divide by zero if the plane is invalid.
  18439. const inverseNormalLength = 1.0 / this.normal.length();
  18440. this.normal.multiplyScalar( inverseNormalLength );
  18441. this.constant *= inverseNormalLength;
  18442. return this;
  18443. }
  18444. /**
  18445. * Negates both the plane normal and the constant.
  18446. *
  18447. * @return {Plane} A reference to this plane.
  18448. */
  18449. negate() {
  18450. this.constant *= -1;
  18451. this.normal.negate();
  18452. return this;
  18453. }
  18454. /**
  18455. * Returns the signed distance from the given point to this plane.
  18456. *
  18457. * @param {Vector3} point - The point to compute the distance for.
  18458. * @return {number} The signed distance.
  18459. */
  18460. distanceToPoint( point ) {
  18461. return this.normal.dot( point ) + this.constant;
  18462. }
  18463. /**
  18464. * Returns the signed distance from the given sphere to this plane.
  18465. *
  18466. * @param {Sphere} sphere - The sphere to compute the distance for.
  18467. * @return {number} The signed distance.
  18468. */
  18469. distanceToSphere( sphere ) {
  18470. return this.distanceToPoint( sphere.center ) - sphere.radius;
  18471. }
  18472. /**
  18473. * Projects a the given point onto the plane.
  18474. *
  18475. * @param {Vector3} point - The point to project.
  18476. * @param {Vector3} target - The target vector that is used to store the method's result.
  18477. * @return {Vector3} The projected point on the plane.
  18478. */
  18479. projectPoint( point, target ) {
  18480. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  18481. }
  18482. /**
  18483. * Returns the intersection point of the passed line and the plane. Returns
  18484. * `null` if the line does not intersect. Returns the line's starting point if
  18485. * the line is coplanar with the plane.
  18486. *
  18487. * @param {Line3} line - The line to compute the intersection for.
  18488. * @param {Vector3} target - The target vector that is used to store the method's result.
  18489. * @return {?Vector3} The intersection point.
  18490. */
  18491. intersectLine( line, target ) {
  18492. const direction = line.delta( _vector1 );
  18493. const denominator = this.normal.dot( direction );
  18494. if ( denominator === 0 ) {
  18495. // line is coplanar, return origin
  18496. if ( this.distanceToPoint( line.start ) === 0 ) {
  18497. return target.copy( line.start );
  18498. }
  18499. // Unsure if this is the correct method to handle this case.
  18500. return null;
  18501. }
  18502. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  18503. if ( t < 0 || t > 1 ) {
  18504. return null;
  18505. }
  18506. return target.copy( line.start ).addScaledVector( direction, t );
  18507. }
  18508. /**
  18509. * Returns `true` if the given line segment intersects with (passes through) the plane.
  18510. *
  18511. * @param {Line3} line - The line to test.
  18512. * @return {boolean} Whether the given line segment intersects with the plane or not.
  18513. */
  18514. intersectsLine( line ) {
  18515. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  18516. const startSign = this.distanceToPoint( line.start );
  18517. const endSign = this.distanceToPoint( line.end );
  18518. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  18519. }
  18520. /**
  18521. * Returns `true` if the given bounding box intersects with the plane.
  18522. *
  18523. * @param {Box3} box - The bounding box to test.
  18524. * @return {boolean} Whether the given bounding box intersects with the plane or not.
  18525. */
  18526. intersectsBox( box ) {
  18527. return box.intersectsPlane( this );
  18528. }
  18529. /**
  18530. * Returns `true` if the given bounding sphere intersects with the plane.
  18531. *
  18532. * @param {Sphere} sphere - The bounding sphere to test.
  18533. * @return {boolean} Whether the given bounding sphere intersects with the plane or not.
  18534. */
  18535. intersectsSphere( sphere ) {
  18536. return sphere.intersectsPlane( this );
  18537. }
  18538. /**
  18539. * Returns a coplanar vector to the plane, by calculating the
  18540. * projection of the normal at the origin onto the plane.
  18541. *
  18542. * @param {Vector3} target - The target vector that is used to store the method's result.
  18543. * @return {Vector3} The coplanar point.
  18544. */
  18545. coplanarPoint( target ) {
  18546. return target.copy( this.normal ).multiplyScalar( - this.constant );
  18547. }
  18548. /**
  18549. * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform.
  18550. *
  18551. * The optional normal matrix can be pre-computed like so:
  18552. * ```js
  18553. * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  18554. * ```
  18555. *
  18556. * @param {Matrix4} matrix - The transformation matrix.
  18557. * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix.
  18558. * @return {Plane} A reference to this plane.
  18559. */
  18560. applyMatrix4( matrix, optionalNormalMatrix ) {
  18561. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  18562. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  18563. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  18564. this.constant = - referencePoint.dot( normal );
  18565. return this;
  18566. }
  18567. /**
  18568. * Translates the plane by the distance defined by the given offset vector.
  18569. * Note that this only affects the plane constant and will not affect the normal vector.
  18570. *
  18571. * @param {Vector3} offset - The offset vector.
  18572. * @return {Plane} A reference to this plane.
  18573. */
  18574. translate( offset ) {
  18575. this.constant -= offset.dot( this.normal );
  18576. return this;
  18577. }
  18578. /**
  18579. * Returns `true` if this plane is equal with the given one.
  18580. *
  18581. * @param {Plane} plane - The plane to test for equality.
  18582. * @return {boolean} Whether this plane is equal with the given one.
  18583. */
  18584. equals( plane ) {
  18585. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  18586. }
  18587. /**
  18588. * Returns a new plane with copied values from this instance.
  18589. *
  18590. * @return {Plane} A clone of this instance.
  18591. */
  18592. clone() {
  18593. return new this.constructor().copy( this );
  18594. }
  18595. }
  18596. const _sphere$3 = /*@__PURE__*/ new Sphere();
  18597. const _defaultSpriteCenter = /*@__PURE__*/ new Vector2( 0.5, 0.5 );
  18598. const _vector$6 = /*@__PURE__*/ new Vector3();
  18599. /**
  18600. * Frustums are used to determine what is inside the camera's field of view.
  18601. * They help speed up the rendering process - objects which lie outside a camera's
  18602. * frustum can safely be excluded from rendering.
  18603. *
  18604. * This class is mainly intended for use internally by a renderer.
  18605. */
  18606. class Frustum {
  18607. /**
  18608. * Constructs a new frustum.
  18609. *
  18610. * @param {Plane} [p0] - The first plane that encloses the frustum.
  18611. * @param {Plane} [p1] - The second plane that encloses the frustum.
  18612. * @param {Plane} [p2] - The third plane that encloses the frustum.
  18613. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  18614. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  18615. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  18616. */
  18617. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  18618. /**
  18619. * This array holds the planes that enclose the frustum.
  18620. *
  18621. * @type {Array<Plane>}
  18622. */
  18623. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  18624. }
  18625. /**
  18626. * Sets the frustum planes by copying the given planes.
  18627. *
  18628. * @param {Plane} [p0] - The first plane that encloses the frustum.
  18629. * @param {Plane} [p1] - The second plane that encloses the frustum.
  18630. * @param {Plane} [p2] - The third plane that encloses the frustum.
  18631. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  18632. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  18633. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  18634. * @return {Frustum} A reference to this frustum.
  18635. */
  18636. set( p0, p1, p2, p3, p4, p5 ) {
  18637. const planes = this.planes;
  18638. planes[ 0 ].copy( p0 );
  18639. planes[ 1 ].copy( p1 );
  18640. planes[ 2 ].copy( p2 );
  18641. planes[ 3 ].copy( p3 );
  18642. planes[ 4 ].copy( p4 );
  18643. planes[ 5 ].copy( p5 );
  18644. return this;
  18645. }
  18646. /**
  18647. * Copies the values of the given frustum to this instance.
  18648. *
  18649. * @param {Frustum} frustum - The frustum to copy.
  18650. * @return {Frustum} A reference to this frustum.
  18651. */
  18652. copy( frustum ) {
  18653. const planes = this.planes;
  18654. for ( let i = 0; i < 6; i ++ ) {
  18655. planes[ i ].copy( frustum.planes[ i ] );
  18656. }
  18657. return this;
  18658. }
  18659. /**
  18660. * Sets the frustum planes from the given projection matrix.
  18661. *
  18662. * @param {Matrix4} m - The projection matrix.
  18663. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system.
  18664. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  18665. * @return {Frustum} A reference to this frustum.
  18666. */
  18667. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  18668. const planes = this.planes;
  18669. const me = m.elements;
  18670. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  18671. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  18672. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  18673. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  18674. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  18675. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  18676. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  18677. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  18678. if ( reversedDepth ) {
  18679. planes[ 4 ].setComponents( me2, me6, me10, me14 ).normalize(); // far
  18680. planes[ 5 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // near
  18681. } else {
  18682. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // far
  18683. if ( coordinateSystem === WebGLCoordinateSystem ) {
  18684. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); // near
  18685. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  18686. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize(); // near
  18687. } else {
  18688. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  18689. }
  18690. }
  18691. return this;
  18692. }
  18693. /**
  18694. * Returns `true` if the 3D object's bounding sphere is intersecting this frustum.
  18695. *
  18696. * Note that the 3D object must have a geometry so that the bounding sphere can be calculated.
  18697. *
  18698. * @param {Object3D} object - The 3D object to test.
  18699. * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not.
  18700. */
  18701. intersectsObject( object ) {
  18702. if ( object.boundingSphere !== undefined ) {
  18703. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  18704. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  18705. } else {
  18706. const geometry = object.geometry;
  18707. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18708. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  18709. }
  18710. return this.intersectsSphere( _sphere$3 );
  18711. }
  18712. /**
  18713. * Returns `true` if the given sprite is intersecting this frustum.
  18714. *
  18715. * @param {Sprite} sprite - The sprite to test.
  18716. * @return {boolean} Whether the sprite is intersecting this frustum or not.
  18717. */
  18718. intersectsSprite( sprite ) {
  18719. _sphere$3.center.set( 0, 0, 0 );
  18720. const offset = _defaultSpriteCenter.distanceTo( sprite.center );
  18721. _sphere$3.radius = 0.7071067811865476 + offset;
  18722. _sphere$3.applyMatrix4( sprite.matrixWorld );
  18723. return this.intersectsSphere( _sphere$3 );
  18724. }
  18725. /**
  18726. * Returns `true` if the given bounding sphere is intersecting this frustum.
  18727. *
  18728. * @param {Sphere} sphere - The bounding sphere to test.
  18729. * @return {boolean} Whether the bounding sphere is intersecting this frustum or not.
  18730. */
  18731. intersectsSphere( sphere ) {
  18732. const planes = this.planes;
  18733. const center = sphere.center;
  18734. const negRadius = - sphere.radius;
  18735. for ( let i = 0; i < 6; i ++ ) {
  18736. const distance = planes[ i ].distanceToPoint( center );
  18737. if ( distance < negRadius ) {
  18738. return false;
  18739. }
  18740. }
  18741. return true;
  18742. }
  18743. /**
  18744. * Returns `true` if the given bounding box is intersecting this frustum.
  18745. *
  18746. * @param {Box3} box - The bounding box to test.
  18747. * @return {boolean} Whether the bounding box is intersecting this frustum or not.
  18748. */
  18749. intersectsBox( box ) {
  18750. const planes = this.planes;
  18751. for ( let i = 0; i < 6; i ++ ) {
  18752. const plane = planes[ i ];
  18753. // corner at max distance
  18754. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  18755. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  18756. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  18757. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  18758. return false;
  18759. }
  18760. }
  18761. return true;
  18762. }
  18763. /**
  18764. * Returns `true` if the given point lies within the frustum.
  18765. *
  18766. * @param {Vector3} point - The point to test.
  18767. * @return {boolean} Whether the point lies within this frustum or not.
  18768. */
  18769. containsPoint( point ) {
  18770. const planes = this.planes;
  18771. for ( let i = 0; i < 6; i ++ ) {
  18772. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  18773. return false;
  18774. }
  18775. }
  18776. return true;
  18777. }
  18778. /**
  18779. * Returns a new frustum with copied values from this instance.
  18780. *
  18781. * @return {Frustum} A clone of this instance.
  18782. */
  18783. clone() {
  18784. return new this.constructor().copy( this );
  18785. }
  18786. }
  18787. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  18788. const _frustum$1 = /*@__PURE__*/ new Frustum();
  18789. /**
  18790. * FrustumArray is used to determine if an object is visible in at least one camera
  18791. * from an array of cameras. This is particularly useful for multi-view renderers.
  18792. */
  18793. class FrustumArray {
  18794. /**
  18795. * Constructs a new frustum array.
  18796. *
  18797. */
  18798. constructor() {
  18799. /**
  18800. * The coordinate system to use.
  18801. *
  18802. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  18803. * @default WebGLCoordinateSystem
  18804. */
  18805. this.coordinateSystem = WebGLCoordinateSystem;
  18806. }
  18807. /**
  18808. * Returns `true` if the 3D object's bounding sphere is intersecting any frustum
  18809. * from the camera array.
  18810. *
  18811. * @param {Object3D} object - The 3D object to test.
  18812. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  18813. * @return {boolean} Whether the 3D object is visible in any camera.
  18814. */
  18815. intersectsObject( object, cameraArray ) {
  18816. if ( ! cameraArray.isArrayCamera || cameraArray.cameras.length === 0 ) {
  18817. return false;
  18818. }
  18819. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  18820. const camera = cameraArray.cameras[ i ];
  18821. _projScreenMatrix$1.multiplyMatrices(
  18822. camera.projectionMatrix,
  18823. camera.matrixWorldInverse
  18824. );
  18825. _frustum$1.setFromProjectionMatrix(
  18826. _projScreenMatrix$1,
  18827. camera.coordinateSystem,
  18828. camera.reversedDepth
  18829. );
  18830. if ( _frustum$1.intersectsObject( object ) ) {
  18831. return true; // Object is visible in at least one camera
  18832. }
  18833. }
  18834. return false; // Not visible in any camera
  18835. }
  18836. /**
  18837. * Returns `true` if the given sprite is intersecting any frustum
  18838. * from the camera array.
  18839. *
  18840. * @param {Sprite} sprite - The sprite to test.
  18841. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  18842. * @return {boolean} Whether the sprite is visible in any camera.
  18843. */
  18844. intersectsSprite( sprite, cameraArray ) {
  18845. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  18846. return false;
  18847. }
  18848. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  18849. const camera = cameraArray.cameras[ i ];
  18850. _projScreenMatrix$1.multiplyMatrices(
  18851. camera.projectionMatrix,
  18852. camera.matrixWorldInverse
  18853. );
  18854. _frustum$1.setFromProjectionMatrix(
  18855. _projScreenMatrix$1,
  18856. camera.coordinateSystem,
  18857. camera.reversedDepth
  18858. );
  18859. if ( _frustum$1.intersectsSprite( sprite ) ) {
  18860. return true; // Sprite is visible in at least one camera
  18861. }
  18862. }
  18863. return false; // Not visible in any camera
  18864. }
  18865. /**
  18866. * Returns `true` if the given bounding sphere is intersecting any frustum
  18867. * from the camera array.
  18868. *
  18869. * @param {Sphere} sphere - The bounding sphere to test.
  18870. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  18871. * @return {boolean} Whether the sphere is visible in any camera.
  18872. */
  18873. intersectsSphere( sphere, cameraArray ) {
  18874. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  18875. return false;
  18876. }
  18877. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  18878. const camera = cameraArray.cameras[ i ];
  18879. _projScreenMatrix$1.multiplyMatrices(
  18880. camera.projectionMatrix,
  18881. camera.matrixWorldInverse
  18882. );
  18883. _frustum$1.setFromProjectionMatrix(
  18884. _projScreenMatrix$1,
  18885. camera.coordinateSystem,
  18886. camera.reversedDepth
  18887. );
  18888. if ( _frustum$1.intersectsSphere( sphere ) ) {
  18889. return true; // Sphere is visible in at least one camera
  18890. }
  18891. }
  18892. return false; // Not visible in any camera
  18893. }
  18894. /**
  18895. * Returns `true` if the given bounding box is intersecting any frustum
  18896. * from the camera array.
  18897. *
  18898. * @param {Box3} box - The bounding box to test.
  18899. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  18900. * @return {boolean} Whether the box is visible in any camera.
  18901. */
  18902. intersectsBox( box, cameraArray ) {
  18903. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  18904. return false;
  18905. }
  18906. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  18907. const camera = cameraArray.cameras[ i ];
  18908. _projScreenMatrix$1.multiplyMatrices(
  18909. camera.projectionMatrix,
  18910. camera.matrixWorldInverse
  18911. );
  18912. _frustum$1.setFromProjectionMatrix(
  18913. _projScreenMatrix$1,
  18914. camera.coordinateSystem,
  18915. camera.reversedDepth
  18916. );
  18917. if ( _frustum$1.intersectsBox( box ) ) {
  18918. return true; // Box is visible in at least one camera
  18919. }
  18920. }
  18921. return false; // Not visible in any camera
  18922. }
  18923. /**
  18924. * Returns `true` if the given point lies within any frustum
  18925. * from the camera array.
  18926. *
  18927. * @param {Vector3} point - The point to test.
  18928. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  18929. * @return {boolean} Whether the point is visible in any camera.
  18930. */
  18931. containsPoint( point, cameraArray ) {
  18932. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  18933. return false;
  18934. }
  18935. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  18936. const camera = cameraArray.cameras[ i ];
  18937. _projScreenMatrix$1.multiplyMatrices(
  18938. camera.projectionMatrix,
  18939. camera.matrixWorldInverse
  18940. );
  18941. _frustum$1.setFromProjectionMatrix(
  18942. _projScreenMatrix$1,
  18943. camera.coordinateSystem,
  18944. camera.reversedDepth
  18945. );
  18946. if ( _frustum$1.containsPoint( point ) ) {
  18947. return true; // Point is visible in at least one camera
  18948. }
  18949. }
  18950. return false; // Not visible in any camera
  18951. }
  18952. /**
  18953. * Returns a new frustum array with copied values from this instance.
  18954. *
  18955. * @return {FrustumArray} A clone of this instance.
  18956. */
  18957. clone() {
  18958. return new FrustumArray();
  18959. }
  18960. }
  18961. function ascIdSort( a, b ) {
  18962. return a - b;
  18963. }
  18964. function sortOpaque( a, b ) {
  18965. return a.z - b.z;
  18966. }
  18967. function sortTransparent( a, b ) {
  18968. return b.z - a.z;
  18969. }
  18970. class MultiDrawRenderList {
  18971. constructor() {
  18972. this.index = 0;
  18973. this.pool = [];
  18974. this.list = [];
  18975. }
  18976. push( start, count, z, index ) {
  18977. const pool = this.pool;
  18978. const list = this.list;
  18979. if ( this.index >= pool.length ) {
  18980. pool.push( {
  18981. start: -1,
  18982. count: -1,
  18983. z: -1,
  18984. index: -1,
  18985. } );
  18986. }
  18987. const item = pool[ this.index ];
  18988. list.push( item );
  18989. this.index ++;
  18990. item.start = start;
  18991. item.count = count;
  18992. item.z = z;
  18993. item.index = index;
  18994. }
  18995. reset() {
  18996. this.list.length = 0;
  18997. this.index = 0;
  18998. }
  18999. }
  19000. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  19001. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  19002. const _frustum = /*@__PURE__*/ new Frustum();
  19003. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  19004. const _box$1 = /*@__PURE__*/ new Box3();
  19005. const _sphere$2 = /*@__PURE__*/ new Sphere();
  19006. const _vector$5 = /*@__PURE__*/ new Vector3();
  19007. const _forward$1 = /*@__PURE__*/ new Vector3();
  19008. const _temp = /*@__PURE__*/ new Vector3();
  19009. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  19010. const _mesh = /*@__PURE__*/ new Mesh();
  19011. const _batchIntersects = [];
  19012. // copies data from attribute "src" into "target" starting at "targetOffset"
  19013. function copyAttributeData( src, target, targetOffset = 0 ) {
  19014. const itemSize = target.itemSize;
  19015. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  19016. // use the component getters and setters if the array data cannot
  19017. // be copied directly
  19018. const vertexCount = src.count;
  19019. for ( let i = 0; i < vertexCount; i ++ ) {
  19020. for ( let c = 0; c < itemSize; c ++ ) {
  19021. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  19022. }
  19023. }
  19024. } else {
  19025. // faster copy approach using typed array set function
  19026. target.array.set( src.array, targetOffset * itemSize );
  19027. }
  19028. target.needsUpdate = true;
  19029. }
  19030. // safely copies array contents to a potentially smaller array
  19031. function copyArrayContents( src, target ) {
  19032. if ( src.constructor !== target.constructor ) {
  19033. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  19034. const len = Math.min( src.length, target.length );
  19035. for ( let i = 0; i < len; i ++ ) {
  19036. target[ i ] = src[ i ];
  19037. }
  19038. } else {
  19039. // if the arrays use the same data layout we can use a fast block copy
  19040. const len = Math.min( src.length, target.length );
  19041. target.set( new src.constructor( src.buffer, 0, len ) );
  19042. }
  19043. }
  19044. /**
  19045. * A special version of a mesh with multi draw batch rendering support. Use
  19046. * this class if you have to render a large number of objects with the same
  19047. * material but with different geometries or world transformations. The usage of
  19048. * `BatchedMesh` will help you to reduce the number of draw calls and thus improve the overall
  19049. * rendering performance in your application.
  19050. *
  19051. * ```js
  19052. * const box = new THREE.BoxGeometry( 1, 1, 1 );
  19053. * const sphere = new THREE.SphereGeometry( 1, 12, 12 );
  19054. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  19055. *
  19056. * // initialize and add geometries into the batched mesh
  19057. * const batchedMesh = new BatchedMesh( 10, 5000, 10000, material );
  19058. * const boxGeometryId = batchedMesh.addGeometry( box );
  19059. * const sphereGeometryId = batchedMesh.addGeometry( sphere );
  19060. *
  19061. * // create instances of those geometries
  19062. * const boxInstancedId1 = batchedMesh.addInstance( boxGeometryId );
  19063. * const boxInstancedId2 = batchedMesh.addInstance( boxGeometryId );
  19064. *
  19065. * const sphereInstancedId1 = batchedMesh.addInstance( sphereGeometryId );
  19066. * const sphereInstancedId2 = batchedMesh.addInstance( sphereGeometryId );
  19067. *
  19068. * // position the geometries
  19069. * batchedMesh.setMatrixAt( boxInstancedId1, boxMatrix1 );
  19070. * batchedMesh.setMatrixAt( boxInstancedId2, boxMatrix2 );
  19071. *
  19072. * batchedMesh.setMatrixAt( sphereInstancedId1, sphereMatrix1 );
  19073. * batchedMesh.setMatrixAt( sphereInstancedId2, sphereMatrix2 );
  19074. *
  19075. * scene.add( batchedMesh );
  19076. * ```
  19077. *
  19078. * @augments Mesh
  19079. */
  19080. class BatchedMesh extends Mesh {
  19081. /**
  19082. * Constructs a new batched mesh.
  19083. *
  19084. * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered.
  19085. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries.
  19086. * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries
  19087. * @param {Material|Array<Material>} [material] - The mesh material.
  19088. */
  19089. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  19090. super( new BufferGeometry(), material );
  19091. /**
  19092. * This flag can be used for type testing.
  19093. *
  19094. * @type {boolean}
  19095. * @readonly
  19096. * @default true
  19097. */
  19098. this.isBatchedMesh = true;
  19099. /**
  19100. * When set ot `true`, the individual objects of a batch are frustum culled.
  19101. *
  19102. * @type {boolean}
  19103. * @default true
  19104. */
  19105. this.perObjectFrustumCulled = true;
  19106. /**
  19107. * When set to `true`, the individual objects of a batch are sorted to improve overdraw-related artifacts.
  19108. * If the material is marked as "transparent" objects are rendered back to front and if not then they are
  19109. * rendered front to back.
  19110. *
  19111. * @type {boolean}
  19112. * @default true
  19113. */
  19114. this.sortObjects = true;
  19115. /**
  19116. * The bounding box of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingBox}.
  19117. *
  19118. * @type {?Box3}
  19119. * @default null
  19120. */
  19121. this.boundingBox = null;
  19122. /**
  19123. * The bounding sphere of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingSphere}.
  19124. *
  19125. * @type {?Sphere}
  19126. * @default null
  19127. */
  19128. this.boundingSphere = null;
  19129. /**
  19130. * Takes a sort a function that is run before render. The function takes a list of instances to
  19131. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered
  19132. * sort with.
  19133. *
  19134. * @type {?Function}
  19135. * @default null
  19136. */
  19137. this.customSort = null;
  19138. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  19139. this._instanceInfo = [];
  19140. this._geometryInfo = [];
  19141. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  19142. this._availableInstanceIds = [];
  19143. this._availableGeometryIds = [];
  19144. // used to track where the next point is that geometry should be inserted
  19145. this._nextIndexStart = 0;
  19146. this._nextVertexStart = 0;
  19147. this._geometryCount = 0;
  19148. // flags
  19149. this._visibilityChanged = true;
  19150. this._geometryInitialized = false;
  19151. // cached user options
  19152. this._maxInstanceCount = maxInstanceCount;
  19153. this._maxVertexCount = maxVertexCount;
  19154. this._maxIndexCount = maxIndexCount;
  19155. // buffers for multi draw
  19156. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  19157. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  19158. this._multiDrawCount = 0;
  19159. this._multiDrawInstances = null;
  19160. // Local matrix per geometry by using data texture
  19161. this._matricesTexture = null;
  19162. this._indirectTexture = null;
  19163. this._colorsTexture = null;
  19164. this._initMatricesTexture();
  19165. this._initIndirectTexture();
  19166. }
  19167. /**
  19168. * The maximum number of individual instances that can be stored in the batch.
  19169. *
  19170. * @type {number}
  19171. * @readonly
  19172. */
  19173. get maxInstanceCount() {
  19174. return this._maxInstanceCount;
  19175. }
  19176. /**
  19177. * The instance count.
  19178. *
  19179. * @type {number}
  19180. * @readonly
  19181. */
  19182. get instanceCount() {
  19183. return this._instanceInfo.length - this._availableInstanceIds.length;
  19184. }
  19185. /**
  19186. * The number of unused vertices.
  19187. *
  19188. * @type {number}
  19189. * @readonly
  19190. */
  19191. get unusedVertexCount() {
  19192. return this._maxVertexCount - this._nextVertexStart;
  19193. }
  19194. /**
  19195. * The number of unused indices.
  19196. *
  19197. * @type {number}
  19198. * @readonly
  19199. */
  19200. get unusedIndexCount() {
  19201. return this._maxIndexCount - this._nextIndexStart;
  19202. }
  19203. _initMatricesTexture() {
  19204. // layout (1 matrix = 4 pixels)
  19205. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  19206. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  19207. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  19208. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  19209. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  19210. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  19211. size = Math.ceil( size / 4 ) * 4;
  19212. size = Math.max( size, 4 );
  19213. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  19214. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  19215. this._matricesTexture = matricesTexture;
  19216. }
  19217. _initIndirectTexture() {
  19218. let size = Math.sqrt( this._maxInstanceCount );
  19219. size = Math.ceil( size );
  19220. const indirectArray = new Uint32Array( size * size );
  19221. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  19222. this._indirectTexture = indirectTexture;
  19223. }
  19224. _initColorsTexture() {
  19225. let size = Math.sqrt( this._maxInstanceCount );
  19226. size = Math.ceil( size );
  19227. // 4 floats per RGBA pixel initialized to white
  19228. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  19229. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  19230. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  19231. this._colorsTexture = colorsTexture;
  19232. }
  19233. _initializeGeometry( reference ) {
  19234. const geometry = this.geometry;
  19235. const maxVertexCount = this._maxVertexCount;
  19236. const maxIndexCount = this._maxIndexCount;
  19237. if ( this._geometryInitialized === false ) {
  19238. for ( const attributeName in reference.attributes ) {
  19239. const srcAttribute = reference.getAttribute( attributeName );
  19240. const { array, itemSize, normalized } = srcAttribute;
  19241. const dstArray = new array.constructor( maxVertexCount * itemSize );
  19242. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  19243. geometry.setAttribute( attributeName, dstAttribute );
  19244. }
  19245. if ( reference.getIndex() !== null ) {
  19246. // Reserve last u16 index for primitive restart.
  19247. const indexArray = maxVertexCount > 65535
  19248. ? new Uint32Array( maxIndexCount )
  19249. : new Uint16Array( maxIndexCount );
  19250. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  19251. }
  19252. this._geometryInitialized = true;
  19253. }
  19254. }
  19255. // Make sure the geometry is compatible with the existing combined geometry attributes
  19256. _validateGeometry( geometry ) {
  19257. // check to ensure the geometries are using consistent attributes and indices
  19258. const batchGeometry = this.geometry;
  19259. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  19260. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  19261. }
  19262. for ( const attributeName in batchGeometry.attributes ) {
  19263. if ( ! geometry.hasAttribute( attributeName ) ) {
  19264. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  19265. }
  19266. const srcAttribute = geometry.getAttribute( attributeName );
  19267. const dstAttribute = batchGeometry.getAttribute( attributeName );
  19268. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  19269. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  19270. }
  19271. }
  19272. }
  19273. /**
  19274. * Validates the instance defined by the given ID.
  19275. *
  19276. * @param {number} instanceId - The instance to validate.
  19277. */
  19278. validateInstanceId( instanceId ) {
  19279. const instanceInfo = this._instanceInfo;
  19280. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  19281. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  19282. }
  19283. }
  19284. /**
  19285. * Validates the geometry defined by the given ID.
  19286. *
  19287. * @param {number} geometryId - The geometry to validate.
  19288. */
  19289. validateGeometryId( geometryId ) {
  19290. const geometryInfoList = this._geometryInfo;
  19291. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  19292. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  19293. }
  19294. }
  19295. /**
  19296. * Takes a sort a function that is run before render. The function takes a list of instances to
  19297. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.
  19298. *
  19299. * @param {Function} func - The custom sort function.
  19300. * @return {BatchedMesh} A reference to this batched mesh.
  19301. */
  19302. setCustomSort( func ) {
  19303. this.customSort = func;
  19304. return this;
  19305. }
  19306. /**
  19307. * Computes the bounding box, updating {@link BatchedMesh#boundingBox}.
  19308. * Bounding boxes aren't computed by default. They need to be explicitly computed,
  19309. * otherwise they are `null`.
  19310. */
  19311. computeBoundingBox() {
  19312. if ( this.boundingBox === null ) {
  19313. this.boundingBox = new Box3();
  19314. }
  19315. const boundingBox = this.boundingBox;
  19316. const instanceInfo = this._instanceInfo;
  19317. boundingBox.makeEmpty();
  19318. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  19319. if ( instanceInfo[ i ].active === false ) continue;
  19320. const geometryId = instanceInfo[ i ].geometryIndex;
  19321. this.getMatrixAt( i, _matrix$1 );
  19322. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  19323. boundingBox.union( _box$1 );
  19324. }
  19325. }
  19326. /**
  19327. * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}.
  19328. * Bounding spheres aren't computed by default. They need to be explicitly computed,
  19329. * otherwise they are `null`.
  19330. */
  19331. computeBoundingSphere() {
  19332. if ( this.boundingSphere === null ) {
  19333. this.boundingSphere = new Sphere();
  19334. }
  19335. const boundingSphere = this.boundingSphere;
  19336. const instanceInfo = this._instanceInfo;
  19337. boundingSphere.makeEmpty();
  19338. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  19339. if ( instanceInfo[ i ].active === false ) continue;
  19340. const geometryId = instanceInfo[ i ].geometryIndex;
  19341. this.getMatrixAt( i, _matrix$1 );
  19342. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  19343. boundingSphere.union( _sphere$2 );
  19344. }
  19345. }
  19346. /**
  19347. * Adds a new instance to the batch using the geometry of the given ID and returns
  19348. * a new id referring to the new instance to be used by other functions.
  19349. *
  19350. * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}.
  19351. * @return {number} The instance ID.
  19352. */
  19353. addInstance( geometryId ) {
  19354. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  19355. // ensure we're not over geometry
  19356. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  19357. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  19358. }
  19359. const instanceInfo = {
  19360. visible: true,
  19361. active: true,
  19362. geometryIndex: geometryId,
  19363. };
  19364. let drawId = null;
  19365. // Prioritize using previously freed instance ids
  19366. if ( this._availableInstanceIds.length > 0 ) {
  19367. this._availableInstanceIds.sort( ascIdSort );
  19368. drawId = this._availableInstanceIds.shift();
  19369. this._instanceInfo[ drawId ] = instanceInfo;
  19370. } else {
  19371. drawId = this._instanceInfo.length;
  19372. this._instanceInfo.push( instanceInfo );
  19373. }
  19374. const matricesTexture = this._matricesTexture;
  19375. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  19376. matricesTexture.needsUpdate = true;
  19377. const colorsTexture = this._colorsTexture;
  19378. if ( colorsTexture ) {
  19379. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  19380. colorsTexture.needsUpdate = true;
  19381. }
  19382. this._visibilityChanged = true;
  19383. return drawId;
  19384. }
  19385. /**
  19386. * Adds the given geometry to the batch and returns the associated
  19387. * geometry id referring to it to be used in other functions.
  19388. *
  19389. * @param {BufferGeometry} geometry - The geometry to add.
  19390. * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of
  19391. * vertex buffer space to reserve for the added geometry. This is necessary if it is planned
  19392. * to set a new geometry at this index at a later time that is larger than the original geometry.
  19393. * Defaults to the length of the given geometry vertex buffer.
  19394. * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index
  19395. * buffer space to reserve for the added geometry. This is necessary if it is planned to set a
  19396. * new geometry at this index at a later time that is larger than the original geometry. Defaults to
  19397. * the length of the given geometry index buffer.
  19398. * @return {number} The geometry ID.
  19399. */
  19400. addGeometry( geometry, reservedVertexCount = -1, reservedIndexCount = -1 ) {
  19401. this._initializeGeometry( geometry );
  19402. this._validateGeometry( geometry );
  19403. const geometryInfo = {
  19404. // geometry information
  19405. vertexStart: -1,
  19406. vertexCount: -1,
  19407. reservedVertexCount: -1,
  19408. indexStart: -1,
  19409. indexCount: -1,
  19410. reservedIndexCount: -1,
  19411. // draw range information
  19412. start: -1,
  19413. count: -1,
  19414. // state
  19415. boundingBox: null,
  19416. boundingSphere: null,
  19417. active: true,
  19418. };
  19419. const geometryInfoList = this._geometryInfo;
  19420. geometryInfo.vertexStart = this._nextVertexStart;
  19421. geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  19422. const index = geometry.getIndex();
  19423. const hasIndex = index !== null;
  19424. if ( hasIndex ) {
  19425. geometryInfo.indexStart = this._nextIndexStart;
  19426. geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount;
  19427. }
  19428. if (
  19429. geometryInfo.indexStart !== -1 &&
  19430. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  19431. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  19432. ) {
  19433. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  19434. }
  19435. // update id
  19436. let geometryId;
  19437. if ( this._availableGeometryIds.length > 0 ) {
  19438. this._availableGeometryIds.sort( ascIdSort );
  19439. geometryId = this._availableGeometryIds.shift();
  19440. geometryInfoList[ geometryId ] = geometryInfo;
  19441. } else {
  19442. geometryId = this._geometryCount;
  19443. this._geometryCount ++;
  19444. geometryInfoList.push( geometryInfo );
  19445. }
  19446. // update the geometry
  19447. this.setGeometryAt( geometryId, geometry );
  19448. // increment the next geometry position
  19449. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  19450. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  19451. return geometryId;
  19452. }
  19453. /**
  19454. * Replaces the geometry at the given ID with the provided geometry. Throws an error if there
  19455. * is not enough space reserved for geometry. Calling this will change all instances that are
  19456. * rendering that geometry.
  19457. *
  19458. * @param {number} geometryId - The ID of the geometry that should be replaced with the given geometry.
  19459. * @param {BufferGeometry} geometry - The new geometry.
  19460. * @return {number} The geometry ID.
  19461. */
  19462. setGeometryAt( geometryId, geometry ) {
  19463. if ( geometryId >= this._geometryCount ) {
  19464. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  19465. }
  19466. this._validateGeometry( geometry );
  19467. const batchGeometry = this.geometry;
  19468. const hasIndex = batchGeometry.getIndex() !== null;
  19469. const dstIndex = batchGeometry.getIndex();
  19470. const srcIndex = geometry.getIndex();
  19471. const geometryInfo = this._geometryInfo[ geometryId ];
  19472. if (
  19473. hasIndex &&
  19474. srcIndex.count > geometryInfo.reservedIndexCount ||
  19475. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  19476. ) {
  19477. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  19478. }
  19479. // copy geometry buffer data over
  19480. const vertexStart = geometryInfo.vertexStart;
  19481. const reservedVertexCount = geometryInfo.reservedVertexCount;
  19482. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  19483. for ( const attributeName in batchGeometry.attributes ) {
  19484. // copy attribute data
  19485. const srcAttribute = geometry.getAttribute( attributeName );
  19486. const dstAttribute = batchGeometry.getAttribute( attributeName );
  19487. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  19488. // fill the rest in with zeroes
  19489. const itemSize = srcAttribute.itemSize;
  19490. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  19491. const index = vertexStart + i;
  19492. for ( let c = 0; c < itemSize; c ++ ) {
  19493. dstAttribute.setComponent( index, c, 0 );
  19494. }
  19495. }
  19496. dstAttribute.needsUpdate = true;
  19497. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  19498. }
  19499. // copy index
  19500. if ( hasIndex ) {
  19501. const indexStart = geometryInfo.indexStart;
  19502. const reservedIndexCount = geometryInfo.reservedIndexCount;
  19503. geometryInfo.indexCount = geometry.getIndex().count;
  19504. // copy index data over
  19505. for ( let i = 0; i < srcIndex.count; i ++ ) {
  19506. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  19507. }
  19508. // fill the rest in with zeroes
  19509. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  19510. dstIndex.setX( indexStart + i, vertexStart );
  19511. }
  19512. dstIndex.needsUpdate = true;
  19513. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  19514. }
  19515. // update the draw range
  19516. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  19517. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  19518. // store the bounding boxes
  19519. geometryInfo.boundingBox = null;
  19520. if ( geometry.boundingBox !== null ) {
  19521. geometryInfo.boundingBox = geometry.boundingBox.clone();
  19522. }
  19523. geometryInfo.boundingSphere = null;
  19524. if ( geometry.boundingSphere !== null ) {
  19525. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  19526. }
  19527. this._visibilityChanged = true;
  19528. return geometryId;
  19529. }
  19530. /**
  19531. * Deletes the geometry defined by the given ID from this batch. Any instances referencing
  19532. * this geometry will also be removed as a side effect.
  19533. *
  19534. * @param {number} geometryId - The ID of the geometry to remove from the batch.
  19535. * @return {BatchedMesh} A reference to this batched mesh.
  19536. */
  19537. deleteGeometry( geometryId ) {
  19538. const geometryInfoList = this._geometryInfo;
  19539. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  19540. return this;
  19541. }
  19542. // delete any instances associated with this geometry
  19543. const instanceInfo = this._instanceInfo;
  19544. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  19545. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  19546. this.deleteInstance( i );
  19547. }
  19548. }
  19549. geometryInfoList[ geometryId ].active = false;
  19550. this._availableGeometryIds.push( geometryId );
  19551. this._visibilityChanged = true;
  19552. return this;
  19553. }
  19554. /**
  19555. * Deletes an existing instance from the batch using the given ID.
  19556. *
  19557. * @param {number} instanceId - The ID of the instance to remove from the batch.
  19558. * @return {BatchedMesh} A reference to this batched mesh.
  19559. */
  19560. deleteInstance( instanceId ) {
  19561. this.validateInstanceId( instanceId );
  19562. this._instanceInfo[ instanceId ].active = false;
  19563. this._availableInstanceIds.push( instanceId );
  19564. this._visibilityChanged = true;
  19565. return this;
  19566. }
  19567. /**
  19568. * Repacks the sub geometries in BatchedMesh to remove any unused space remaining from
  19569. * previously deleted geometry, freeing up space to add new geometry.
  19570. *
  19571. * @return {BatchedMesh} A reference to this batched mesh.
  19572. */
  19573. optimize() {
  19574. // track the next indices to copy data to
  19575. let nextVertexStart = 0;
  19576. let nextIndexStart = 0;
  19577. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  19578. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  19579. const geometryInfoList = this._geometryInfo;
  19580. const indices = geometryInfoList
  19581. .map( ( e, i ) => i )
  19582. .sort( ( a, b ) => {
  19583. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  19584. } );
  19585. const geometry = this.geometry;
  19586. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  19587. // if a geometry range is inactive then don't copy anything
  19588. const index = indices[ i ];
  19589. const geometryInfo = geometryInfoList[ index ];
  19590. if ( geometryInfo.active === false ) {
  19591. continue;
  19592. }
  19593. // if a geometry contains an index buffer then shift it, as well
  19594. if ( geometry.index !== null ) {
  19595. if ( geometryInfo.indexStart !== nextIndexStart ) {
  19596. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  19597. const index = geometry.index;
  19598. const array = index.array;
  19599. // shift the index pointers based on how the vertex data will shift
  19600. // adjusting the index must happen first so the original vertex start value is available
  19601. const elementDelta = nextVertexStart - vertexStart;
  19602. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  19603. array[ j ] = array[ j ] + elementDelta;
  19604. }
  19605. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  19606. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  19607. index.needsUpdate = true;
  19608. geometryInfo.indexStart = nextIndexStart;
  19609. }
  19610. nextIndexStart += geometryInfo.reservedIndexCount;
  19611. }
  19612. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  19613. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  19614. const { vertexStart, reservedVertexCount } = geometryInfo;
  19615. const attributes = geometry.attributes;
  19616. for ( const key in attributes ) {
  19617. const attribute = attributes[ key ];
  19618. const { array, itemSize } = attribute;
  19619. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  19620. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  19621. attribute.needsUpdate = true;
  19622. }
  19623. geometryInfo.vertexStart = nextVertexStart;
  19624. }
  19625. nextVertexStart += geometryInfo.reservedVertexCount;
  19626. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  19627. }
  19628. this._nextIndexStart = nextIndexStart;
  19629. this._nextVertexStart = nextVertexStart;
  19630. this._visibilityChanged = true;
  19631. return this;
  19632. }
  19633. /**
  19634. * Returns the bounding box for the given geometry.
  19635. *
  19636. * @param {number} geometryId - The ID of the geometry to return the bounding box for.
  19637. * @param {Box3} target - The target object that is used to store the method's result.
  19638. * @return {?Box3} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID.
  19639. */
  19640. getBoundingBoxAt( geometryId, target ) {
  19641. if ( geometryId >= this._geometryCount ) {
  19642. return null;
  19643. }
  19644. // compute bounding box
  19645. const geometry = this.geometry;
  19646. const geometryInfo = this._geometryInfo[ geometryId ];
  19647. if ( geometryInfo.boundingBox === null ) {
  19648. const box = new Box3();
  19649. const index = geometry.index;
  19650. const position = geometry.attributes.position;
  19651. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  19652. let iv = i;
  19653. if ( index ) {
  19654. iv = index.getX( iv );
  19655. }
  19656. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  19657. }
  19658. geometryInfo.boundingBox = box;
  19659. }
  19660. target.copy( geometryInfo.boundingBox );
  19661. return target;
  19662. }
  19663. /**
  19664. * Returns the bounding sphere for the given geometry.
  19665. *
  19666. * @param {number} geometryId - The ID of the geometry to return the bounding sphere for.
  19667. * @param {Sphere} target - The target object that is used to store the method's result.
  19668. * @return {?Sphere} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID.
  19669. */
  19670. getBoundingSphereAt( geometryId, target ) {
  19671. if ( geometryId >= this._geometryCount ) {
  19672. return null;
  19673. }
  19674. // compute bounding sphere
  19675. const geometry = this.geometry;
  19676. const geometryInfo = this._geometryInfo[ geometryId ];
  19677. if ( geometryInfo.boundingSphere === null ) {
  19678. const sphere = new Sphere();
  19679. this.getBoundingBoxAt( geometryId, _box$1 );
  19680. _box$1.getCenter( sphere.center );
  19681. const index = geometry.index;
  19682. const position = geometry.attributes.position;
  19683. let maxRadiusSq = 0;
  19684. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  19685. let iv = i;
  19686. if ( index ) {
  19687. iv = index.getX( iv );
  19688. }
  19689. _vector$5.fromBufferAttribute( position, iv );
  19690. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  19691. }
  19692. sphere.radius = Math.sqrt( maxRadiusSq );
  19693. geometryInfo.boundingSphere = sphere;
  19694. }
  19695. target.copy( geometryInfo.boundingSphere );
  19696. return target;
  19697. }
  19698. /**
  19699. * Sets the given local transformation matrix to the defined instance.
  19700. * Negatively scaled matrices are not supported.
  19701. *
  19702. * @param {number} instanceId - The ID of an instance to set the matrix of.
  19703. * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance.
  19704. * @return {BatchedMesh} A reference to this batched mesh.
  19705. */
  19706. setMatrixAt( instanceId, matrix ) {
  19707. this.validateInstanceId( instanceId );
  19708. const matricesTexture = this._matricesTexture;
  19709. const matricesArray = this._matricesTexture.image.data;
  19710. matrix.toArray( matricesArray, instanceId * 16 );
  19711. matricesTexture.needsUpdate = true;
  19712. return this;
  19713. }
  19714. /**
  19715. * Returns the local transformation matrix of the defined instance.
  19716. *
  19717. * @param {number} instanceId - The ID of an instance to get the matrix of.
  19718. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  19719. * @return {Matrix4} The instance's local transformation matrix.
  19720. */
  19721. getMatrixAt( instanceId, matrix ) {
  19722. this.validateInstanceId( instanceId );
  19723. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  19724. }
  19725. /**
  19726. * Sets the given color to the defined instance.
  19727. *
  19728. * @param {number} instanceId - The ID of an instance to set the color of.
  19729. * @param {Color|Vector4} color - The color to set the instance to. Use a `Vector4` to also define alpha.
  19730. * @return {BatchedMesh} A reference to this batched mesh.
  19731. */
  19732. setColorAt( instanceId, color ) {
  19733. this.validateInstanceId( instanceId );
  19734. if ( this._colorsTexture === null ) {
  19735. this._initColorsTexture();
  19736. }
  19737. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  19738. this._colorsTexture.needsUpdate = true;
  19739. return this;
  19740. }
  19741. /**
  19742. * Returns the color of the defined instance.
  19743. *
  19744. * @param {number} instanceId - The ID of an instance to get the color of.
  19745. * @param {Color|Vector4} color - The target object that is used to store the method's result.
  19746. * @return {Color|Vector4} The instance's color. Use a `Vector4` to also retrieve alpha.
  19747. */
  19748. getColorAt( instanceId, color ) {
  19749. this.validateInstanceId( instanceId );
  19750. if ( this._colorsTexture === null ) {
  19751. if ( color.isVector4 ) {
  19752. return color.set( 1, 1, 1, 1 );
  19753. } else {
  19754. return color.setRGB( 1, 1, 1 );
  19755. }
  19756. } else {
  19757. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  19758. }
  19759. }
  19760. /**
  19761. * Sets the visibility of the instance.
  19762. *
  19763. * @param {number} instanceId - The id of the instance to set the visibility of.
  19764. * @param {boolean} visible - Whether the instance is visible or not.
  19765. * @return {BatchedMesh} A reference to this batched mesh.
  19766. */
  19767. setVisibleAt( instanceId, visible ) {
  19768. this.validateInstanceId( instanceId );
  19769. if ( this._instanceInfo[ instanceId ].visible === visible ) {
  19770. return this;
  19771. }
  19772. this._instanceInfo[ instanceId ].visible = visible;
  19773. this._visibilityChanged = true;
  19774. return this;
  19775. }
  19776. /**
  19777. * Returns the visibility state of the defined instance.
  19778. *
  19779. * @param {number} instanceId - The ID of an instance to get the visibility state of.
  19780. * @return {boolean} Whether the instance is visible or not.
  19781. */
  19782. getVisibleAt( instanceId ) {
  19783. this.validateInstanceId( instanceId );
  19784. return this._instanceInfo[ instanceId ].visible;
  19785. }
  19786. /**
  19787. * Sets the geometry ID of the instance at the given index.
  19788. *
  19789. * @param {number} instanceId - The ID of the instance to set the geometry ID of.
  19790. * @param {number} geometryId - The geometry ID to be use by the instance.
  19791. * @return {BatchedMesh} A reference to this batched mesh.
  19792. */
  19793. setGeometryIdAt( instanceId, geometryId ) {
  19794. this.validateInstanceId( instanceId );
  19795. this.validateGeometryId( geometryId );
  19796. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  19797. return this;
  19798. }
  19799. /**
  19800. * Returns the geometry ID of the defined instance.
  19801. *
  19802. * @param {number} instanceId - The ID of an instance to get the geometry ID of.
  19803. * @return {number} The instance's geometry ID.
  19804. */
  19805. getGeometryIdAt( instanceId ) {
  19806. this.validateInstanceId( instanceId );
  19807. return this._instanceInfo[ instanceId ].geometryIndex;
  19808. }
  19809. /**
  19810. * Get the range representing the subset of triangles related to the attached geometry,
  19811. * indicating the starting offset and count, or `null` if invalid.
  19812. *
  19813. * @param {number} geometryId - The id of the geometry to get the range of.
  19814. * @param {Object} [target] - The target object that is used to store the method's result.
  19815. * @return {{
  19816. * vertexStart:number,vertexCount:number,reservedVertexCount:number,
  19817. * indexStart:number,indexCount:number,reservedIndexCount:number,
  19818. * start:number,count:number
  19819. * }} The result object with range data.
  19820. */
  19821. getGeometryRangeAt( geometryId, target = {} ) {
  19822. this.validateGeometryId( geometryId );
  19823. const geometryInfo = this._geometryInfo[ geometryId ];
  19824. target.vertexStart = geometryInfo.vertexStart;
  19825. target.vertexCount = geometryInfo.vertexCount;
  19826. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  19827. target.indexStart = geometryInfo.indexStart;
  19828. target.indexCount = geometryInfo.indexCount;
  19829. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  19830. target.start = geometryInfo.start;
  19831. target.count = geometryInfo.count;
  19832. return target;
  19833. }
  19834. /**
  19835. * Resizes the necessary buffers to support the provided number of instances.
  19836. * If the provided arguments shrink the number of instances but there are not enough
  19837. * unused Ids at the end of the list then an error is thrown.
  19838. *
  19839. * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch.
  19840. */
  19841. setInstanceCount( maxInstanceCount ) {
  19842. // shrink the available instances as much as possible
  19843. const availableInstanceIds = this._availableInstanceIds;
  19844. const instanceInfo = this._instanceInfo;
  19845. availableInstanceIds.sort( ascIdSort );
  19846. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length - 1 ) {
  19847. instanceInfo.pop();
  19848. availableInstanceIds.pop();
  19849. }
  19850. // throw an error if it can't be shrunk to the desired size
  19851. if ( maxInstanceCount < instanceInfo.length ) {
  19852. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  19853. }
  19854. // copy the multi draw counts
  19855. const multiDrawCounts = new Int32Array( maxInstanceCount );
  19856. const multiDrawStarts = new Int32Array( maxInstanceCount );
  19857. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  19858. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  19859. this._multiDrawCounts = multiDrawCounts;
  19860. this._multiDrawStarts = multiDrawStarts;
  19861. this._maxInstanceCount = maxInstanceCount;
  19862. // update texture data for instance sampling
  19863. const indirectTexture = this._indirectTexture;
  19864. const matricesTexture = this._matricesTexture;
  19865. const colorsTexture = this._colorsTexture;
  19866. indirectTexture.dispose();
  19867. this._initIndirectTexture();
  19868. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  19869. matricesTexture.dispose();
  19870. this._initMatricesTexture();
  19871. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  19872. if ( colorsTexture ) {
  19873. colorsTexture.dispose();
  19874. this._initColorsTexture();
  19875. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  19876. }
  19877. }
  19878. /**
  19879. * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes.
  19880. * If the provided arguments shrink the geometry buffers but there is not enough unused space at the
  19881. * end of the geometry attributes then an error is thrown.
  19882. *
  19883. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to.
  19884. * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to.
  19885. */
  19886. setGeometrySize( maxVertexCount, maxIndexCount ) {
  19887. // Check if we can shrink to the requested vertex attribute size
  19888. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  19889. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  19890. if ( requiredVertexLength > maxVertexCount ) {
  19891. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  19892. }
  19893. // Check if we can shrink to the requested index attribute size
  19894. if ( this.geometry.index ) {
  19895. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  19896. if ( requiredIndexLength > maxIndexCount ) {
  19897. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  19898. }
  19899. }
  19900. //
  19901. // dispose of the previous geometry
  19902. const oldGeometry = this.geometry;
  19903. oldGeometry.dispose();
  19904. // recreate the geometry needed based on the previous variant
  19905. this._maxVertexCount = maxVertexCount;
  19906. this._maxIndexCount = maxIndexCount;
  19907. if ( this._geometryInitialized ) {
  19908. this._geometryInitialized = false;
  19909. this.geometry = new BufferGeometry();
  19910. this._initializeGeometry( oldGeometry );
  19911. }
  19912. // copy data from the previous geometry
  19913. const geometry = this.geometry;
  19914. if ( oldGeometry.index ) {
  19915. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  19916. }
  19917. for ( const key in oldGeometry.attributes ) {
  19918. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  19919. }
  19920. }
  19921. raycast( raycaster, intersects ) {
  19922. const instanceInfo = this._instanceInfo;
  19923. const geometryInfoList = this._geometryInfo;
  19924. const matrixWorld = this.matrixWorld;
  19925. const batchGeometry = this.geometry;
  19926. // iterate over each geometry
  19927. _mesh.material = this.material;
  19928. _mesh.geometry.index = batchGeometry.index;
  19929. _mesh.geometry.attributes = batchGeometry.attributes;
  19930. if ( _mesh.geometry.boundingBox === null ) {
  19931. _mesh.geometry.boundingBox = new Box3();
  19932. }
  19933. if ( _mesh.geometry.boundingSphere === null ) {
  19934. _mesh.geometry.boundingSphere = new Sphere();
  19935. }
  19936. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  19937. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  19938. continue;
  19939. }
  19940. const geometryId = instanceInfo[ i ].geometryIndex;
  19941. const geometryInfo = geometryInfoList[ geometryId ];
  19942. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  19943. // get the intersects
  19944. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  19945. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  19946. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  19947. _mesh.raycast( raycaster, _batchIntersects );
  19948. // add batch id to the intersects
  19949. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  19950. const intersect = _batchIntersects[ j ];
  19951. intersect.object = this;
  19952. intersect.batchId = i;
  19953. intersects.push( intersect );
  19954. }
  19955. _batchIntersects.length = 0;
  19956. }
  19957. _mesh.material = null;
  19958. _mesh.geometry.index = null;
  19959. _mesh.geometry.attributes = {};
  19960. _mesh.geometry.setDrawRange( 0, Infinity );
  19961. }
  19962. copy( source ) {
  19963. super.copy( source );
  19964. this.geometry = source.geometry.clone();
  19965. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  19966. this.sortObjects = source.sortObjects;
  19967. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  19968. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  19969. this._geometryInfo = source._geometryInfo.map( info => ( {
  19970. ...info,
  19971. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  19972. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  19973. } ) );
  19974. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  19975. this._availableInstanceIds = source._availableInstanceIds.slice();
  19976. this._availableGeometryIds = source._availableGeometryIds.slice();
  19977. this._nextIndexStart = source._nextIndexStart;
  19978. this._nextVertexStart = source._nextVertexStart;
  19979. this._geometryCount = source._geometryCount;
  19980. this._maxInstanceCount = source._maxInstanceCount;
  19981. this._maxVertexCount = source._maxVertexCount;
  19982. this._maxIndexCount = source._maxIndexCount;
  19983. this._geometryInitialized = source._geometryInitialized;
  19984. this._multiDrawCounts = source._multiDrawCounts.slice();
  19985. this._multiDrawStarts = source._multiDrawStarts.slice();
  19986. this._indirectTexture = source._indirectTexture.clone();
  19987. this._indirectTexture.image.data = this._indirectTexture.image.data.slice();
  19988. this._matricesTexture = source._matricesTexture.clone();
  19989. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  19990. if ( this._colorsTexture !== null ) {
  19991. this._colorsTexture = source._colorsTexture.clone();
  19992. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  19993. }
  19994. return this;
  19995. }
  19996. /**
  19997. * Frees the GPU-related resources allocated by this instance. Call this
  19998. * method whenever this instance is no longer used in your app.
  19999. */
  20000. dispose() {
  20001. // Assuming the geometry is not shared with other meshes
  20002. this.geometry.dispose();
  20003. this._matricesTexture.dispose();
  20004. this._matricesTexture = null;
  20005. this._indirectTexture.dispose();
  20006. this._indirectTexture = null;
  20007. if ( this._colorsTexture !== null ) {
  20008. this._colorsTexture.dispose();
  20009. this._colorsTexture = null;
  20010. }
  20011. }
  20012. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  20013. // if visibility has not changed and frustum culling and object sorting is not required
  20014. // then skip iterating over all items
  20015. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  20016. return;
  20017. }
  20018. // the indexed version of the multi draw function requires specifying the start
  20019. // offset in bytes.
  20020. const index = geometry.getIndex();
  20021. let bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  20022. // the "wireframe" attribute implicitly creates a line attribute in the renderer, which is double
  20023. // the vertices to draw (3 lines per triangle) so we multiply the draw counts / starts and make
  20024. // assumptions about the index buffer byte size.
  20025. let multiDrawMultiplier = 1;
  20026. if ( material.wireframe ) {
  20027. multiDrawMultiplier = 2;
  20028. bytesPerElement = geometry.attributes.position.count > 65535 ? 4 : 2;
  20029. }
  20030. const instanceInfo = this._instanceInfo;
  20031. const multiDrawStarts = this._multiDrawStarts;
  20032. const multiDrawCounts = this._multiDrawCounts;
  20033. const geometryInfoList = this._geometryInfo;
  20034. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  20035. const indirectTexture = this._indirectTexture;
  20036. const indirectArray = indirectTexture.image.data;
  20037. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  20038. // prepare the frustum in the local frame
  20039. if ( perObjectFrustumCulled && ! camera.isArrayCamera ) {
  20040. _matrix$1
  20041. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  20042. .multiply( this.matrixWorld );
  20043. _frustum.setFromProjectionMatrix(
  20044. _matrix$1,
  20045. camera.coordinateSystem,
  20046. camera.reversedDepth
  20047. );
  20048. }
  20049. let multiDrawCount = 0;
  20050. if ( this.sortObjects ) {
  20051. // get the camera position in the local frame
  20052. _matrix$1.copy( this.matrixWorld ).invert();
  20053. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  20054. _forward$1.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  20055. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20056. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20057. const geometryId = instanceInfo[ i ].geometryIndex;
  20058. // get the bounds in world space
  20059. this.getMatrixAt( i, _matrix$1 );
  20060. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20061. // determine whether the batched geometry is within the frustum
  20062. let culled = false;
  20063. if ( perObjectFrustumCulled ) {
  20064. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  20065. }
  20066. if ( ! culled ) {
  20067. // get the distance from camera used for sorting
  20068. const geometryInfo = geometryInfoList[ geometryId ];
  20069. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward$1 );
  20070. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  20071. }
  20072. }
  20073. }
  20074. // Sort the draw ranges and prep for rendering
  20075. const list = _renderList.list;
  20076. const customSort = this.customSort;
  20077. if ( customSort === null ) {
  20078. list.sort( material.transparent ? sortTransparent : sortOpaque );
  20079. } else {
  20080. customSort.call( this, list, camera );
  20081. }
  20082. for ( let i = 0, l = list.length; i < l; i ++ ) {
  20083. const item = list[ i ];
  20084. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement * multiDrawMultiplier;
  20085. multiDrawCounts[ multiDrawCount ] = item.count * multiDrawMultiplier;
  20086. indirectArray[ multiDrawCount ] = item.index;
  20087. multiDrawCount ++;
  20088. }
  20089. _renderList.reset();
  20090. } else {
  20091. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20092. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20093. const geometryId = instanceInfo[ i ].geometryIndex;
  20094. // determine whether the batched geometry is within the frustum
  20095. let culled = false;
  20096. if ( perObjectFrustumCulled ) {
  20097. // get the bounds in world space
  20098. this.getMatrixAt( i, _matrix$1 );
  20099. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20100. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  20101. }
  20102. if ( ! culled ) {
  20103. const geometryInfo = geometryInfoList[ geometryId ];
  20104. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement * multiDrawMultiplier;
  20105. multiDrawCounts[ multiDrawCount ] = geometryInfo.count * multiDrawMultiplier;
  20106. indirectArray[ multiDrawCount ] = i;
  20107. multiDrawCount ++;
  20108. }
  20109. }
  20110. }
  20111. }
  20112. indirectTexture.needsUpdate = true;
  20113. this._multiDrawCount = multiDrawCount;
  20114. this._visibilityChanged = false;
  20115. }
  20116. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  20117. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  20118. }
  20119. }
  20120. /**
  20121. * A material for rendering line primitives.
  20122. *
  20123. * Materials define the appearance of renderable 3D objects.
  20124. *
  20125. * ```js
  20126. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  20127. * ```
  20128. *
  20129. * @augments Material
  20130. */
  20131. class LineBasicMaterial extends Material {
  20132. /**
  20133. * Constructs a new line basic material.
  20134. *
  20135. * @param {Object} [parameters] - An object with one or more properties
  20136. * defining the material's appearance. Any property of the material
  20137. * (including any property from inherited materials) can be passed
  20138. * in here. Color values can be passed any type of value accepted
  20139. * by {@link Color#set}.
  20140. */
  20141. constructor( parameters ) {
  20142. super();
  20143. /**
  20144. * This flag can be used for type testing.
  20145. *
  20146. * @type {boolean}
  20147. * @readonly
  20148. * @default true
  20149. */
  20150. this.isLineBasicMaterial = true;
  20151. this.type = 'LineBasicMaterial';
  20152. /**
  20153. * Color of the material.
  20154. *
  20155. * @type {Color}
  20156. * @default (1,1,1)
  20157. */
  20158. this.color = new Color( 0xffffff );
  20159. /**
  20160. * Sets the color of the lines using data from a texture. The texture map
  20161. * color is modulated by the diffuse `color`.
  20162. *
  20163. * @type {?Texture}
  20164. * @default null
  20165. */
  20166. this.map = null;
  20167. /**
  20168. * Controls line thickness or lines.
  20169. *
  20170. * Can only be used with {@link SVGRenderer}. WebGL and WebGPU
  20171. * ignore this setting and always render line primitives with a
  20172. * width of one pixel.
  20173. *
  20174. * @type {number}
  20175. * @default 1
  20176. */
  20177. this.linewidth = 1;
  20178. /**
  20179. * Defines appearance of line ends.
  20180. *
  20181. * Can only be used with {@link SVGRenderer}.
  20182. *
  20183. * @type {('butt'|'round'|'square')}
  20184. * @default 'round'
  20185. */
  20186. this.linecap = 'round';
  20187. /**
  20188. * Defines appearance of line joints.
  20189. *
  20190. * Can only be used with {@link SVGRenderer}.
  20191. *
  20192. * @type {('round'|'bevel'|'miter')}
  20193. * @default 'round'
  20194. */
  20195. this.linejoin = 'round';
  20196. /**
  20197. * Whether the material is affected by fog or not.
  20198. *
  20199. * @type {boolean}
  20200. * @default true
  20201. */
  20202. this.fog = true;
  20203. this.setValues( parameters );
  20204. }
  20205. copy( source ) {
  20206. super.copy( source );
  20207. this.color.copy( source.color );
  20208. this.map = source.map;
  20209. this.linewidth = source.linewidth;
  20210. this.linecap = source.linecap;
  20211. this.linejoin = source.linejoin;
  20212. this.fog = source.fog;
  20213. return this;
  20214. }
  20215. }
  20216. const _vStart = /*@__PURE__*/ new Vector3();
  20217. const _vEnd = /*@__PURE__*/ new Vector3();
  20218. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  20219. const _ray$1 = /*@__PURE__*/ new Ray();
  20220. const _sphere$1 = /*@__PURE__*/ new Sphere();
  20221. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  20222. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  20223. /**
  20224. * A continuous line. The line are rendered by connecting consecutive
  20225. * vertices with straight lines.
  20226. *
  20227. * ```js
  20228. * const material = new THREE.LineBasicMaterial( { color: 0x0000ff } );
  20229. *
  20230. * const points = [];
  20231. * points.push( new THREE.Vector3( - 10, 0, 0 ) );
  20232. * points.push( new THREE.Vector3( 0, 10, 0 ) );
  20233. * points.push( new THREE.Vector3( 10, 0, 0 ) );
  20234. *
  20235. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  20236. *
  20237. * const line = new THREE.Line( geometry, material );
  20238. * scene.add( line );
  20239. * ```
  20240. *
  20241. * @augments Object3D
  20242. */
  20243. class Line extends Object3D {
  20244. /**
  20245. * Constructs a new line.
  20246. *
  20247. * @param {BufferGeometry} [geometry] - The line geometry.
  20248. * @param {Material|Array<Material>} [material] - The line material.
  20249. */
  20250. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  20251. super();
  20252. /**
  20253. * This flag can be used for type testing.
  20254. *
  20255. * @type {boolean}
  20256. * @readonly
  20257. * @default true
  20258. */
  20259. this.isLine = true;
  20260. this.type = 'Line';
  20261. /**
  20262. * The line geometry.
  20263. *
  20264. * @type {BufferGeometry}
  20265. */
  20266. this.geometry = geometry;
  20267. /**
  20268. * The line material.
  20269. *
  20270. * @type {Material|Array<Material>}
  20271. * @default LineBasicMaterial
  20272. */
  20273. this.material = material;
  20274. /**
  20275. * A dictionary representing the morph targets in the geometry. The key is the
  20276. * morph targets name, the value its attribute index. This member is `undefined`
  20277. * by default and only set when morph targets are detected in the geometry.
  20278. *
  20279. * @type {Object<string,number>|undefined}
  20280. * @default undefined
  20281. */
  20282. this.morphTargetDictionary = undefined;
  20283. /**
  20284. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  20285. * is applied. This member is `undefined` by default and only set when morph targets are
  20286. * detected in the geometry.
  20287. *
  20288. * @type {Array<number>|undefined}
  20289. * @default undefined
  20290. */
  20291. this.morphTargetInfluences = undefined;
  20292. this.updateMorphTargets();
  20293. }
  20294. copy( source, recursive ) {
  20295. super.copy( source, recursive );
  20296. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  20297. this.geometry = source.geometry;
  20298. return this;
  20299. }
  20300. /**
  20301. * Computes an array of distance values which are necessary for rendering dashed lines.
  20302. * For each vertex in the geometry, the method calculates the cumulative length from the
  20303. * current point to the very beginning of the line.
  20304. *
  20305. * @return {Line} A reference to this line.
  20306. */
  20307. computeLineDistances() {
  20308. const geometry = this.geometry;
  20309. // we assume non-indexed geometry
  20310. if ( geometry.index === null ) {
  20311. const positionAttribute = geometry.attributes.position;
  20312. const lineDistances = [ 0 ];
  20313. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  20314. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  20315. _vEnd.fromBufferAttribute( positionAttribute, i );
  20316. lineDistances[ i ] = lineDistances[ i - 1 ];
  20317. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  20318. }
  20319. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20320. } else {
  20321. warn( 'Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20322. }
  20323. return this;
  20324. }
  20325. /**
  20326. * Computes intersection points between a casted ray and this line.
  20327. *
  20328. * @param {Raycaster} raycaster - The raycaster.
  20329. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  20330. */
  20331. raycast( raycaster, intersects ) {
  20332. const geometry = this.geometry;
  20333. const matrixWorld = this.matrixWorld;
  20334. const threshold = raycaster.params.Line.threshold;
  20335. const drawRange = geometry.drawRange;
  20336. // Checking boundingSphere distance to ray
  20337. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20338. _sphere$1.copy( geometry.boundingSphere );
  20339. _sphere$1.applyMatrix4( matrixWorld );
  20340. _sphere$1.radius += threshold;
  20341. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  20342. //
  20343. _inverseMatrix$1.copy( matrixWorld ).invert();
  20344. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  20345. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20346. const localThresholdSq = localThreshold * localThreshold;
  20347. const step = this.isLineSegments ? 2 : 1;
  20348. const index = geometry.index;
  20349. const attributes = geometry.attributes;
  20350. const positionAttribute = attributes.position;
  20351. if ( index !== null ) {
  20352. const start = Math.max( 0, drawRange.start );
  20353. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  20354. for ( let i = start, l = end - 1; i < l; i += step ) {
  20355. const a = index.getX( i );
  20356. const b = index.getX( i + 1 );
  20357. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i );
  20358. if ( intersect ) {
  20359. intersects.push( intersect );
  20360. }
  20361. }
  20362. if ( this.isLineLoop ) {
  20363. const a = index.getX( end - 1 );
  20364. const b = index.getX( start );
  20365. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 );
  20366. if ( intersect ) {
  20367. intersects.push( intersect );
  20368. }
  20369. }
  20370. } else {
  20371. const start = Math.max( 0, drawRange.start );
  20372. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  20373. for ( let i = start, l = end - 1; i < l; i += step ) {
  20374. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i );
  20375. if ( intersect ) {
  20376. intersects.push( intersect );
  20377. }
  20378. }
  20379. if ( this.isLineLoop ) {
  20380. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 );
  20381. if ( intersect ) {
  20382. intersects.push( intersect );
  20383. }
  20384. }
  20385. }
  20386. }
  20387. /**
  20388. * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences}
  20389. * to make sure existing morph targets can influence this 3D object.
  20390. */
  20391. updateMorphTargets() {
  20392. const geometry = this.geometry;
  20393. const morphAttributes = geometry.morphAttributes;
  20394. const keys = Object.keys( morphAttributes );
  20395. if ( keys.length > 0 ) {
  20396. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  20397. if ( morphAttribute !== undefined ) {
  20398. this.morphTargetInfluences = [];
  20399. this.morphTargetDictionary = {};
  20400. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  20401. const name = morphAttribute[ m ].name || String( m );
  20402. this.morphTargetInfluences.push( 0 );
  20403. this.morphTargetDictionary[ name ] = m;
  20404. }
  20405. }
  20406. }
  20407. }
  20408. }
  20409. function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) {
  20410. const positionAttribute = object.geometry.attributes.position;
  20411. _vStart.fromBufferAttribute( positionAttribute, a );
  20412. _vEnd.fromBufferAttribute( positionAttribute, b );
  20413. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  20414. if ( distSq > thresholdSq ) return;
  20415. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  20416. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  20417. if ( distance < raycaster.near || distance > raycaster.far ) return;
  20418. return {
  20419. distance: distance,
  20420. // What do we want? intersection point on the ray or on the segment??
  20421. // point: raycaster.ray.at( distance ),
  20422. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  20423. index: i,
  20424. face: null,
  20425. faceIndex: null,
  20426. barycoord: null,
  20427. object: object
  20428. };
  20429. }
  20430. const _start = /*@__PURE__*/ new Vector3();
  20431. const _end = /*@__PURE__*/ new Vector3();
  20432. /**
  20433. * A series of lines drawn between pairs of vertices.
  20434. *
  20435. * @augments Line
  20436. */
  20437. class LineSegments extends Line {
  20438. /**
  20439. * Constructs a new line segments.
  20440. *
  20441. * @param {BufferGeometry} [geometry] - The line geometry.
  20442. * @param {Material|Array<Material>} [material] - The line material.
  20443. */
  20444. constructor( geometry, material ) {
  20445. super( geometry, material );
  20446. /**
  20447. * This flag can be used for type testing.
  20448. *
  20449. * @type {boolean}
  20450. * @readonly
  20451. * @default true
  20452. */
  20453. this.isLineSegments = true;
  20454. this.type = 'LineSegments';
  20455. }
  20456. computeLineDistances() {
  20457. const geometry = this.geometry;
  20458. // we assume non-indexed geometry
  20459. if ( geometry.index === null ) {
  20460. const positionAttribute = geometry.attributes.position;
  20461. const lineDistances = [];
  20462. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  20463. _start.fromBufferAttribute( positionAttribute, i );
  20464. _end.fromBufferAttribute( positionAttribute, i + 1 );
  20465. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  20466. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  20467. }
  20468. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20469. } else {
  20470. warn( 'LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20471. }
  20472. return this;
  20473. }
  20474. }
  20475. /**
  20476. * A continuous line. This is nearly the same as {@link Line} the only difference
  20477. * is that the last vertex is connected with the first vertex in order to close
  20478. * the line to form a loop.
  20479. *
  20480. * @augments Line
  20481. */
  20482. class LineLoop extends Line {
  20483. /**
  20484. * Constructs a new line loop.
  20485. *
  20486. * @param {BufferGeometry} [geometry] - The line geometry.
  20487. * @param {Material|Array<Material>} [material] - The line material.
  20488. */
  20489. constructor( geometry, material ) {
  20490. super( geometry, material );
  20491. /**
  20492. * This flag can be used for type testing.
  20493. *
  20494. * @type {boolean}
  20495. * @readonly
  20496. * @default true
  20497. */
  20498. this.isLineLoop = true;
  20499. this.type = 'LineLoop';
  20500. }
  20501. }
  20502. /**
  20503. * A material for rendering point primitives.
  20504. *
  20505. * Materials define the appearance of renderable 3D objects.
  20506. *
  20507. * ```js
  20508. * const vertices = [];
  20509. *
  20510. * for ( let i = 0; i < 10000; i ++ ) {
  20511. * const x = THREE.MathUtils.randFloatSpread( 2000 );
  20512. * const y = THREE.MathUtils.randFloatSpread( 2000 );
  20513. * const z = THREE.MathUtils.randFloatSpread( 2000 );
  20514. *
  20515. * vertices.push( x, y, z );
  20516. * }
  20517. *
  20518. * const geometry = new THREE.BufferGeometry();
  20519. * geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  20520. * const material = new THREE.PointsMaterial( { color: 0x888888 } );
  20521. * const points = new THREE.Points( geometry, material );
  20522. * scene.add( points );
  20523. * ```
  20524. *
  20525. * @augments Material
  20526. */
  20527. class PointsMaterial extends Material {
  20528. /**
  20529. * Constructs a new points material.
  20530. *
  20531. * @param {Object} [parameters] - An object with one or more properties
  20532. * defining the material's appearance. Any property of the material
  20533. * (including any property from inherited materials) can be passed
  20534. * in here. Color values can be passed any type of value accepted
  20535. * by {@link Color#set}.
  20536. */
  20537. constructor( parameters ) {
  20538. super();
  20539. /**
  20540. * This flag can be used for type testing.
  20541. *
  20542. * @type {boolean}
  20543. * @readonly
  20544. * @default true
  20545. */
  20546. this.isPointsMaterial = true;
  20547. this.type = 'PointsMaterial';
  20548. /**
  20549. * Color of the material.
  20550. *
  20551. * @type {Color}
  20552. * @default (1,1,1)
  20553. */
  20554. this.color = new Color( 0xffffff );
  20555. /**
  20556. * The color map. May optionally include an alpha channel, typically combined
  20557. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  20558. * color is modulated by the diffuse `color`.
  20559. *
  20560. * @type {?Texture}
  20561. * @default null
  20562. */
  20563. this.map = null;
  20564. /**
  20565. * The alpha map is a grayscale texture that controls the opacity across the
  20566. * surface (black: fully transparent; white: fully opaque).
  20567. *
  20568. * Only the color of the texture is used, ignoring the alpha channel if one
  20569. * exists. For RGB and RGBA textures, the renderer will use the green channel
  20570. * when sampling this texture due to the extra bit of precision provided for
  20571. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  20572. * luminance/alpha textures will also still work as expected.
  20573. *
  20574. * @type {?Texture}
  20575. * @default null
  20576. */
  20577. this.alphaMap = null;
  20578. /**
  20579. * Defines the size of the points in pixels.
  20580. *
  20581. * Might be capped if the value exceeds hardware dependent parameters like [gl.ALIASED_POINT_SIZE_RANGE](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getParamete).
  20582. *
  20583. * @type {number}
  20584. * @default 1
  20585. */
  20586. this.size = 1;
  20587. /**
  20588. * Specifies whether size of individual points is attenuated by the camera depth (perspective camera only).
  20589. *
  20590. * @type {boolean}
  20591. * @default true
  20592. */
  20593. this.sizeAttenuation = true;
  20594. /**
  20595. * Whether the material is affected by fog or not.
  20596. *
  20597. * @type {boolean}
  20598. * @default true
  20599. */
  20600. this.fog = true;
  20601. this.setValues( parameters );
  20602. }
  20603. copy( source ) {
  20604. super.copy( source );
  20605. this.color.copy( source.color );
  20606. this.map = source.map;
  20607. this.alphaMap = source.alphaMap;
  20608. this.size = source.size;
  20609. this.sizeAttenuation = source.sizeAttenuation;
  20610. this.fog = source.fog;
  20611. return this;
  20612. }
  20613. }
  20614. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  20615. const _ray = /*@__PURE__*/ new Ray();
  20616. const _sphere = /*@__PURE__*/ new Sphere();
  20617. const _position$3 = /*@__PURE__*/ new Vector3();
  20618. /**
  20619. * A class for displaying points or point clouds.
  20620. *
  20621. * @augments Object3D
  20622. */
  20623. class Points extends Object3D {
  20624. /**
  20625. * Constructs a new point cloud.
  20626. *
  20627. * @param {BufferGeometry} [geometry] - The points geometry.
  20628. * @param {Material|Array<Material>} [material] - The points material.
  20629. */
  20630. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  20631. super();
  20632. /**
  20633. * This flag can be used for type testing.
  20634. *
  20635. * @type {boolean}
  20636. * @readonly
  20637. * @default true
  20638. */
  20639. this.isPoints = true;
  20640. this.type = 'Points';
  20641. /**
  20642. * The points geometry.
  20643. *
  20644. * @type {BufferGeometry}
  20645. */
  20646. this.geometry = geometry;
  20647. /**
  20648. * The line material.
  20649. *
  20650. * @type {Material|Array<Material>}
  20651. * @default PointsMaterial
  20652. */
  20653. this.material = material;
  20654. /**
  20655. * A dictionary representing the morph targets in the geometry. The key is the
  20656. * morph targets name, the value its attribute index. This member is `undefined`
  20657. * by default and only set when morph targets are detected in the geometry.
  20658. *
  20659. * @type {Object<string,number>|undefined}
  20660. * @default undefined
  20661. */
  20662. this.morphTargetDictionary = undefined;
  20663. /**
  20664. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  20665. * is applied. This member is `undefined` by default and only set when morph targets are
  20666. * detected in the geometry.
  20667. *
  20668. * @type {Array<number>|undefined}
  20669. * @default undefined
  20670. */
  20671. this.morphTargetInfluences = undefined;
  20672. this.updateMorphTargets();
  20673. }
  20674. copy( source, recursive ) {
  20675. super.copy( source, recursive );
  20676. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  20677. this.geometry = source.geometry;
  20678. return this;
  20679. }
  20680. /**
  20681. * Computes intersection points between a casted ray and this point cloud.
  20682. *
  20683. * @param {Raycaster} raycaster - The raycaster.
  20684. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  20685. */
  20686. raycast( raycaster, intersects ) {
  20687. const geometry = this.geometry;
  20688. const matrixWorld = this.matrixWorld;
  20689. const threshold = raycaster.params.Points.threshold;
  20690. const drawRange = geometry.drawRange;
  20691. // Checking boundingSphere distance to ray
  20692. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20693. _sphere.copy( geometry.boundingSphere );
  20694. _sphere.applyMatrix4( matrixWorld );
  20695. _sphere.radius += threshold;
  20696. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  20697. //
  20698. _inverseMatrix.copy( matrixWorld ).invert();
  20699. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  20700. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20701. const localThresholdSq = localThreshold * localThreshold;
  20702. const index = geometry.index;
  20703. const attributes = geometry.attributes;
  20704. const positionAttribute = attributes.position;
  20705. if ( index !== null ) {
  20706. const start = Math.max( 0, drawRange.start );
  20707. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  20708. for ( let i = start, il = end; i < il; i ++ ) {
  20709. const a = index.getX( i );
  20710. _position$3.fromBufferAttribute( positionAttribute, a );
  20711. testPoint( _position$3, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  20712. }
  20713. } else {
  20714. const start = Math.max( 0, drawRange.start );
  20715. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  20716. for ( let i = start, l = end; i < l; i ++ ) {
  20717. _position$3.fromBufferAttribute( positionAttribute, i );
  20718. testPoint( _position$3, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  20719. }
  20720. }
  20721. }
  20722. /**
  20723. * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences}
  20724. * to make sure existing morph targets can influence this 3D object.
  20725. */
  20726. updateMorphTargets() {
  20727. const geometry = this.geometry;
  20728. const morphAttributes = geometry.morphAttributes;
  20729. const keys = Object.keys( morphAttributes );
  20730. if ( keys.length > 0 ) {
  20731. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  20732. if ( morphAttribute !== undefined ) {
  20733. this.morphTargetInfluences = [];
  20734. this.morphTargetDictionary = {};
  20735. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  20736. const name = morphAttribute[ m ].name || String( m );
  20737. this.morphTargetInfluences.push( 0 );
  20738. this.morphTargetDictionary[ name ] = m;
  20739. }
  20740. }
  20741. }
  20742. }
  20743. }
  20744. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  20745. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  20746. if ( rayPointDistanceSq < localThresholdSq ) {
  20747. const intersectPoint = new Vector3();
  20748. _ray.closestPointToPoint( point, intersectPoint );
  20749. intersectPoint.applyMatrix4( matrixWorld );
  20750. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  20751. if ( distance < raycaster.near || distance > raycaster.far ) return;
  20752. intersects.push( {
  20753. distance: distance,
  20754. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  20755. point: intersectPoint,
  20756. index: index,
  20757. face: null,
  20758. faceIndex: null,
  20759. barycoord: null,
  20760. object: object
  20761. } );
  20762. }
  20763. }
  20764. /**
  20765. * A texture for use with a video.
  20766. *
  20767. * ```js
  20768. * // assuming you have created a HTML video element with id="video"
  20769. * const video = document.getElementById( 'video' );
  20770. * const texture = new THREE.VideoTexture( video );
  20771. * ```
  20772. *
  20773. * Note: When using video textures with {@link WebGPURenderer}, {@link Texture#colorSpace} must be
  20774. * set to THREE.SRGBColorSpace.
  20775. *
  20776. * Note: After the initial use of a texture, its dimensions, format, and type
  20777. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  20778. *
  20779. * @augments Texture
  20780. */
  20781. class VideoTexture extends Texture {
  20782. /**
  20783. * Constructs a new video texture.
  20784. *
  20785. * @param {HTMLVideoElement} video - The video element to use as a data source for the texture.
  20786. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  20787. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  20788. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  20789. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  20790. * @param {number} [minFilter=LinearFilter] - The min filter value.
  20791. * @param {number} [format=RGBAFormat] - The texture format.
  20792. * @param {number} [type=UnsignedByteType] - The texture type.
  20793. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  20794. */
  20795. constructor( video, mapping, wrapS, wrapT, magFilter = LinearFilter, minFilter = LinearFilter, format, type, anisotropy ) {
  20796. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  20797. /**
  20798. * This flag can be used for type testing.
  20799. *
  20800. * @type {boolean}
  20801. * @readonly
  20802. * @default true
  20803. */
  20804. this.isVideoTexture = true;
  20805. /**
  20806. * Whether to generate mipmaps (if possible) for a texture.
  20807. *
  20808. * Overwritten and set to `false` by default.
  20809. *
  20810. * @type {boolean}
  20811. * @default false
  20812. */
  20813. this.generateMipmaps = false;
  20814. /**
  20815. * The video frame request callback identifier, which is a positive integer.
  20816. *
  20817. * Value of 0 represents no scheduled rVFC.
  20818. *
  20819. * @private
  20820. * @type {number}
  20821. */
  20822. this._requestVideoFrameCallbackId = 0;
  20823. const scope = this;
  20824. function updateVideo() {
  20825. scope.needsUpdate = true;
  20826. scope._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  20827. }
  20828. if ( 'requestVideoFrameCallback' in video ) {
  20829. this._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  20830. }
  20831. }
  20832. clone() {
  20833. return new this.constructor( this.image ).copy( this );
  20834. }
  20835. /**
  20836. * This method is called automatically by the renderer and sets {@link Texture#needsUpdate}
  20837. * to `true` every time a new frame is available.
  20838. *
  20839. * Only relevant if `requestVideoFrameCallback` is not supported in the browser.
  20840. */
  20841. update() {
  20842. const video = this.image;
  20843. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  20844. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  20845. this.needsUpdate = true;
  20846. }
  20847. }
  20848. dispose() {
  20849. if ( this._requestVideoFrameCallbackId !== 0 ) {
  20850. this.source.data.cancelVideoFrameCallback( this._requestVideoFrameCallbackId );
  20851. this._requestVideoFrameCallbackId = 0;
  20852. }
  20853. super.dispose();
  20854. }
  20855. }
  20856. /**
  20857. * This class can be used as an alternative way to define video data. Instead of using
  20858. * an instance of `HTMLVideoElement` like with `VideoTexture`, `VideoFrameTexture` expects each frame is
  20859. * defined manually via {@link VideoFrameTexture#setFrame}. A typical use case for this module is when
  20860. * video frames are decoded with the WebCodecs API.
  20861. *
  20862. * ```js
  20863. * const texture = new THREE.VideoFrameTexture();
  20864. * texture.setFrame( frame );
  20865. * ```
  20866. *
  20867. * @augments VideoTexture
  20868. */
  20869. class VideoFrameTexture extends VideoTexture {
  20870. /**
  20871. * Constructs a new video frame texture.
  20872. *
  20873. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  20874. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  20875. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  20876. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  20877. * @param {number} [minFilter=LinearFilter] - The min filter value.
  20878. * @param {number} [format=RGBAFormat] - The texture format.
  20879. * @param {number} [type=UnsignedByteType] - The texture type.
  20880. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  20881. */
  20882. constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  20883. super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  20884. /**
  20885. * This flag can be used for type testing.
  20886. *
  20887. * @type {boolean}
  20888. * @readonly
  20889. * @default true
  20890. */
  20891. this.isVideoFrameTexture = true;
  20892. }
  20893. /**
  20894. * This method overwritten with an empty implementation since
  20895. * this type of texture is updated via `setFrame()`.
  20896. */
  20897. update() {}
  20898. clone() {
  20899. return new this.constructor().copy( this ); // restoring Texture.clone()
  20900. }
  20901. /**
  20902. * Sets the current frame of the video. This will automatically update the texture
  20903. * so the data can be used for rendering.
  20904. *
  20905. * @param {VideoFrame} frame - The video frame.
  20906. */
  20907. setFrame( frame ) {
  20908. this.image = frame;
  20909. this.needsUpdate = true;
  20910. }
  20911. }
  20912. /**
  20913. * This class can only be used in combination with `copyFramebufferToTexture()` methods
  20914. * of renderers. It extracts the contents of the current bound framebuffer and provides it
  20915. * as a texture for further usage.
  20916. *
  20917. * ```js
  20918. * const pixelRatio = window.devicePixelRatio;
  20919. * const textureSize = 128 * pixelRatio;
  20920. *
  20921. * const frameTexture = new FramebufferTexture( textureSize, textureSize );
  20922. *
  20923. * // calculate start position for copying part of the frame data
  20924. * const vector = new Vector2();
  20925. * vector.x = ( window.innerWidth * pixelRatio / 2 ) - ( textureSize / 2 );
  20926. * vector.y = ( window.innerHeight * pixelRatio / 2 ) - ( textureSize / 2 );
  20927. *
  20928. * renderer.render( scene, camera );
  20929. *
  20930. * // copy part of the rendered frame into the framebuffer texture
  20931. * renderer.copyFramebufferToTexture( frameTexture, vector );
  20932. * ```
  20933. *
  20934. * @augments Texture
  20935. */
  20936. class FramebufferTexture extends Texture {
  20937. /**
  20938. * Constructs a new framebuffer texture.
  20939. *
  20940. * @param {number} [width] - The width of the texture.
  20941. * @param {number} [height] - The height of the texture.
  20942. */
  20943. constructor( width, height ) {
  20944. super( { width, height } );
  20945. /**
  20946. * This flag can be used for type testing.
  20947. *
  20948. * @type {boolean}
  20949. * @readonly
  20950. * @default true
  20951. */
  20952. this.isFramebufferTexture = true;
  20953. /**
  20954. * How the texture is sampled when a texel covers more than one pixel.
  20955. *
  20956. * Overwritten and set to `NearestFilter` by default to disable filtering.
  20957. *
  20958. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  20959. * @default NearestFilter
  20960. */
  20961. this.magFilter = NearestFilter;
  20962. /**
  20963. * How the texture is sampled when a texel covers less than one pixel.
  20964. *
  20965. * Overwritten and set to `NearestFilter` by default to disable filtering.
  20966. *
  20967. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  20968. * @default NearestFilter
  20969. */
  20970. this.minFilter = NearestFilter;
  20971. /**
  20972. * Whether to generate mipmaps (if possible) for a texture.
  20973. *
  20974. * Overwritten and set to `false` by default.
  20975. *
  20976. * @type {boolean}
  20977. * @default false
  20978. */
  20979. this.generateMipmaps = false;
  20980. this.needsUpdate = true;
  20981. }
  20982. }
  20983. /**
  20984. * Creates a texture based on data in compressed form.
  20985. *
  20986. * These texture are usually loaded with {@link CompressedTextureLoader}.
  20987. *
  20988. * @augments Texture
  20989. */
  20990. class CompressedTexture extends Texture {
  20991. /**
  20992. * Constructs a new compressed texture.
  20993. *
  20994. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  20995. * the data and dimensions.
  20996. * @param {number} width - The width of the texture.
  20997. * @param {number} height - The height of the texture.
  20998. * @param {number} [format=RGBAFormat] - The texture format.
  20999. * @param {number} [type=UnsignedByteType] - The texture type.
  21000. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21001. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21002. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21003. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21004. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21005. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21006. * @param {string} [colorSpace=NoColorSpace] - The color space.
  21007. */
  21008. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  21009. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  21010. /**
  21011. * This flag can be used for type testing.
  21012. *
  21013. * @type {boolean}
  21014. * @readonly
  21015. * @default true
  21016. */
  21017. this.isCompressedTexture = true;
  21018. /**
  21019. * The image property of a compressed texture just defines its dimensions.
  21020. *
  21021. * @type {{width:number,height:number}}
  21022. */
  21023. this.image = { width: width, height: height };
  21024. /**
  21025. * This array holds for all mipmaps (including the bases mip) the data and dimensions.
  21026. *
  21027. * @type {Array<Object>}
  21028. */
  21029. this.mipmaps = mipmaps;
  21030. /**
  21031. * If set to `true`, the texture is flipped along the vertical axis when
  21032. * uploaded to the GPU.
  21033. *
  21034. * Overwritten and set to `false` by default since it is not possible to
  21035. * flip compressed textures.
  21036. *
  21037. * @type {boolean}
  21038. * @default false
  21039. * @readonly
  21040. */
  21041. this.flipY = false;
  21042. /**
  21043. * Whether to generate mipmaps (if possible) for a texture.
  21044. *
  21045. * Overwritten and set to `false` by default since it is not
  21046. * possible to generate mipmaps for compressed data. Mipmaps
  21047. * must be embedded in the compressed texture file.
  21048. *
  21049. * @type {boolean}
  21050. * @default false
  21051. * @readonly
  21052. */
  21053. this.generateMipmaps = false;
  21054. }
  21055. }
  21056. /**
  21057. * Creates a texture 2D array based on data in compressed form.
  21058. *
  21059. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21060. *
  21061. * @augments CompressedTexture
  21062. */
  21063. class CompressedArrayTexture extends CompressedTexture {
  21064. /**
  21065. * Constructs a new compressed array texture.
  21066. *
  21067. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21068. * the data and dimensions.
  21069. * @param {number} width - The width of the texture.
  21070. * @param {number} height - The height of the texture.
  21071. * @param {number} depth - The depth of the texture.
  21072. * @param {number} [format=RGBAFormat] - The min filter value.
  21073. * @param {number} [type=UnsignedByteType] - The min filter value.
  21074. */
  21075. constructor( mipmaps, width, height, depth, format, type ) {
  21076. super( mipmaps, width, height, format, type );
  21077. /**
  21078. * This flag can be used for type testing.
  21079. *
  21080. * @type {boolean}
  21081. * @readonly
  21082. * @default true
  21083. */
  21084. this.isCompressedArrayTexture = true;
  21085. /**
  21086. * The image property of a compressed texture just defines its dimensions.
  21087. *
  21088. * @name CompressedArrayTexture#image
  21089. * @type {{width:number,height:number,depth:number}}
  21090. */
  21091. this.image.depth = depth;
  21092. /**
  21093. * This defines how the texture is wrapped in the depth and corresponds to
  21094. * *W* in UVW mapping.
  21095. *
  21096. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  21097. * @default ClampToEdgeWrapping
  21098. */
  21099. this.wrapR = ClampToEdgeWrapping;
  21100. /**
  21101. * A set of all layers which need to be updated in the texture.
  21102. *
  21103. * @type {Set<number>}
  21104. */
  21105. this.layerUpdates = new Set();
  21106. }
  21107. /**
  21108. * Describes that a specific layer of the texture needs to be updated.
  21109. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  21110. * entire compressed texture array is sent to the GPU. Marking specific
  21111. * layers will only transmit subsets of all mipmaps associated with a
  21112. * specific depth in the array which is often much more performant.
  21113. *
  21114. * @param {number} layerIndex - The layer index that should be updated.
  21115. */
  21116. addLayerUpdate( layerIndex ) {
  21117. this.layerUpdates.add( layerIndex );
  21118. }
  21119. /**
  21120. * Resets the layer updates registry.
  21121. */
  21122. clearLayerUpdates() {
  21123. this.layerUpdates.clear();
  21124. }
  21125. }
  21126. /**
  21127. * Creates a cube texture based on data in compressed form.
  21128. *
  21129. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21130. *
  21131. * @augments CompressedTexture
  21132. */
  21133. class CompressedCubeTexture extends CompressedTexture {
  21134. /**
  21135. * Constructs a new compressed texture.
  21136. *
  21137. * @param {Array<CompressedTexture>} images - An array of compressed textures.
  21138. * @param {number} [format=RGBAFormat] - The texture format.
  21139. * @param {number} [type=UnsignedByteType] - The texture type.
  21140. */
  21141. constructor( images, format, type ) {
  21142. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  21143. /**
  21144. * This flag can be used for type testing.
  21145. *
  21146. * @type {boolean}
  21147. * @readonly
  21148. * @default true
  21149. */
  21150. this.isCompressedCubeTexture = true;
  21151. /**
  21152. * This flag can be used for type testing.
  21153. *
  21154. * @type {boolean}
  21155. * @readonly
  21156. * @default true
  21157. */
  21158. this.isCubeTexture = true;
  21159. this.image = images;
  21160. }
  21161. }
  21162. /**
  21163. * Creates a cube texture made up of six images.
  21164. *
  21165. * ```js
  21166. * const loader = new THREE.CubeTextureLoader();
  21167. * loader.setPath( 'textures/cube/pisa/' );
  21168. *
  21169. * const textureCube = loader.load( [
  21170. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  21171. * ] );
  21172. *
  21173. * const material = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } );
  21174. * ```
  21175. *
  21176. * @augments Texture
  21177. */
  21178. class CubeTexture extends Texture {
  21179. /**
  21180. * Constructs a new cube texture.
  21181. *
  21182. * @param {Array<Image>} [images=[]] - An array holding a image for each side of a cube.
  21183. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  21184. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21185. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21186. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21187. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21188. * @param {number} [format=RGBAFormat] - The texture format.
  21189. * @param {number} [type=UnsignedByteType] - The texture type.
  21190. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21191. * @param {string} [colorSpace=NoColorSpace] - The color space value.
  21192. */
  21193. constructor( images = [], mapping = CubeReflectionMapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  21194. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  21195. /**
  21196. * This flag can be used for type testing.
  21197. *
  21198. * @type {boolean}
  21199. * @readonly
  21200. * @default true
  21201. */
  21202. this.isCubeTexture = true;
  21203. /**
  21204. * If set to `true`, the texture is flipped along the vertical axis when
  21205. * uploaded to the GPU.
  21206. *
  21207. * Overwritten and set to `false` by default.
  21208. *
  21209. * @type {boolean}
  21210. * @default false
  21211. */
  21212. this.flipY = false;
  21213. }
  21214. /**
  21215. * Alias for {@link CubeTexture#image}.
  21216. *
  21217. * @type {Array<Image>}
  21218. */
  21219. get images() {
  21220. return this.image;
  21221. }
  21222. set images( value ) {
  21223. this.image = value;
  21224. }
  21225. }
  21226. /**
  21227. * Creates a texture from a canvas element.
  21228. *
  21229. * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate}
  21230. * to `true` immediately since a canvas can directly be used for rendering.
  21231. *
  21232. * @augments Texture
  21233. */
  21234. class CanvasTexture extends Texture {
  21235. /**
  21236. * Constructs a new texture.
  21237. *
  21238. * @param {HTMLCanvasElement} [canvas] - The HTML canvas element.
  21239. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21240. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21241. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21242. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21243. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21244. * @param {number} [format=RGBAFormat] - The texture format.
  21245. * @param {number} [type=UnsignedByteType] - The texture type.
  21246. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21247. */
  21248. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21249. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21250. /**
  21251. * This flag can be used for type testing.
  21252. *
  21253. * @type {boolean}
  21254. * @readonly
  21255. * @default true
  21256. */
  21257. this.isCanvasTexture = true;
  21258. this.needsUpdate = true;
  21259. }
  21260. }
  21261. /**
  21262. * This class can be used to automatically save the depth information of a
  21263. * rendering into a texture.
  21264. *
  21265. * @augments Texture
  21266. */
  21267. class DepthTexture extends Texture {
  21268. /**
  21269. * Constructs a new depth texture.
  21270. *
  21271. * @param {number} width - The width of the texture.
  21272. * @param {number} height - The height of the texture.
  21273. * @param {number} [type=UnsignedIntType] - The texture type.
  21274. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21275. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21276. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21277. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21278. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21279. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21280. * @param {number} [format=DepthFormat] - The texture format.
  21281. * @param {number} [depth=1] - The depth of the texture.
  21282. */
  21283. constructor( width, height, type = UnsignedIntType, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat, depth = 1 ) {
  21284. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  21285. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  21286. }
  21287. const image = { width: width, height: height, depth: depth };
  21288. super( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21289. /**
  21290. * This flag can be used for type testing.
  21291. *
  21292. * @type {boolean}
  21293. * @readonly
  21294. * @default true
  21295. */
  21296. this.isDepthTexture = true;
  21297. /**
  21298. * If set to `true`, the texture is flipped along the vertical axis when
  21299. * uploaded to the GPU.
  21300. *
  21301. * Overwritten and set to `false` by default.
  21302. *
  21303. * @type {boolean}
  21304. * @default false
  21305. */
  21306. this.flipY = false;
  21307. /**
  21308. * Whether to generate mipmaps (if possible) for a texture.
  21309. *
  21310. * Overwritten and set to `false` by default.
  21311. *
  21312. * @type {boolean}
  21313. * @default false
  21314. */
  21315. this.generateMipmaps = false;
  21316. /**
  21317. * Code corresponding to the depth compare function.
  21318. *
  21319. * @type {?(NeverCompare|LessCompare|EqualCompare|LessEqualCompare|GreaterCompare|NotEqualCompare|GreaterEqualCompare|AlwaysCompare)}
  21320. * @default null
  21321. */
  21322. this.compareFunction = null;
  21323. }
  21324. copy( source ) {
  21325. super.copy( source );
  21326. this.source = new Source( Object.assign( {}, source.image ) ); // see #30540
  21327. this.compareFunction = source.compareFunction;
  21328. return this;
  21329. }
  21330. toJSON( meta ) {
  21331. const data = super.toJSON( meta );
  21332. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  21333. return data;
  21334. }
  21335. }
  21336. /**
  21337. * This class can be used to automatically save the depth information of a
  21338. * cube rendering into a cube texture with depth format. Used for PointLight shadows.
  21339. *
  21340. * @augments DepthTexture
  21341. */
  21342. class CubeDepthTexture extends DepthTexture {
  21343. /**
  21344. * Constructs a new cube depth texture.
  21345. *
  21346. * @param {number} size - The size (width and height) of each cube face.
  21347. * @param {number} [type=UnsignedIntType] - The texture type.
  21348. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  21349. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21350. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21351. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  21352. * @param {number} [minFilter=NearestFilter] - The min filter value.
  21353. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21354. * @param {number} [format=DepthFormat] - The texture format.
  21355. */
  21356. constructor( size, type = UnsignedIntType, mapping = CubeReflectionMapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat ) {
  21357. // Create 6 identical image descriptors for the cube faces
  21358. const image = { width: size, height: size, depth: 1 };
  21359. const images = [ image, image, image, image, image, image ];
  21360. // Call DepthTexture constructor with width, height
  21361. super( size, size, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format );
  21362. // Replace the single image with the array of 6 images
  21363. this.image = images;
  21364. /**
  21365. * This flag can be used for type testing.
  21366. *
  21367. * @type {boolean}
  21368. * @readonly
  21369. * @default true
  21370. */
  21371. this.isCubeDepthTexture = true;
  21372. /**
  21373. * Set to true for cube texture handling in WebGLTextures.
  21374. *
  21375. * @type {boolean}
  21376. * @readonly
  21377. * @default true
  21378. */
  21379. this.isCubeTexture = true;
  21380. }
  21381. /**
  21382. * Alias for {@link CubeDepthTexture#image}.
  21383. *
  21384. * @type {Array<Image>}
  21385. */
  21386. get images() {
  21387. return this.image;
  21388. }
  21389. set images( value ) {
  21390. this.image = value;
  21391. }
  21392. }
  21393. /**
  21394. * Represents a texture created externally with the same renderer context.
  21395. *
  21396. * This may be a texture from a protected media stream, device camera feed,
  21397. * or other data feeds like a depth sensor.
  21398. *
  21399. * Note that this class is only supported in {@link WebGLRenderer}, and in
  21400. * the {@link WebGPURenderer} WebGPU backend.
  21401. *
  21402. * @augments Texture
  21403. */
  21404. class ExternalTexture extends Texture {
  21405. /**
  21406. * Creates a new raw texture.
  21407. *
  21408. * @param {?(WebGLTexture|GPUTexture)} [sourceTexture=null] - The external texture.
  21409. */
  21410. constructor( sourceTexture = null ) {
  21411. super();
  21412. /**
  21413. * The external source texture.
  21414. *
  21415. * @type {?(WebGLTexture|GPUTexture)}
  21416. * @default null
  21417. */
  21418. this.sourceTexture = sourceTexture;
  21419. /**
  21420. * This flag can be used for type testing.
  21421. *
  21422. * @type {boolean}
  21423. * @readonly
  21424. * @default true
  21425. */
  21426. this.isExternalTexture = true;
  21427. }
  21428. copy( source ) {
  21429. super.copy( source );
  21430. this.sourceTexture = source.sourceTexture;
  21431. return this;
  21432. }
  21433. }
  21434. /**
  21435. * A geometry class for a rectangular cuboid with a given width, height, and depth.
  21436. * On creation, the cuboid is centred on the origin, with each edge parallel to one
  21437. * of the axes.
  21438. *
  21439. * ```js
  21440. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  21441. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  21442. * const cube = new THREE.Mesh( geometry, material );
  21443. * scene.add( cube );
  21444. * ```
  21445. *
  21446. * @augments BufferGeometry
  21447. * @demo scenes/geometry-browser.html#BoxGeometry
  21448. */
  21449. class BoxGeometry extends BufferGeometry {
  21450. /**
  21451. * Constructs a new box geometry.
  21452. *
  21453. * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis.
  21454. * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis.
  21455. * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis.
  21456. * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides.
  21457. * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides.
  21458. * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides.
  21459. */
  21460. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  21461. super();
  21462. this.type = 'BoxGeometry';
  21463. /**
  21464. * Holds the constructor parameters that have been
  21465. * used to generate the geometry. Any modification
  21466. * after instantiation does not change the geometry.
  21467. *
  21468. * @type {Object}
  21469. */
  21470. this.parameters = {
  21471. width: width,
  21472. height: height,
  21473. depth: depth,
  21474. widthSegments: widthSegments,
  21475. heightSegments: heightSegments,
  21476. depthSegments: depthSegments
  21477. };
  21478. const scope = this;
  21479. // segments
  21480. widthSegments = Math.floor( widthSegments );
  21481. heightSegments = Math.floor( heightSegments );
  21482. depthSegments = Math.floor( depthSegments );
  21483. // buffers
  21484. const indices = [];
  21485. const vertices = [];
  21486. const normals = [];
  21487. const uvs = [];
  21488. // helper variables
  21489. let numberOfVertices = 0;
  21490. let groupStart = 0;
  21491. // build each side of the box geometry
  21492. buildPlane( 'z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  21493. buildPlane( 'z', 'y', 'x', 1, -1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  21494. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  21495. buildPlane( 'x', 'z', 'y', 1, -1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  21496. buildPlane( 'x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  21497. buildPlane( 'x', 'y', 'z', -1, -1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  21498. // build geometry
  21499. this.setIndex( indices );
  21500. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21501. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21502. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21503. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  21504. const segmentWidth = width / gridX;
  21505. const segmentHeight = height / gridY;
  21506. const widthHalf = width / 2;
  21507. const heightHalf = height / 2;
  21508. const depthHalf = depth / 2;
  21509. const gridX1 = gridX + 1;
  21510. const gridY1 = gridY + 1;
  21511. let vertexCounter = 0;
  21512. let groupCount = 0;
  21513. const vector = new Vector3();
  21514. // generate vertices, normals and uvs
  21515. for ( let iy = 0; iy < gridY1; iy ++ ) {
  21516. const y = iy * segmentHeight - heightHalf;
  21517. for ( let ix = 0; ix < gridX1; ix ++ ) {
  21518. const x = ix * segmentWidth - widthHalf;
  21519. // set values to correct vector component
  21520. vector[ u ] = x * udir;
  21521. vector[ v ] = y * vdir;
  21522. vector[ w ] = depthHalf;
  21523. // now apply vector to vertex buffer
  21524. vertices.push( vector.x, vector.y, vector.z );
  21525. // set values to correct vector component
  21526. vector[ u ] = 0;
  21527. vector[ v ] = 0;
  21528. vector[ w ] = depth > 0 ? 1 : -1;
  21529. // now apply vector to normal buffer
  21530. normals.push( vector.x, vector.y, vector.z );
  21531. // uvs
  21532. uvs.push( ix / gridX );
  21533. uvs.push( 1 - ( iy / gridY ) );
  21534. // counters
  21535. vertexCounter += 1;
  21536. }
  21537. }
  21538. // indices
  21539. // 1. you need three indices to draw a single face
  21540. // 2. a single segment consists of two faces
  21541. // 3. so we need to generate six (2*3) indices per segment
  21542. for ( let iy = 0; iy < gridY; iy ++ ) {
  21543. for ( let ix = 0; ix < gridX; ix ++ ) {
  21544. const a = numberOfVertices + ix + gridX1 * iy;
  21545. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  21546. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  21547. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  21548. // faces
  21549. indices.push( a, b, d );
  21550. indices.push( b, c, d );
  21551. // increase counter
  21552. groupCount += 6;
  21553. }
  21554. }
  21555. // add a group to the geometry. this will ensure multi material support
  21556. scope.addGroup( groupStart, groupCount, materialIndex );
  21557. // calculate new start value for groups
  21558. groupStart += groupCount;
  21559. // update total number of vertices
  21560. numberOfVertices += vertexCounter;
  21561. }
  21562. }
  21563. copy( source ) {
  21564. super.copy( source );
  21565. this.parameters = Object.assign( {}, source.parameters );
  21566. return this;
  21567. }
  21568. /**
  21569. * Factory method for creating an instance of this class from the given
  21570. * JSON object.
  21571. *
  21572. * @param {Object} data - A JSON object representing the serialized geometry.
  21573. * @return {BoxGeometry} A new instance.
  21574. */
  21575. static fromJSON( data ) {
  21576. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  21577. }
  21578. }
  21579. /**
  21580. * A geometry class for representing a capsule.
  21581. *
  21582. * ```js
  21583. * const geometry = new THREE.CapsuleGeometry( 1, 1, 4, 8, 1 );
  21584. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  21585. * const capsule = new THREE.Mesh( geometry, material );
  21586. * scene.add( capsule );
  21587. * ```
  21588. *
  21589. * @augments BufferGeometry
  21590. * @demo scenes/geometry-browser.html#CapsuleGeometry
  21591. */
  21592. class CapsuleGeometry extends BufferGeometry {
  21593. /**
  21594. * Constructs a new capsule geometry.
  21595. *
  21596. * @param {number} [radius=1] - Radius of the capsule.
  21597. * @param {number} [height=1] - Height of the middle section.
  21598. * @param {number} [capSegments=4] - Number of curve segments used to build each cap.
  21599. * @param {number} [radialSegments=8] - Number of segmented faces around the circumference of the capsule. Must be an integer >= 3.
  21600. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the middle section. Must be an integer >= 1.
  21601. */
  21602. constructor( radius = 1, height = 1, capSegments = 4, radialSegments = 8, heightSegments = 1 ) {
  21603. super();
  21604. this.type = 'CapsuleGeometry';
  21605. /**
  21606. * Holds the constructor parameters that have been
  21607. * used to generate the geometry. Any modification
  21608. * after instantiation does not change the geometry.
  21609. *
  21610. * @type {Object}
  21611. */
  21612. this.parameters = {
  21613. radius: radius,
  21614. height: height,
  21615. capSegments: capSegments,
  21616. radialSegments: radialSegments,
  21617. heightSegments: heightSegments,
  21618. };
  21619. height = Math.max( 0, height );
  21620. capSegments = Math.max( 1, Math.floor( capSegments ) );
  21621. radialSegments = Math.max( 3, Math.floor( radialSegments ) );
  21622. heightSegments = Math.max( 1, Math.floor( heightSegments ) );
  21623. // buffers
  21624. const indices = [];
  21625. const vertices = [];
  21626. const normals = [];
  21627. const uvs = [];
  21628. // helper variables
  21629. const halfHeight = height / 2;
  21630. const capArcLength = ( Math.PI / 2 ) * radius;
  21631. const cylinderPartLength = height;
  21632. const totalArcLength = 2 * capArcLength + cylinderPartLength;
  21633. const numVerticalSegments = capSegments * 2 + heightSegments;
  21634. const verticesPerRow = radialSegments + 1;
  21635. const normal = new Vector3();
  21636. const vertex = new Vector3();
  21637. // generate vertices, normals, and uvs
  21638. for ( let iy = 0; iy <= numVerticalSegments; iy ++ ) {
  21639. let currentArcLength = 0;
  21640. let profileY = 0;
  21641. let profileRadius = 0;
  21642. let normalYComponent = 0;
  21643. if ( iy <= capSegments ) {
  21644. // bottom cap
  21645. const segmentProgress = iy / capSegments;
  21646. const angle = ( segmentProgress * Math.PI ) / 2;
  21647. profileY = - halfHeight - radius * Math.cos( angle );
  21648. profileRadius = radius * Math.sin( angle );
  21649. normalYComponent = - radius * Math.cos( angle );
  21650. currentArcLength = segmentProgress * capArcLength;
  21651. } else if ( iy <= capSegments + heightSegments ) {
  21652. // middle section
  21653. const segmentProgress = ( iy - capSegments ) / heightSegments;
  21654. profileY = - halfHeight + segmentProgress * height;
  21655. profileRadius = radius;
  21656. normalYComponent = 0;
  21657. currentArcLength = capArcLength + segmentProgress * cylinderPartLength;
  21658. } else {
  21659. // top cap
  21660. const segmentProgress =
  21661. ( iy - capSegments - heightSegments ) / capSegments;
  21662. const angle = ( segmentProgress * Math.PI ) / 2;
  21663. profileY = halfHeight + radius * Math.sin( angle );
  21664. profileRadius = radius * Math.cos( angle );
  21665. normalYComponent = radius * Math.sin( angle );
  21666. currentArcLength =
  21667. capArcLength + cylinderPartLength + segmentProgress * capArcLength;
  21668. }
  21669. const v = Math.max( 0, Math.min( 1, currentArcLength / totalArcLength ) );
  21670. // special case for the poles
  21671. let uOffset = 0;
  21672. if ( iy === 0 ) {
  21673. uOffset = 0.5 / radialSegments;
  21674. } else if ( iy === numVerticalSegments ) {
  21675. uOffset = -0.5 / radialSegments;
  21676. }
  21677. for ( let ix = 0; ix <= radialSegments; ix ++ ) {
  21678. const u = ix / radialSegments;
  21679. const theta = u * Math.PI * 2;
  21680. const sinTheta = Math.sin( theta );
  21681. const cosTheta = Math.cos( theta );
  21682. // vertex
  21683. vertex.x = - profileRadius * cosTheta;
  21684. vertex.y = profileY;
  21685. vertex.z = profileRadius * sinTheta;
  21686. vertices.push( vertex.x, vertex.y, vertex.z );
  21687. // normal
  21688. normal.set(
  21689. - profileRadius * cosTheta,
  21690. normalYComponent,
  21691. profileRadius * sinTheta
  21692. );
  21693. normal.normalize();
  21694. normals.push( normal.x, normal.y, normal.z );
  21695. // uv
  21696. uvs.push( u + uOffset, v );
  21697. }
  21698. if ( iy > 0 ) {
  21699. const prevIndexRow = ( iy - 1 ) * verticesPerRow;
  21700. for ( let ix = 0; ix < radialSegments; ix ++ ) {
  21701. const i1 = prevIndexRow + ix;
  21702. const i2 = prevIndexRow + ix + 1;
  21703. const i3 = iy * verticesPerRow + ix;
  21704. const i4 = iy * verticesPerRow + ix + 1;
  21705. indices.push( i1, i2, i3 );
  21706. indices.push( i2, i4, i3 );
  21707. }
  21708. }
  21709. }
  21710. // build geometry
  21711. this.setIndex( indices );
  21712. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21713. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21714. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21715. }
  21716. copy( source ) {
  21717. super.copy( source );
  21718. this.parameters = Object.assign( {}, source.parameters );
  21719. return this;
  21720. }
  21721. /**
  21722. * Factory method for creating an instance of this class from the given
  21723. * JSON object.
  21724. *
  21725. * @param {Object} data - A JSON object representing the serialized geometry.
  21726. * @return {CapsuleGeometry} A new instance.
  21727. */
  21728. static fromJSON( data ) {
  21729. return new CapsuleGeometry( data.radius, data.height, data.capSegments, data.radialSegments, data.heightSegments );
  21730. }
  21731. }
  21732. /**
  21733. * A simple shape of Euclidean geometry. It is constructed from a
  21734. * number of triangular segments that are oriented around a central point and
  21735. * extend as far out as a given radius. It is built counter-clockwise from a
  21736. * start angle and a given central angle. It can also be used to create
  21737. * regular polygons, where the number of segments determines the number of
  21738. * sides.
  21739. *
  21740. * ```js
  21741. * const geometry = new THREE.CircleGeometry( 5, 32 );
  21742. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  21743. * const circle = new THREE.Mesh( geometry, material );
  21744. * scene.add( circle )
  21745. * ```
  21746. *
  21747. * @augments BufferGeometry
  21748. * @demo scenes/geometry-browser.html#CircleGeometry
  21749. */
  21750. class CircleGeometry extends BufferGeometry {
  21751. /**
  21752. * Constructs a new circle geometry.
  21753. *
  21754. * @param {number} [radius=1] - Radius of the circle.
  21755. * @param {number} [segments=32] - Number of segments (triangles), minimum = `3`.
  21756. * @param {number} [thetaStart=0] - Start angle for first segment in radians.
  21757. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta,
  21758. * of the circular sector in radians. The default value results in a complete circle.
  21759. */
  21760. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21761. super();
  21762. this.type = 'CircleGeometry';
  21763. /**
  21764. * Holds the constructor parameters that have been
  21765. * used to generate the geometry. Any modification
  21766. * after instantiation does not change the geometry.
  21767. *
  21768. * @type {Object}
  21769. */
  21770. this.parameters = {
  21771. radius: radius,
  21772. segments: segments,
  21773. thetaStart: thetaStart,
  21774. thetaLength: thetaLength
  21775. };
  21776. segments = Math.max( 3, segments );
  21777. // buffers
  21778. const indices = [];
  21779. const vertices = [];
  21780. const normals = [];
  21781. const uvs = [];
  21782. // helper variables
  21783. const vertex = new Vector3();
  21784. const uv = new Vector2();
  21785. // center point
  21786. vertices.push( 0, 0, 0 );
  21787. normals.push( 0, 0, 1 );
  21788. uvs.push( 0.5, 0.5 );
  21789. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  21790. const segment = thetaStart + s / segments * thetaLength;
  21791. // vertex
  21792. vertex.x = radius * Math.cos( segment );
  21793. vertex.y = radius * Math.sin( segment );
  21794. vertices.push( vertex.x, vertex.y, vertex.z );
  21795. // normal
  21796. normals.push( 0, 0, 1 );
  21797. // uvs
  21798. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  21799. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  21800. uvs.push( uv.x, uv.y );
  21801. }
  21802. // indices
  21803. for ( let i = 1; i <= segments; i ++ ) {
  21804. indices.push( i, i + 1, 0 );
  21805. }
  21806. // build geometry
  21807. this.setIndex( indices );
  21808. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21809. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21810. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21811. }
  21812. copy( source ) {
  21813. super.copy( source );
  21814. this.parameters = Object.assign( {}, source.parameters );
  21815. return this;
  21816. }
  21817. /**
  21818. * Factory method for creating an instance of this class from the given
  21819. * JSON object.
  21820. *
  21821. * @param {Object} data - A JSON object representing the serialized geometry.
  21822. * @return {CircleGeometry} A new instance.
  21823. */
  21824. static fromJSON( data ) {
  21825. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  21826. }
  21827. }
  21828. /**
  21829. * A geometry class for representing a cylinder.
  21830. *
  21831. * ```js
  21832. * const geometry = new THREE.CylinderGeometry( 5, 5, 20, 32 );
  21833. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  21834. * const cylinder = new THREE.Mesh( geometry, material );
  21835. * scene.add( cylinder );
  21836. * ```
  21837. *
  21838. * @augments BufferGeometry
  21839. * @demo scenes/geometry-browser.html#CylinderGeometry
  21840. */
  21841. class CylinderGeometry extends BufferGeometry {
  21842. /**
  21843. * Constructs a new cylinder geometry.
  21844. *
  21845. * @param {number} [radiusTop=1] - Radius of the cylinder at the top.
  21846. * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom.
  21847. * @param {number} [height=1] - Height of the cylinder.
  21848. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder.
  21849. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder.
  21850. * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped.
  21851. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  21852. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  21853. * The default value results in a complete cylinder.
  21854. */
  21855. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21856. super();
  21857. this.type = 'CylinderGeometry';
  21858. /**
  21859. * Holds the constructor parameters that have been
  21860. * used to generate the geometry. Any modification
  21861. * after instantiation does not change the geometry.
  21862. *
  21863. * @type {Object}
  21864. */
  21865. this.parameters = {
  21866. radiusTop: radiusTop,
  21867. radiusBottom: radiusBottom,
  21868. height: height,
  21869. radialSegments: radialSegments,
  21870. heightSegments: heightSegments,
  21871. openEnded: openEnded,
  21872. thetaStart: thetaStart,
  21873. thetaLength: thetaLength
  21874. };
  21875. const scope = this;
  21876. radialSegments = Math.floor( radialSegments );
  21877. heightSegments = Math.floor( heightSegments );
  21878. // buffers
  21879. const indices = [];
  21880. const vertices = [];
  21881. const normals = [];
  21882. const uvs = [];
  21883. // helper variables
  21884. let index = 0;
  21885. const indexArray = [];
  21886. const halfHeight = height / 2;
  21887. let groupStart = 0;
  21888. // generate geometry
  21889. generateTorso();
  21890. if ( openEnded === false ) {
  21891. if ( radiusTop > 0 ) generateCap( true );
  21892. if ( radiusBottom > 0 ) generateCap( false );
  21893. }
  21894. // build geometry
  21895. this.setIndex( indices );
  21896. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21897. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21898. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21899. function generateTorso() {
  21900. const normal = new Vector3();
  21901. const vertex = new Vector3();
  21902. let groupCount = 0;
  21903. // this will be used to calculate the normal
  21904. const slope = ( radiusBottom - radiusTop ) / height;
  21905. // generate vertices, normals and uvs
  21906. for ( let y = 0; y <= heightSegments; y ++ ) {
  21907. const indexRow = [];
  21908. const v = y / heightSegments;
  21909. // calculate the radius of the current row
  21910. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  21911. for ( let x = 0; x <= radialSegments; x ++ ) {
  21912. const u = x / radialSegments;
  21913. const theta = u * thetaLength + thetaStart;
  21914. const sinTheta = Math.sin( theta );
  21915. const cosTheta = Math.cos( theta );
  21916. // vertex
  21917. vertex.x = radius * sinTheta;
  21918. vertex.y = - v * height + halfHeight;
  21919. vertex.z = radius * cosTheta;
  21920. vertices.push( vertex.x, vertex.y, vertex.z );
  21921. // normal
  21922. normal.set( sinTheta, slope, cosTheta ).normalize();
  21923. normals.push( normal.x, normal.y, normal.z );
  21924. // uv
  21925. uvs.push( u, 1 - v );
  21926. // save index of vertex in respective row
  21927. indexRow.push( index ++ );
  21928. }
  21929. // now save vertices of the row in our index array
  21930. indexArray.push( indexRow );
  21931. }
  21932. // generate indices
  21933. for ( let x = 0; x < radialSegments; x ++ ) {
  21934. for ( let y = 0; y < heightSegments; y ++ ) {
  21935. // we use the index array to access the correct indices
  21936. const a = indexArray[ y ][ x ];
  21937. const b = indexArray[ y + 1 ][ x ];
  21938. const c = indexArray[ y + 1 ][ x + 1 ];
  21939. const d = indexArray[ y ][ x + 1 ];
  21940. // faces
  21941. if ( radiusTop > 0 || y !== 0 ) {
  21942. indices.push( a, b, d );
  21943. groupCount += 3;
  21944. }
  21945. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  21946. indices.push( b, c, d );
  21947. groupCount += 3;
  21948. }
  21949. }
  21950. }
  21951. // add a group to the geometry. this will ensure multi material support
  21952. scope.addGroup( groupStart, groupCount, 0 );
  21953. // calculate new start value for groups
  21954. groupStart += groupCount;
  21955. }
  21956. function generateCap( top ) {
  21957. // save the index of the first center vertex
  21958. const centerIndexStart = index;
  21959. const uv = new Vector2();
  21960. const vertex = new Vector3();
  21961. let groupCount = 0;
  21962. const radius = ( top === true ) ? radiusTop : radiusBottom;
  21963. const sign = ( top === true ) ? 1 : -1;
  21964. // first we generate the center vertex data of the cap.
  21965. // because the geometry needs one set of uvs per face,
  21966. // we must generate a center vertex per face/segment
  21967. for ( let x = 1; x <= radialSegments; x ++ ) {
  21968. // vertex
  21969. vertices.push( 0, halfHeight * sign, 0 );
  21970. // normal
  21971. normals.push( 0, sign, 0 );
  21972. // uv
  21973. uvs.push( 0.5, 0.5 );
  21974. // increase index
  21975. index ++;
  21976. }
  21977. // save the index of the last center vertex
  21978. const centerIndexEnd = index;
  21979. // now we generate the surrounding vertices, normals and uvs
  21980. for ( let x = 0; x <= radialSegments; x ++ ) {
  21981. const u = x / radialSegments;
  21982. const theta = u * thetaLength + thetaStart;
  21983. const cosTheta = Math.cos( theta );
  21984. const sinTheta = Math.sin( theta );
  21985. // vertex
  21986. vertex.x = radius * sinTheta;
  21987. vertex.y = halfHeight * sign;
  21988. vertex.z = radius * cosTheta;
  21989. vertices.push( vertex.x, vertex.y, vertex.z );
  21990. // normal
  21991. normals.push( 0, sign, 0 );
  21992. // uv
  21993. uv.x = ( cosTheta * 0.5 ) + 0.5;
  21994. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  21995. uvs.push( uv.x, uv.y );
  21996. // increase index
  21997. index ++;
  21998. }
  21999. // generate indices
  22000. for ( let x = 0; x < radialSegments; x ++ ) {
  22001. const c = centerIndexStart + x;
  22002. const i = centerIndexEnd + x;
  22003. if ( top === true ) {
  22004. // face top
  22005. indices.push( i, i + 1, c );
  22006. } else {
  22007. // face bottom
  22008. indices.push( i + 1, i, c );
  22009. }
  22010. groupCount += 3;
  22011. }
  22012. // add a group to the geometry. this will ensure multi material support
  22013. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  22014. // calculate new start value for groups
  22015. groupStart += groupCount;
  22016. }
  22017. }
  22018. copy( source ) {
  22019. super.copy( source );
  22020. this.parameters = Object.assign( {}, source.parameters );
  22021. return this;
  22022. }
  22023. /**
  22024. * Factory method for creating an instance of this class from the given
  22025. * JSON object.
  22026. *
  22027. * @param {Object} data - A JSON object representing the serialized geometry.
  22028. * @return {CylinderGeometry} A new instance.
  22029. */
  22030. static fromJSON( data ) {
  22031. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22032. }
  22033. }
  22034. /**
  22035. * A geometry class for representing a cone.
  22036. *
  22037. * ```js
  22038. * const geometry = new THREE.ConeGeometry( 5, 20, 32 );
  22039. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22040. * const cone = new THREE.Mesh(geometry, material );
  22041. * scene.add( cone );
  22042. * ```
  22043. *
  22044. * @augments CylinderGeometry
  22045. * @demo scenes/geometry-browser.html#ConeGeometry
  22046. */
  22047. class ConeGeometry extends CylinderGeometry {
  22048. /**
  22049. * Constructs a new cone geometry.
  22050. *
  22051. * @param {number} [radius=1] - Radius of the cone base.
  22052. * @param {number} [height=1] - Height of the cone.
  22053. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone.
  22054. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone.
  22055. * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped.
  22056. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22057. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22058. * The default value results in a complete cone.
  22059. */
  22060. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22061. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  22062. this.type = 'ConeGeometry';
  22063. /**
  22064. * Holds the constructor parameters that have been
  22065. * used to generate the geometry. Any modification
  22066. * after instantiation does not change the geometry.
  22067. *
  22068. * @type {Object}
  22069. */
  22070. this.parameters = {
  22071. radius: radius,
  22072. height: height,
  22073. radialSegments: radialSegments,
  22074. heightSegments: heightSegments,
  22075. openEnded: openEnded,
  22076. thetaStart: thetaStart,
  22077. thetaLength: thetaLength
  22078. };
  22079. }
  22080. /**
  22081. * Factory method for creating an instance of this class from the given
  22082. * JSON object.
  22083. *
  22084. * @param {Object} data - A JSON object representing the serialized geometry.
  22085. * @return {ConeGeometry} A new instance.
  22086. */
  22087. static fromJSON( data ) {
  22088. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22089. }
  22090. }
  22091. /**
  22092. * A polyhedron is a solid in three dimensions with flat faces. This class
  22093. * will take an array of vertices, project them onto a sphere, and then
  22094. * divide them up to the desired level of detail.
  22095. *
  22096. * @augments BufferGeometry
  22097. */
  22098. class PolyhedronGeometry extends BufferGeometry {
  22099. /**
  22100. * Constructs a new polyhedron geometry.
  22101. *
  22102. * @param {Array<number>} [vertices] - A flat array of vertices describing the base shape.
  22103. * @param {Array<number>} [indices] - A flat array of indices describing the base shape.
  22104. * @param {number} [radius=1] - The radius of the shape.
  22105. * @param {number} [detail=0] - How many levels to subdivide the geometry. The more detail, the smoother the shape.
  22106. */
  22107. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  22108. super();
  22109. this.type = 'PolyhedronGeometry';
  22110. /**
  22111. * Holds the constructor parameters that have been
  22112. * used to generate the geometry. Any modification
  22113. * after instantiation does not change the geometry.
  22114. *
  22115. * @type {Object}
  22116. */
  22117. this.parameters = {
  22118. vertices: vertices,
  22119. indices: indices,
  22120. radius: radius,
  22121. detail: detail
  22122. };
  22123. // default buffer data
  22124. const vertexBuffer = [];
  22125. const uvBuffer = [];
  22126. // the subdivision creates the vertex buffer data
  22127. subdivide( detail );
  22128. // all vertices should lie on a conceptual sphere with a given radius
  22129. applyRadius( radius );
  22130. // finally, create the uv data
  22131. generateUVs();
  22132. // build non-indexed geometry
  22133. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  22134. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  22135. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  22136. if ( detail === 0 ) {
  22137. this.computeVertexNormals(); // flat normals
  22138. } else {
  22139. this.normalizeNormals(); // smooth normals
  22140. }
  22141. // helper functions
  22142. function subdivide( detail ) {
  22143. const a = new Vector3();
  22144. const b = new Vector3();
  22145. const c = new Vector3();
  22146. // iterate over all faces and apply a subdivision with the given detail value
  22147. for ( let i = 0; i < indices.length; i += 3 ) {
  22148. // get the vertices of the face
  22149. getVertexByIndex( indices[ i + 0 ], a );
  22150. getVertexByIndex( indices[ i + 1 ], b );
  22151. getVertexByIndex( indices[ i + 2 ], c );
  22152. // perform subdivision
  22153. subdivideFace( a, b, c, detail );
  22154. }
  22155. }
  22156. function subdivideFace( a, b, c, detail ) {
  22157. const cols = detail + 1;
  22158. // we use this multidimensional array as a data structure for creating the subdivision
  22159. const v = [];
  22160. // construct all of the vertices for this subdivision
  22161. for ( let i = 0; i <= cols; i ++ ) {
  22162. v[ i ] = [];
  22163. const aj = a.clone().lerp( c, i / cols );
  22164. const bj = b.clone().lerp( c, i / cols );
  22165. const rows = cols - i;
  22166. for ( let j = 0; j <= rows; j ++ ) {
  22167. if ( j === 0 && i === cols ) {
  22168. v[ i ][ j ] = aj;
  22169. } else {
  22170. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  22171. }
  22172. }
  22173. }
  22174. // construct all of the faces
  22175. for ( let i = 0; i < cols; i ++ ) {
  22176. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  22177. const k = Math.floor( j / 2 );
  22178. if ( j % 2 === 0 ) {
  22179. pushVertex( v[ i ][ k + 1 ] );
  22180. pushVertex( v[ i + 1 ][ k ] );
  22181. pushVertex( v[ i ][ k ] );
  22182. } else {
  22183. pushVertex( v[ i ][ k + 1 ] );
  22184. pushVertex( v[ i + 1 ][ k + 1 ] );
  22185. pushVertex( v[ i + 1 ][ k ] );
  22186. }
  22187. }
  22188. }
  22189. }
  22190. function applyRadius( radius ) {
  22191. const vertex = new Vector3();
  22192. // iterate over the entire buffer and apply the radius to each vertex
  22193. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22194. vertex.x = vertexBuffer[ i + 0 ];
  22195. vertex.y = vertexBuffer[ i + 1 ];
  22196. vertex.z = vertexBuffer[ i + 2 ];
  22197. vertex.normalize().multiplyScalar( radius );
  22198. vertexBuffer[ i + 0 ] = vertex.x;
  22199. vertexBuffer[ i + 1 ] = vertex.y;
  22200. vertexBuffer[ i + 2 ] = vertex.z;
  22201. }
  22202. }
  22203. function generateUVs() {
  22204. const vertex = new Vector3();
  22205. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22206. vertex.x = vertexBuffer[ i + 0 ];
  22207. vertex.y = vertexBuffer[ i + 1 ];
  22208. vertex.z = vertexBuffer[ i + 2 ];
  22209. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  22210. const v = inclination( vertex ) / Math.PI + 0.5;
  22211. uvBuffer.push( u, 1 - v );
  22212. }
  22213. correctUVs();
  22214. correctSeam();
  22215. }
  22216. function correctSeam() {
  22217. // handle case when face straddles the seam, see #3269
  22218. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  22219. // uv data of a single face
  22220. const x0 = uvBuffer[ i + 0 ];
  22221. const x1 = uvBuffer[ i + 2 ];
  22222. const x2 = uvBuffer[ i + 4 ];
  22223. const max = Math.max( x0, x1, x2 );
  22224. const min = Math.min( x0, x1, x2 );
  22225. // 0.9 is somewhat arbitrary
  22226. if ( max > 0.9 && min < 0.1 ) {
  22227. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  22228. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  22229. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  22230. }
  22231. }
  22232. }
  22233. function pushVertex( vertex ) {
  22234. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  22235. }
  22236. function getVertexByIndex( index, vertex ) {
  22237. const stride = index * 3;
  22238. vertex.x = vertices[ stride + 0 ];
  22239. vertex.y = vertices[ stride + 1 ];
  22240. vertex.z = vertices[ stride + 2 ];
  22241. }
  22242. function correctUVs() {
  22243. const a = new Vector3();
  22244. const b = new Vector3();
  22245. const c = new Vector3();
  22246. const centroid = new Vector3();
  22247. const uvA = new Vector2();
  22248. const uvB = new Vector2();
  22249. const uvC = new Vector2();
  22250. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  22251. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  22252. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  22253. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  22254. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  22255. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  22256. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  22257. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  22258. const azi = azimuth( centroid );
  22259. correctUV( uvA, j + 0, a, azi );
  22260. correctUV( uvB, j + 2, b, azi );
  22261. correctUV( uvC, j + 4, c, azi );
  22262. }
  22263. }
  22264. function correctUV( uv, stride, vector, azimuth ) {
  22265. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  22266. uvBuffer[ stride ] = uv.x - 1;
  22267. }
  22268. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  22269. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  22270. }
  22271. }
  22272. // Angle around the Y axis, counter-clockwise when looking from above.
  22273. function azimuth( vector ) {
  22274. return Math.atan2( vector.z, - vector.x );
  22275. }
  22276. // Angle above the XZ plane.
  22277. function inclination( vector ) {
  22278. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  22279. }
  22280. }
  22281. copy( source ) {
  22282. super.copy( source );
  22283. this.parameters = Object.assign( {}, source.parameters );
  22284. return this;
  22285. }
  22286. /**
  22287. * Factory method for creating an instance of this class from the given
  22288. * JSON object.
  22289. *
  22290. * @param {Object} data - A JSON object representing the serialized geometry.
  22291. * @return {PolyhedronGeometry} A new instance.
  22292. */
  22293. static fromJSON( data ) {
  22294. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.detail );
  22295. }
  22296. }
  22297. /**
  22298. * A geometry class for representing a dodecahedron.
  22299. *
  22300. * ```js
  22301. * const geometry = new THREE.DodecahedronGeometry();
  22302. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22303. * const dodecahedron = new THREE.Mesh( geometry, material );
  22304. * scene.add( dodecahedron );
  22305. * ```
  22306. *
  22307. * @augments PolyhedronGeometry
  22308. * @demo scenes/geometry-browser.html#DodecahedronGeometry
  22309. */
  22310. class DodecahedronGeometry extends PolyhedronGeometry {
  22311. /**
  22312. * Constructs a new dodecahedron geometry.
  22313. *
  22314. * @param {number} [radius=1] - Radius of the dodecahedron.
  22315. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a dodecahedron.
  22316. */
  22317. constructor( radius = 1, detail = 0 ) {
  22318. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22319. const r = 1 / t;
  22320. const vertices = [
  22321. // (±1, ±1, ±1)
  22322. -1, -1, -1, -1, -1, 1,
  22323. -1, 1, -1, -1, 1, 1,
  22324. 1, -1, -1, 1, -1, 1,
  22325. 1, 1, -1, 1, 1, 1,
  22326. // (0, ±1/φ, ±φ)
  22327. 0, - r, - t, 0, - r, t,
  22328. 0, r, - t, 0, r, t,
  22329. // (±1/φ, ±φ, 0)
  22330. - r, - t, 0, - r, t, 0,
  22331. r, - t, 0, r, t, 0,
  22332. // (±φ, 0, ±1/φ)
  22333. - t, 0, - r, t, 0, - r,
  22334. - t, 0, r, t, 0, r
  22335. ];
  22336. const indices = [
  22337. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  22338. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  22339. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  22340. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  22341. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  22342. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  22343. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  22344. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  22345. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  22346. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  22347. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  22348. 1, 12, 14, 1, 14, 5, 1, 5, 9
  22349. ];
  22350. super( vertices, indices, radius, detail );
  22351. this.type = 'DodecahedronGeometry';
  22352. /**
  22353. * Holds the constructor parameters that have been
  22354. * used to generate the geometry. Any modification
  22355. * after instantiation does not change the geometry.
  22356. *
  22357. * @type {Object}
  22358. */
  22359. this.parameters = {
  22360. radius: radius,
  22361. detail: detail
  22362. };
  22363. }
  22364. /**
  22365. * Factory method for creating an instance of this class from the given
  22366. * JSON object.
  22367. *
  22368. * @param {Object} data - A JSON object representing the serialized geometry.
  22369. * @return {DodecahedronGeometry} A new instance.
  22370. */
  22371. static fromJSON( data ) {
  22372. return new DodecahedronGeometry( data.radius, data.detail );
  22373. }
  22374. }
  22375. const _v0 = /*@__PURE__*/ new Vector3();
  22376. const _v1$1 = /*@__PURE__*/ new Vector3();
  22377. const _normal = /*@__PURE__*/ new Vector3();
  22378. const _triangle = /*@__PURE__*/ new Triangle();
  22379. /**
  22380. * Can be used as a helper object to view the edges of a geometry.
  22381. *
  22382. * ```js
  22383. * const geometry = new THREE.BoxGeometry();
  22384. * const edges = new THREE.EdgesGeometry( geometry );
  22385. * const line = new THREE.LineSegments( edges );
  22386. * scene.add( line );
  22387. * ```
  22388. *
  22389. * Note: It is not yet possible to serialize/deserialize instances of this class.
  22390. *
  22391. * @augments BufferGeometry
  22392. */
  22393. class EdgesGeometry extends BufferGeometry {
  22394. /**
  22395. * Constructs a new edges geometry.
  22396. *
  22397. * @param {?BufferGeometry} [geometry=null] - The geometry.
  22398. * @param {number} [thresholdAngle=1] - An edge is only rendered if the angle (in degrees)
  22399. * between the face normals of the adjoining faces exceeds this value.
  22400. */
  22401. constructor( geometry = null, thresholdAngle = 1 ) {
  22402. super();
  22403. this.type = 'EdgesGeometry';
  22404. /**
  22405. * Holds the constructor parameters that have been
  22406. * used to generate the geometry. Any modification
  22407. * after instantiation does not change the geometry.
  22408. *
  22409. * @type {Object}
  22410. */
  22411. this.parameters = {
  22412. geometry: geometry,
  22413. thresholdAngle: thresholdAngle
  22414. };
  22415. if ( geometry !== null ) {
  22416. const precisionPoints = 4;
  22417. const precision = Math.pow( 10, precisionPoints );
  22418. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  22419. const indexAttr = geometry.getIndex();
  22420. const positionAttr = geometry.getAttribute( 'position' );
  22421. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  22422. const indexArr = [ 0, 0, 0 ];
  22423. const vertKeys = [ 'a', 'b', 'c' ];
  22424. const hashes = new Array( 3 );
  22425. const edgeData = {};
  22426. const vertices = [];
  22427. for ( let i = 0; i < indexCount; i += 3 ) {
  22428. if ( indexAttr ) {
  22429. indexArr[ 0 ] = indexAttr.getX( i );
  22430. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  22431. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  22432. } else {
  22433. indexArr[ 0 ] = i;
  22434. indexArr[ 1 ] = i + 1;
  22435. indexArr[ 2 ] = i + 2;
  22436. }
  22437. const { a, b, c } = _triangle;
  22438. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  22439. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  22440. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  22441. _triangle.getNormal( _normal );
  22442. // create hashes for the edge from the vertices
  22443. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  22444. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  22445. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  22446. // skip degenerate triangles
  22447. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  22448. continue;
  22449. }
  22450. // iterate over every edge
  22451. for ( let j = 0; j < 3; j ++ ) {
  22452. // get the first and next vertex making up the edge
  22453. const jNext = ( j + 1 ) % 3;
  22454. const vecHash0 = hashes[ j ];
  22455. const vecHash1 = hashes[ jNext ];
  22456. const v0 = _triangle[ vertKeys[ j ] ];
  22457. const v1 = _triangle[ vertKeys[ jNext ] ];
  22458. const hash = `${ vecHash0 }_${ vecHash1 }`;
  22459. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  22460. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  22461. // if we found a sibling edge add it into the vertex array if
  22462. // it meets the angle threshold and delete the edge from the map.
  22463. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  22464. vertices.push( v0.x, v0.y, v0.z );
  22465. vertices.push( v1.x, v1.y, v1.z );
  22466. }
  22467. edgeData[ reverseHash ] = null;
  22468. } else if ( ! ( hash in edgeData ) ) {
  22469. // if we've already got an edge here then skip adding a new one
  22470. edgeData[ hash ] = {
  22471. index0: indexArr[ j ],
  22472. index1: indexArr[ jNext ],
  22473. normal: _normal.clone(),
  22474. };
  22475. }
  22476. }
  22477. }
  22478. // iterate over all remaining, unmatched edges and add them to the vertex array
  22479. for ( const key in edgeData ) {
  22480. if ( edgeData[ key ] ) {
  22481. const { index0, index1 } = edgeData[ key ];
  22482. _v0.fromBufferAttribute( positionAttr, index0 );
  22483. _v1$1.fromBufferAttribute( positionAttr, index1 );
  22484. vertices.push( _v0.x, _v0.y, _v0.z );
  22485. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  22486. }
  22487. }
  22488. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22489. }
  22490. }
  22491. copy( source ) {
  22492. super.copy( source );
  22493. this.parameters = Object.assign( {}, source.parameters );
  22494. return this;
  22495. }
  22496. }
  22497. /**
  22498. * An abstract base class for creating an analytic curve object that contains methods
  22499. * for interpolation.
  22500. *
  22501. * @abstract
  22502. */
  22503. class Curve {
  22504. /**
  22505. * Constructs a new curve.
  22506. */
  22507. constructor() {
  22508. /**
  22509. * The type property is used for detecting the object type
  22510. * in context of serialization/deserialization.
  22511. *
  22512. * @type {string}
  22513. * @readonly
  22514. */
  22515. this.type = 'Curve';
  22516. /**
  22517. * This value determines the amount of divisions when calculating the
  22518. * cumulative segment lengths of a curve via {@link Curve#getLengths}. To ensure
  22519. * precision when using methods like {@link Curve#getSpacedPoints}, it is
  22520. * recommended to increase the value of this property if the curve is very large.
  22521. *
  22522. * @type {number}
  22523. * @default 200
  22524. */
  22525. this.arcLengthDivisions = 200;
  22526. /**
  22527. * Must be set to `true` if the curve parameters have changed.
  22528. *
  22529. * @type {boolean}
  22530. * @default false
  22531. */
  22532. this.needsUpdate = false;
  22533. /**
  22534. * An internal cache that holds precomputed curve length values.
  22535. *
  22536. * @private
  22537. * @type {?Array<number>}
  22538. * @default null
  22539. */
  22540. this.cacheArcLengths = null;
  22541. }
  22542. /**
  22543. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  22544. * for the given interpolation factor.
  22545. *
  22546. * @abstract
  22547. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  22548. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  22549. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  22550. */
  22551. getPoint( /* t, optionalTarget */ ) {
  22552. warn( 'Curve: .getPoint() not implemented.' );
  22553. }
  22554. /**
  22555. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  22556. * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length
  22557. * of the curve which equidistant samples.
  22558. *
  22559. * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  22560. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  22561. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  22562. */
  22563. getPointAt( u, optionalTarget ) {
  22564. const t = this.getUtoTmapping( u );
  22565. return this.getPoint( t, optionalTarget );
  22566. }
  22567. /**
  22568. * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing
  22569. * the curve shape.
  22570. *
  22571. * @param {number} [divisions=5] - The number of divisions.
  22572. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  22573. */
  22574. getPoints( divisions = 5 ) {
  22575. const points = [];
  22576. for ( let d = 0; d <= divisions; d ++ ) {
  22577. points.push( this.getPoint( d / divisions ) );
  22578. }
  22579. return points;
  22580. }
  22581. // Get sequence of points using getPointAt( u )
  22582. /**
  22583. * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing
  22584. * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire
  22585. * curve.
  22586. *
  22587. * @param {number} [divisions=5] - The number of divisions.
  22588. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  22589. */
  22590. getSpacedPoints( divisions = 5 ) {
  22591. const points = [];
  22592. for ( let d = 0; d <= divisions; d ++ ) {
  22593. points.push( this.getPointAt( d / divisions ) );
  22594. }
  22595. return points;
  22596. }
  22597. /**
  22598. * Returns the total arc length of the curve.
  22599. *
  22600. * @return {number} The length of the curve.
  22601. */
  22602. getLength() {
  22603. const lengths = this.getLengths();
  22604. return lengths[ lengths.length - 1 ];
  22605. }
  22606. /**
  22607. * Returns an array of cumulative segment lengths of the curve.
  22608. *
  22609. * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions.
  22610. * @return {Array<number>} An array holding the cumulative segment lengths.
  22611. */
  22612. getLengths( divisions = this.arcLengthDivisions ) {
  22613. if ( this.cacheArcLengths &&
  22614. ( this.cacheArcLengths.length === divisions + 1 ) &&
  22615. ! this.needsUpdate ) {
  22616. return this.cacheArcLengths;
  22617. }
  22618. this.needsUpdate = false;
  22619. const cache = [];
  22620. let current, last = this.getPoint( 0 );
  22621. let sum = 0;
  22622. cache.push( 0 );
  22623. for ( let p = 1; p <= divisions; p ++ ) {
  22624. current = this.getPoint( p / divisions );
  22625. sum += current.distanceTo( last );
  22626. cache.push( sum );
  22627. last = current;
  22628. }
  22629. this.cacheArcLengths = cache;
  22630. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  22631. }
  22632. /**
  22633. * Update the cumulative segment distance cache. The method must be called
  22634. * every time curve parameters are changed. If an updated curve is part of a
  22635. * composed curve like {@link CurvePath}, this method must be called on the
  22636. * composed curve, too.
  22637. */
  22638. updateArcLengths() {
  22639. this.needsUpdate = true;
  22640. this.getLengths();
  22641. }
  22642. /**
  22643. * Given an interpolation factor in the range `[0,1]`, this method returns an updated
  22644. * interpolation factor in the same range that can be ued to sample equidistant points
  22645. * from a curve.
  22646. *
  22647. * @param {number} u - The interpolation factor.
  22648. * @param {?number} distance - An optional distance on the curve.
  22649. * @return {number} The updated interpolation factor.
  22650. */
  22651. getUtoTmapping( u, distance = null ) {
  22652. const arcLengths = this.getLengths();
  22653. let i = 0;
  22654. const il = arcLengths.length;
  22655. let targetArcLength; // The targeted u distance value to get
  22656. if ( distance ) {
  22657. targetArcLength = distance;
  22658. } else {
  22659. targetArcLength = u * arcLengths[ il - 1 ];
  22660. }
  22661. // binary search for the index with largest value smaller than target u distance
  22662. let low = 0, high = il - 1, comparison;
  22663. while ( low <= high ) {
  22664. 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
  22665. comparison = arcLengths[ i ] - targetArcLength;
  22666. if ( comparison < 0 ) {
  22667. low = i + 1;
  22668. } else if ( comparison > 0 ) {
  22669. high = i - 1;
  22670. } else {
  22671. high = i;
  22672. break;
  22673. // DONE
  22674. }
  22675. }
  22676. i = high;
  22677. if ( arcLengths[ i ] === targetArcLength ) {
  22678. return i / ( il - 1 );
  22679. }
  22680. // we could get finer grain at lengths, or use simple interpolation between two points
  22681. const lengthBefore = arcLengths[ i ];
  22682. const lengthAfter = arcLengths[ i + 1 ];
  22683. const segmentLength = lengthAfter - lengthBefore;
  22684. // determine where we are between the 'before' and 'after' points
  22685. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  22686. // add that fractional amount to t
  22687. const t = ( i + segmentFraction ) / ( il - 1 );
  22688. return t;
  22689. }
  22690. /**
  22691. * Returns a unit vector tangent for the given interpolation factor.
  22692. * If the derived curve does not implement its tangent derivation,
  22693. * two points a small delta apart will be used to find its gradient
  22694. * which seems to give a reasonable approximation.
  22695. *
  22696. * @param {number} t - The interpolation factor.
  22697. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  22698. * @return {(Vector2|Vector3)} The tangent vector.
  22699. */
  22700. getTangent( t, optionalTarget ) {
  22701. const delta = 0.0001;
  22702. let t1 = t - delta;
  22703. let t2 = t + delta;
  22704. // Capping in case of danger
  22705. if ( t1 < 0 ) t1 = 0;
  22706. if ( t2 > 1 ) t2 = 1;
  22707. const pt1 = this.getPoint( t1 );
  22708. const pt2 = this.getPoint( t2 );
  22709. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  22710. tangent.copy( pt2 ).sub( pt1 ).normalize();
  22711. return tangent;
  22712. }
  22713. /**
  22714. * Same as {@link Curve#getTangent} but with equidistant samples.
  22715. *
  22716. * @param {number} u - The interpolation factor.
  22717. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  22718. * @return {(Vector2|Vector3)} The tangent vector.
  22719. * @see {@link Curve#getPointAt}
  22720. */
  22721. getTangentAt( u, optionalTarget ) {
  22722. const t = this.getUtoTmapping( u );
  22723. return this.getTangent( t, optionalTarget );
  22724. }
  22725. /**
  22726. * Generates the Frenet Frames. Requires a curve definition in 3D space. Used
  22727. * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}.
  22728. *
  22729. * @param {number} segments - The number of segments.
  22730. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  22731. * @return {{tangents: Array<Vector3>, normals: Array<Vector3>, binormals: Array<Vector3>}} The Frenet Frames.
  22732. */
  22733. computeFrenetFrames( segments, closed = false ) {
  22734. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  22735. const normal = new Vector3();
  22736. const tangents = [];
  22737. const normals = [];
  22738. const binormals = [];
  22739. const vec = new Vector3();
  22740. const mat = new Matrix4();
  22741. // compute the tangent vectors for each segment on the curve
  22742. for ( let i = 0; i <= segments; i ++ ) {
  22743. const u = i / segments;
  22744. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  22745. }
  22746. // select an initial normal vector perpendicular to the first tangent vector,
  22747. // and in the direction of the minimum tangent xyz component
  22748. normals[ 0 ] = new Vector3();
  22749. binormals[ 0 ] = new Vector3();
  22750. let min = Number.MAX_VALUE;
  22751. const tx = Math.abs( tangents[ 0 ].x );
  22752. const ty = Math.abs( tangents[ 0 ].y );
  22753. const tz = Math.abs( tangents[ 0 ].z );
  22754. if ( tx <= min ) {
  22755. min = tx;
  22756. normal.set( 1, 0, 0 );
  22757. }
  22758. if ( ty <= min ) {
  22759. min = ty;
  22760. normal.set( 0, 1, 0 );
  22761. }
  22762. if ( tz <= min ) {
  22763. normal.set( 0, 0, 1 );
  22764. }
  22765. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  22766. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  22767. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  22768. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  22769. for ( let i = 1; i <= segments; i ++ ) {
  22770. normals[ i ] = normals[ i - 1 ].clone();
  22771. binormals[ i ] = binormals[ i - 1 ].clone();
  22772. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  22773. if ( vec.length() > Number.EPSILON ) {
  22774. vec.normalize();
  22775. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  22776. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  22777. }
  22778. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  22779. }
  22780. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  22781. if ( closed === true ) {
  22782. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), -1, 1 ) );
  22783. theta /= segments;
  22784. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  22785. theta = - theta;
  22786. }
  22787. for ( let i = 1; i <= segments; i ++ ) {
  22788. // twist a little...
  22789. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  22790. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  22791. }
  22792. }
  22793. return {
  22794. tangents: tangents,
  22795. normals: normals,
  22796. binormals: binormals
  22797. };
  22798. }
  22799. /**
  22800. * Returns a new curve with copied values from this instance.
  22801. *
  22802. * @return {Curve} A clone of this instance.
  22803. */
  22804. clone() {
  22805. return new this.constructor().copy( this );
  22806. }
  22807. /**
  22808. * Copies the values of the given curve to this instance.
  22809. *
  22810. * @param {Curve} source - The curve to copy.
  22811. * @return {Curve} A reference to this curve.
  22812. */
  22813. copy( source ) {
  22814. this.arcLengthDivisions = source.arcLengthDivisions;
  22815. return this;
  22816. }
  22817. /**
  22818. * Serializes the curve into JSON.
  22819. *
  22820. * @return {Object} A JSON object representing the serialized curve.
  22821. * @see {@link ObjectLoader#parse}
  22822. */
  22823. toJSON() {
  22824. const data = {
  22825. metadata: {
  22826. version: 4.7,
  22827. type: 'Curve',
  22828. generator: 'Curve.toJSON'
  22829. }
  22830. };
  22831. data.arcLengthDivisions = this.arcLengthDivisions;
  22832. data.type = this.type;
  22833. return data;
  22834. }
  22835. /**
  22836. * Deserializes the curve from the given JSON.
  22837. *
  22838. * @param {Object} json - The JSON holding the serialized curve.
  22839. * @return {Curve} A reference to this curve.
  22840. */
  22841. fromJSON( json ) {
  22842. this.arcLengthDivisions = json.arcLengthDivisions;
  22843. return this;
  22844. }
  22845. }
  22846. /**
  22847. * A curve representing an ellipse.
  22848. *
  22849. * ```js
  22850. * const curve = new THREE.EllipseCurve(
  22851. * 0, 0,
  22852. * 10, 10,
  22853. * 0, 2 * Math.PI,
  22854. * false,
  22855. * 0
  22856. * );
  22857. *
  22858. * const points = curve.getPoints( 50 );
  22859. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  22860. *
  22861. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  22862. *
  22863. * // Create the final object to add to the scene
  22864. * const ellipse = new THREE.Line( geometry, material );
  22865. * ```
  22866. *
  22867. * @augments Curve
  22868. */
  22869. class EllipseCurve extends Curve {
  22870. /**
  22871. * Constructs a new ellipse curve.
  22872. *
  22873. * @param {number} [aX=0] - The X center of the ellipse.
  22874. * @param {number} [aY=0] - The Y center of the ellipse.
  22875. * @param {number} [xRadius=1] - The radius of the ellipse in the x direction.
  22876. * @param {number} [yRadius=1] - The radius of the ellipse in the y direction.
  22877. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  22878. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  22879. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  22880. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  22881. */
  22882. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  22883. super();
  22884. /**
  22885. * This flag can be used for type testing.
  22886. *
  22887. * @type {boolean}
  22888. * @readonly
  22889. * @default true
  22890. */
  22891. this.isEllipseCurve = true;
  22892. this.type = 'EllipseCurve';
  22893. /**
  22894. * The X center of the ellipse.
  22895. *
  22896. * @type {number}
  22897. * @default 0
  22898. */
  22899. this.aX = aX;
  22900. /**
  22901. * The Y center of the ellipse.
  22902. *
  22903. * @type {number}
  22904. * @default 0
  22905. */
  22906. this.aY = aY;
  22907. /**
  22908. * The radius of the ellipse in the x direction.
  22909. * Setting the this value equal to the {@link EllipseCurve#yRadius} will result in a circle.
  22910. *
  22911. * @type {number}
  22912. * @default 1
  22913. */
  22914. this.xRadius = xRadius;
  22915. /**
  22916. * The radius of the ellipse in the y direction.
  22917. * Setting the this value equal to the {@link EllipseCurve#xRadius} will result in a circle.
  22918. *
  22919. * @type {number}
  22920. * @default 1
  22921. */
  22922. this.yRadius = yRadius;
  22923. /**
  22924. * The start angle of the curve in radians starting from the positive X axis.
  22925. *
  22926. * @type {number}
  22927. * @default 0
  22928. */
  22929. this.aStartAngle = aStartAngle;
  22930. /**
  22931. * The end angle of the curve in radians starting from the positive X axis.
  22932. *
  22933. * @type {number}
  22934. * @default Math.PI*2
  22935. */
  22936. this.aEndAngle = aEndAngle;
  22937. /**
  22938. * Whether the ellipse is drawn clockwise or not.
  22939. *
  22940. * @type {boolean}
  22941. * @default false
  22942. */
  22943. this.aClockwise = aClockwise;
  22944. /**
  22945. * The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  22946. *
  22947. * @type {number}
  22948. * @default 0
  22949. */
  22950. this.aRotation = aRotation;
  22951. }
  22952. /**
  22953. * Returns a point on the curve.
  22954. *
  22955. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  22956. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  22957. * @return {Vector2} The position on the curve.
  22958. */
  22959. getPoint( t, optionalTarget = new Vector2() ) {
  22960. const point = optionalTarget;
  22961. const twoPi = Math.PI * 2;
  22962. let deltaAngle = this.aEndAngle - this.aStartAngle;
  22963. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  22964. // ensures that deltaAngle is 0 .. 2 PI
  22965. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  22966. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  22967. if ( deltaAngle < Number.EPSILON ) {
  22968. if ( samePoints ) {
  22969. deltaAngle = 0;
  22970. } else {
  22971. deltaAngle = twoPi;
  22972. }
  22973. }
  22974. if ( this.aClockwise === true && ! samePoints ) {
  22975. if ( deltaAngle === twoPi ) {
  22976. deltaAngle = - twoPi;
  22977. } else {
  22978. deltaAngle = deltaAngle - twoPi;
  22979. }
  22980. }
  22981. const angle = this.aStartAngle + t * deltaAngle;
  22982. let x = this.aX + this.xRadius * Math.cos( angle );
  22983. let y = this.aY + this.yRadius * Math.sin( angle );
  22984. if ( this.aRotation !== 0 ) {
  22985. const cos = Math.cos( this.aRotation );
  22986. const sin = Math.sin( this.aRotation );
  22987. const tx = x - this.aX;
  22988. const ty = y - this.aY;
  22989. // Rotate the point about the center of the ellipse.
  22990. x = tx * cos - ty * sin + this.aX;
  22991. y = tx * sin + ty * cos + this.aY;
  22992. }
  22993. return point.set( x, y );
  22994. }
  22995. copy( source ) {
  22996. super.copy( source );
  22997. this.aX = source.aX;
  22998. this.aY = source.aY;
  22999. this.xRadius = source.xRadius;
  23000. this.yRadius = source.yRadius;
  23001. this.aStartAngle = source.aStartAngle;
  23002. this.aEndAngle = source.aEndAngle;
  23003. this.aClockwise = source.aClockwise;
  23004. this.aRotation = source.aRotation;
  23005. return this;
  23006. }
  23007. toJSON() {
  23008. const data = super.toJSON();
  23009. data.aX = this.aX;
  23010. data.aY = this.aY;
  23011. data.xRadius = this.xRadius;
  23012. data.yRadius = this.yRadius;
  23013. data.aStartAngle = this.aStartAngle;
  23014. data.aEndAngle = this.aEndAngle;
  23015. data.aClockwise = this.aClockwise;
  23016. data.aRotation = this.aRotation;
  23017. return data;
  23018. }
  23019. fromJSON( json ) {
  23020. super.fromJSON( json );
  23021. this.aX = json.aX;
  23022. this.aY = json.aY;
  23023. this.xRadius = json.xRadius;
  23024. this.yRadius = json.yRadius;
  23025. this.aStartAngle = json.aStartAngle;
  23026. this.aEndAngle = json.aEndAngle;
  23027. this.aClockwise = json.aClockwise;
  23028. this.aRotation = json.aRotation;
  23029. return this;
  23030. }
  23031. }
  23032. /**
  23033. * A curve representing an arc.
  23034. *
  23035. * @augments EllipseCurve
  23036. */
  23037. class ArcCurve extends EllipseCurve {
  23038. /**
  23039. * Constructs a new arc curve.
  23040. *
  23041. * @param {number} [aX=0] - The X center of the ellipse.
  23042. * @param {number} [aY=0] - The Y center of the ellipse.
  23043. * @param {number} [aRadius=1] - The radius of the ellipse in the x direction.
  23044. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23045. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23046. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23047. */
  23048. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23049. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  23050. /**
  23051. * This flag can be used for type testing.
  23052. *
  23053. * @type {boolean}
  23054. * @readonly
  23055. * @default true
  23056. */
  23057. this.isArcCurve = true;
  23058. this.type = 'ArcCurve';
  23059. }
  23060. }
  23061. function CubicPoly() {
  23062. /**
  23063. * Centripetal CatmullRom Curve - which is useful for avoiding
  23064. * cusps and self-intersections in non-uniform catmull rom curves.
  23065. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  23066. *
  23067. * curve.type accepts centripetal(default), chordal and catmullrom
  23068. * curve.tension is used for catmullrom which defaults to 0.5
  23069. */
  23070. /*
  23071. Based on an optimized c++ solution in
  23072. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  23073. - http://ideone.com/NoEbVM
  23074. This CubicPoly class could be used for reusing some variables and calculations,
  23075. but for three.js curve use, it could be possible inlined and flatten into a single function call
  23076. which can be placed in CurveUtils.
  23077. */
  23078. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  23079. /*
  23080. * Compute coefficients for a cubic polynomial
  23081. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  23082. * such that
  23083. * p(0) = x0, p(1) = x1
  23084. * and
  23085. * p'(0) = t0, p'(1) = t1.
  23086. */
  23087. function init( x0, x1, t0, t1 ) {
  23088. c0 = x0;
  23089. c1 = t0;
  23090. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  23091. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  23092. }
  23093. return {
  23094. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  23095. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  23096. },
  23097. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  23098. // compute tangents when parameterized in [t1,t2]
  23099. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  23100. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  23101. // rescale tangents for parametrization in [0,1]
  23102. t1 *= dt1;
  23103. t2 *= dt1;
  23104. init( x1, x2, t1, t2 );
  23105. },
  23106. calc: function ( t ) {
  23107. const t2 = t * t;
  23108. const t3 = t2 * t;
  23109. return c0 + c1 * t + c2 * t2 + c3 * t3;
  23110. }
  23111. };
  23112. }
  23113. //
  23114. const tmp = /*@__PURE__*/ new Vector3();
  23115. const px = /*@__PURE__*/ new CubicPoly();
  23116. const py = /*@__PURE__*/ new CubicPoly();
  23117. const pz = /*@__PURE__*/ new CubicPoly();
  23118. /**
  23119. * A curve representing a Catmull-Rom spline.
  23120. *
  23121. * ```js
  23122. * //Create a closed wavey loop
  23123. * const curve = new THREE.CatmullRomCurve3( [
  23124. * new THREE.Vector3( -10, 0, 10 ),
  23125. * new THREE.Vector3( -5, 5, 5 ),
  23126. * new THREE.Vector3( 0, 0, 0 ),
  23127. * new THREE.Vector3( 5, -5, 5 ),
  23128. * new THREE.Vector3( 10, 0, 10 )
  23129. * ] );
  23130. *
  23131. * const points = curve.getPoints( 50 );
  23132. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23133. *
  23134. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23135. *
  23136. * // Create the final object to add to the scene
  23137. * const curveObject = new THREE.Line( geometry, material );
  23138. * ```
  23139. *
  23140. * @augments Curve
  23141. */
  23142. class CatmullRomCurve3 extends Curve {
  23143. /**
  23144. * Constructs a new Catmull-Rom curve.
  23145. *
  23146. * @param {Array<Vector3>} [points] - An array of 3D points defining the curve.
  23147. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23148. * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type.
  23149. * @param {number} [tension=0.5] - Tension of the curve.
  23150. */
  23151. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  23152. super();
  23153. /**
  23154. * This flag can be used for type testing.
  23155. *
  23156. * @type {boolean}
  23157. * @readonly
  23158. * @default true
  23159. */
  23160. this.isCatmullRomCurve3 = true;
  23161. this.type = 'CatmullRomCurve3';
  23162. /**
  23163. * An array of 3D points defining the curve.
  23164. *
  23165. * @type {Array<Vector3>}
  23166. */
  23167. this.points = points;
  23168. /**
  23169. * Whether the curve is closed or not.
  23170. *
  23171. * @type {boolean}
  23172. * @default false
  23173. */
  23174. this.closed = closed;
  23175. /**
  23176. * The curve type.
  23177. *
  23178. * @type {('centripetal'|'chordal'|'catmullrom')}
  23179. * @default 'centripetal'
  23180. */
  23181. this.curveType = curveType;
  23182. /**
  23183. * Tension of the curve.
  23184. *
  23185. * @type {number}
  23186. * @default 0.5
  23187. */
  23188. this.tension = tension;
  23189. }
  23190. /**
  23191. * Returns a point on the curve.
  23192. *
  23193. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23194. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23195. * @return {Vector3} The position on the curve.
  23196. */
  23197. getPoint( t, optionalTarget = new Vector3() ) {
  23198. const point = optionalTarget;
  23199. const points = this.points;
  23200. const l = points.length;
  23201. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  23202. let intPoint = Math.floor( p );
  23203. let weight = p - intPoint;
  23204. if ( this.closed ) {
  23205. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  23206. } else if ( weight === 0 && intPoint === l - 1 ) {
  23207. intPoint = l - 2;
  23208. weight = 1;
  23209. }
  23210. let p0, p3; // 4 points (p1 & p2 defined below)
  23211. if ( this.closed || intPoint > 0 ) {
  23212. p0 = points[ ( intPoint - 1 ) % l ];
  23213. } else {
  23214. // extrapolate first point
  23215. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  23216. p0 = tmp;
  23217. }
  23218. const p1 = points[ intPoint % l ];
  23219. const p2 = points[ ( intPoint + 1 ) % l ];
  23220. if ( this.closed || intPoint + 2 < l ) {
  23221. p3 = points[ ( intPoint + 2 ) % l ];
  23222. } else {
  23223. // extrapolate last point
  23224. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  23225. p3 = tmp;
  23226. }
  23227. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  23228. // init Centripetal / Chordal Catmull-Rom
  23229. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  23230. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  23231. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  23232. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  23233. // safety check for repeated points
  23234. if ( dt1 < 1e-4 ) dt1 = 1.0;
  23235. if ( dt0 < 1e-4 ) dt0 = dt1;
  23236. if ( dt2 < 1e-4 ) dt2 = dt1;
  23237. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  23238. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  23239. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  23240. } else if ( this.curveType === 'catmullrom' ) {
  23241. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  23242. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  23243. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  23244. }
  23245. point.set(
  23246. px.calc( weight ),
  23247. py.calc( weight ),
  23248. pz.calc( weight )
  23249. );
  23250. return point;
  23251. }
  23252. copy( source ) {
  23253. super.copy( source );
  23254. this.points = [];
  23255. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  23256. const point = source.points[ i ];
  23257. this.points.push( point.clone() );
  23258. }
  23259. this.closed = source.closed;
  23260. this.curveType = source.curveType;
  23261. this.tension = source.tension;
  23262. return this;
  23263. }
  23264. toJSON() {
  23265. const data = super.toJSON();
  23266. data.points = [];
  23267. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  23268. const point = this.points[ i ];
  23269. data.points.push( point.toArray() );
  23270. }
  23271. data.closed = this.closed;
  23272. data.curveType = this.curveType;
  23273. data.tension = this.tension;
  23274. return data;
  23275. }
  23276. fromJSON( json ) {
  23277. super.fromJSON( json );
  23278. this.points = [];
  23279. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  23280. const point = json.points[ i ];
  23281. this.points.push( new Vector3().fromArray( point ) );
  23282. }
  23283. this.closed = json.closed;
  23284. this.curveType = json.curveType;
  23285. this.tension = json.tension;
  23286. return this;
  23287. }
  23288. }
  23289. /**
  23290. * Interpolations contains spline and Bézier functions internally used by concrete curve classes.
  23291. *
  23292. * Bezier Curves formulas obtained from: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  23293. *
  23294. * @module Interpolations
  23295. */
  23296. /**
  23297. * Computes a point on a Catmull-Rom spline.
  23298. *
  23299. * @param {number} t - The interpolation factor.
  23300. * @param {number} p0 - The first control point.
  23301. * @param {number} p1 - The second control point.
  23302. * @param {number} p2 - The third control point.
  23303. * @param {number} p3 - The fourth control point.
  23304. * @return {number} The calculated point on a Catmull-Rom spline.
  23305. */
  23306. function CatmullRom( t, p0, p1, p2, p3 ) {
  23307. const v0 = ( p2 - p0 ) * 0.5;
  23308. const v1 = ( p3 - p1 ) * 0.5;
  23309. const t2 = t * t;
  23310. const t3 = t * t2;
  23311. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( -3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  23312. }
  23313. //
  23314. function QuadraticBezierP0( t, p ) {
  23315. const k = 1 - t;
  23316. return k * k * p;
  23317. }
  23318. function QuadraticBezierP1( t, p ) {
  23319. return 2 * ( 1 - t ) * t * p;
  23320. }
  23321. function QuadraticBezierP2( t, p ) {
  23322. return t * t * p;
  23323. }
  23324. /**
  23325. * Computes a point on a Quadratic Bezier curve.
  23326. *
  23327. * @param {number} t - The interpolation factor.
  23328. * @param {number} p0 - The first control point.
  23329. * @param {number} p1 - The second control point.
  23330. * @param {number} p2 - The third control point.
  23331. * @return {number} The calculated point on a Quadratic Bezier curve.
  23332. */
  23333. function QuadraticBezier( t, p0, p1, p2 ) {
  23334. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  23335. QuadraticBezierP2( t, p2 );
  23336. }
  23337. //
  23338. function CubicBezierP0( t, p ) {
  23339. const k = 1 - t;
  23340. return k * k * k * p;
  23341. }
  23342. function CubicBezierP1( t, p ) {
  23343. const k = 1 - t;
  23344. return 3 * k * k * t * p;
  23345. }
  23346. function CubicBezierP2( t, p ) {
  23347. return 3 * ( 1 - t ) * t * t * p;
  23348. }
  23349. function CubicBezierP3( t, p ) {
  23350. return t * t * t * p;
  23351. }
  23352. /**
  23353. * Computes a point on a Cubic Bezier curve.
  23354. *
  23355. * @param {number} t - The interpolation factor.
  23356. * @param {number} p0 - The first control point.
  23357. * @param {number} p1 - The second control point.
  23358. * @param {number} p2 - The third control point.
  23359. * @param {number} p3 - The fourth control point.
  23360. * @return {number} The calculated point on a Cubic Bezier curve.
  23361. */
  23362. function CubicBezier( t, p0, p1, p2, p3 ) {
  23363. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  23364. CubicBezierP3( t, p3 );
  23365. }
  23366. /**
  23367. * A curve representing a 2D Cubic Bezier curve.
  23368. *
  23369. * ```js
  23370. * const curve = new THREE.CubicBezierCurve(
  23371. * new THREE.Vector2( - 0, 0 ),
  23372. * new THREE.Vector2( - 5, 15 ),
  23373. * new THREE.Vector2( 20, 15 ),
  23374. * new THREE.Vector2( 10, 0 )
  23375. * );
  23376. *
  23377. * const points = curve.getPoints( 50 );
  23378. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23379. *
  23380. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23381. *
  23382. * // Create the final object to add to the scene
  23383. * const curveObject = new THREE.Line( geometry, material );
  23384. * ```
  23385. *
  23386. * @augments Curve
  23387. */
  23388. class CubicBezierCurve extends Curve {
  23389. /**
  23390. * Constructs a new Cubic Bezier curve.
  23391. *
  23392. * @param {Vector2} [v0] - The start point.
  23393. * @param {Vector2} [v1] - The first control point.
  23394. * @param {Vector2} [v2] - The second control point.
  23395. * @param {Vector2} [v3] - The end point.
  23396. */
  23397. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  23398. super();
  23399. /**
  23400. * This flag can be used for type testing.
  23401. *
  23402. * @type {boolean}
  23403. * @readonly
  23404. * @default true
  23405. */
  23406. this.isCubicBezierCurve = true;
  23407. this.type = 'CubicBezierCurve';
  23408. /**
  23409. * The start point.
  23410. *
  23411. * @type {Vector2}
  23412. */
  23413. this.v0 = v0;
  23414. /**
  23415. * The first control point.
  23416. *
  23417. * @type {Vector2}
  23418. */
  23419. this.v1 = v1;
  23420. /**
  23421. * The second control point.
  23422. *
  23423. * @type {Vector2}
  23424. */
  23425. this.v2 = v2;
  23426. /**
  23427. * The end point.
  23428. *
  23429. * @type {Vector2}
  23430. */
  23431. this.v3 = v3;
  23432. }
  23433. /**
  23434. * Returns a point on the curve.
  23435. *
  23436. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23437. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23438. * @return {Vector2} The position on the curve.
  23439. */
  23440. getPoint( t, optionalTarget = new Vector2() ) {
  23441. const point = optionalTarget;
  23442. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23443. point.set(
  23444. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23445. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  23446. );
  23447. return point;
  23448. }
  23449. copy( source ) {
  23450. super.copy( source );
  23451. this.v0.copy( source.v0 );
  23452. this.v1.copy( source.v1 );
  23453. this.v2.copy( source.v2 );
  23454. this.v3.copy( source.v3 );
  23455. return this;
  23456. }
  23457. toJSON() {
  23458. const data = super.toJSON();
  23459. data.v0 = this.v0.toArray();
  23460. data.v1 = this.v1.toArray();
  23461. data.v2 = this.v2.toArray();
  23462. data.v3 = this.v3.toArray();
  23463. return data;
  23464. }
  23465. fromJSON( json ) {
  23466. super.fromJSON( json );
  23467. this.v0.fromArray( json.v0 );
  23468. this.v1.fromArray( json.v1 );
  23469. this.v2.fromArray( json.v2 );
  23470. this.v3.fromArray( json.v3 );
  23471. return this;
  23472. }
  23473. }
  23474. /**
  23475. * A curve representing a 3D Cubic Bezier curve.
  23476. *
  23477. * @augments Curve
  23478. */
  23479. class CubicBezierCurve3 extends Curve {
  23480. /**
  23481. * Constructs a new Cubic Bezier curve.
  23482. *
  23483. * @param {Vector3} [v0] - The start point.
  23484. * @param {Vector3} [v1] - The first control point.
  23485. * @param {Vector3} [v2] - The second control point.
  23486. * @param {Vector3} [v3] - The end point.
  23487. */
  23488. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  23489. super();
  23490. /**
  23491. * This flag can be used for type testing.
  23492. *
  23493. * @type {boolean}
  23494. * @readonly
  23495. * @default true
  23496. */
  23497. this.isCubicBezierCurve3 = true;
  23498. this.type = 'CubicBezierCurve3';
  23499. /**
  23500. * The start point.
  23501. *
  23502. * @type {Vector3}
  23503. */
  23504. this.v0 = v0;
  23505. /**
  23506. * The first control point.
  23507. *
  23508. * @type {Vector3}
  23509. */
  23510. this.v1 = v1;
  23511. /**
  23512. * The second control point.
  23513. *
  23514. * @type {Vector3}
  23515. */
  23516. this.v2 = v2;
  23517. /**
  23518. * The end point.
  23519. *
  23520. * @type {Vector3}
  23521. */
  23522. this.v3 = v3;
  23523. }
  23524. /**
  23525. * Returns a point on the curve.
  23526. *
  23527. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23528. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23529. * @return {Vector3} The position on the curve.
  23530. */
  23531. getPoint( t, optionalTarget = new Vector3() ) {
  23532. const point = optionalTarget;
  23533. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23534. point.set(
  23535. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23536. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  23537. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  23538. );
  23539. return point;
  23540. }
  23541. copy( source ) {
  23542. super.copy( source );
  23543. this.v0.copy( source.v0 );
  23544. this.v1.copy( source.v1 );
  23545. this.v2.copy( source.v2 );
  23546. this.v3.copy( source.v3 );
  23547. return this;
  23548. }
  23549. toJSON() {
  23550. const data = super.toJSON();
  23551. data.v0 = this.v0.toArray();
  23552. data.v1 = this.v1.toArray();
  23553. data.v2 = this.v2.toArray();
  23554. data.v3 = this.v3.toArray();
  23555. return data;
  23556. }
  23557. fromJSON( json ) {
  23558. super.fromJSON( json );
  23559. this.v0.fromArray( json.v0 );
  23560. this.v1.fromArray( json.v1 );
  23561. this.v2.fromArray( json.v2 );
  23562. this.v3.fromArray( json.v3 );
  23563. return this;
  23564. }
  23565. }
  23566. /**
  23567. * A curve representing a 2D line segment.
  23568. *
  23569. * @augments Curve
  23570. */
  23571. class LineCurve extends Curve {
  23572. /**
  23573. * Constructs a new line curve.
  23574. *
  23575. * @param {Vector2} [v1] - The start point.
  23576. * @param {Vector2} [v2] - The end point.
  23577. */
  23578. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  23579. super();
  23580. /**
  23581. * This flag can be used for type testing.
  23582. *
  23583. * @type {boolean}
  23584. * @readonly
  23585. * @default true
  23586. */
  23587. this.isLineCurve = true;
  23588. this.type = 'LineCurve';
  23589. /**
  23590. * The start point.
  23591. *
  23592. * @type {Vector2}
  23593. */
  23594. this.v1 = v1;
  23595. /**
  23596. * The end point.
  23597. *
  23598. * @type {Vector2}
  23599. */
  23600. this.v2 = v2;
  23601. }
  23602. /**
  23603. * Returns a point on the line.
  23604. *
  23605. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  23606. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23607. * @return {Vector2} The position on the line.
  23608. */
  23609. getPoint( t, optionalTarget = new Vector2() ) {
  23610. const point = optionalTarget;
  23611. if ( t === 1 ) {
  23612. point.copy( this.v2 );
  23613. } else {
  23614. point.copy( this.v2 ).sub( this.v1 );
  23615. point.multiplyScalar( t ).add( this.v1 );
  23616. }
  23617. return point;
  23618. }
  23619. // Line curve is linear, so we can overwrite default getPointAt
  23620. getPointAt( u, optionalTarget ) {
  23621. return this.getPoint( u, optionalTarget );
  23622. }
  23623. getTangent( t, optionalTarget = new Vector2() ) {
  23624. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  23625. }
  23626. getTangentAt( u, optionalTarget ) {
  23627. return this.getTangent( u, optionalTarget );
  23628. }
  23629. copy( source ) {
  23630. super.copy( source );
  23631. this.v1.copy( source.v1 );
  23632. this.v2.copy( source.v2 );
  23633. return this;
  23634. }
  23635. toJSON() {
  23636. const data = super.toJSON();
  23637. data.v1 = this.v1.toArray();
  23638. data.v2 = this.v2.toArray();
  23639. return data;
  23640. }
  23641. fromJSON( json ) {
  23642. super.fromJSON( json );
  23643. this.v1.fromArray( json.v1 );
  23644. this.v2.fromArray( json.v2 );
  23645. return this;
  23646. }
  23647. }
  23648. /**
  23649. * A curve representing a 3D line segment.
  23650. *
  23651. * @augments Curve
  23652. */
  23653. class LineCurve3 extends Curve {
  23654. /**
  23655. * Constructs a new line curve.
  23656. *
  23657. * @param {Vector3} [v1] - The start point.
  23658. * @param {Vector3} [v2] - The end point.
  23659. */
  23660. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  23661. super();
  23662. /**
  23663. * This flag can be used for type testing.
  23664. *
  23665. * @type {boolean}
  23666. * @readonly
  23667. * @default true
  23668. */
  23669. this.isLineCurve3 = true;
  23670. this.type = 'LineCurve3';
  23671. /**
  23672. * The start point.
  23673. *
  23674. * @type {Vector3}
  23675. */
  23676. this.v1 = v1;
  23677. /**
  23678. * The end point.
  23679. *
  23680. * @type {Vector2}
  23681. */
  23682. this.v2 = v2;
  23683. }
  23684. /**
  23685. * Returns a point on the line.
  23686. *
  23687. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  23688. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23689. * @return {Vector3} The position on the line.
  23690. */
  23691. getPoint( t, optionalTarget = new Vector3() ) {
  23692. const point = optionalTarget;
  23693. if ( t === 1 ) {
  23694. point.copy( this.v2 );
  23695. } else {
  23696. point.copy( this.v2 ).sub( this.v1 );
  23697. point.multiplyScalar( t ).add( this.v1 );
  23698. }
  23699. return point;
  23700. }
  23701. // Line curve is linear, so we can overwrite default getPointAt
  23702. getPointAt( u, optionalTarget ) {
  23703. return this.getPoint( u, optionalTarget );
  23704. }
  23705. getTangent( t, optionalTarget = new Vector3() ) {
  23706. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  23707. }
  23708. getTangentAt( u, optionalTarget ) {
  23709. return this.getTangent( u, optionalTarget );
  23710. }
  23711. copy( source ) {
  23712. super.copy( source );
  23713. this.v1.copy( source.v1 );
  23714. this.v2.copy( source.v2 );
  23715. return this;
  23716. }
  23717. toJSON() {
  23718. const data = super.toJSON();
  23719. data.v1 = this.v1.toArray();
  23720. data.v2 = this.v2.toArray();
  23721. return data;
  23722. }
  23723. fromJSON( json ) {
  23724. super.fromJSON( json );
  23725. this.v1.fromArray( json.v1 );
  23726. this.v2.fromArray( json.v2 );
  23727. return this;
  23728. }
  23729. }
  23730. /**
  23731. * A curve representing a 2D Quadratic Bezier curve.
  23732. *
  23733. * ```js
  23734. * const curve = new THREE.QuadraticBezierCurve(
  23735. * new THREE.Vector2( - 10, 0 ),
  23736. * new THREE.Vector2( 20, 15 ),
  23737. * new THREE.Vector2( 10, 0 )
  23738. * )
  23739. *
  23740. * const points = curve.getPoints( 50 );
  23741. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23742. *
  23743. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23744. *
  23745. * // Create the final object to add to the scene
  23746. * const curveObject = new THREE.Line( geometry, material );
  23747. * ```
  23748. *
  23749. * @augments Curve
  23750. */
  23751. class QuadraticBezierCurve extends Curve {
  23752. /**
  23753. * Constructs a new Quadratic Bezier curve.
  23754. *
  23755. * @param {Vector2} [v0] - The start point.
  23756. * @param {Vector2} [v1] - The control point.
  23757. * @param {Vector2} [v2] - The end point.
  23758. */
  23759. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  23760. super();
  23761. /**
  23762. * This flag can be used for type testing.
  23763. *
  23764. * @type {boolean}
  23765. * @readonly
  23766. * @default true
  23767. */
  23768. this.isQuadraticBezierCurve = true;
  23769. this.type = 'QuadraticBezierCurve';
  23770. /**
  23771. * The start point.
  23772. *
  23773. * @type {Vector2}
  23774. */
  23775. this.v0 = v0;
  23776. /**
  23777. * The control point.
  23778. *
  23779. * @type {Vector2}
  23780. */
  23781. this.v1 = v1;
  23782. /**
  23783. * The end point.
  23784. *
  23785. * @type {Vector2}
  23786. */
  23787. this.v2 = v2;
  23788. }
  23789. /**
  23790. * Returns a point on the curve.
  23791. *
  23792. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23793. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23794. * @return {Vector2} The position on the curve.
  23795. */
  23796. getPoint( t, optionalTarget = new Vector2() ) {
  23797. const point = optionalTarget;
  23798. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  23799. point.set(
  23800. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  23801. QuadraticBezier( t, v0.y, v1.y, v2.y )
  23802. );
  23803. return point;
  23804. }
  23805. copy( source ) {
  23806. super.copy( source );
  23807. this.v0.copy( source.v0 );
  23808. this.v1.copy( source.v1 );
  23809. this.v2.copy( source.v2 );
  23810. return this;
  23811. }
  23812. toJSON() {
  23813. const data = super.toJSON();
  23814. data.v0 = this.v0.toArray();
  23815. data.v1 = this.v1.toArray();
  23816. data.v2 = this.v2.toArray();
  23817. return data;
  23818. }
  23819. fromJSON( json ) {
  23820. super.fromJSON( json );
  23821. this.v0.fromArray( json.v0 );
  23822. this.v1.fromArray( json.v1 );
  23823. this.v2.fromArray( json.v2 );
  23824. return this;
  23825. }
  23826. }
  23827. /**
  23828. * A curve representing a 3D Quadratic Bezier curve.
  23829. *
  23830. * @augments Curve
  23831. */
  23832. class QuadraticBezierCurve3 extends Curve {
  23833. /**
  23834. * Constructs a new Quadratic Bezier curve.
  23835. *
  23836. * @param {Vector3} [v0] - The start point.
  23837. * @param {Vector3} [v1] - The control point.
  23838. * @param {Vector3} [v2] - The end point.
  23839. */
  23840. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  23841. super();
  23842. /**
  23843. * This flag can be used for type testing.
  23844. *
  23845. * @type {boolean}
  23846. * @readonly
  23847. * @default true
  23848. */
  23849. this.isQuadraticBezierCurve3 = true;
  23850. this.type = 'QuadraticBezierCurve3';
  23851. /**
  23852. * The start point.
  23853. *
  23854. * @type {Vector3}
  23855. */
  23856. this.v0 = v0;
  23857. /**
  23858. * The control point.
  23859. *
  23860. * @type {Vector3}
  23861. */
  23862. this.v1 = v1;
  23863. /**
  23864. * The end point.
  23865. *
  23866. * @type {Vector3}
  23867. */
  23868. this.v2 = v2;
  23869. }
  23870. /**
  23871. * Returns a point on the curve.
  23872. *
  23873. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23874. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23875. * @return {Vector3} The position on the curve.
  23876. */
  23877. getPoint( t, optionalTarget = new Vector3() ) {
  23878. const point = optionalTarget;
  23879. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  23880. point.set(
  23881. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  23882. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  23883. QuadraticBezier( t, v0.z, v1.z, v2.z )
  23884. );
  23885. return point;
  23886. }
  23887. copy( source ) {
  23888. super.copy( source );
  23889. this.v0.copy( source.v0 );
  23890. this.v1.copy( source.v1 );
  23891. this.v2.copy( source.v2 );
  23892. return this;
  23893. }
  23894. toJSON() {
  23895. const data = super.toJSON();
  23896. data.v0 = this.v0.toArray();
  23897. data.v1 = this.v1.toArray();
  23898. data.v2 = this.v2.toArray();
  23899. return data;
  23900. }
  23901. fromJSON( json ) {
  23902. super.fromJSON( json );
  23903. this.v0.fromArray( json.v0 );
  23904. this.v1.fromArray( json.v1 );
  23905. this.v2.fromArray( json.v2 );
  23906. return this;
  23907. }
  23908. }
  23909. /**
  23910. * A curve representing a 2D spline curve.
  23911. *
  23912. * ```js
  23913. * // Create a sine-like wave
  23914. * const curve = new THREE.SplineCurve( [
  23915. * new THREE.Vector2( -10, 0 ),
  23916. * new THREE.Vector2( -5, 5 ),
  23917. * new THREE.Vector2( 0, 0 ),
  23918. * new THREE.Vector2( 5, -5 ),
  23919. * new THREE.Vector2( 10, 0 )
  23920. * ] );
  23921. *
  23922. * const points = curve.getPoints( 50 );
  23923. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23924. *
  23925. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23926. *
  23927. * // Create the final object to add to the scene
  23928. * const splineObject = new THREE.Line( geometry, material );
  23929. * ```
  23930. *
  23931. * @augments Curve
  23932. */
  23933. class SplineCurve extends Curve {
  23934. /**
  23935. * Constructs a new 2D spline curve.
  23936. *
  23937. * @param {Array<Vector2>} [points] - An array of 2D points defining the curve.
  23938. */
  23939. constructor( points = [] ) {
  23940. super();
  23941. /**
  23942. * This flag can be used for type testing.
  23943. *
  23944. * @type {boolean}
  23945. * @readonly
  23946. * @default true
  23947. */
  23948. this.isSplineCurve = true;
  23949. this.type = 'SplineCurve';
  23950. /**
  23951. * An array of 2D points defining the curve.
  23952. *
  23953. * @type {Array<Vector2>}
  23954. */
  23955. this.points = points;
  23956. }
  23957. /**
  23958. * Returns a point on the curve.
  23959. *
  23960. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23961. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23962. * @return {Vector2} The position on the curve.
  23963. */
  23964. getPoint( t, optionalTarget = new Vector2() ) {
  23965. const point = optionalTarget;
  23966. const points = this.points;
  23967. const p = ( points.length - 1 ) * t;
  23968. const intPoint = Math.floor( p );
  23969. const weight = p - intPoint;
  23970. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  23971. const p1 = points[ intPoint ];
  23972. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  23973. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  23974. point.set(
  23975. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  23976. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  23977. );
  23978. return point;
  23979. }
  23980. copy( source ) {
  23981. super.copy( source );
  23982. this.points = [];
  23983. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  23984. const point = source.points[ i ];
  23985. this.points.push( point.clone() );
  23986. }
  23987. return this;
  23988. }
  23989. toJSON() {
  23990. const data = super.toJSON();
  23991. data.points = [];
  23992. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  23993. const point = this.points[ i ];
  23994. data.points.push( point.toArray() );
  23995. }
  23996. return data;
  23997. }
  23998. fromJSON( json ) {
  23999. super.fromJSON( json );
  24000. this.points = [];
  24001. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  24002. const point = json.points[ i ];
  24003. this.points.push( new Vector2().fromArray( point ) );
  24004. }
  24005. return this;
  24006. }
  24007. }
  24008. var Curves = /*#__PURE__*/Object.freeze({
  24009. __proto__: null,
  24010. ArcCurve: ArcCurve,
  24011. CatmullRomCurve3: CatmullRomCurve3,
  24012. CubicBezierCurve: CubicBezierCurve,
  24013. CubicBezierCurve3: CubicBezierCurve3,
  24014. EllipseCurve: EllipseCurve,
  24015. LineCurve: LineCurve,
  24016. LineCurve3: LineCurve3,
  24017. QuadraticBezierCurve: QuadraticBezierCurve,
  24018. QuadraticBezierCurve3: QuadraticBezierCurve3,
  24019. SplineCurve: SplineCurve
  24020. });
  24021. /**
  24022. * A base class extending {@link Curve}. `CurvePath` is simply an
  24023. * array of connected curves, but retains the API of a curve.
  24024. *
  24025. * @augments Curve
  24026. */
  24027. class CurvePath extends Curve {
  24028. /**
  24029. * Constructs a new curve path.
  24030. */
  24031. constructor() {
  24032. super();
  24033. this.type = 'CurvePath';
  24034. /**
  24035. * An array of curves defining the
  24036. * path.
  24037. *
  24038. * @type {Array<Curve>}
  24039. */
  24040. this.curves = [];
  24041. /**
  24042. * Whether the path should automatically be closed
  24043. * by a line curve.
  24044. *
  24045. * @type {boolean}
  24046. * @default false
  24047. */
  24048. this.autoClose = false;
  24049. }
  24050. /**
  24051. * Adds a curve to this curve path.
  24052. *
  24053. * @param {Curve} curve - The curve to add.
  24054. */
  24055. add( curve ) {
  24056. this.curves.push( curve );
  24057. }
  24058. /**
  24059. * Adds a line curve to close the path.
  24060. *
  24061. * @return {CurvePath} A reference to this curve path.
  24062. */
  24063. closePath() {
  24064. // Add a line curve if start and end of lines are not connected
  24065. const startPoint = this.curves[ 0 ].getPoint( 0 );
  24066. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  24067. if ( ! startPoint.equals( endPoint ) ) {
  24068. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  24069. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  24070. }
  24071. return this;
  24072. }
  24073. /**
  24074. * This method returns a vector in 2D or 3D space (depending on the curve definitions)
  24075. * for the given interpolation factor.
  24076. *
  24077. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24078. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  24079. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  24080. */
  24081. getPoint( t, optionalTarget ) {
  24082. // To get accurate point with reference to
  24083. // entire path distance at time t,
  24084. // following has to be done:
  24085. // 1. Length of each sub path have to be known
  24086. // 2. Locate and identify type of curve
  24087. // 3. Get t for the curve
  24088. // 4. Return curve.getPointAt(t')
  24089. const d = t * this.getLength();
  24090. const curveLengths = this.getCurveLengths();
  24091. let i = 0;
  24092. // To think about boundaries points.
  24093. while ( i < curveLengths.length ) {
  24094. if ( curveLengths[ i ] >= d ) {
  24095. const diff = curveLengths[ i ] - d;
  24096. const curve = this.curves[ i ];
  24097. const segmentLength = curve.getLength();
  24098. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  24099. return curve.getPointAt( u, optionalTarget );
  24100. }
  24101. i ++;
  24102. }
  24103. return null;
  24104. // loop where sum != 0, sum > d , sum+1 <d
  24105. }
  24106. getLength() {
  24107. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  24108. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  24109. // getPoint() depends on getLength
  24110. const lens = this.getCurveLengths();
  24111. return lens[ lens.length - 1 ];
  24112. }
  24113. updateArcLengths() {
  24114. // cacheLengths must be recalculated.
  24115. this.needsUpdate = true;
  24116. this.cacheLengths = null;
  24117. this.getCurveLengths();
  24118. }
  24119. /**
  24120. * Returns list of cumulative curve lengths of the defined curves.
  24121. *
  24122. * @return {Array<number>} The curve lengths.
  24123. */
  24124. getCurveLengths() {
  24125. // Compute lengths and cache them
  24126. // We cannot overwrite getLengths() because UtoT mapping uses it.
  24127. // We use cache values if curves and cache array are same length
  24128. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  24129. return this.cacheLengths;
  24130. }
  24131. // Get length of sub-curve
  24132. // Push sums into cached array
  24133. const lengths = [];
  24134. let sums = 0;
  24135. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24136. sums += this.curves[ i ].getLength();
  24137. lengths.push( sums );
  24138. }
  24139. this.cacheLengths = lengths;
  24140. return lengths;
  24141. }
  24142. getSpacedPoints( divisions = 40 ) {
  24143. const points = [];
  24144. for ( let i = 0; i <= divisions; i ++ ) {
  24145. points.push( this.getPoint( i / divisions ) );
  24146. }
  24147. if ( this.autoClose ) {
  24148. points.push( points[ 0 ] );
  24149. }
  24150. return points;
  24151. }
  24152. getPoints( divisions = 12 ) {
  24153. const points = [];
  24154. let last;
  24155. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  24156. const curve = curves[ i ];
  24157. const resolution = curve.isEllipseCurve ? divisions * 2
  24158. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  24159. : curve.isSplineCurve ? divisions * curve.points.length
  24160. : divisions;
  24161. const pts = curve.getPoints( resolution );
  24162. for ( let j = 0; j < pts.length; j ++ ) {
  24163. const point = pts[ j ];
  24164. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  24165. points.push( point );
  24166. last = point;
  24167. }
  24168. }
  24169. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  24170. points.push( points[ 0 ] );
  24171. }
  24172. return points;
  24173. }
  24174. copy( source ) {
  24175. super.copy( source );
  24176. this.curves = [];
  24177. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  24178. const curve = source.curves[ i ];
  24179. this.curves.push( curve.clone() );
  24180. }
  24181. this.autoClose = source.autoClose;
  24182. return this;
  24183. }
  24184. toJSON() {
  24185. const data = super.toJSON();
  24186. data.autoClose = this.autoClose;
  24187. data.curves = [];
  24188. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24189. const curve = this.curves[ i ];
  24190. data.curves.push( curve.toJSON() );
  24191. }
  24192. return data;
  24193. }
  24194. fromJSON( json ) {
  24195. super.fromJSON( json );
  24196. this.autoClose = json.autoClose;
  24197. this.curves = [];
  24198. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  24199. const curve = json.curves[ i ];
  24200. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  24201. }
  24202. return this;
  24203. }
  24204. }
  24205. /**
  24206. * A 2D path representation. The class provides methods for creating paths
  24207. * and contours of 2D shapes similar to the 2D Canvas API.
  24208. *
  24209. * ```js
  24210. * const path = new THREE.Path();
  24211. *
  24212. * path.lineTo( 0, 0.8 );
  24213. * path.quadraticCurveTo( 0, 1, 0.2, 1 );
  24214. * path.lineTo( 1, 1 );
  24215. *
  24216. * const points = path.getPoints();
  24217. *
  24218. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24219. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  24220. *
  24221. * const line = new THREE.Line( geometry, material );
  24222. * scene.add( line );
  24223. * ```
  24224. *
  24225. * @augments CurvePath
  24226. */
  24227. class Path extends CurvePath {
  24228. /**
  24229. * Constructs a new path.
  24230. *
  24231. * @param {Array<Vector2>} [points] - An array of 2D points defining the path.
  24232. */
  24233. constructor( points ) {
  24234. super();
  24235. this.type = 'Path';
  24236. /**
  24237. * The current offset of the path. Any new curve added will start here.
  24238. *
  24239. * @type {Vector2}
  24240. */
  24241. this.currentPoint = new Vector2();
  24242. if ( points ) {
  24243. this.setFromPoints( points );
  24244. }
  24245. }
  24246. /**
  24247. * Creates a path from the given list of points. The points are added
  24248. * to the path as instances of {@link LineCurve}.
  24249. *
  24250. * @param {Array<Vector2>} points - An array of 2D points.
  24251. * @return {Path} A reference to this path.
  24252. */
  24253. setFromPoints( points ) {
  24254. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  24255. for ( let i = 1, l = points.length; i < l; i ++ ) {
  24256. this.lineTo( points[ i ].x, points[ i ].y );
  24257. }
  24258. return this;
  24259. }
  24260. /**
  24261. * Moves {@link Path#currentPoint} to the given point.
  24262. *
  24263. * @param {number} x - The x coordinate.
  24264. * @param {number} y - The y coordinate.
  24265. * @return {Path} A reference to this path.
  24266. */
  24267. moveTo( x, y ) {
  24268. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  24269. return this;
  24270. }
  24271. /**
  24272. * Adds an instance of {@link LineCurve} to the path by connecting
  24273. * the current point with the given one.
  24274. *
  24275. * @param {number} x - The x coordinate of the end point.
  24276. * @param {number} y - The y coordinate of the end point.
  24277. * @return {Path} A reference to this path.
  24278. */
  24279. lineTo( x, y ) {
  24280. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  24281. this.curves.push( curve );
  24282. this.currentPoint.set( x, y );
  24283. return this;
  24284. }
  24285. /**
  24286. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  24287. * the current point with the given one.
  24288. *
  24289. * @param {number} aCPx - The x coordinate of the control point.
  24290. * @param {number} aCPy - The y coordinate of the control point.
  24291. * @param {number} aX - The x coordinate of the end point.
  24292. * @param {number} aY - The y coordinate of the end point.
  24293. * @return {Path} A reference to this path.
  24294. */
  24295. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  24296. const curve = new QuadraticBezierCurve(
  24297. this.currentPoint.clone(),
  24298. new Vector2( aCPx, aCPy ),
  24299. new Vector2( aX, aY )
  24300. );
  24301. this.curves.push( curve );
  24302. this.currentPoint.set( aX, aY );
  24303. return this;
  24304. }
  24305. /**
  24306. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  24307. * the current point with the given one.
  24308. *
  24309. * @param {number} aCP1x - The x coordinate of the first control point.
  24310. * @param {number} aCP1y - The y coordinate of the first control point.
  24311. * @param {number} aCP2x - The x coordinate of the second control point.
  24312. * @param {number} aCP2y - The y coordinate of the second control point.
  24313. * @param {number} aX - The x coordinate of the end point.
  24314. * @param {number} aY - The y coordinate of the end point.
  24315. * @return {Path} A reference to this path.
  24316. */
  24317. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  24318. const curve = new CubicBezierCurve(
  24319. this.currentPoint.clone(),
  24320. new Vector2( aCP1x, aCP1y ),
  24321. new Vector2( aCP2x, aCP2y ),
  24322. new Vector2( aX, aY )
  24323. );
  24324. this.curves.push( curve );
  24325. this.currentPoint.set( aX, aY );
  24326. return this;
  24327. }
  24328. /**
  24329. * Adds an instance of {@link SplineCurve} to the path by connecting
  24330. * the current point with the given list of points.
  24331. *
  24332. * @param {Array<Vector2>} pts - An array of points in 2D space.
  24333. * @return {Path} A reference to this path.
  24334. */
  24335. splineThru( pts ) {
  24336. const npts = [ this.currentPoint.clone() ].concat( pts );
  24337. const curve = new SplineCurve( npts );
  24338. this.curves.push( curve );
  24339. this.currentPoint.copy( pts[ pts.length - 1 ] );
  24340. return this;
  24341. }
  24342. /**
  24343. * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative
  24344. * to the current point.
  24345. *
  24346. * @param {number} [aX=0] - The x coordinate of the center of the arc offsetted from the previous curve.
  24347. * @param {number} [aY=0] - The y coordinate of the center of the arc offsetted from the previous curve.
  24348. * @param {number} [aRadius=1] - The radius of the arc.
  24349. * @param {number} [aStartAngle=0] - The start angle in radians.
  24350. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24351. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  24352. * @return {Path} A reference to this path.
  24353. */
  24354. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24355. const x0 = this.currentPoint.x;
  24356. const y0 = this.currentPoint.y;
  24357. this.absarc( aX + x0, aY + y0, aRadius,
  24358. aStartAngle, aEndAngle, aClockwise );
  24359. return this;
  24360. }
  24361. /**
  24362. * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path.
  24363. *
  24364. * @param {number} [aX=0] - The x coordinate of the center of the arc.
  24365. * @param {number} [aY=0] - The y coordinate of the center of the arc.
  24366. * @param {number} [aRadius=1] - The radius of the arc.
  24367. * @param {number} [aStartAngle=0] - The start angle in radians.
  24368. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24369. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  24370. * @return {Path} A reference to this path.
  24371. */
  24372. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24373. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24374. return this;
  24375. }
  24376. /**
  24377. * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative
  24378. * to the current point
  24379. *
  24380. * @param {number} [aX=0] - The x coordinate of the center of the ellipse offsetted from the previous curve.
  24381. * @param {number} [aY=0] - The y coordinate of the center of the ellipse offsetted from the previous curve.
  24382. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  24383. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  24384. * @param {number} [aStartAngle=0] - The start angle in radians.
  24385. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24386. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  24387. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  24388. * @return {Path} A reference to this path.
  24389. */
  24390. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24391. const x0 = this.currentPoint.x;
  24392. const y0 = this.currentPoint.y;
  24393. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24394. return this;
  24395. }
  24396. /**
  24397. * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path.
  24398. *
  24399. * @param {number} [aX=0] - The x coordinate of the absolute center of the ellipse.
  24400. * @param {number} [aY=0] - The y coordinate of the absolute center of the ellipse.
  24401. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  24402. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  24403. * @param {number} [aStartAngle=0] - The start angle in radians.
  24404. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24405. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  24406. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  24407. * @return {Path} A reference to this path.
  24408. */
  24409. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24410. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24411. if ( this.curves.length > 0 ) {
  24412. // if a previous curve is present, attempt to join
  24413. const firstPoint = curve.getPoint( 0 );
  24414. if ( ! firstPoint.equals( this.currentPoint ) ) {
  24415. this.lineTo( firstPoint.x, firstPoint.y );
  24416. }
  24417. }
  24418. this.curves.push( curve );
  24419. const lastPoint = curve.getPoint( 1 );
  24420. this.currentPoint.copy( lastPoint );
  24421. return this;
  24422. }
  24423. copy( source ) {
  24424. super.copy( source );
  24425. this.currentPoint.copy( source.currentPoint );
  24426. return this;
  24427. }
  24428. toJSON() {
  24429. const data = super.toJSON();
  24430. data.currentPoint = this.currentPoint.toArray();
  24431. return data;
  24432. }
  24433. fromJSON( json ) {
  24434. super.fromJSON( json );
  24435. this.currentPoint.fromArray( json.currentPoint );
  24436. return this;
  24437. }
  24438. }
  24439. /**
  24440. * Defines an arbitrary 2d shape plane using paths with optional holes. It
  24441. * can be used with {@link ExtrudeGeometry}, {@link ShapeGeometry}, to get
  24442. * points, or to get triangulated faces.
  24443. *
  24444. * ```js
  24445. * const heartShape = new THREE.Shape();
  24446. *
  24447. * heartShape.moveTo( 25, 25 );
  24448. * heartShape.bezierCurveTo( 25, 25, 20, 0, 0, 0 );
  24449. * heartShape.bezierCurveTo( - 30, 0, - 30, 35, - 30, 35 );
  24450. * heartShape.bezierCurveTo( - 30, 55, - 10, 77, 25, 95 );
  24451. * heartShape.bezierCurveTo( 60, 77, 80, 55, 80, 35 );
  24452. * heartShape.bezierCurveTo( 80, 35, 80, 0, 50, 0 );
  24453. * heartShape.bezierCurveTo( 35, 0, 25, 25, 25, 25 );
  24454. *
  24455. * const extrudeSettings = {
  24456. * depth: 8,
  24457. * bevelEnabled: true,
  24458. * bevelSegments: 2,
  24459. * steps: 2,
  24460. * bevelSize: 1,
  24461. * bevelThickness: 1
  24462. * };
  24463. *
  24464. * const geometry = new THREE.ExtrudeGeometry( heartShape, extrudeSettings );
  24465. * const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
  24466. * ```
  24467. *
  24468. * @augments Path
  24469. */
  24470. class Shape extends Path {
  24471. /**
  24472. * Constructs a new shape.
  24473. *
  24474. * @param {Array<Vector2>} [points] - An array of 2D points defining the shape.
  24475. */
  24476. constructor( points ) {
  24477. super( points );
  24478. /**
  24479. * The UUID of the shape.
  24480. *
  24481. * @type {string}
  24482. * @readonly
  24483. */
  24484. this.uuid = generateUUID();
  24485. this.type = 'Shape';
  24486. /**
  24487. * Defines the holes in the shape. Hole definitions must use the
  24488. * opposite winding order (CW/CCW) than the outer shape.
  24489. *
  24490. * @type {Array<Path>}
  24491. * @readonly
  24492. */
  24493. this.holes = [];
  24494. }
  24495. /**
  24496. * Returns an array representing each contour of the holes
  24497. * as a list of 2D points.
  24498. *
  24499. * @param {number} divisions - The fineness of the result.
  24500. * @return {Array<Array<Vector2>>} The holes as a series of 2D points.
  24501. */
  24502. getPointsHoles( divisions ) {
  24503. const holesPts = [];
  24504. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  24505. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  24506. }
  24507. return holesPts;
  24508. }
  24509. // get points of shape and holes (keypoints based on segments parameter)
  24510. /**
  24511. * Returns an object that holds contour data for the shape and its holes as
  24512. * arrays of 2D points.
  24513. *
  24514. * @param {number} divisions - The fineness of the result.
  24515. * @return {{shape:Array<Vector2>,holes:Array<Array<Vector2>>}} An object with contour data.
  24516. */
  24517. extractPoints( divisions ) {
  24518. return {
  24519. shape: this.getPoints( divisions ),
  24520. holes: this.getPointsHoles( divisions )
  24521. };
  24522. }
  24523. copy( source ) {
  24524. super.copy( source );
  24525. this.holes = [];
  24526. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  24527. const hole = source.holes[ i ];
  24528. this.holes.push( hole.clone() );
  24529. }
  24530. return this;
  24531. }
  24532. toJSON() {
  24533. const data = super.toJSON();
  24534. data.uuid = this.uuid;
  24535. data.holes = [];
  24536. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  24537. const hole = this.holes[ i ];
  24538. data.holes.push( hole.toJSON() );
  24539. }
  24540. return data;
  24541. }
  24542. fromJSON( json ) {
  24543. super.fromJSON( json );
  24544. this.uuid = json.uuid;
  24545. this.holes = [];
  24546. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  24547. const hole = json.holes[ i ];
  24548. this.holes.push( new Path().fromJSON( hole ) );
  24549. }
  24550. return this;
  24551. }
  24552. }
  24553. /* eslint-disable */
  24554. // copy of mapbox/earcut version 3.0.2
  24555. // https://github.com/mapbox/earcut/tree/v3.0.2
  24556. function earcut(data, holeIndices, dim = 2) {
  24557. const hasHoles = holeIndices && holeIndices.length;
  24558. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  24559. let outerNode = linkedList(data, 0, outerLen, dim, true);
  24560. const triangles = [];
  24561. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  24562. let minX, minY, invSize;
  24563. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  24564. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  24565. if (data.length > 80 * dim) {
  24566. minX = data[0];
  24567. minY = data[1];
  24568. let maxX = minX;
  24569. let maxY = minY;
  24570. for (let i = dim; i < outerLen; i += dim) {
  24571. const x = data[i];
  24572. const y = data[i + 1];
  24573. if (x < minX) minX = x;
  24574. if (y < minY) minY = y;
  24575. if (x > maxX) maxX = x;
  24576. if (y > maxY) maxY = y;
  24577. }
  24578. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  24579. invSize = Math.max(maxX - minX, maxY - minY);
  24580. invSize = invSize !== 0 ? 32767 / invSize : 0;
  24581. }
  24582. earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
  24583. return triangles;
  24584. }
  24585. // create a circular doubly linked list from polygon points in the specified winding order
  24586. function linkedList(data, start, end, dim, clockwise) {
  24587. let last;
  24588. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  24589. for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  24590. } else {
  24591. for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  24592. }
  24593. if (last && equals(last, last.next)) {
  24594. removeNode(last);
  24595. last = last.next;
  24596. }
  24597. return last;
  24598. }
  24599. // eliminate colinear or duplicate points
  24600. function filterPoints(start, end) {
  24601. if (!start) return start;
  24602. if (!end) end = start;
  24603. let p = start,
  24604. again;
  24605. do {
  24606. again = false;
  24607. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  24608. removeNode(p);
  24609. p = end = p.prev;
  24610. if (p === p.next) break;
  24611. again = true;
  24612. } else {
  24613. p = p.next;
  24614. }
  24615. } while (again || p !== end);
  24616. return end;
  24617. }
  24618. // main ear slicing loop which triangulates a polygon (given as a linked list)
  24619. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  24620. if (!ear) return;
  24621. // interlink polygon nodes in z-order
  24622. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  24623. let stop = ear;
  24624. // iterate through ears, slicing them one by one
  24625. while (ear.prev !== ear.next) {
  24626. const prev = ear.prev;
  24627. const next = ear.next;
  24628. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  24629. triangles.push(prev.i, ear.i, next.i); // cut off the triangle
  24630. removeNode(ear);
  24631. // skipping the next vertex leads to less sliver triangles
  24632. ear = next.next;
  24633. stop = next.next;
  24634. continue;
  24635. }
  24636. ear = next;
  24637. // if we looped through the whole remaining polygon and can't find any more ears
  24638. if (ear === stop) {
  24639. // try filtering points and slicing again
  24640. if (!pass) {
  24641. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
  24642. // if this didn't work, try curing all small self-intersections locally
  24643. } else if (pass === 1) {
  24644. ear = cureLocalIntersections(filterPoints(ear), triangles);
  24645. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
  24646. // as a last resort, try splitting the remaining polygon into two
  24647. } else if (pass === 2) {
  24648. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  24649. }
  24650. break;
  24651. }
  24652. }
  24653. }
  24654. // check whether a polygon node forms a valid ear with adjacent nodes
  24655. function isEar(ear) {
  24656. const a = ear.prev,
  24657. b = ear,
  24658. c = ear.next;
  24659. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  24660. // now make sure we don't have other points inside the potential ear
  24661. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  24662. // triangle bbox
  24663. const x0 = Math.min(ax, bx, cx),
  24664. y0 = Math.min(ay, by, cy),
  24665. x1 = Math.max(ax, bx, cx),
  24666. y1 = Math.max(ay, by, cy);
  24667. let p = c.next;
  24668. while (p !== a) {
  24669. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  24670. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&
  24671. area(p.prev, p, p.next) >= 0) return false;
  24672. p = p.next;
  24673. }
  24674. return true;
  24675. }
  24676. function isEarHashed(ear, minX, minY, invSize) {
  24677. const a = ear.prev,
  24678. b = ear,
  24679. c = ear.next;
  24680. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  24681. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  24682. // triangle bbox
  24683. const x0 = Math.min(ax, bx, cx),
  24684. y0 = Math.min(ay, by, cy),
  24685. x1 = Math.max(ax, bx, cx),
  24686. y1 = Math.max(ay, by, cy);
  24687. // z-order range for the current triangle bbox;
  24688. const minZ = zOrder(x0, y0, minX, minY, invSize),
  24689. maxZ = zOrder(x1, y1, minX, minY, invSize);
  24690. let p = ear.prevZ,
  24691. n = ear.nextZ;
  24692. // look for points inside the triangle in both directions
  24693. while (p && p.z >= minZ && n && n.z <= maxZ) {
  24694. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  24695. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  24696. p = p.prevZ;
  24697. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  24698. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  24699. n = n.nextZ;
  24700. }
  24701. // look for remaining points in decreasing z-order
  24702. while (p && p.z >= minZ) {
  24703. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  24704. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  24705. p = p.prevZ;
  24706. }
  24707. // look for remaining points in increasing z-order
  24708. while (n && n.z <= maxZ) {
  24709. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  24710. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  24711. n = n.nextZ;
  24712. }
  24713. return true;
  24714. }
  24715. // go through all polygon nodes and cure small local self-intersections
  24716. function cureLocalIntersections(start, triangles) {
  24717. let p = start;
  24718. do {
  24719. const a = p.prev,
  24720. b = p.next.next;
  24721. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  24722. triangles.push(a.i, p.i, b.i);
  24723. // remove two nodes involved
  24724. removeNode(p);
  24725. removeNode(p.next);
  24726. p = start = b;
  24727. }
  24728. p = p.next;
  24729. } while (p !== start);
  24730. return filterPoints(p);
  24731. }
  24732. // try splitting polygon into two and triangulate them independently
  24733. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  24734. // look for a valid diagonal that divides the polygon into two
  24735. let a = start;
  24736. do {
  24737. let b = a.next.next;
  24738. while (b !== a.prev) {
  24739. if (a.i !== b.i && isValidDiagonal(a, b)) {
  24740. // split the polygon in two by the diagonal
  24741. let c = splitPolygon(a, b);
  24742. // filter colinear points around the cuts
  24743. a = filterPoints(a, a.next);
  24744. c = filterPoints(c, c.next);
  24745. // run earcut on each half
  24746. earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
  24747. earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
  24748. return;
  24749. }
  24750. b = b.next;
  24751. }
  24752. a = a.next;
  24753. } while (a !== start);
  24754. }
  24755. // link every hole into the outer loop, producing a single-ring polygon without holes
  24756. function eliminateHoles(data, holeIndices, outerNode, dim) {
  24757. const queue = [];
  24758. for (let i = 0, len = holeIndices.length; i < len; i++) {
  24759. const start = holeIndices[i] * dim;
  24760. const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  24761. const list = linkedList(data, start, end, dim, false);
  24762. if (list === list.next) list.steiner = true;
  24763. queue.push(getLeftmost(list));
  24764. }
  24765. queue.sort(compareXYSlope);
  24766. // process holes from left to right
  24767. for (let i = 0; i < queue.length; i++) {
  24768. outerNode = eliminateHole(queue[i], outerNode);
  24769. }
  24770. return outerNode;
  24771. }
  24772. function compareXYSlope(a, b) {
  24773. let result = a.x - b.x;
  24774. // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find
  24775. // the bridge to the outer shell is always the point that they meet at.
  24776. if (result === 0) {
  24777. result = a.y - b.y;
  24778. if (result === 0) {
  24779. const aSlope = (a.next.y - a.y) / (a.next.x - a.x);
  24780. const bSlope = (b.next.y - b.y) / (b.next.x - b.x);
  24781. result = aSlope - bSlope;
  24782. }
  24783. }
  24784. return result;
  24785. }
  24786. // find a bridge between vertices that connects hole with an outer ring and link it
  24787. function eliminateHole(hole, outerNode) {
  24788. const bridge = findHoleBridge(hole, outerNode);
  24789. if (!bridge) {
  24790. return outerNode;
  24791. }
  24792. const bridgeReverse = splitPolygon(bridge, hole);
  24793. // filter collinear points around the cuts
  24794. filterPoints(bridgeReverse, bridgeReverse.next);
  24795. return filterPoints(bridge, bridge.next);
  24796. }
  24797. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  24798. function findHoleBridge(hole, outerNode) {
  24799. let p = outerNode;
  24800. const hx = hole.x;
  24801. const hy = hole.y;
  24802. let qx = -Infinity;
  24803. let m;
  24804. // find a segment intersected by a ray from the hole's leftmost point to the left;
  24805. // segment's endpoint with lesser x will be potential connection point
  24806. // unless they intersect at a vertex, then choose the vertex
  24807. if (equals(hole, p)) return p;
  24808. do {
  24809. if (equals(hole, p.next)) return p.next;
  24810. else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  24811. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  24812. if (x <= hx && x > qx) {
  24813. qx = x;
  24814. m = p.x < p.next.x ? p : p.next;
  24815. if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint
  24816. }
  24817. }
  24818. p = p.next;
  24819. } while (p !== outerNode);
  24820. if (!m) return null;
  24821. // look for points inside the triangle of hole point, segment intersection and endpoint;
  24822. // if there are no points found, we have a valid connection;
  24823. // otherwise choose the point of the minimum angle with the ray as connection point
  24824. const stop = m;
  24825. const mx = m.x;
  24826. const my = m.y;
  24827. let tanMin = Infinity;
  24828. p = m;
  24829. do {
  24830. if (hx >= p.x && p.x >= mx && hx !== p.x &&
  24831. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  24832. const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  24833. if (locallyInside(p, hole) &&
  24834. (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {
  24835. m = p;
  24836. tanMin = tan;
  24837. }
  24838. }
  24839. p = p.next;
  24840. } while (p !== stop);
  24841. return m;
  24842. }
  24843. // whether sector in vertex m contains sector in vertex p in the same coordinates
  24844. function sectorContainsSector(m, p) {
  24845. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  24846. }
  24847. // interlink polygon nodes in z-order
  24848. function indexCurve(start, minX, minY, invSize) {
  24849. let p = start;
  24850. do {
  24851. if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  24852. p.prevZ = p.prev;
  24853. p.nextZ = p.next;
  24854. p = p.next;
  24855. } while (p !== start);
  24856. p.prevZ.nextZ = null;
  24857. p.prevZ = null;
  24858. sortLinked(p);
  24859. }
  24860. // Simon Tatham's linked list merge sort algorithm
  24861. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  24862. function sortLinked(list) {
  24863. let numMerges;
  24864. let inSize = 1;
  24865. do {
  24866. let p = list;
  24867. let e;
  24868. list = null;
  24869. let tail = null;
  24870. numMerges = 0;
  24871. while (p) {
  24872. numMerges++;
  24873. let q = p;
  24874. let pSize = 0;
  24875. for (let i = 0; i < inSize; i++) {
  24876. pSize++;
  24877. q = q.nextZ;
  24878. if (!q) break;
  24879. }
  24880. let qSize = inSize;
  24881. while (pSize > 0 || (qSize > 0 && q)) {
  24882. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  24883. e = p;
  24884. p = p.nextZ;
  24885. pSize--;
  24886. } else {
  24887. e = q;
  24888. q = q.nextZ;
  24889. qSize--;
  24890. }
  24891. if (tail) tail.nextZ = e;
  24892. else list = e;
  24893. e.prevZ = tail;
  24894. tail = e;
  24895. }
  24896. p = q;
  24897. }
  24898. tail.nextZ = null;
  24899. inSize *= 2;
  24900. } while (numMerges > 1);
  24901. return list;
  24902. }
  24903. // z-order of a point given coords and inverse of the longer side of data bbox
  24904. function zOrder(x, y, minX, minY, invSize) {
  24905. // coords are transformed into non-negative 15-bit integer range
  24906. x = (x - minX) * invSize | 0;
  24907. y = (y - minY) * invSize | 0;
  24908. x = (x | (x << 8)) & 0x00FF00FF;
  24909. x = (x | (x << 4)) & 0x0F0F0F0F;
  24910. x = (x | (x << 2)) & 0x33333333;
  24911. x = (x | (x << 1)) & 0x55555555;
  24912. y = (y | (y << 8)) & 0x00FF00FF;
  24913. y = (y | (y << 4)) & 0x0F0F0F0F;
  24914. y = (y | (y << 2)) & 0x33333333;
  24915. y = (y | (y << 1)) & 0x55555555;
  24916. return x | (y << 1);
  24917. }
  24918. // find the leftmost node of a polygon ring
  24919. function getLeftmost(start) {
  24920. let p = start,
  24921. leftmost = start;
  24922. do {
  24923. if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;
  24924. p = p.next;
  24925. } while (p !== start);
  24926. return leftmost;
  24927. }
  24928. // check if a point lies within a convex triangle
  24929. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  24930. return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&
  24931. (ax - px) * (by - py) >= (bx - px) * (ay - py) &&
  24932. (bx - px) * (cy - py) >= (cx - px) * (by - py);
  24933. }
  24934. // check if a point lies within a convex triangle but false if its equal to the first point of the triangle
  24935. function pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {
  24936. return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);
  24937. }
  24938. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  24939. function isValidDiagonal(a, b) {
  24940. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // doesn't intersect other edges
  24941. (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible
  24942. (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  24943. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  24944. }
  24945. // signed area of a triangle
  24946. function area(p, q, r) {
  24947. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  24948. }
  24949. // check if two points are equal
  24950. function equals(p1, p2) {
  24951. return p1.x === p2.x && p1.y === p2.y;
  24952. }
  24953. // check if two segments intersect
  24954. function intersects(p1, q1, p2, q2) {
  24955. const o1 = sign(area(p1, q1, p2));
  24956. const o2 = sign(area(p1, q1, q2));
  24957. const o3 = sign(area(p2, q2, p1));
  24958. const o4 = sign(area(p2, q2, q1));
  24959. if (o1 !== o2 && o3 !== o4) return true; // general case
  24960. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  24961. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  24962. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  24963. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  24964. return false;
  24965. }
  24966. // for collinear points p, q, r, check if point q lies on segment pr
  24967. function onSegment(p, q, r) {
  24968. 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);
  24969. }
  24970. function sign(num) {
  24971. return num > 0 ? 1 : num < 0 ? -1 : 0;
  24972. }
  24973. // check if a polygon diagonal intersects any polygon segments
  24974. function intersectsPolygon(a, b) {
  24975. let p = a;
  24976. do {
  24977. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  24978. intersects(p, p.next, a, b)) return true;
  24979. p = p.next;
  24980. } while (p !== a);
  24981. return false;
  24982. }
  24983. // check if a polygon diagonal is locally inside the polygon
  24984. function locallyInside(a, b) {
  24985. return area(a.prev, a, a.next) < 0 ?
  24986. area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
  24987. area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  24988. }
  24989. // check if the middle point of a polygon diagonal is inside the polygon
  24990. function middleInside(a, b) {
  24991. let p = a;
  24992. let inside = false;
  24993. const px = (a.x + b.x) / 2;
  24994. const py = (a.y + b.y) / 2;
  24995. do {
  24996. if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
  24997. (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  24998. inside = !inside;
  24999. p = p.next;
  25000. } while (p !== a);
  25001. return inside;
  25002. }
  25003. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  25004. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  25005. function splitPolygon(a, b) {
  25006. const a2 = createNode(a.i, a.x, a.y),
  25007. b2 = createNode(b.i, b.x, b.y),
  25008. an = a.next,
  25009. bp = b.prev;
  25010. a.next = b;
  25011. b.prev = a;
  25012. a2.next = an;
  25013. an.prev = a2;
  25014. b2.next = a2;
  25015. a2.prev = b2;
  25016. bp.next = b2;
  25017. b2.prev = bp;
  25018. return b2;
  25019. }
  25020. // create a node and optionally link it with previous one (in a circular doubly linked list)
  25021. function insertNode(i, x, y, last) {
  25022. const p = createNode(i, x, y);
  25023. if (!last) {
  25024. p.prev = p;
  25025. p.next = p;
  25026. } else {
  25027. p.next = last.next;
  25028. p.prev = last;
  25029. last.next.prev = p;
  25030. last.next = p;
  25031. }
  25032. return p;
  25033. }
  25034. function removeNode(p) {
  25035. p.next.prev = p.prev;
  25036. p.prev.next = p.next;
  25037. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  25038. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  25039. }
  25040. function createNode(i, x, y) {
  25041. return {
  25042. i, // vertex index in coordinates array
  25043. x, y, // vertex coordinates
  25044. prev: null, // previous and next vertex nodes in a polygon ring
  25045. next: null,
  25046. z: 0, // z-order curve value
  25047. prevZ: null, // previous and next nodes in z-order
  25048. nextZ: null,
  25049. steiner: false // indicates whether this is a steiner point
  25050. };
  25051. }
  25052. function signedArea(data, start, end, dim) {
  25053. let sum = 0;
  25054. for (let i = start, j = end - dim; i < end; i += dim) {
  25055. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  25056. j = i;
  25057. }
  25058. return sum;
  25059. }
  25060. /**
  25061. * An implementation of the earcut polygon triangulation algorithm.
  25062. * The code is a port of [mapbox/earcut](https://github.com/mapbox/earcut).
  25063. *
  25064. * @see https://github.com/mapbox/earcut
  25065. */
  25066. class Earcut {
  25067. /**
  25068. * Triangulates the given shape definition by returning an array of triangles.
  25069. *
  25070. * @param {Array<number>} data - An array with 2D points.
  25071. * @param {Array<number>} holeIndices - An array with indices defining holes.
  25072. * @param {number} [dim=2] - The number of coordinates per vertex in the input array.
  25073. * @return {Array<number>} An array representing the triangulated faces. Each face is defined by three consecutive numbers
  25074. * representing vertex indices.
  25075. */
  25076. static triangulate( data, holeIndices, dim = 2 ) {
  25077. return earcut( data, holeIndices, dim );
  25078. }
  25079. }
  25080. /**
  25081. * A class containing utility functions for shapes.
  25082. *
  25083. * @hideconstructor
  25084. */
  25085. class ShapeUtils {
  25086. /**
  25087. * Calculate area of a ( 2D ) contour polygon.
  25088. *
  25089. * @param {Array<Vector2>} contour - An array of 2D points.
  25090. * @return {number} The area.
  25091. */
  25092. static area( contour ) {
  25093. const n = contour.length;
  25094. let a = 0.0;
  25095. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  25096. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  25097. }
  25098. return a * 0.5;
  25099. }
  25100. /**
  25101. * Returns `true` if the given contour uses a clockwise winding order.
  25102. *
  25103. * @param {Array<Vector2>} pts - An array of 2D points defining a polygon.
  25104. * @return {boolean} Whether the given contour uses a clockwise winding order or not.
  25105. */
  25106. static isClockWise( pts ) {
  25107. return ShapeUtils.area( pts ) < 0;
  25108. }
  25109. /**
  25110. * Triangulates the given shape definition.
  25111. *
  25112. * @param {Array<Vector2>} contour - An array of 2D points defining the contour.
  25113. * @param {Array<Array<Vector2>>} holes - An array that holds arrays of 2D points defining the holes.
  25114. * @return {Array<Array<number>>} An array that holds for each face definition an array with three indices.
  25115. */
  25116. static triangulateShape( contour, holes ) {
  25117. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  25118. const holeIndices = []; // array of hole indices
  25119. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  25120. removeDupEndPts( contour );
  25121. addContour( vertices, contour );
  25122. //
  25123. let holeIndex = contour.length;
  25124. holes.forEach( removeDupEndPts );
  25125. for ( let i = 0; i < holes.length; i ++ ) {
  25126. holeIndices.push( holeIndex );
  25127. holeIndex += holes[ i ].length;
  25128. addContour( vertices, holes[ i ] );
  25129. }
  25130. //
  25131. const triangles = Earcut.triangulate( vertices, holeIndices );
  25132. //
  25133. for ( let i = 0; i < triangles.length; i += 3 ) {
  25134. faces.push( triangles.slice( i, i + 3 ) );
  25135. }
  25136. return faces;
  25137. }
  25138. }
  25139. function removeDupEndPts( points ) {
  25140. const l = points.length;
  25141. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  25142. points.pop();
  25143. }
  25144. }
  25145. function addContour( vertices, contour ) {
  25146. for ( let i = 0; i < contour.length; i ++ ) {
  25147. vertices.push( contour[ i ].x );
  25148. vertices.push( contour[ i ].y );
  25149. }
  25150. }
  25151. /**
  25152. * Creates extruded geometry from a path shape.
  25153. *
  25154. * ```js
  25155. * const length = 12, width = 8;
  25156. *
  25157. * const shape = new THREE.Shape();
  25158. * shape.moveTo( 0,0 );
  25159. * shape.lineTo( 0, width );
  25160. * shape.lineTo( length, width );
  25161. * shape.lineTo( length, 0 );
  25162. * shape.lineTo( 0, 0 );
  25163. *
  25164. * const geometry = new THREE.ExtrudeGeometry( shape );
  25165. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  25166. * const mesh = new THREE.Mesh( geometry, material ) ;
  25167. * scene.add( mesh );
  25168. * ```
  25169. *
  25170. * @augments BufferGeometry
  25171. * @demo scenes/geometry-browser.html#ExtrudeGeometry
  25172. */
  25173. class ExtrudeGeometry extends BufferGeometry {
  25174. /**
  25175. * Constructs a new extrude geometry.
  25176. *
  25177. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  25178. * @param {ExtrudeGeometry~Options} [options] - The extrude settings.
  25179. */
  25180. 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 = {} ) {
  25181. super();
  25182. this.type = 'ExtrudeGeometry';
  25183. /**
  25184. * Holds the constructor parameters that have been
  25185. * used to generate the geometry. Any modification
  25186. * after instantiation does not change the geometry.
  25187. *
  25188. * @type {Object}
  25189. */
  25190. this.parameters = {
  25191. shapes: shapes,
  25192. options: options
  25193. };
  25194. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  25195. const scope = this;
  25196. const verticesArray = [];
  25197. const uvArray = [];
  25198. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  25199. const shape = shapes[ i ];
  25200. addShape( shape );
  25201. }
  25202. // build geometry
  25203. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  25204. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  25205. this.computeVertexNormals();
  25206. // functions
  25207. function addShape( shape ) {
  25208. const placeholder = [];
  25209. // options
  25210. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  25211. const steps = options.steps !== undefined ? options.steps : 1;
  25212. const depth = options.depth !== undefined ? options.depth : 1;
  25213. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  25214. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  25215. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  25216. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  25217. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  25218. const extrudePath = options.extrudePath;
  25219. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  25220. //
  25221. let extrudePts, extrudeByPath = false;
  25222. let splineTube, binormal, normal, position2;
  25223. if ( extrudePath ) {
  25224. extrudePts = extrudePath.getSpacedPoints( steps );
  25225. extrudeByPath = true;
  25226. bevelEnabled = false; // bevels not supported for path extrusion
  25227. // SETUP TNB variables
  25228. const isClosed = extrudePath.isCatmullRomCurve3 ? extrudePath.closed : false;
  25229. splineTube = extrudePath.computeFrenetFrames( steps, isClosed );
  25230. // log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  25231. binormal = new Vector3();
  25232. normal = new Vector3();
  25233. position2 = new Vector3();
  25234. }
  25235. // Safeguards if bevels are not enabled
  25236. if ( ! bevelEnabled ) {
  25237. bevelSegments = 0;
  25238. bevelThickness = 0;
  25239. bevelSize = 0;
  25240. bevelOffset = 0;
  25241. }
  25242. // Variables initialization
  25243. const shapePoints = shape.extractPoints( curveSegments );
  25244. let vertices = shapePoints.shape;
  25245. const holes = shapePoints.holes;
  25246. const reverse = ! ShapeUtils.isClockWise( vertices );
  25247. if ( reverse ) {
  25248. vertices = vertices.reverse();
  25249. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  25250. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25251. const ahole = holes[ h ];
  25252. if ( ShapeUtils.isClockWise( ahole ) ) {
  25253. holes[ h ] = ahole.reverse();
  25254. }
  25255. }
  25256. }
  25257. /**Merges index-adjacent points that are within a threshold distance of each other. Array is modified in-place. Threshold distance is empirical, and scaled based on the magnitude of point coordinates.
  25258. * @param {Array<Vector2>} points
  25259. */
  25260. function mergeOverlappingPoints( points ) {
  25261. const THRESHOLD = 1e-10;
  25262. const THRESHOLD_SQ = THRESHOLD * THRESHOLD;
  25263. let prevPos = points[ 0 ];
  25264. for ( let i = 1; i <= points.length; i ++ ) {
  25265. const currentIndex = i % points.length;
  25266. const currentPos = points[ currentIndex ];
  25267. const dx = currentPos.x - prevPos.x;
  25268. const dy = currentPos.y - prevPos.y;
  25269. const distSq = dx * dx + dy * dy;
  25270. const scalingFactorSqrt = Math.max(
  25271. Math.abs( currentPos.x ),
  25272. Math.abs( currentPos.y ),
  25273. Math.abs( prevPos.x ),
  25274. Math.abs( prevPos.y )
  25275. );
  25276. const thresholdSqScaled = THRESHOLD_SQ * scalingFactorSqrt * scalingFactorSqrt;
  25277. if ( distSq <= thresholdSqScaled ) {
  25278. points.splice( currentIndex, 1 );
  25279. i --;
  25280. continue;
  25281. }
  25282. prevPos = currentPos;
  25283. }
  25284. }
  25285. mergeOverlappingPoints( vertices );
  25286. holes.forEach( mergeOverlappingPoints );
  25287. const numHoles = holes.length;
  25288. /* Vertices */
  25289. const contour = vertices; // vertices has all points but contour has only points of circumference
  25290. for ( let h = 0; h < numHoles; h ++ ) {
  25291. const ahole = holes[ h ];
  25292. vertices = vertices.concat( ahole );
  25293. }
  25294. function scalePt2( pt, vec, size ) {
  25295. if ( ! vec ) error( 'ExtrudeGeometry: vec does not exist' );
  25296. return pt.clone().addScaledVector( vec, size );
  25297. }
  25298. const vlen = vertices.length;
  25299. // Find directions for point movement
  25300. function getBevelVec( inPt, inPrev, inNext ) {
  25301. // computes for inPt the corresponding point inPt' on a new contour
  25302. // shifted by 1 unit (length of normalized vector) to the left
  25303. // if we walk along contour clockwise, this new contour is outside the old one
  25304. //
  25305. // inPt' is the intersection of the two lines parallel to the two
  25306. // adjacent edges of inPt at a distance of 1 unit on the left side.
  25307. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  25308. // good reading for geometry algorithms (here: line-line intersection)
  25309. // http://geomalgorithms.com/a05-_intersect-1.html
  25310. const v_prev_x = inPt.x - inPrev.x,
  25311. v_prev_y = inPt.y - inPrev.y;
  25312. const v_next_x = inNext.x - inPt.x,
  25313. v_next_y = inNext.y - inPt.y;
  25314. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  25315. // check for collinear edges
  25316. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25317. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  25318. // not collinear
  25319. // length of vectors for normalizing
  25320. const v_prev_len = Math.sqrt( v_prev_lensq );
  25321. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  25322. // shift adjacent points by unit vectors to the left
  25323. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  25324. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  25325. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  25326. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  25327. // scaling factor for v_prev to intersection point
  25328. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  25329. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  25330. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25331. // vector from inPt to intersection point
  25332. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  25333. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  25334. // Don't normalize!, otherwise sharp corners become ugly
  25335. // but prevent crazy spikes
  25336. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  25337. if ( v_trans_lensq <= 2 ) {
  25338. return new Vector2( v_trans_x, v_trans_y );
  25339. } else {
  25340. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  25341. }
  25342. } else {
  25343. // handle special case of collinear edges
  25344. let direction_eq = false; // assumes: opposite
  25345. if ( v_prev_x > Number.EPSILON ) {
  25346. if ( v_next_x > Number.EPSILON ) {
  25347. direction_eq = true;
  25348. }
  25349. } else {
  25350. if ( v_prev_x < - Number.EPSILON ) {
  25351. if ( v_next_x < - Number.EPSILON ) {
  25352. direction_eq = true;
  25353. }
  25354. } else {
  25355. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  25356. direction_eq = true;
  25357. }
  25358. }
  25359. }
  25360. if ( direction_eq ) {
  25361. // log("Warning: lines are a straight sequence");
  25362. v_trans_x = - v_prev_y;
  25363. v_trans_y = v_prev_x;
  25364. shrink_by = Math.sqrt( v_prev_lensq );
  25365. } else {
  25366. // log("Warning: lines are a straight spike");
  25367. v_trans_x = v_prev_x;
  25368. v_trans_y = v_prev_y;
  25369. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  25370. }
  25371. }
  25372. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  25373. }
  25374. const contourMovements = [];
  25375. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25376. if ( j === il ) j = 0;
  25377. if ( k === il ) k = 0;
  25378. // (j)---(i)---(k)
  25379. // log('i,j,k', i, j , k)
  25380. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  25381. }
  25382. const holesMovements = [];
  25383. let oneHoleMovements, verticesMovements = contourMovements.concat();
  25384. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  25385. const ahole = holes[ h ];
  25386. oneHoleMovements = [];
  25387. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25388. if ( j === il ) j = 0;
  25389. if ( k === il ) k = 0;
  25390. // (j)---(i)---(k)
  25391. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  25392. }
  25393. holesMovements.push( oneHoleMovements );
  25394. verticesMovements = verticesMovements.concat( oneHoleMovements );
  25395. }
  25396. let faces;
  25397. if ( bevelSegments === 0 ) {
  25398. faces = ShapeUtils.triangulateShape( contour, holes );
  25399. } else {
  25400. const contractedContourVertices = [];
  25401. const expandedHoleVertices = [];
  25402. // Loop bevelSegments, 1 for the front, 1 for the back
  25403. for ( let b = 0; b < bevelSegments; b ++ ) {
  25404. //for ( b = bevelSegments; b > 0; b -- ) {
  25405. const t = b / bevelSegments;
  25406. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25407. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  25408. // contract shape
  25409. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  25410. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  25411. v( vert.x, vert.y, - z );
  25412. if ( t === 0 ) contractedContourVertices.push( vert );
  25413. }
  25414. // expand holes
  25415. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  25416. const ahole = holes[ h ];
  25417. oneHoleMovements = holesMovements[ h ];
  25418. const oneHoleVertices = [];
  25419. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  25420. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  25421. v( vert.x, vert.y, - z );
  25422. if ( t === 0 ) oneHoleVertices.push( vert );
  25423. }
  25424. if ( t === 0 ) expandedHoleVertices.push( oneHoleVertices );
  25425. }
  25426. }
  25427. faces = ShapeUtils.triangulateShape( contractedContourVertices, expandedHoleVertices );
  25428. }
  25429. const flen = faces.length;
  25430. const bs = bevelSize + bevelOffset;
  25431. // Back facing vertices
  25432. for ( let i = 0; i < vlen; i ++ ) {
  25433. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  25434. if ( ! extrudeByPath ) {
  25435. v( vert.x, vert.y, 0 );
  25436. } else {
  25437. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  25438. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  25439. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  25440. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  25441. v( position2.x, position2.y, position2.z );
  25442. }
  25443. }
  25444. // Add stepped vertices...
  25445. // Including front facing vertices
  25446. for ( let s = 1; s <= steps; s ++ ) {
  25447. for ( let i = 0; i < vlen; i ++ ) {
  25448. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  25449. if ( ! extrudeByPath ) {
  25450. v( vert.x, vert.y, depth / steps * s );
  25451. } else {
  25452. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  25453. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  25454. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  25455. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  25456. v( position2.x, position2.y, position2.z );
  25457. }
  25458. }
  25459. }
  25460. // Add bevel segments planes
  25461. //for ( b = 1; b <= bevelSegments; b ++ ) {
  25462. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  25463. const t = b / bevelSegments;
  25464. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25465. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  25466. // contract shape
  25467. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  25468. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  25469. v( vert.x, vert.y, depth + z );
  25470. }
  25471. // expand holes
  25472. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25473. const ahole = holes[ h ];
  25474. oneHoleMovements = holesMovements[ h ];
  25475. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  25476. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  25477. if ( ! extrudeByPath ) {
  25478. v( vert.x, vert.y, depth + z );
  25479. } else {
  25480. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  25481. }
  25482. }
  25483. }
  25484. }
  25485. /* Faces */
  25486. // Top and bottom faces
  25487. buildLidFaces();
  25488. // Sides faces
  25489. buildSideFaces();
  25490. ///// Internal functions
  25491. function buildLidFaces() {
  25492. const start = verticesArray.length / 3;
  25493. if ( bevelEnabled ) {
  25494. let layer = 0; // steps + 1
  25495. let offset = vlen * layer;
  25496. // Bottom faces
  25497. for ( let i = 0; i < flen; i ++ ) {
  25498. const face = faces[ i ];
  25499. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  25500. }
  25501. layer = steps + bevelSegments * 2;
  25502. offset = vlen * layer;
  25503. // Top faces
  25504. for ( let i = 0; i < flen; i ++ ) {
  25505. const face = faces[ i ];
  25506. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  25507. }
  25508. } else {
  25509. // Bottom faces
  25510. for ( let i = 0; i < flen; i ++ ) {
  25511. const face = faces[ i ];
  25512. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  25513. }
  25514. // Top faces
  25515. for ( let i = 0; i < flen; i ++ ) {
  25516. const face = faces[ i ];
  25517. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  25518. }
  25519. }
  25520. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  25521. }
  25522. // Create faces for the z-sides of the shape
  25523. function buildSideFaces() {
  25524. const start = verticesArray.length / 3;
  25525. let layeroffset = 0;
  25526. sidewalls( contour, layeroffset );
  25527. layeroffset += contour.length;
  25528. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25529. const ahole = holes[ h ];
  25530. sidewalls( ahole, layeroffset );
  25531. //, true
  25532. layeroffset += ahole.length;
  25533. }
  25534. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  25535. }
  25536. function sidewalls( contour, layeroffset ) {
  25537. let i = contour.length;
  25538. while ( -- i >= 0 ) {
  25539. const j = i;
  25540. let k = i - 1;
  25541. if ( k < 0 ) k = contour.length - 1;
  25542. //log('b', i,j, i-1, k,vertices.length);
  25543. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  25544. const slen1 = vlen * s;
  25545. const slen2 = vlen * ( s + 1 );
  25546. const a = layeroffset + j + slen1,
  25547. b = layeroffset + k + slen1,
  25548. c = layeroffset + k + slen2,
  25549. d = layeroffset + j + slen2;
  25550. f4( a, b, c, d );
  25551. }
  25552. }
  25553. }
  25554. function v( x, y, z ) {
  25555. placeholder.push( x );
  25556. placeholder.push( y );
  25557. placeholder.push( z );
  25558. }
  25559. function f3( a, b, c ) {
  25560. addVertex( a );
  25561. addVertex( b );
  25562. addVertex( c );
  25563. const nextIndex = verticesArray.length / 3;
  25564. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  25565. addUV( uvs[ 0 ] );
  25566. addUV( uvs[ 1 ] );
  25567. addUV( uvs[ 2 ] );
  25568. }
  25569. function f4( a, b, c, d ) {
  25570. addVertex( a );
  25571. addVertex( b );
  25572. addVertex( d );
  25573. addVertex( b );
  25574. addVertex( c );
  25575. addVertex( d );
  25576. const nextIndex = verticesArray.length / 3;
  25577. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  25578. addUV( uvs[ 0 ] );
  25579. addUV( uvs[ 1 ] );
  25580. addUV( uvs[ 3 ] );
  25581. addUV( uvs[ 1 ] );
  25582. addUV( uvs[ 2 ] );
  25583. addUV( uvs[ 3 ] );
  25584. }
  25585. function addVertex( index ) {
  25586. verticesArray.push( placeholder[ index * 3 + 0 ] );
  25587. verticesArray.push( placeholder[ index * 3 + 1 ] );
  25588. verticesArray.push( placeholder[ index * 3 + 2 ] );
  25589. }
  25590. function addUV( vector2 ) {
  25591. uvArray.push( vector2.x );
  25592. uvArray.push( vector2.y );
  25593. }
  25594. }
  25595. }
  25596. copy( source ) {
  25597. super.copy( source );
  25598. this.parameters = Object.assign( {}, source.parameters );
  25599. return this;
  25600. }
  25601. toJSON() {
  25602. const data = super.toJSON();
  25603. const shapes = this.parameters.shapes;
  25604. const options = this.parameters.options;
  25605. return toJSON$1( shapes, options, data );
  25606. }
  25607. /**
  25608. * Factory method for creating an instance of this class from the given
  25609. * JSON object.
  25610. *
  25611. * @param {Object} data - A JSON object representing the serialized geometry.
  25612. * @param {Array<Shape>} shapes - An array of shapes.
  25613. * @return {ExtrudeGeometry} A new instance.
  25614. */
  25615. static fromJSON( data, shapes ) {
  25616. const geometryShapes = [];
  25617. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  25618. const shape = shapes[ data.shapes[ j ] ];
  25619. geometryShapes.push( shape );
  25620. }
  25621. const extrudePath = data.options.extrudePath;
  25622. if ( extrudePath !== undefined ) {
  25623. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  25624. }
  25625. return new ExtrudeGeometry( geometryShapes, data.options );
  25626. }
  25627. }
  25628. const WorldUVGenerator = {
  25629. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  25630. const a_x = vertices[ indexA * 3 ];
  25631. const a_y = vertices[ indexA * 3 + 1 ];
  25632. const b_x = vertices[ indexB * 3 ];
  25633. const b_y = vertices[ indexB * 3 + 1 ];
  25634. const c_x = vertices[ indexC * 3 ];
  25635. const c_y = vertices[ indexC * 3 + 1 ];
  25636. return [
  25637. new Vector2( a_x, a_y ),
  25638. new Vector2( b_x, b_y ),
  25639. new Vector2( c_x, c_y )
  25640. ];
  25641. },
  25642. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  25643. const a_x = vertices[ indexA * 3 ];
  25644. const a_y = vertices[ indexA * 3 + 1 ];
  25645. const a_z = vertices[ indexA * 3 + 2 ];
  25646. const b_x = vertices[ indexB * 3 ];
  25647. const b_y = vertices[ indexB * 3 + 1 ];
  25648. const b_z = vertices[ indexB * 3 + 2 ];
  25649. const c_x = vertices[ indexC * 3 ];
  25650. const c_y = vertices[ indexC * 3 + 1 ];
  25651. const c_z = vertices[ indexC * 3 + 2 ];
  25652. const d_x = vertices[ indexD * 3 ];
  25653. const d_y = vertices[ indexD * 3 + 1 ];
  25654. const d_z = vertices[ indexD * 3 + 2 ];
  25655. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  25656. return [
  25657. new Vector2( a_x, 1 - a_z ),
  25658. new Vector2( b_x, 1 - b_z ),
  25659. new Vector2( c_x, 1 - c_z ),
  25660. new Vector2( d_x, 1 - d_z )
  25661. ];
  25662. } else {
  25663. return [
  25664. new Vector2( a_y, 1 - a_z ),
  25665. new Vector2( b_y, 1 - b_z ),
  25666. new Vector2( c_y, 1 - c_z ),
  25667. new Vector2( d_y, 1 - d_z )
  25668. ];
  25669. }
  25670. }
  25671. };
  25672. function toJSON$1( shapes, options, data ) {
  25673. data.shapes = [];
  25674. if ( Array.isArray( shapes ) ) {
  25675. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  25676. const shape = shapes[ i ];
  25677. data.shapes.push( shape.uuid );
  25678. }
  25679. } else {
  25680. data.shapes.push( shapes.uuid );
  25681. }
  25682. data.options = Object.assign( {}, options );
  25683. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  25684. return data;
  25685. }
  25686. /**
  25687. * A geometry class for representing an icosahedron.
  25688. *
  25689. * ```js
  25690. * const geometry = new THREE.IcosahedronGeometry();
  25691. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  25692. * const icosahedron = new THREE.Mesh( geometry, material );
  25693. * scene.add( icosahedron );
  25694. * ```
  25695. *
  25696. * @augments PolyhedronGeometry
  25697. * @demo scenes/geometry-browser.html#IcosahedronGeometry
  25698. */
  25699. class IcosahedronGeometry extends PolyhedronGeometry {
  25700. /**
  25701. * Constructs a new icosahedron geometry.
  25702. *
  25703. * @param {number} [radius=1] - Radius of the icosahedron.
  25704. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a icosahedron.
  25705. */
  25706. constructor( radius = 1, detail = 0 ) {
  25707. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  25708. const vertices = [
  25709. -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, 0,
  25710. 0, -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t,
  25711. t, 0, -1, t, 0, 1, - t, 0, -1, - t, 0, 1
  25712. ];
  25713. const indices = [
  25714. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  25715. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  25716. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  25717. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  25718. ];
  25719. super( vertices, indices, radius, detail );
  25720. this.type = 'IcosahedronGeometry';
  25721. /**
  25722. * Holds the constructor parameters that have been
  25723. * used to generate the geometry. Any modification
  25724. * after instantiation does not change the geometry.
  25725. *
  25726. * @type {Object}
  25727. */
  25728. this.parameters = {
  25729. radius: radius,
  25730. detail: detail
  25731. };
  25732. }
  25733. /**
  25734. * Factory method for creating an instance of this class from the given
  25735. * JSON object.
  25736. *
  25737. * @param {Object} data - A JSON object representing the serialized geometry.
  25738. * @return {IcosahedronGeometry} A new instance.
  25739. */
  25740. static fromJSON( data ) {
  25741. return new IcosahedronGeometry( data.radius, data.detail );
  25742. }
  25743. }
  25744. /**
  25745. * Creates meshes with axial symmetry like vases. The lathe rotates around the Y axis.
  25746. *
  25747. * ```js
  25748. * const points = [];
  25749. * for ( let i = 0; i < 10; i ++ ) {
  25750. * points.push( new THREE.Vector2( Math.sin( i * 0.2 ) * 10 + 5, ( i - 5 ) * 2 ) );
  25751. * }
  25752. * const geometry = new THREE.LatheGeometry( points );
  25753. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  25754. * const lathe = new THREE.Mesh( geometry, material );
  25755. * scene.add( lathe );
  25756. * ```
  25757. *
  25758. * @augments BufferGeometry
  25759. * @demo scenes/geometry-browser.html#LatheGeometry
  25760. */
  25761. class LatheGeometry extends BufferGeometry {
  25762. /**
  25763. * Constructs a new lathe geometry.
  25764. *
  25765. * @param {Array<Vector2|Vector3>} [points] - An array of points in 2D space. The x-coordinate of each point
  25766. * must be greater than zero.
  25767. * @param {number} [segments=12] - The number of circumference segments to generate.
  25768. * @param {number} [phiStart=0] - The starting angle in radians.
  25769. * @param {number} [phiLength=Math.PI*2] - The radian (0 to 2PI) range of the lathed section 2PI is a
  25770. * closed lathe, less than 2PI is a portion.
  25771. */
  25772. 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 ) {
  25773. super();
  25774. this.type = 'LatheGeometry';
  25775. /**
  25776. * Holds the constructor parameters that have been
  25777. * used to generate the geometry. Any modification
  25778. * after instantiation does not change the geometry.
  25779. *
  25780. * @type {Object}
  25781. */
  25782. this.parameters = {
  25783. points: points,
  25784. segments: segments,
  25785. phiStart: phiStart,
  25786. phiLength: phiLength
  25787. };
  25788. segments = Math.floor( segments );
  25789. // clamp phiLength so it's in range of [ 0, 2PI ]
  25790. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  25791. // buffers
  25792. const indices = [];
  25793. const vertices = [];
  25794. const uvs = [];
  25795. const initNormals = [];
  25796. const normals = [];
  25797. // helper variables
  25798. const inverseSegments = 1.0 / segments;
  25799. const vertex = new Vector3();
  25800. const uv = new Vector2();
  25801. const normal = new Vector3();
  25802. const curNormal = new Vector3();
  25803. const prevNormal = new Vector3();
  25804. let dx = 0;
  25805. let dy = 0;
  25806. // pre-compute normals for initial "meridian"
  25807. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  25808. switch ( j ) {
  25809. case 0: // special handling for 1st vertex on path
  25810. dx = points[ j + 1 ].x - points[ j ].x;
  25811. dy = points[ j + 1 ].y - points[ j ].y;
  25812. normal.x = dy * 1.0;
  25813. normal.y = - dx;
  25814. normal.z = dy * 0.0;
  25815. prevNormal.copy( normal );
  25816. normal.normalize();
  25817. initNormals.push( normal.x, normal.y, normal.z );
  25818. break;
  25819. case ( points.length - 1 ): // special handling for last Vertex on path
  25820. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  25821. break;
  25822. default: // default handling for all vertices in between
  25823. dx = points[ j + 1 ].x - points[ j ].x;
  25824. dy = points[ j + 1 ].y - points[ j ].y;
  25825. normal.x = dy * 1.0;
  25826. normal.y = - dx;
  25827. normal.z = dy * 0.0;
  25828. curNormal.copy( normal );
  25829. normal.x += prevNormal.x;
  25830. normal.y += prevNormal.y;
  25831. normal.z += prevNormal.z;
  25832. normal.normalize();
  25833. initNormals.push( normal.x, normal.y, normal.z );
  25834. prevNormal.copy( curNormal );
  25835. }
  25836. }
  25837. // generate vertices, uvs and normals
  25838. for ( let i = 0; i <= segments; i ++ ) {
  25839. const phi = phiStart + i * inverseSegments * phiLength;
  25840. const sin = Math.sin( phi );
  25841. const cos = Math.cos( phi );
  25842. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  25843. // vertex
  25844. vertex.x = points[ j ].x * sin;
  25845. vertex.y = points[ j ].y;
  25846. vertex.z = points[ j ].x * cos;
  25847. vertices.push( vertex.x, vertex.y, vertex.z );
  25848. // uv
  25849. uv.x = i / segments;
  25850. uv.y = j / ( points.length - 1 );
  25851. uvs.push( uv.x, uv.y );
  25852. // normal
  25853. const x = initNormals[ 3 * j + 0 ] * sin;
  25854. const y = initNormals[ 3 * j + 1 ];
  25855. const z = initNormals[ 3 * j + 0 ] * cos;
  25856. normals.push( x, y, z );
  25857. }
  25858. }
  25859. // indices
  25860. for ( let i = 0; i < segments; i ++ ) {
  25861. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  25862. const base = j + i * points.length;
  25863. const a = base;
  25864. const b = base + points.length;
  25865. const c = base + points.length + 1;
  25866. const d = base + 1;
  25867. // faces
  25868. indices.push( a, b, d );
  25869. indices.push( c, d, b );
  25870. }
  25871. }
  25872. // build geometry
  25873. this.setIndex( indices );
  25874. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  25875. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  25876. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  25877. }
  25878. copy( source ) {
  25879. super.copy( source );
  25880. this.parameters = Object.assign( {}, source.parameters );
  25881. return this;
  25882. }
  25883. /**
  25884. * Factory method for creating an instance of this class from the given
  25885. * JSON object.
  25886. *
  25887. * @param {Object} data - A JSON object representing the serialized geometry.
  25888. * @return {LatheGeometry} A new instance.
  25889. */
  25890. static fromJSON( data ) {
  25891. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  25892. }
  25893. }
  25894. /**
  25895. * A geometry class for representing an octahedron.
  25896. *
  25897. * ```js
  25898. * const geometry = new THREE.OctahedronGeometry();
  25899. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  25900. * const octahedron = new THREE.Mesh( geometry, material );
  25901. * scene.add( octahedron );
  25902. * ```
  25903. *
  25904. * @augments PolyhedronGeometry
  25905. * @demo scenes/geometry-browser.html#OctahedronGeometry
  25906. */
  25907. class OctahedronGeometry extends PolyhedronGeometry {
  25908. /**
  25909. * Constructs a new octahedron geometry.
  25910. *
  25911. * @param {number} [radius=1] - Radius of the octahedron.
  25912. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a octahedron.
  25913. */
  25914. constructor( radius = 1, detail = 0 ) {
  25915. const vertices = [
  25916. 1, 0, 0, -1, 0, 0, 0, 1, 0,
  25917. 0, -1, 0, 0, 0, 1, 0, 0, -1
  25918. ];
  25919. const indices = [
  25920. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  25921. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  25922. 1, 3, 4, 1, 4, 2
  25923. ];
  25924. super( vertices, indices, radius, detail );
  25925. this.type = 'OctahedronGeometry';
  25926. /**
  25927. * Holds the constructor parameters that have been
  25928. * used to generate the geometry. Any modification
  25929. * after instantiation does not change the geometry.
  25930. *
  25931. * @type {Object}
  25932. */
  25933. this.parameters = {
  25934. radius: radius,
  25935. detail: detail
  25936. };
  25937. }
  25938. /**
  25939. * Factory method for creating an instance of this class from the given
  25940. * JSON object.
  25941. *
  25942. * @param {Object} data - A JSON object representing the serialized geometry.
  25943. * @return {OctahedronGeometry} A new instance.
  25944. */
  25945. static fromJSON( data ) {
  25946. return new OctahedronGeometry( data.radius, data.detail );
  25947. }
  25948. }
  25949. /**
  25950. * A geometry class for representing a plane.
  25951. *
  25952. * ```js
  25953. * const geometry = new THREE.PlaneGeometry( 1, 1 );
  25954. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  25955. * const plane = new THREE.Mesh( geometry, material );
  25956. * scene.add( plane );
  25957. * ```
  25958. *
  25959. * @augments BufferGeometry
  25960. * @demo scenes/geometry-browser.html#PlaneGeometry
  25961. */
  25962. class PlaneGeometry extends BufferGeometry {
  25963. /**
  25964. * Constructs a new plane geometry.
  25965. *
  25966. * @param {number} [width=1] - The width along the X axis.
  25967. * @param {number} [height=1] - The height along the Y axis
  25968. * @param {number} [widthSegments=1] - The number of segments along the X axis.
  25969. * @param {number} [heightSegments=1] - The number of segments along the Y axis.
  25970. */
  25971. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  25972. super();
  25973. this.type = 'PlaneGeometry';
  25974. /**
  25975. * Holds the constructor parameters that have been
  25976. * used to generate the geometry. Any modification
  25977. * after instantiation does not change the geometry.
  25978. *
  25979. * @type {Object}
  25980. */
  25981. this.parameters = {
  25982. width: width,
  25983. height: height,
  25984. widthSegments: widthSegments,
  25985. heightSegments: heightSegments
  25986. };
  25987. const width_half = width / 2;
  25988. const height_half = height / 2;
  25989. const gridX = Math.floor( widthSegments );
  25990. const gridY = Math.floor( heightSegments );
  25991. const gridX1 = gridX + 1;
  25992. const gridY1 = gridY + 1;
  25993. const segment_width = width / gridX;
  25994. const segment_height = height / gridY;
  25995. //
  25996. const indices = [];
  25997. const vertices = [];
  25998. const normals = [];
  25999. const uvs = [];
  26000. for ( let iy = 0; iy < gridY1; iy ++ ) {
  26001. const y = iy * segment_height - height_half;
  26002. for ( let ix = 0; ix < gridX1; ix ++ ) {
  26003. const x = ix * segment_width - width_half;
  26004. vertices.push( x, - y, 0 );
  26005. normals.push( 0, 0, 1 );
  26006. uvs.push( ix / gridX );
  26007. uvs.push( 1 - ( iy / gridY ) );
  26008. }
  26009. }
  26010. for ( let iy = 0; iy < gridY; iy ++ ) {
  26011. for ( let ix = 0; ix < gridX; ix ++ ) {
  26012. const a = ix + gridX1 * iy;
  26013. const b = ix + gridX1 * ( iy + 1 );
  26014. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  26015. const d = ( ix + 1 ) + gridX1 * iy;
  26016. indices.push( a, b, d );
  26017. indices.push( b, c, d );
  26018. }
  26019. }
  26020. this.setIndex( indices );
  26021. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26022. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26023. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26024. }
  26025. copy( source ) {
  26026. super.copy( source );
  26027. this.parameters = Object.assign( {}, source.parameters );
  26028. return this;
  26029. }
  26030. /**
  26031. * Factory method for creating an instance of this class from the given
  26032. * JSON object.
  26033. *
  26034. * @param {Object} data - A JSON object representing the serialized geometry.
  26035. * @return {PlaneGeometry} A new instance.
  26036. */
  26037. static fromJSON( data ) {
  26038. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  26039. }
  26040. }
  26041. /**
  26042. * A class for generating a two-dimensional ring geometry.
  26043. *
  26044. * ```js
  26045. * const geometry = new THREE.RingGeometry( 1, 5, 32 );
  26046. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26047. * const mesh = new THREE.Mesh( geometry, material );
  26048. * scene.add( mesh );
  26049. * ```
  26050. *
  26051. * @augments BufferGeometry
  26052. * @demo scenes/geometry-browser.html#RingGeometry
  26053. */
  26054. class RingGeometry extends BufferGeometry {
  26055. /**
  26056. * Constructs a new ring geometry.
  26057. *
  26058. * @param {number} [innerRadius=0.5] - The inner radius of the ring.
  26059. * @param {number} [outerRadius=1] - The outer radius of the ring.
  26060. * @param {number} [thetaSegments=32] - Number of segments. A higher number means the ring will be more round. Minimum is `3`.
  26061. * @param {number} [phiSegments=1] - Number of segments per ring segment. Minimum is `1`.
  26062. * @param {number} [thetaStart=0] - Starting angle in radians.
  26063. * @param {number} [thetaLength=Math.PI*2] - Central angle in radians.
  26064. */
  26065. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  26066. super();
  26067. this.type = 'RingGeometry';
  26068. /**
  26069. * Holds the constructor parameters that have been
  26070. * used to generate the geometry. Any modification
  26071. * after instantiation does not change the geometry.
  26072. *
  26073. * @type {Object}
  26074. */
  26075. this.parameters = {
  26076. innerRadius: innerRadius,
  26077. outerRadius: outerRadius,
  26078. thetaSegments: thetaSegments,
  26079. phiSegments: phiSegments,
  26080. thetaStart: thetaStart,
  26081. thetaLength: thetaLength
  26082. };
  26083. thetaSegments = Math.max( 3, thetaSegments );
  26084. phiSegments = Math.max( 1, phiSegments );
  26085. // buffers
  26086. const indices = [];
  26087. const vertices = [];
  26088. const normals = [];
  26089. const uvs = [];
  26090. // some helper variables
  26091. let radius = innerRadius;
  26092. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  26093. const vertex = new Vector3();
  26094. const uv = new Vector2();
  26095. // generate vertices, normals and uvs
  26096. for ( let j = 0; j <= phiSegments; j ++ ) {
  26097. for ( let i = 0; i <= thetaSegments; i ++ ) {
  26098. // values are generate from the inside of the ring to the outside
  26099. const segment = thetaStart + i / thetaSegments * thetaLength;
  26100. // vertex
  26101. vertex.x = radius * Math.cos( segment );
  26102. vertex.y = radius * Math.sin( segment );
  26103. vertices.push( vertex.x, vertex.y, vertex.z );
  26104. // normal
  26105. normals.push( 0, 0, 1 );
  26106. // uv
  26107. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  26108. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  26109. uvs.push( uv.x, uv.y );
  26110. }
  26111. // increase the radius for next row of vertices
  26112. radius += radiusStep;
  26113. }
  26114. // indices
  26115. for ( let j = 0; j < phiSegments; j ++ ) {
  26116. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  26117. for ( let i = 0; i < thetaSegments; i ++ ) {
  26118. const segment = i + thetaSegmentLevel;
  26119. const a = segment;
  26120. const b = segment + thetaSegments + 1;
  26121. const c = segment + thetaSegments + 2;
  26122. const d = segment + 1;
  26123. // faces
  26124. indices.push( a, b, d );
  26125. indices.push( b, c, d );
  26126. }
  26127. }
  26128. // build geometry
  26129. this.setIndex( indices );
  26130. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26131. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26132. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26133. }
  26134. copy( source ) {
  26135. super.copy( source );
  26136. this.parameters = Object.assign( {}, source.parameters );
  26137. return this;
  26138. }
  26139. /**
  26140. * Factory method for creating an instance of this class from the given
  26141. * JSON object.
  26142. *
  26143. * @param {Object} data - A JSON object representing the serialized geometry.
  26144. * @return {RingGeometry} A new instance.
  26145. */
  26146. static fromJSON( data ) {
  26147. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  26148. }
  26149. }
  26150. /**
  26151. * Creates an one-sided polygonal geometry from one or more path shapes.
  26152. *
  26153. * ```js
  26154. * const arcShape = new THREE.Shape()
  26155. * .moveTo( 5, 1 )
  26156. * .absarc( 1, 1, 4, 0, Math.PI * 2, false );
  26157. *
  26158. * const geometry = new THREE.ShapeGeometry( arcShape );
  26159. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00, side: THREE.DoubleSide } );
  26160. * const mesh = new THREE.Mesh( geometry, material ) ;
  26161. * scene.add( mesh );
  26162. * ```
  26163. *
  26164. * @augments BufferGeometry
  26165. * @demo scenes/geometry-browser.html#ShapeGeometry
  26166. */
  26167. class ShapeGeometry extends BufferGeometry {
  26168. /**
  26169. * Constructs a new shape geometry.
  26170. *
  26171. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  26172. * @param {number} [curveSegments=12] - Number of segments per shape.
  26173. */
  26174. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), curveSegments = 12 ) {
  26175. super();
  26176. this.type = 'ShapeGeometry';
  26177. /**
  26178. * Holds the constructor parameters that have been
  26179. * used to generate the geometry. Any modification
  26180. * after instantiation does not change the geometry.
  26181. *
  26182. * @type {Object}
  26183. */
  26184. this.parameters = {
  26185. shapes: shapes,
  26186. curveSegments: curveSegments
  26187. };
  26188. // buffers
  26189. const indices = [];
  26190. const vertices = [];
  26191. const normals = [];
  26192. const uvs = [];
  26193. // helper variables
  26194. let groupStart = 0;
  26195. let groupCount = 0;
  26196. // allow single and array values for "shapes" parameter
  26197. if ( Array.isArray( shapes ) === false ) {
  26198. addShape( shapes );
  26199. } else {
  26200. for ( let i = 0; i < shapes.length; i ++ ) {
  26201. addShape( shapes[ i ] );
  26202. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  26203. groupStart += groupCount;
  26204. groupCount = 0;
  26205. }
  26206. }
  26207. // build geometry
  26208. this.setIndex( indices );
  26209. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26210. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26211. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26212. // helper functions
  26213. function addShape( shape ) {
  26214. const indexOffset = vertices.length / 3;
  26215. const points = shape.extractPoints( curveSegments );
  26216. let shapeVertices = points.shape;
  26217. const shapeHoles = points.holes;
  26218. // check direction of vertices
  26219. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  26220. shapeVertices = shapeVertices.reverse();
  26221. }
  26222. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26223. const shapeHole = shapeHoles[ i ];
  26224. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  26225. shapeHoles[ i ] = shapeHole.reverse();
  26226. }
  26227. }
  26228. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  26229. // join vertices of inner and outer paths to a single array
  26230. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26231. const shapeHole = shapeHoles[ i ];
  26232. shapeVertices = shapeVertices.concat( shapeHole );
  26233. }
  26234. // vertices, normals, uvs
  26235. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  26236. const vertex = shapeVertices[ i ];
  26237. vertices.push( vertex.x, vertex.y, 0 );
  26238. normals.push( 0, 0, 1 );
  26239. uvs.push( vertex.x, vertex.y ); // world uvs
  26240. }
  26241. // indices
  26242. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  26243. const face = faces[ i ];
  26244. const a = face[ 0 ] + indexOffset;
  26245. const b = face[ 1 ] + indexOffset;
  26246. const c = face[ 2 ] + indexOffset;
  26247. indices.push( a, b, c );
  26248. groupCount += 3;
  26249. }
  26250. }
  26251. }
  26252. copy( source ) {
  26253. super.copy( source );
  26254. this.parameters = Object.assign( {}, source.parameters );
  26255. return this;
  26256. }
  26257. toJSON() {
  26258. const data = super.toJSON();
  26259. const shapes = this.parameters.shapes;
  26260. return toJSON( shapes, data );
  26261. }
  26262. /**
  26263. * Factory method for creating an instance of this class from the given
  26264. * JSON object.
  26265. *
  26266. * @param {Object} data - A JSON object representing the serialized geometry.
  26267. * @param {Array<Shape>} shapes - An array of shapes.
  26268. * @return {ShapeGeometry} A new instance.
  26269. */
  26270. static fromJSON( data, shapes ) {
  26271. const geometryShapes = [];
  26272. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26273. const shape = shapes[ data.shapes[ j ] ];
  26274. geometryShapes.push( shape );
  26275. }
  26276. return new ShapeGeometry( geometryShapes, data.curveSegments );
  26277. }
  26278. }
  26279. function toJSON( shapes, data ) {
  26280. data.shapes = [];
  26281. if ( Array.isArray( shapes ) ) {
  26282. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26283. const shape = shapes[ i ];
  26284. data.shapes.push( shape.uuid );
  26285. }
  26286. } else {
  26287. data.shapes.push( shapes.uuid );
  26288. }
  26289. return data;
  26290. }
  26291. /**
  26292. * A class for generating a sphere geometry.
  26293. *
  26294. * ```js
  26295. * const geometry = new THREE.SphereGeometry( 15, 32, 16 );
  26296. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26297. * const sphere = new THREE.Mesh( geometry, material );
  26298. * scene.add( sphere );
  26299. * ```
  26300. *
  26301. * @augments BufferGeometry
  26302. * @demo scenes/geometry-browser.html#SphereGeometry
  26303. */
  26304. class SphereGeometry extends BufferGeometry {
  26305. /**
  26306. * Constructs a new sphere geometry.
  26307. *
  26308. * @param {number} [radius=1] - The sphere radius.
  26309. * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`.
  26310. * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`.
  26311. * @param {number} [phiStart=0] - The horizontal starting angle in radians.
  26312. * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size.
  26313. * @param {number} [thetaStart=0] - The vertical starting angle in radians.
  26314. * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size.
  26315. */
  26316. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  26317. super();
  26318. this.type = 'SphereGeometry';
  26319. /**
  26320. * Holds the constructor parameters that have been
  26321. * used to generate the geometry. Any modification
  26322. * after instantiation does not change the geometry.
  26323. *
  26324. * @type {Object}
  26325. */
  26326. this.parameters = {
  26327. radius: radius,
  26328. widthSegments: widthSegments,
  26329. heightSegments: heightSegments,
  26330. phiStart: phiStart,
  26331. phiLength: phiLength,
  26332. thetaStart: thetaStart,
  26333. thetaLength: thetaLength
  26334. };
  26335. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  26336. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  26337. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  26338. let index = 0;
  26339. const grid = [];
  26340. const vertex = new Vector3();
  26341. const normal = new Vector3();
  26342. // buffers
  26343. const indices = [];
  26344. const vertices = [];
  26345. const normals = [];
  26346. const uvs = [];
  26347. // generate vertices, normals and uvs
  26348. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  26349. const verticesRow = [];
  26350. const v = iy / heightSegments;
  26351. // special case for the poles
  26352. let uOffset = 0;
  26353. if ( iy === 0 && thetaStart === 0 ) {
  26354. uOffset = 0.5 / widthSegments;
  26355. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  26356. uOffset = -0.5 / widthSegments;
  26357. }
  26358. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  26359. const u = ix / widthSegments;
  26360. // vertex
  26361. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  26362. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  26363. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  26364. vertices.push( vertex.x, vertex.y, vertex.z );
  26365. // normal
  26366. normal.copy( vertex ).normalize();
  26367. normals.push( normal.x, normal.y, normal.z );
  26368. // uv
  26369. uvs.push( u + uOffset, 1 - v );
  26370. verticesRow.push( index ++ );
  26371. }
  26372. grid.push( verticesRow );
  26373. }
  26374. // indices
  26375. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  26376. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  26377. const a = grid[ iy ][ ix + 1 ];
  26378. const b = grid[ iy ][ ix ];
  26379. const c = grid[ iy + 1 ][ ix ];
  26380. const d = grid[ iy + 1 ][ ix + 1 ];
  26381. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  26382. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  26383. }
  26384. }
  26385. // build geometry
  26386. this.setIndex( indices );
  26387. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26388. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26389. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26390. }
  26391. copy( source ) {
  26392. super.copy( source );
  26393. this.parameters = Object.assign( {}, source.parameters );
  26394. return this;
  26395. }
  26396. /**
  26397. * Factory method for creating an instance of this class from the given
  26398. * JSON object.
  26399. *
  26400. * @param {Object} data - A JSON object representing the serialized geometry.
  26401. * @return {SphereGeometry} A new instance.
  26402. */
  26403. static fromJSON( data ) {
  26404. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  26405. }
  26406. }
  26407. /**
  26408. * A geometry class for representing an tetrahedron.
  26409. *
  26410. * ```js
  26411. * const geometry = new THREE.TetrahedronGeometry();
  26412. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26413. * const tetrahedron = new THREE.Mesh( geometry, material );
  26414. * scene.add( tetrahedron );
  26415. * ```
  26416. *
  26417. * @augments PolyhedronGeometry
  26418. * @demo scenes/geometry-browser.html#TetrahedronGeometry
  26419. */
  26420. class TetrahedronGeometry extends PolyhedronGeometry {
  26421. /**
  26422. * Constructs a new tetrahedron geometry.
  26423. *
  26424. * @param {number} [radius=1] - Radius of the tetrahedron.
  26425. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a tetrahedron.
  26426. */
  26427. constructor( radius = 1, detail = 0 ) {
  26428. const vertices = [
  26429. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  26430. ];
  26431. const indices = [
  26432. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  26433. ];
  26434. super( vertices, indices, radius, detail );
  26435. this.type = 'TetrahedronGeometry';
  26436. /**
  26437. * Holds the constructor parameters that have been
  26438. * used to generate the geometry. Any modification
  26439. * after instantiation does not change the geometry.
  26440. *
  26441. * @type {Object}
  26442. */
  26443. this.parameters = {
  26444. radius: radius,
  26445. detail: detail
  26446. };
  26447. }
  26448. /**
  26449. * Factory method for creating an instance of this class from the given
  26450. * JSON object.
  26451. *
  26452. * @param {Object} data - A JSON object representing the serialized geometry.
  26453. * @return {TetrahedronGeometry} A new instance.
  26454. */
  26455. static fromJSON( data ) {
  26456. return new TetrahedronGeometry( data.radius, data.detail );
  26457. }
  26458. }
  26459. /**
  26460. * A geometry class for representing an torus.
  26461. *
  26462. * ```js
  26463. * const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 );
  26464. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26465. * const torus = new THREE.Mesh( geometry, material );
  26466. * scene.add( torus );
  26467. * ```
  26468. *
  26469. * @augments BufferGeometry
  26470. * @demo scenes/geometry-browser.html#TorusGeometry
  26471. */
  26472. class TorusGeometry extends BufferGeometry {
  26473. /**
  26474. * Constructs a new torus geometry.
  26475. *
  26476. * @param {number} [radius=1] - Radius of the torus, from the center of the torus to the center of the tube.
  26477. * @param {number} [tube=0.4] - Radius of the tube. Must be smaller than `radius`.
  26478. * @param {number} [radialSegments=12] - The number of radial segments.
  26479. * @param {number} [tubularSegments=48] - The number of tubular segments.
  26480. * @param {number} [arc=Math.PI*2] - Central angle in radians.
  26481. * @param {number} [thetaStart=0] - Start of the tubular sweep in radians.
  26482. * @param {number} [thetaLength=Math.PI*2] - Length of the tubular sweep in radians.
  26483. */
  26484. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  26485. super();
  26486. this.type = 'TorusGeometry';
  26487. /**
  26488. * Holds the constructor parameters that have been
  26489. * used to generate the geometry. Any modification
  26490. * after instantiation does not change the geometry.
  26491. *
  26492. * @type {Object}
  26493. */
  26494. this.parameters = {
  26495. radius: radius,
  26496. tube: tube,
  26497. radialSegments: radialSegments,
  26498. tubularSegments: tubularSegments,
  26499. arc: arc,
  26500. thetaStart: thetaStart,
  26501. thetaLength: thetaLength,
  26502. };
  26503. radialSegments = Math.floor( radialSegments );
  26504. tubularSegments = Math.floor( tubularSegments );
  26505. // buffers
  26506. const indices = [];
  26507. const vertices = [];
  26508. const normals = [];
  26509. const uvs = [];
  26510. // helper variables
  26511. const center = new Vector3();
  26512. const vertex = new Vector3();
  26513. const normal = new Vector3();
  26514. // generate vertices, normals and uvs
  26515. for ( let j = 0; j <= radialSegments; j ++ ) {
  26516. const v = thetaStart + ( j / radialSegments ) * thetaLength;
  26517. for ( let i = 0; i <= tubularSegments; i ++ ) {
  26518. const u = i / tubularSegments * arc;
  26519. // vertex
  26520. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  26521. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  26522. vertex.z = tube * Math.sin( v );
  26523. vertices.push( vertex.x, vertex.y, vertex.z );
  26524. // normal
  26525. center.x = radius * Math.cos( u );
  26526. center.y = radius * Math.sin( u );
  26527. normal.subVectors( vertex, center ).normalize();
  26528. normals.push( normal.x, normal.y, normal.z );
  26529. // uv
  26530. uvs.push( i / tubularSegments );
  26531. uvs.push( j / radialSegments );
  26532. }
  26533. }
  26534. // generate indices
  26535. for ( let j = 1; j <= radialSegments; j ++ ) {
  26536. for ( let i = 1; i <= tubularSegments; i ++ ) {
  26537. // indices
  26538. const a = ( tubularSegments + 1 ) * j + i - 1;
  26539. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  26540. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  26541. const d = ( tubularSegments + 1 ) * j + i;
  26542. // faces
  26543. indices.push( a, b, d );
  26544. indices.push( b, c, d );
  26545. }
  26546. }
  26547. // build geometry
  26548. this.setIndex( indices );
  26549. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26550. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26551. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26552. }
  26553. copy( source ) {
  26554. super.copy( source );
  26555. this.parameters = Object.assign( {}, source.parameters );
  26556. return this;
  26557. }
  26558. /**
  26559. * Factory method for creating an instance of this class from the given
  26560. * JSON object.
  26561. *
  26562. * @param {Object} data - A JSON object representing the serialized geometry.
  26563. * @return {TorusGeometry} A new instance.
  26564. */
  26565. static fromJSON( data ) {
  26566. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  26567. }
  26568. }
  26569. /**
  26570. * Creates a torus knot, the particular shape of which is defined by a pair
  26571. * of coprime integers, p and q. If p and q are not coprime, the result will
  26572. * be a torus link.
  26573. *
  26574. * ```js
  26575. * const geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 );
  26576. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26577. * const torusKnot = new THREE.Mesh( geometry, material );
  26578. * scene.add( torusKnot );
  26579. * ```
  26580. *
  26581. * @augments BufferGeometry
  26582. * @demo scenes/geometry-browser.html#TorusKnotGeometry
  26583. */
  26584. class TorusKnotGeometry extends BufferGeometry {
  26585. /**
  26586. * Constructs a new torus knot geometry.
  26587. *
  26588. * @param {number} [radius=1] - Radius of the torus knot.
  26589. * @param {number} [tube=0.4] - Radius of the tube.
  26590. * @param {number} [tubularSegments=64] - The number of tubular segments.
  26591. * @param {number} [radialSegments=8] - The number of radial segments.
  26592. * @param {number} [p=2] - This value determines, how many times the geometry winds around its axis of rotational symmetry.
  26593. * @param {number} [q=3] - This value determines, how many times the geometry winds around a circle in the interior of the torus.
  26594. */
  26595. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  26596. super();
  26597. this.type = 'TorusKnotGeometry';
  26598. /**
  26599. * Holds the constructor parameters that have been
  26600. * used to generate the geometry. Any modification
  26601. * after instantiation does not change the geometry.
  26602. *
  26603. * @type {Object}
  26604. */
  26605. this.parameters = {
  26606. radius: radius,
  26607. tube: tube,
  26608. tubularSegments: tubularSegments,
  26609. radialSegments: radialSegments,
  26610. p: p,
  26611. q: q
  26612. };
  26613. tubularSegments = Math.floor( tubularSegments );
  26614. radialSegments = Math.floor( radialSegments );
  26615. // buffers
  26616. const indices = [];
  26617. const vertices = [];
  26618. const normals = [];
  26619. const uvs = [];
  26620. // helper variables
  26621. const vertex = new Vector3();
  26622. const normal = new Vector3();
  26623. const P1 = new Vector3();
  26624. const P2 = new Vector3();
  26625. const B = new Vector3();
  26626. const T = new Vector3();
  26627. const N = new Vector3();
  26628. // generate vertices, normals and uvs
  26629. for ( let i = 0; i <= tubularSegments; ++ i ) {
  26630. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  26631. const u = i / tubularSegments * p * Math.PI * 2;
  26632. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  26633. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  26634. calculatePositionOnCurve( u, p, q, radius, P1 );
  26635. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  26636. // calculate orthonormal basis
  26637. T.subVectors( P2, P1 );
  26638. N.addVectors( P2, P1 );
  26639. B.crossVectors( T, N );
  26640. N.crossVectors( B, T );
  26641. // normalize B, N. T can be ignored, we don't use it
  26642. B.normalize();
  26643. N.normalize();
  26644. for ( let j = 0; j <= radialSegments; ++ j ) {
  26645. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  26646. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  26647. const v = j / radialSegments * Math.PI * 2;
  26648. const cx = - tube * Math.cos( v );
  26649. const cy = tube * Math.sin( v );
  26650. // now calculate the final vertex position.
  26651. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  26652. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  26653. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  26654. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  26655. vertices.push( vertex.x, vertex.y, vertex.z );
  26656. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  26657. normal.subVectors( vertex, P1 ).normalize();
  26658. normals.push( normal.x, normal.y, normal.z );
  26659. // uv
  26660. uvs.push( i / tubularSegments );
  26661. uvs.push( j / radialSegments );
  26662. }
  26663. }
  26664. // generate indices
  26665. for ( let j = 1; j <= tubularSegments; j ++ ) {
  26666. for ( let i = 1; i <= radialSegments; i ++ ) {
  26667. // indices
  26668. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  26669. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  26670. const c = ( radialSegments + 1 ) * j + i;
  26671. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  26672. // faces
  26673. indices.push( a, b, d );
  26674. indices.push( b, c, d );
  26675. }
  26676. }
  26677. // build geometry
  26678. this.setIndex( indices );
  26679. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26680. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26681. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26682. // this function calculates the current position on the torus curve
  26683. function calculatePositionOnCurve( u, p, q, radius, position ) {
  26684. const cu = Math.cos( u );
  26685. const su = Math.sin( u );
  26686. const quOverP = q / p * u;
  26687. const cs = Math.cos( quOverP );
  26688. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  26689. position.y = radius * ( 2 + cs ) * su * 0.5;
  26690. position.z = radius * Math.sin( quOverP ) * 0.5;
  26691. }
  26692. }
  26693. copy( source ) {
  26694. super.copy( source );
  26695. this.parameters = Object.assign( {}, source.parameters );
  26696. return this;
  26697. }
  26698. /**
  26699. * Factory method for creating an instance of this class from the given
  26700. * JSON object.
  26701. *
  26702. * @param {Object} data - A JSON object representing the serialized geometry.
  26703. * @return {TorusKnotGeometry} A new instance.
  26704. */
  26705. static fromJSON( data ) {
  26706. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  26707. }
  26708. }
  26709. /**
  26710. * Creates a tube that extrudes along a 3D curve.
  26711. *
  26712. * ```js
  26713. * class CustomSinCurve extends THREE.Curve {
  26714. *
  26715. * getPoint( t, optionalTarget = new THREE.Vector3() ) {
  26716. *
  26717. * const tx = t * 3 - 1.5;
  26718. * const ty = Math.sin( 2 * Math.PI * t );
  26719. * const tz = 0;
  26720. *
  26721. * return optionalTarget.set( tx, ty, tz );
  26722. * }
  26723. *
  26724. * }
  26725. *
  26726. * const path = new CustomSinCurve( 10 );
  26727. * const geometry = new THREE.TubeGeometry( path, 20, 2, 8, false );
  26728. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  26729. * const mesh = new THREE.Mesh( geometry, material );
  26730. * scene.add( mesh );
  26731. * ```
  26732. *
  26733. * @augments BufferGeometry
  26734. * @demo scenes/geometry-browser.html#TubeGeometry
  26735. */
  26736. class TubeGeometry extends BufferGeometry {
  26737. /**
  26738. * Constructs a new tube geometry.
  26739. *
  26740. * @param {Curve} [path=QuadraticBezierCurve3] - A 3D curve defining the path of the tube.
  26741. * @param {number} [tubularSegments=64] - The number of segments that make up the tube.
  26742. * @param {number} [radius=1] -The radius of the tube.
  26743. * @param {number} [radialSegments=8] - The number of segments that make up the cross-section.
  26744. * @param {boolean} [closed=false] - Whether the tube is closed or not.
  26745. */
  26746. 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 ) {
  26747. super();
  26748. this.type = 'TubeGeometry';
  26749. /**
  26750. * Holds the constructor parameters that have been
  26751. * used to generate the geometry. Any modification
  26752. * after instantiation does not change the geometry.
  26753. *
  26754. * @type {Object}
  26755. */
  26756. this.parameters = {
  26757. path: path,
  26758. tubularSegments: tubularSegments,
  26759. radius: radius,
  26760. radialSegments: radialSegments,
  26761. closed: closed
  26762. };
  26763. const frames = path.computeFrenetFrames( tubularSegments, closed );
  26764. // expose internals
  26765. this.tangents = frames.tangents;
  26766. this.normals = frames.normals;
  26767. this.binormals = frames.binormals;
  26768. // helper variables
  26769. const vertex = new Vector3();
  26770. const normal = new Vector3();
  26771. const uv = new Vector2();
  26772. let P = new Vector3();
  26773. // buffer
  26774. const vertices = [];
  26775. const normals = [];
  26776. const uvs = [];
  26777. const indices = [];
  26778. // create buffer data
  26779. generateBufferData();
  26780. // build geometry
  26781. this.setIndex( indices );
  26782. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26783. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26784. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26785. // functions
  26786. function generateBufferData() {
  26787. for ( let i = 0; i < tubularSegments; i ++ ) {
  26788. generateSegment( i );
  26789. }
  26790. // if the geometry is not closed, generate the last row of vertices and normals
  26791. // at the regular position on the given path
  26792. //
  26793. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  26794. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  26795. // uvs are generated in a separate function.
  26796. // this makes it easy compute correct values for closed geometries
  26797. generateUVs();
  26798. // finally create faces
  26799. generateIndices();
  26800. }
  26801. function generateSegment( i ) {
  26802. // we use getPointAt to sample evenly distributed points from the given path
  26803. P = path.getPointAt( i / tubularSegments, P );
  26804. // retrieve corresponding normal and binormal
  26805. const N = frames.normals[ i ];
  26806. const B = frames.binormals[ i ];
  26807. // generate normals and vertices for the current segment
  26808. for ( let j = 0; j <= radialSegments; j ++ ) {
  26809. const v = j / radialSegments * Math.PI * 2;
  26810. const sin = Math.sin( v );
  26811. const cos = - Math.cos( v );
  26812. // normal
  26813. normal.x = ( cos * N.x + sin * B.x );
  26814. normal.y = ( cos * N.y + sin * B.y );
  26815. normal.z = ( cos * N.z + sin * B.z );
  26816. normal.normalize();
  26817. normals.push( normal.x, normal.y, normal.z );
  26818. // vertex
  26819. vertex.x = P.x + radius * normal.x;
  26820. vertex.y = P.y + radius * normal.y;
  26821. vertex.z = P.z + radius * normal.z;
  26822. vertices.push( vertex.x, vertex.y, vertex.z );
  26823. }
  26824. }
  26825. function generateIndices() {
  26826. for ( let j = 1; j <= tubularSegments; j ++ ) {
  26827. for ( let i = 1; i <= radialSegments; i ++ ) {
  26828. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  26829. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  26830. const c = ( radialSegments + 1 ) * j + i;
  26831. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  26832. // faces
  26833. indices.push( a, b, d );
  26834. indices.push( b, c, d );
  26835. }
  26836. }
  26837. }
  26838. function generateUVs() {
  26839. for ( let i = 0; i <= tubularSegments; i ++ ) {
  26840. for ( let j = 0; j <= radialSegments; j ++ ) {
  26841. uv.x = i / tubularSegments;
  26842. uv.y = j / radialSegments;
  26843. uvs.push( uv.x, uv.y );
  26844. }
  26845. }
  26846. }
  26847. }
  26848. copy( source ) {
  26849. super.copy( source );
  26850. this.parameters = Object.assign( {}, source.parameters );
  26851. return this;
  26852. }
  26853. toJSON() {
  26854. const data = super.toJSON();
  26855. data.path = this.parameters.path.toJSON();
  26856. return data;
  26857. }
  26858. /**
  26859. * Factory method for creating an instance of this class from the given
  26860. * JSON object.
  26861. *
  26862. * @param {Object} data - A JSON object representing the serialized geometry.
  26863. * @return {TubeGeometry} A new instance.
  26864. */
  26865. static fromJSON( data ) {
  26866. // This only works for built-in curves (e.g. CatmullRomCurve3).
  26867. // User defined curves or instances of CurvePath will not be deserialized.
  26868. return new TubeGeometry(
  26869. new Curves[ data.path.type ]().fromJSON( data.path ),
  26870. data.tubularSegments,
  26871. data.radius,
  26872. data.radialSegments,
  26873. data.closed
  26874. );
  26875. }
  26876. }
  26877. /**
  26878. * Can be used as a helper object to visualize a geometry as a wireframe.
  26879. *
  26880. * ```js
  26881. * const geometry = new THREE.SphereGeometry();
  26882. *
  26883. * const wireframe = new THREE.WireframeGeometry( geometry );
  26884. *
  26885. * const line = new THREE.LineSegments( wireframe );
  26886. * line.material.depthWrite = false;
  26887. * line.material.opacity = 0.25;
  26888. * line.material.transparent = true;
  26889. *
  26890. * scene.add( line );
  26891. * ```
  26892. *
  26893. * Note: It is not yet possible to serialize/deserialize instances of this class.
  26894. *
  26895. * @augments BufferGeometry
  26896. */
  26897. class WireframeGeometry extends BufferGeometry {
  26898. /**
  26899. * Constructs a new wireframe geometry.
  26900. *
  26901. * @param {?BufferGeometry} [geometry=null] - The geometry.
  26902. */
  26903. constructor( geometry = null ) {
  26904. super();
  26905. this.type = 'WireframeGeometry';
  26906. /**
  26907. * Holds the constructor parameters that have been
  26908. * used to generate the geometry. Any modification
  26909. * after instantiation does not change the geometry.
  26910. *
  26911. * @type {Object}
  26912. */
  26913. this.parameters = {
  26914. geometry: geometry
  26915. };
  26916. if ( geometry !== null ) {
  26917. // buffer
  26918. const vertices = [];
  26919. const edges = new Set();
  26920. // helper variables
  26921. const start = new Vector3();
  26922. const end = new Vector3();
  26923. if ( geometry.index !== null ) {
  26924. // indexed BufferGeometry
  26925. const position = geometry.attributes.position;
  26926. const indices = geometry.index;
  26927. let groups = geometry.groups;
  26928. if ( groups.length === 0 ) {
  26929. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  26930. }
  26931. // create a data structure that contains all edges without duplicates
  26932. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  26933. const group = groups[ o ];
  26934. const groupStart = group.start;
  26935. const groupCount = group.count;
  26936. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  26937. for ( let j = 0; j < 3; j ++ ) {
  26938. const index1 = indices.getX( i + j );
  26939. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  26940. start.fromBufferAttribute( position, index1 );
  26941. end.fromBufferAttribute( position, index2 );
  26942. if ( isUniqueEdge( start, end, edges ) === true ) {
  26943. vertices.push( start.x, start.y, start.z );
  26944. vertices.push( end.x, end.y, end.z );
  26945. }
  26946. }
  26947. }
  26948. }
  26949. } else {
  26950. // non-indexed BufferGeometry
  26951. const position = geometry.attributes.position;
  26952. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  26953. for ( let j = 0; j < 3; j ++ ) {
  26954. // three edges per triangle, an edge is represented as (index1, index2)
  26955. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  26956. const index1 = 3 * i + j;
  26957. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  26958. start.fromBufferAttribute( position, index1 );
  26959. end.fromBufferAttribute( position, index2 );
  26960. if ( isUniqueEdge( start, end, edges ) === true ) {
  26961. vertices.push( start.x, start.y, start.z );
  26962. vertices.push( end.x, end.y, end.z );
  26963. }
  26964. }
  26965. }
  26966. }
  26967. // build geometry
  26968. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26969. }
  26970. }
  26971. copy( source ) {
  26972. super.copy( source );
  26973. this.parameters = Object.assign( {}, source.parameters );
  26974. return this;
  26975. }
  26976. }
  26977. function isUniqueEdge( start, end, edges ) {
  26978. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  26979. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  26980. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  26981. return false;
  26982. } else {
  26983. edges.add( hash1 );
  26984. edges.add( hash2 );
  26985. return true;
  26986. }
  26987. }
  26988. var Geometries = /*#__PURE__*/Object.freeze({
  26989. __proto__: null,
  26990. BoxGeometry: BoxGeometry,
  26991. CapsuleGeometry: CapsuleGeometry,
  26992. CircleGeometry: CircleGeometry,
  26993. ConeGeometry: ConeGeometry,
  26994. CylinderGeometry: CylinderGeometry,
  26995. DodecahedronGeometry: DodecahedronGeometry,
  26996. EdgesGeometry: EdgesGeometry,
  26997. ExtrudeGeometry: ExtrudeGeometry,
  26998. IcosahedronGeometry: IcosahedronGeometry,
  26999. LatheGeometry: LatheGeometry,
  27000. OctahedronGeometry: OctahedronGeometry,
  27001. PlaneGeometry: PlaneGeometry,
  27002. PolyhedronGeometry: PolyhedronGeometry,
  27003. RingGeometry: RingGeometry,
  27004. ShapeGeometry: ShapeGeometry,
  27005. SphereGeometry: SphereGeometry,
  27006. TetrahedronGeometry: TetrahedronGeometry,
  27007. TorusGeometry: TorusGeometry,
  27008. TorusKnotGeometry: TorusKnotGeometry,
  27009. TubeGeometry: TubeGeometry,
  27010. WireframeGeometry: WireframeGeometry
  27011. });
  27012. /**
  27013. * This material can receive shadows, but otherwise is completely transparent.
  27014. *
  27015. * ```js
  27016. * const geometry = new THREE.PlaneGeometry( 2000, 2000 );
  27017. * geometry.rotateX( - Math.PI / 2 );
  27018. *
  27019. * const material = new THREE.ShadowMaterial();
  27020. * material.opacity = 0.2;
  27021. *
  27022. * const plane = new THREE.Mesh( geometry, material );
  27023. * plane.position.y = -200;
  27024. * plane.receiveShadow = true;
  27025. * scene.add( plane );
  27026. * ```
  27027. *
  27028. * @augments Material
  27029. */
  27030. class ShadowMaterial extends Material {
  27031. /**
  27032. * Constructs a new shadow material.
  27033. *
  27034. * @param {Object} [parameters] - An object with one or more properties
  27035. * defining the material's appearance. Any property of the material
  27036. * (including any property from inherited materials) can be passed
  27037. * in here. Color values can be passed any type of value accepted
  27038. * by {@link Color#set}.
  27039. */
  27040. constructor( parameters ) {
  27041. super();
  27042. /**
  27043. * This flag can be used for type testing.
  27044. *
  27045. * @type {boolean}
  27046. * @readonly
  27047. * @default true
  27048. */
  27049. this.isShadowMaterial = true;
  27050. this.type = 'ShadowMaterial';
  27051. /**
  27052. * Color of the material.
  27053. *
  27054. * @type {Color}
  27055. * @default (0,0,0)
  27056. */
  27057. this.color = new Color( 0x000000 );
  27058. /**
  27059. * Overwritten since shadow materials are transparent
  27060. * by default.
  27061. *
  27062. * @type {boolean}
  27063. * @default true
  27064. */
  27065. this.transparent = true;
  27066. /**
  27067. * Whether the material is affected by fog or not.
  27068. *
  27069. * @type {boolean}
  27070. * @default true
  27071. */
  27072. this.fog = true;
  27073. this.setValues( parameters );
  27074. }
  27075. copy( source ) {
  27076. super.copy( source );
  27077. this.color.copy( source.color );
  27078. this.fog = source.fog;
  27079. return this;
  27080. }
  27081. }
  27082. /**
  27083. * Provides utility functions for managing uniforms.
  27084. *
  27085. * @module UniformsUtils
  27086. */
  27087. /**
  27088. * Clones the given uniform definitions by performing a deep-copy. That means
  27089. * if the value of a uniform refers to an object like a Vector3 or Texture,
  27090. * the cloned uniform will refer to a new object reference.
  27091. *
  27092. * @param {Object} src - An object representing uniform definitions.
  27093. * @return {Object} The cloned uniforms.
  27094. */
  27095. function cloneUniforms( src ) {
  27096. const dst = {};
  27097. for ( const u in src ) {
  27098. dst[ u ] = {};
  27099. for ( const p in src[ u ] ) {
  27100. const property = src[ u ][ p ];
  27101. if ( property && ( property.isColor ||
  27102. property.isMatrix3 || property.isMatrix4 ||
  27103. property.isVector2 || property.isVector3 || property.isVector4 ||
  27104. property.isTexture || property.isQuaternion ) ) {
  27105. if ( property.isRenderTargetTexture ) {
  27106. warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  27107. dst[ u ][ p ] = null;
  27108. } else {
  27109. dst[ u ][ p ] = property.clone();
  27110. }
  27111. } else if ( Array.isArray( property ) ) {
  27112. dst[ u ][ p ] = property.slice();
  27113. } else {
  27114. dst[ u ][ p ] = property;
  27115. }
  27116. }
  27117. }
  27118. return dst;
  27119. }
  27120. /**
  27121. * Merges the given uniform definitions into a single object. Since the
  27122. * method internally uses cloneUniforms(), it performs a deep-copy when
  27123. * producing the merged uniform definitions.
  27124. *
  27125. * @param {Array} uniforms - An array of objects containing uniform definitions.
  27126. * @return {Object} The merged uniforms.
  27127. */
  27128. function mergeUniforms( uniforms ) {
  27129. const merged = {};
  27130. for ( let u = 0; u < uniforms.length; u ++ ) {
  27131. const tmp = cloneUniforms( uniforms[ u ] );
  27132. for ( const p in tmp ) {
  27133. merged[ p ] = tmp[ p ];
  27134. }
  27135. }
  27136. return merged;
  27137. }
  27138. function cloneUniformsGroups( src ) {
  27139. const dst = [];
  27140. for ( let u = 0; u < src.length; u ++ ) {
  27141. dst.push( src[ u ].clone() );
  27142. }
  27143. return dst;
  27144. }
  27145. function getUnlitUniformColorSpace( renderer ) {
  27146. const currentRenderTarget = renderer.getRenderTarget();
  27147. if ( currentRenderTarget === null ) {
  27148. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  27149. return renderer.outputColorSpace;
  27150. }
  27151. // https://github.com/mrdoob/three.js/issues/27868
  27152. if ( currentRenderTarget.isXRRenderTarget === true ) {
  27153. return currentRenderTarget.texture.colorSpace;
  27154. }
  27155. return ColorManagement.workingColorSpace;
  27156. }
  27157. // Legacy
  27158. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  27159. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  27160. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  27161. /**
  27162. * A material rendered with custom shaders. A shader is a small program written in GLSL.
  27163. * that runs on the GPU. You may want to use a custom shader if you need to implement an
  27164. * effect not included with any of the built-in materials.
  27165. *
  27166. * There are the following notes to bear in mind when using a `ShaderMaterial`:
  27167. *
  27168. * - `ShaderMaterial` can only be used with {@link WebGLRenderer}.
  27169. * - Built in attributes and uniforms are passed to the shaders along with your code. If
  27170. * you don't want that, use {@link RawShaderMaterial} instead.
  27171. * - You can use the directive `#pragma unroll_loop_start` and `#pragma unroll_loop_end`
  27172. * in order to unroll a `for` loop in GLSL by the shader preprocessor. The directive has
  27173. * to be placed right above the loop. The loop formatting has to correspond to a defined standard.
  27174. * - The loop has to be [normalized](https://en.wikipedia.org/wiki/Normalized_loop).
  27175. * - The loop variable has to be *i*.
  27176. * - The value `UNROLLED_LOOP_INDEX` will be replaced with the explicitly
  27177. * value of *i* for the given iteration and can be used in preprocessor
  27178. * statements.
  27179. *
  27180. * ```js
  27181. * const material = new THREE.ShaderMaterial( {
  27182. * uniforms: {
  27183. * time: { value: 1.0 },
  27184. * resolution: { value: new THREE.Vector2() }
  27185. * },
  27186. * vertexShader: document.getElementById( 'vertexShader' ).textContent,
  27187. * fragmentShader: document.getElementById( 'fragmentShader' ).textContent
  27188. * } );
  27189. * ```
  27190. *
  27191. * @augments Material
  27192. */
  27193. class ShaderMaterial extends Material {
  27194. /**
  27195. * Constructs a new shader material.
  27196. *
  27197. * @param {Object} [parameters] - An object with one or more properties
  27198. * defining the material's appearance. Any property of the material
  27199. * (including any property from inherited materials) can be passed
  27200. * in here. Color values can be passed any type of value accepted
  27201. * by {@link Color#set}.
  27202. */
  27203. constructor( parameters ) {
  27204. super();
  27205. /**
  27206. * This flag can be used for type testing.
  27207. *
  27208. * @type {boolean}
  27209. * @readonly
  27210. * @default true
  27211. */
  27212. this.isShaderMaterial = true;
  27213. this.type = 'ShaderMaterial';
  27214. /**
  27215. * Defines custom constants using `#define` directives within the GLSL code
  27216. * for both the vertex shader and the fragment shader; each key/value pair
  27217. * yields another directive.
  27218. * ```js
  27219. * defines: {
  27220. * FOO: 15,
  27221. * BAR: true
  27222. * }
  27223. * ```
  27224. * Yields the lines:
  27225. * ```
  27226. * #define FOO 15
  27227. * #define BAR true
  27228. * ```
  27229. *
  27230. * @type {Object}
  27231. */
  27232. this.defines = {};
  27233. /**
  27234. * An object of the form:
  27235. * ```js
  27236. * {
  27237. * "uniform1": { value: 1.0 },
  27238. * "uniform2": { value: 2 }
  27239. * }
  27240. * ```
  27241. * specifying the uniforms to be passed to the shader code; keys are uniform
  27242. * names, values are definitions of the form
  27243. * ```
  27244. * {
  27245. * value: 1.0
  27246. * }
  27247. * ```
  27248. * where `value` is the value of the uniform. Names must match the name of
  27249. * the uniform, as defined in the GLSL code. Note that uniforms are refreshed
  27250. * on every frame, so updating the value of the uniform will immediately
  27251. * update the value available to the GLSL code.
  27252. *
  27253. * @type {Object}
  27254. */
  27255. this.uniforms = {};
  27256. /**
  27257. * An array holding uniforms groups for configuring UBOs.
  27258. *
  27259. * @type {Array<UniformsGroup>}
  27260. */
  27261. this.uniformsGroups = [];
  27262. /**
  27263. * Vertex shader GLSL code. This is the actual code for the shader.
  27264. *
  27265. * @type {string}
  27266. */
  27267. this.vertexShader = default_vertex;
  27268. /**
  27269. * Fragment shader GLSL code. This is the actual code for the shader.
  27270. *
  27271. * @type {string}
  27272. */
  27273. this.fragmentShader = default_fragment;
  27274. /**
  27275. * Controls line thickness or lines.
  27276. *
  27277. * WebGL and WebGPU ignore this setting and always render line primitives with a
  27278. * width of one pixel.
  27279. *
  27280. * @type {number}
  27281. * @default 1
  27282. */
  27283. this.linewidth = 1;
  27284. /**
  27285. * Renders the geometry as a wireframe.
  27286. *
  27287. * @type {boolean}
  27288. * @default false
  27289. */
  27290. this.wireframe = false;
  27291. /**
  27292. * Controls the thickness of the wireframe.
  27293. *
  27294. * WebGL and WebGPU ignore this property and always render
  27295. * 1 pixel wide lines.
  27296. *
  27297. * @type {number}
  27298. * @default 1
  27299. */
  27300. this.wireframeLinewidth = 1;
  27301. /**
  27302. * Defines whether the material color is affected by global fog settings; `true`
  27303. * to pass fog uniforms to the shader.
  27304. *
  27305. * Setting this property to `true` requires the definition of fog uniforms. It is
  27306. * recommended to use `UniformsUtils.merge()` to combine the custom shader uniforms
  27307. * with predefined fog uniforms.
  27308. *
  27309. * ```js
  27310. * const material = new ShaderMaterial( {
  27311. * uniforms: UniformsUtils.merge( [ UniformsLib[ 'fog' ], shaderUniforms ] );
  27312. * vertexShader: vertexShader,
  27313. * fragmentShader: fragmentShader,
  27314. * fog: true
  27315. * } );
  27316. * ```
  27317. *
  27318. * @type {boolean}
  27319. * @default false
  27320. */
  27321. this.fog = false;
  27322. /**
  27323. * Defines whether this material uses lighting; `true` to pass uniform data
  27324. * related to lighting to this shader.
  27325. *
  27326. * @type {boolean}
  27327. * @default false
  27328. */
  27329. this.lights = false;
  27330. /**
  27331. * Defines whether this material supports clipping; `true` to let the renderer
  27332. * pass the clippingPlanes uniform.
  27333. *
  27334. * @type {boolean}
  27335. * @default false
  27336. */
  27337. this.clipping = false;
  27338. /**
  27339. * Overwritten and set to `true` by default.
  27340. *
  27341. * @type {boolean}
  27342. * @default true
  27343. */
  27344. this.forceSinglePass = true;
  27345. /**
  27346. * This object allows to enable certain WebGL 2 extensions.
  27347. *
  27348. * - clipCullDistance: set to `true` to use vertex shader clipping
  27349. * - multiDraw: set to `true` to use vertex shader multi_draw / enable gl_DrawID
  27350. *
  27351. * @type {{clipCullDistance:false,multiDraw:false}}
  27352. */
  27353. this.extensions = {
  27354. clipCullDistance: false, // set to use vertex shader clipping
  27355. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  27356. };
  27357. /**
  27358. * When the rendered geometry doesn't include these attributes but the
  27359. * material does, these default values will be passed to the shaders. This
  27360. * avoids errors when buffer data is missing.
  27361. *
  27362. * - color: [ 1, 1, 1 ]
  27363. * - uv: [ 0, 0 ]
  27364. * - uv1: [ 0, 0 ]
  27365. *
  27366. * @type {Object}
  27367. */
  27368. this.defaultAttributeValues = {
  27369. 'color': [ 1, 1, 1 ],
  27370. 'uv': [ 0, 0 ],
  27371. 'uv1': [ 0, 0 ]
  27372. };
  27373. /**
  27374. * If set, this calls [gl.bindAttribLocation](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindAttribLocation)
  27375. * to bind a generic vertex index to an attribute variable.
  27376. *
  27377. * @type {string|undefined}
  27378. * @default undefined
  27379. */
  27380. this.index0AttributeName = undefined;
  27381. /**
  27382. * Can be used to force a uniform update while changing uniforms in
  27383. * {@link Object3D#onBeforeRender}.
  27384. *
  27385. * @type {boolean}
  27386. * @default false
  27387. */
  27388. this.uniformsNeedUpdate = false;
  27389. /**
  27390. * Defines the GLSL version of custom shader code.
  27391. *
  27392. * @type {?(GLSL1|GLSL3)}
  27393. * @default null
  27394. */
  27395. this.glslVersion = null;
  27396. if ( parameters !== undefined ) {
  27397. this.setValues( parameters );
  27398. }
  27399. }
  27400. copy( source ) {
  27401. super.copy( source );
  27402. this.fragmentShader = source.fragmentShader;
  27403. this.vertexShader = source.vertexShader;
  27404. this.uniforms = cloneUniforms( source.uniforms );
  27405. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  27406. this.defines = Object.assign( {}, source.defines );
  27407. this.wireframe = source.wireframe;
  27408. this.wireframeLinewidth = source.wireframeLinewidth;
  27409. this.fog = source.fog;
  27410. this.lights = source.lights;
  27411. this.clipping = source.clipping;
  27412. this.extensions = Object.assign( {}, source.extensions );
  27413. this.glslVersion = source.glslVersion;
  27414. this.defaultAttributeValues = Object.assign( {}, source.defaultAttributeValues );
  27415. this.index0AttributeName = source.index0AttributeName;
  27416. this.uniformsNeedUpdate = source.uniformsNeedUpdate;
  27417. return this;
  27418. }
  27419. toJSON( meta ) {
  27420. const data = super.toJSON( meta );
  27421. data.glslVersion = this.glslVersion;
  27422. data.uniforms = {};
  27423. for ( const name in this.uniforms ) {
  27424. const uniform = this.uniforms[ name ];
  27425. const value = uniform.value;
  27426. if ( value && value.isTexture ) {
  27427. data.uniforms[ name ] = {
  27428. type: 't',
  27429. value: value.toJSON( meta ).uuid
  27430. };
  27431. } else if ( value && value.isColor ) {
  27432. data.uniforms[ name ] = {
  27433. type: 'c',
  27434. value: value.getHex()
  27435. };
  27436. } else if ( value && value.isVector2 ) {
  27437. data.uniforms[ name ] = {
  27438. type: 'v2',
  27439. value: value.toArray()
  27440. };
  27441. } else if ( value && value.isVector3 ) {
  27442. data.uniforms[ name ] = {
  27443. type: 'v3',
  27444. value: value.toArray()
  27445. };
  27446. } else if ( value && value.isVector4 ) {
  27447. data.uniforms[ name ] = {
  27448. type: 'v4',
  27449. value: value.toArray()
  27450. };
  27451. } else if ( value && value.isMatrix3 ) {
  27452. data.uniforms[ name ] = {
  27453. type: 'm3',
  27454. value: value.toArray()
  27455. };
  27456. } else if ( value && value.isMatrix4 ) {
  27457. data.uniforms[ name ] = {
  27458. type: 'm4',
  27459. value: value.toArray()
  27460. };
  27461. } else {
  27462. data.uniforms[ name ] = {
  27463. value: value
  27464. };
  27465. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  27466. }
  27467. }
  27468. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  27469. data.vertexShader = this.vertexShader;
  27470. data.fragmentShader = this.fragmentShader;
  27471. data.lights = this.lights;
  27472. data.clipping = this.clipping;
  27473. const extensions = {};
  27474. for ( const key in this.extensions ) {
  27475. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  27476. }
  27477. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  27478. return data;
  27479. }
  27480. }
  27481. /**
  27482. * This class works just like {@link ShaderMaterial}, except that definitions
  27483. * of built-in uniforms and attributes are not automatically prepended to the
  27484. * GLSL shader code.
  27485. *
  27486. * `RawShaderMaterial` can only be used with {@link WebGLRenderer}.
  27487. *
  27488. * @augments ShaderMaterial
  27489. */
  27490. class RawShaderMaterial extends ShaderMaterial {
  27491. /**
  27492. * Constructs a new raw shader material.
  27493. *
  27494. * @param {Object} [parameters] - An object with one or more properties
  27495. * defining the material's appearance. Any property of the material
  27496. * (including any property from inherited materials) can be passed
  27497. * in here. Color values can be passed any type of value accepted
  27498. * by {@link Color#set}.
  27499. */
  27500. constructor( parameters ) {
  27501. super( parameters );
  27502. /**
  27503. * This flag can be used for type testing.
  27504. *
  27505. * @type {boolean}
  27506. * @readonly
  27507. * @default true
  27508. */
  27509. this.isRawShaderMaterial = true;
  27510. this.type = 'RawShaderMaterial';
  27511. }
  27512. }
  27513. /**
  27514. * A standard physically based material, using Metallic-Roughness workflow.
  27515. *
  27516. * Physically based rendering (PBR) has recently become the standard in many
  27517. * 3D applications, such as [Unity](https://blogs.unity3d.com/2014/10/29/physically-based-shading-in-unity-5-a-primer/),
  27518. * [Unreal](https://docs.unrealengine.com/latest/INT/Engine/Rendering/Materials/PhysicallyBased/) and
  27519. * [3D Studio Max](http://area.autodesk.com/blogs/the-3ds-max-blog/what039s-new-for-rendering-in-3ds-max-2017).
  27520. *
  27521. * This approach differs from older approaches in that instead of using
  27522. * approximations for the way in which light interacts with a surface, a
  27523. * physically correct model is used. The idea is that, instead of tweaking
  27524. * materials to look good under specific lighting, a material can be created
  27525. * that will react 'correctly' under all lighting scenarios.
  27526. *
  27527. * In practice this gives a more accurate and realistic looking result than
  27528. * the {@link MeshLambertMaterial} or {@link MeshPhongMaterial}, at the cost of
  27529. * being somewhat more computationally expensive. `MeshStandardMaterial` uses per-fragment
  27530. * shading.
  27531. *
  27532. * Note that for best results you should always specify an environment map when using this material.
  27533. *
  27534. * For a non-technical introduction to the concept of PBR and how to set up a
  27535. * PBR material, check out these articles by the people at [marmoset](https://www.marmoset.co):
  27536. *
  27537. * - [Basic Theory of Physically Based Rendering](https://www.marmoset.co/posts/basic-theory-of-physically-based-rendering/)
  27538. * - [Physically Based Rendering and You Can Too](https://www.marmoset.co/posts/physically-based-rendering-and-you-can-too/)
  27539. *
  27540. * Technical details of the approach used in three.js (and most other PBR systems) can be found is this
  27541. * [paper from Disney](https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf)
  27542. * (pdf), by Brent Burley.
  27543. *
  27544. * @augments Material
  27545. * @demo scenes/material-browser.html#MeshStandardMaterial
  27546. */
  27547. class MeshStandardMaterial extends Material {
  27548. /**
  27549. * Constructs a new mesh standard material.
  27550. *
  27551. * @param {Object} [parameters] - An object with one or more properties
  27552. * defining the material's appearance. Any property of the material
  27553. * (including any property from inherited materials) can be passed
  27554. * in here. Color values can be passed any type of value accepted
  27555. * by {@link Color#set}.
  27556. */
  27557. constructor( parameters ) {
  27558. super();
  27559. /**
  27560. * This flag can be used for type testing.
  27561. *
  27562. * @type {boolean}
  27563. * @readonly
  27564. * @default true
  27565. */
  27566. this.isMeshStandardMaterial = true;
  27567. this.type = 'MeshStandardMaterial';
  27568. this.defines = { 'STANDARD': '' };
  27569. /**
  27570. * Color of the material.
  27571. *
  27572. * @type {Color}
  27573. * @default (1,1,1)
  27574. */
  27575. this.color = new Color( 0xffffff ); // diffuse
  27576. /**
  27577. * How rough the material appears. `0.0` means a smooth mirror reflection, `1.0`
  27578. * means fully diffuse. If `roughnessMap` is also provided,
  27579. * both values are multiplied.
  27580. *
  27581. * @type {number}
  27582. * @default 1
  27583. */
  27584. this.roughness = 1.0;
  27585. /**
  27586. * How much the material is like a metal. Non-metallic materials such as wood
  27587. * or stone use `0.0`, metallic use `1.0`, with nothing (usually) in between.
  27588. * A value between `0.0` and `1.0` could be used for a rusty metal look.
  27589. * If `metalnessMap` is also provided, both values are multiplied.
  27590. *
  27591. * @type {number}
  27592. * @default 0
  27593. */
  27594. this.metalness = 0.0;
  27595. /**
  27596. * The color map. May optionally include an alpha channel, typically combined
  27597. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  27598. * color is modulated by the diffuse `color`.
  27599. *
  27600. * @type {?Texture}
  27601. * @default null
  27602. */
  27603. this.map = null;
  27604. /**
  27605. * The light map. Requires a second set of UVs.
  27606. *
  27607. * @type {?Texture}
  27608. * @default null
  27609. */
  27610. this.lightMap = null;
  27611. /**
  27612. * Intensity of the baked light.
  27613. *
  27614. * @type {number}
  27615. * @default 1
  27616. */
  27617. this.lightMapIntensity = 1.0;
  27618. /**
  27619. * The red channel of this texture is used as the ambient occlusion map.
  27620. * Requires a second set of UVs.
  27621. *
  27622. * @type {?Texture}
  27623. * @default null
  27624. */
  27625. this.aoMap = null;
  27626. /**
  27627. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  27628. * disables ambient occlusion. Where intensity is `1` and the AO map's
  27629. * red channel is also `1`, ambient light is fully occluded on a surface.
  27630. *
  27631. * @type {number}
  27632. * @default 1
  27633. */
  27634. this.aoMapIntensity = 1.0;
  27635. /**
  27636. * Emissive (light) color of the material, essentially a solid color
  27637. * unaffected by other lighting.
  27638. *
  27639. * @type {Color}
  27640. * @default (0,0,0)
  27641. */
  27642. this.emissive = new Color( 0x000000 );
  27643. /**
  27644. * Intensity of the emissive light. Modulates the emissive color.
  27645. *
  27646. * @type {number}
  27647. * @default 1
  27648. */
  27649. this.emissiveIntensity = 1.0;
  27650. /**
  27651. * Set emissive (glow) map. The emissive map color is modulated by the
  27652. * emissive color and the emissive intensity. If you have an emissive map,
  27653. * be sure to set the emissive color to something other than black.
  27654. *
  27655. * @type {?Texture}
  27656. * @default null
  27657. */
  27658. this.emissiveMap = null;
  27659. /**
  27660. * The texture to create a bump map. The black and white values map to the
  27661. * perceived depth in relation to the lights. Bump doesn't actually affect
  27662. * the geometry of the object, only the lighting. If a normal map is defined
  27663. * this will be ignored.
  27664. *
  27665. * @type {?Texture}
  27666. * @default null
  27667. */
  27668. this.bumpMap = null;
  27669. /**
  27670. * How much the bump map affects the material. Typical range is `[0,1]`.
  27671. *
  27672. * @type {number}
  27673. * @default 1
  27674. */
  27675. this.bumpScale = 1;
  27676. /**
  27677. * The texture to create a normal map. The RGB values affect the surface
  27678. * normal for each pixel fragment and change the way the color is lit. Normal
  27679. * maps do not change the actual shape of the surface, only the lighting. In
  27680. * case the material has a normal map authored using the left handed
  27681. * convention, the `y` component of `normalScale` should be negated to compensate
  27682. * for the different handedness.
  27683. *
  27684. * @type {?Texture}
  27685. * @default null
  27686. */
  27687. this.normalMap = null;
  27688. /**
  27689. * The type of normal map.
  27690. *
  27691. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  27692. * @default TangentSpaceNormalMap
  27693. */
  27694. this.normalMapType = TangentSpaceNormalMap;
  27695. /**
  27696. * How much the normal map affects the material. Typical value range is `[0,1]`.
  27697. *
  27698. * @type {Vector2}
  27699. * @default (1,1)
  27700. */
  27701. this.normalScale = new Vector2( 1, 1 );
  27702. /**
  27703. * The displacement map affects the position of the mesh's vertices. Unlike
  27704. * other maps which only affect the light and shade of the material the
  27705. * displaced vertices can cast shadows, block other objects, and otherwise
  27706. * act as real geometry. The displacement texture is an image where the value
  27707. * of each pixel (white being the highest) is mapped against, and
  27708. * repositions, the vertices of the mesh.
  27709. *
  27710. * @type {?Texture}
  27711. * @default null
  27712. */
  27713. this.displacementMap = null;
  27714. /**
  27715. * How much the displacement map affects the mesh (where black is no
  27716. * displacement, and white is maximum displacement). Without a displacement
  27717. * map set, this value is not applied.
  27718. *
  27719. * @type {number}
  27720. * @default 0
  27721. */
  27722. this.displacementScale = 1;
  27723. /**
  27724. * The offset of the displacement map's values on the mesh's vertices.
  27725. * The bias is added to the scaled sample of the displacement map.
  27726. * Without a displacement map set, this value is not applied.
  27727. *
  27728. * @type {number}
  27729. * @default 0
  27730. */
  27731. this.displacementBias = 0;
  27732. /**
  27733. * The green channel of this texture is used to alter the roughness of the
  27734. * material.
  27735. *
  27736. * @type {?Texture}
  27737. * @default null
  27738. */
  27739. this.roughnessMap = null;
  27740. /**
  27741. * The blue channel of this texture is used to alter the metalness of the
  27742. * material.
  27743. *
  27744. * @type {?Texture}
  27745. * @default null
  27746. */
  27747. this.metalnessMap = null;
  27748. /**
  27749. * The alpha map is a grayscale texture that controls the opacity across the
  27750. * surface (black: fully transparent; white: fully opaque).
  27751. *
  27752. * Only the color of the texture is used, ignoring the alpha channel if one
  27753. * exists. For RGB and RGBA textures, the renderer will use the green channel
  27754. * when sampling this texture due to the extra bit of precision provided for
  27755. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  27756. * luminance/alpha textures will also still work as expected.
  27757. *
  27758. * @type {?Texture}
  27759. * @default null
  27760. */
  27761. this.alphaMap = null;
  27762. /**
  27763. * The environment map. To ensure a physically correct rendering, environment maps
  27764. * are internally pre-processed with {@link PMREMGenerator}.
  27765. *
  27766. * @type {?Texture}
  27767. * @default null
  27768. */
  27769. this.envMap = null;
  27770. /**
  27771. * The rotation of the environment map in radians.
  27772. *
  27773. * @type {Euler}
  27774. * @default (0,0,0)
  27775. */
  27776. this.envMapRotation = new Euler();
  27777. /**
  27778. * Scales the effect of the environment map by multiplying its color.
  27779. *
  27780. * @type {number}
  27781. * @default 1
  27782. */
  27783. this.envMapIntensity = 1.0;
  27784. /**
  27785. * Renders the geometry as a wireframe.
  27786. *
  27787. * @type {boolean}
  27788. * @default false
  27789. */
  27790. this.wireframe = false;
  27791. /**
  27792. * Controls the thickness of the wireframe.
  27793. *
  27794. * Can only be used with {@link SVGRenderer}.
  27795. *
  27796. * @type {number}
  27797. * @default 1
  27798. */
  27799. this.wireframeLinewidth = 1;
  27800. /**
  27801. * Defines appearance of wireframe ends.
  27802. *
  27803. * Can only be used with {@link SVGRenderer}.
  27804. *
  27805. * @type {('round'|'bevel'|'miter')}
  27806. * @default 'round'
  27807. */
  27808. this.wireframeLinecap = 'round';
  27809. /**
  27810. * Defines appearance of wireframe joints.
  27811. *
  27812. * Can only be used with {@link SVGRenderer}.
  27813. *
  27814. * @type {('round'|'bevel'|'miter')}
  27815. * @default 'round'
  27816. */
  27817. this.wireframeLinejoin = 'round';
  27818. /**
  27819. * Whether the material is rendered with flat shading or not.
  27820. *
  27821. * @type {boolean}
  27822. * @default false
  27823. */
  27824. this.flatShading = false;
  27825. /**
  27826. * Whether the material is affected by fog or not.
  27827. *
  27828. * @type {boolean}
  27829. * @default true
  27830. */
  27831. this.fog = true;
  27832. this.setValues( parameters );
  27833. }
  27834. copy( source ) {
  27835. super.copy( source );
  27836. this.defines = { 'STANDARD': '' };
  27837. this.color.copy( source.color );
  27838. this.roughness = source.roughness;
  27839. this.metalness = source.metalness;
  27840. this.map = source.map;
  27841. this.lightMap = source.lightMap;
  27842. this.lightMapIntensity = source.lightMapIntensity;
  27843. this.aoMap = source.aoMap;
  27844. this.aoMapIntensity = source.aoMapIntensity;
  27845. this.emissive.copy( source.emissive );
  27846. this.emissiveMap = source.emissiveMap;
  27847. this.emissiveIntensity = source.emissiveIntensity;
  27848. this.bumpMap = source.bumpMap;
  27849. this.bumpScale = source.bumpScale;
  27850. this.normalMap = source.normalMap;
  27851. this.normalMapType = source.normalMapType;
  27852. this.normalScale.copy( source.normalScale );
  27853. this.displacementMap = source.displacementMap;
  27854. this.displacementScale = source.displacementScale;
  27855. this.displacementBias = source.displacementBias;
  27856. this.roughnessMap = source.roughnessMap;
  27857. this.metalnessMap = source.metalnessMap;
  27858. this.alphaMap = source.alphaMap;
  27859. this.envMap = source.envMap;
  27860. this.envMapRotation.copy( source.envMapRotation );
  27861. this.envMapIntensity = source.envMapIntensity;
  27862. this.wireframe = source.wireframe;
  27863. this.wireframeLinewidth = source.wireframeLinewidth;
  27864. this.wireframeLinecap = source.wireframeLinecap;
  27865. this.wireframeLinejoin = source.wireframeLinejoin;
  27866. this.flatShading = source.flatShading;
  27867. this.fog = source.fog;
  27868. return this;
  27869. }
  27870. }
  27871. /**
  27872. * An extension of the {@link MeshStandardMaterial}, providing more advanced
  27873. * physically-based rendering properties:
  27874. *
  27875. * - Anisotropy: Ability to represent the anisotropic property of materials
  27876. * as observable with brushed metals.
  27877. * - Clearcoat: Some materials — like car paints, carbon fiber, and wet surfaces — require
  27878. * a clear, reflective layer on top of another layer that may be irregular or rough.
  27879. * Clearcoat approximates this effect, without the need for a separate transparent surface.
  27880. * - Iridescence: Allows to render the effect where hue varies depending on the viewing
  27881. * angle and illumination angle. This can be seen on soap bubbles, oil films, or on the
  27882. * wings of many insects.
  27883. * - Physically-based transparency: One limitation of {@link Material#opacity} is that highly
  27884. * transparent materials are less reflective. Physically-based transmission provides a more
  27885. * realistic option for thin, transparent surfaces like glass.
  27886. * - Advanced reflectivity: More flexible reflectivity for non-metallic materials.
  27887. * - Sheen: Can be used for representing cloth and fabric materials.
  27888. *
  27889. * As a result of these complex shading features, `MeshPhysicalMaterial` has a
  27890. * higher performance cost, per pixel, than other three.js materials. Most
  27891. * effects are disabled by default, and add cost as they are enabled. For
  27892. * best results, always specify an environment map when using this material.
  27893. *
  27894. * @augments MeshStandardMaterial
  27895. * @demo scenes/material-browser.html#MeshPhysicalMaterial
  27896. */
  27897. class MeshPhysicalMaterial extends MeshStandardMaterial {
  27898. /**
  27899. * Constructs a new mesh physical material.
  27900. *
  27901. * @param {Object} [parameters] - An object with one or more properties
  27902. * defining the material's appearance. Any property of the material
  27903. * (including any property from inherited materials) can be passed
  27904. * in here. Color values can be passed any type of value accepted
  27905. * by {@link Color#set}.
  27906. */
  27907. constructor( parameters ) {
  27908. super();
  27909. /**
  27910. * This flag can be used for type testing.
  27911. *
  27912. * @type {boolean}
  27913. * @readonly
  27914. * @default true
  27915. */
  27916. this.isMeshPhysicalMaterial = true;
  27917. this.defines = {
  27918. 'STANDARD': '',
  27919. 'PHYSICAL': ''
  27920. };
  27921. this.type = 'MeshPhysicalMaterial';
  27922. /**
  27923. * The rotation of the anisotropy in tangent, bitangent space, measured in radians
  27924. * counter-clockwise from the tangent. When `anisotropyMap` is present, this
  27925. * property provides additional rotation to the vectors in the texture.
  27926. *
  27927. * @type {number}
  27928. * @default 1
  27929. */
  27930. this.anisotropyRotation = 0;
  27931. /**
  27932. * Red and green channels represent the anisotropy direction in `[-1, 1]` tangent,
  27933. * bitangent space, to be rotated by `anisotropyRotation`. The blue channel
  27934. * contains strength as `[0, 1]` to be multiplied by `anisotropy`.
  27935. *
  27936. * @type {?Texture}
  27937. * @default null
  27938. */
  27939. this.anisotropyMap = null;
  27940. /**
  27941. * The red channel of this texture is multiplied against `clearcoat`,
  27942. * for per-pixel control over a coating's intensity.
  27943. *
  27944. * @type {?Texture}
  27945. * @default null
  27946. */
  27947. this.clearcoatMap = null;
  27948. /**
  27949. * Roughness of the clear coat layer, from `0.0` to `1.0`.
  27950. *
  27951. * @type {number}
  27952. * @default 0
  27953. */
  27954. this.clearcoatRoughness = 0.0;
  27955. /**
  27956. * The green channel of this texture is multiplied against
  27957. * `clearcoatRoughness`, for per-pixel control over a coating's roughness.
  27958. *
  27959. * @type {?Texture}
  27960. * @default null
  27961. */
  27962. this.clearcoatRoughnessMap = null;
  27963. /**
  27964. * How much `clearcoatNormalMap` affects the clear coat layer, from
  27965. * `(0,0)` to `(1,1)`.
  27966. *
  27967. * @type {Vector2}
  27968. * @default (1,1)
  27969. */
  27970. this.clearcoatNormalScale = new Vector2( 1, 1 );
  27971. /**
  27972. * Can be used to enable independent normals for the clear coat layer.
  27973. *
  27974. * @type {?Texture}
  27975. * @default null
  27976. */
  27977. this.clearcoatNormalMap = null;
  27978. /**
  27979. * Index-of-refraction for non-metallic materials, from `1.0` to `2.333`.
  27980. *
  27981. * @type {number}
  27982. * @default 1.5
  27983. */
  27984. this.ior = 1.5;
  27985. /**
  27986. * Degree of reflectivity, from `0.0` to `1.0`. Default is `0.5`, which
  27987. * corresponds to an index-of-refraction of `1.5`.
  27988. *
  27989. * This models the reflectivity of non-metallic materials. It has no effect
  27990. * when `metalness` is `1.0`
  27991. *
  27992. * @name MeshPhysicalMaterial#reflectivity
  27993. * @type {number}
  27994. * @default 0.5
  27995. */
  27996. Object.defineProperty( this, 'reflectivity', {
  27997. get: function () {
  27998. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  27999. },
  28000. set: function ( reflectivity ) {
  28001. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  28002. }
  28003. } );
  28004. /**
  28005. * The red channel of this texture is multiplied against `iridescence`, for per-pixel
  28006. * control over iridescence.
  28007. *
  28008. * @type {?Texture}
  28009. * @default null
  28010. */
  28011. this.iridescenceMap = null;
  28012. /**
  28013. * Strength of the iridescence RGB color shift effect, represented by an index-of-refraction.
  28014. * Between `1.0` to `2.333`.
  28015. *
  28016. * @type {number}
  28017. * @default 1.3
  28018. */
  28019. this.iridescenceIOR = 1.3;
  28020. /**
  28021. *Array of exactly 2 elements, specifying minimum and maximum thickness of the iridescence layer.
  28022. Thickness of iridescence layer has an equivalent effect of the one `thickness` has on `ior`.
  28023. *
  28024. * @type {Array<number,number>}
  28025. * @default [100,400]
  28026. */
  28027. this.iridescenceThicknessRange = [ 100, 400 ];
  28028. /**
  28029. * A texture that defines the thickness of the iridescence layer, stored in the green channel.
  28030. * Minimum and maximum values of thickness are defined by `iridescenceThicknessRange` array:
  28031. * - `0.0` in the green channel will result in thickness equal to first element of the array.
  28032. * - `1.0` in the green channel will result in thickness equal to second element of the array.
  28033. * - Values in-between will linearly interpolate between the elements of the array.
  28034. *
  28035. * @type {?Texture}
  28036. * @default null
  28037. */
  28038. this.iridescenceThicknessMap = null;
  28039. /**
  28040. * The sheen tint.
  28041. *
  28042. * @type {Color}
  28043. * @default (0,0,0)
  28044. */
  28045. this.sheenColor = new Color( 0x000000 );
  28046. /**
  28047. * The RGB channels of this texture are multiplied against `sheenColor`, for per-pixel control
  28048. * over sheen tint.
  28049. *
  28050. * @type {?Texture}
  28051. * @default null
  28052. */
  28053. this.sheenColorMap = null;
  28054. /**
  28055. * Roughness of the sheen layer, from `0.0` to `1.0`.
  28056. *
  28057. * @type {number}
  28058. * @default 1
  28059. */
  28060. this.sheenRoughness = 1.0;
  28061. /**
  28062. * The alpha channel of this texture is multiplied against `sheenRoughness`, for per-pixel control
  28063. * over sheen roughness.
  28064. *
  28065. * @type {?Texture}
  28066. * @default null
  28067. */
  28068. this.sheenRoughnessMap = null;
  28069. /**
  28070. * The red channel of this texture is multiplied against `transmission`, for per-pixel control over
  28071. * optical transparency.
  28072. *
  28073. * @type {?Texture}
  28074. * @default null
  28075. */
  28076. this.transmissionMap = null;
  28077. /**
  28078. * The thickness of the volume beneath the surface. The value is given in the
  28079. * coordinate space of the mesh. If the value is `0` the material is
  28080. * thin-walled. Otherwise the material is a volume boundary.
  28081. *
  28082. * @type {number}
  28083. * @default 0
  28084. */
  28085. this.thickness = 0;
  28086. /**
  28087. * A texture that defines the thickness, stored in the green channel. This will
  28088. * be multiplied by `thickness`.
  28089. *
  28090. * @type {?Texture}
  28091. * @default null
  28092. */
  28093. this.thicknessMap = null;
  28094. /**
  28095. * Density of the medium given as the average distance that light travels in
  28096. * the medium before interacting with a particle. The value is given in world
  28097. * space units, and must be greater than zero.
  28098. *
  28099. * @type {number}
  28100. * @default Infinity
  28101. */
  28102. this.attenuationDistance = Infinity;
  28103. /**
  28104. * The color that white light turns into due to absorption when reaching the
  28105. * attenuation distance.
  28106. *
  28107. * @type {Color}
  28108. * @default (1,1,1)
  28109. */
  28110. this.attenuationColor = new Color( 1, 1, 1 );
  28111. /**
  28112. * A float that scales the amount of specular reflection for non-metals only.
  28113. * When set to zero, the model is effectively Lambertian. From `0.0` to `1.0`.
  28114. *
  28115. * @type {number}
  28116. * @default 1
  28117. */
  28118. this.specularIntensity = 1.0;
  28119. /**
  28120. * The alpha channel of this texture is multiplied against `specularIntensity`,
  28121. * for per-pixel control over specular intensity.
  28122. *
  28123. * @type {?Texture}
  28124. * @default null
  28125. */
  28126. this.specularIntensityMap = null;
  28127. /**
  28128. * Tints the specular reflection at normal incidence for non-metals only.
  28129. *
  28130. * @type {Color}
  28131. * @default (1,1,1)
  28132. */
  28133. this.specularColor = new Color( 1, 1, 1 );
  28134. /**
  28135. * The RGB channels of this texture are multiplied against `specularColor`,
  28136. * for per-pixel control over specular color.
  28137. *
  28138. * @type {?Texture}
  28139. * @default null
  28140. */
  28141. this.specularColorMap = null;
  28142. this._anisotropy = 0;
  28143. this._clearcoat = 0;
  28144. this._dispersion = 0;
  28145. this._iridescence = 0;
  28146. this._sheen = 0.0;
  28147. this._transmission = 0;
  28148. this.setValues( parameters );
  28149. }
  28150. /**
  28151. * The anisotropy strength, from `0.0` to `1.0`.
  28152. *
  28153. * @type {number}
  28154. * @default 0
  28155. */
  28156. get anisotropy() {
  28157. return this._anisotropy;
  28158. }
  28159. set anisotropy( value ) {
  28160. if ( this._anisotropy > 0 !== value > 0 ) {
  28161. this.version ++;
  28162. }
  28163. this._anisotropy = value;
  28164. }
  28165. /**
  28166. * Represents the intensity of the clear coat layer, from `0.0` to `1.0`. Use
  28167. * clear coat related properties to enable multilayer materials that have a
  28168. * thin translucent layer over the base layer.
  28169. *
  28170. * @type {number}
  28171. * @default 0
  28172. */
  28173. get clearcoat() {
  28174. return this._clearcoat;
  28175. }
  28176. set clearcoat( value ) {
  28177. if ( this._clearcoat > 0 !== value > 0 ) {
  28178. this.version ++;
  28179. }
  28180. this._clearcoat = value;
  28181. }
  28182. /**
  28183. * The intensity of the iridescence layer, simulating RGB color shift based on the angle between
  28184. * the surface and the viewer, from `0.0` to `1.0`.
  28185. *
  28186. * @type {number}
  28187. * @default 0
  28188. */
  28189. get iridescence() {
  28190. return this._iridescence;
  28191. }
  28192. set iridescence( value ) {
  28193. if ( this._iridescence > 0 !== value > 0 ) {
  28194. this.version ++;
  28195. }
  28196. this._iridescence = value;
  28197. }
  28198. /**
  28199. * Defines the strength of the angular separation of colors (chromatic aberration) transmitting
  28200. * through a relatively clear volume. Any value zero or larger is valid, the typical range of
  28201. * realistic values is `[0, 1]`. This property can be only be used with transmissive objects.
  28202. *
  28203. * @type {number}
  28204. * @default 0
  28205. */
  28206. get dispersion() {
  28207. return this._dispersion;
  28208. }
  28209. set dispersion( value ) {
  28210. if ( this._dispersion > 0 !== value > 0 ) {
  28211. this.version ++;
  28212. }
  28213. this._dispersion = value;
  28214. }
  28215. /**
  28216. * The intensity of the sheen layer, from `0.0` to `1.0`.
  28217. *
  28218. * @type {number}
  28219. * @default 0
  28220. */
  28221. get sheen() {
  28222. return this._sheen;
  28223. }
  28224. set sheen( value ) {
  28225. if ( this._sheen > 0 !== value > 0 ) {
  28226. this.version ++;
  28227. }
  28228. this._sheen = value;
  28229. }
  28230. /**
  28231. * Degree of transmission (or optical transparency), from `0.0` to `1.0`.
  28232. *
  28233. * Thin, transparent or semitransparent, plastic or glass materials remain
  28234. * largely reflective even if they are fully transmissive. The transmission
  28235. * property can be used to model these materials.
  28236. *
  28237. * When transmission is non-zero, `opacity` should be set to `1`.
  28238. *
  28239. * @type {number}
  28240. * @default 0
  28241. */
  28242. get transmission() {
  28243. return this._transmission;
  28244. }
  28245. set transmission( value ) {
  28246. if ( this._transmission > 0 !== value > 0 ) {
  28247. this.version ++;
  28248. }
  28249. this._transmission = value;
  28250. }
  28251. copy( source ) {
  28252. super.copy( source );
  28253. this.defines = {
  28254. 'STANDARD': '',
  28255. 'PHYSICAL': ''
  28256. };
  28257. this.anisotropy = source.anisotropy;
  28258. this.anisotropyRotation = source.anisotropyRotation;
  28259. this.anisotropyMap = source.anisotropyMap;
  28260. this.clearcoat = source.clearcoat;
  28261. this.clearcoatMap = source.clearcoatMap;
  28262. this.clearcoatRoughness = source.clearcoatRoughness;
  28263. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  28264. this.clearcoatNormalMap = source.clearcoatNormalMap;
  28265. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  28266. this.dispersion = source.dispersion;
  28267. this.ior = source.ior;
  28268. this.iridescence = source.iridescence;
  28269. this.iridescenceMap = source.iridescenceMap;
  28270. this.iridescenceIOR = source.iridescenceIOR;
  28271. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  28272. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  28273. this.sheen = source.sheen;
  28274. this.sheenColor.copy( source.sheenColor );
  28275. this.sheenColorMap = source.sheenColorMap;
  28276. this.sheenRoughness = source.sheenRoughness;
  28277. this.sheenRoughnessMap = source.sheenRoughnessMap;
  28278. this.transmission = source.transmission;
  28279. this.transmissionMap = source.transmissionMap;
  28280. this.thickness = source.thickness;
  28281. this.thicknessMap = source.thicknessMap;
  28282. this.attenuationDistance = source.attenuationDistance;
  28283. this.attenuationColor.copy( source.attenuationColor );
  28284. this.specularIntensity = source.specularIntensity;
  28285. this.specularIntensityMap = source.specularIntensityMap;
  28286. this.specularColor.copy( source.specularColor );
  28287. this.specularColorMap = source.specularColorMap;
  28288. return this;
  28289. }
  28290. }
  28291. /**
  28292. * A material for shiny surfaces with specular highlights.
  28293. *
  28294. * The material uses a non-physically based [Blinn-Phong](https://en.wikipedia.org/wiki/Blinn-Phong_shading_model)
  28295. * model for calculating reflectance. Unlike the Lambertian model used in the
  28296. * {@link MeshLambertMaterial} this can simulate shiny surfaces with specular
  28297. * highlights (such as varnished wood). `MeshPhongMaterial` uses per-fragment shading.
  28298. *
  28299. * Performance will generally be greater when using this material over the
  28300. * {@link MeshStandardMaterial} or {@link MeshPhysicalMaterial}, at the cost of
  28301. * some graphical accuracy.
  28302. *
  28303. * @augments Material
  28304. * @demo scenes/material-browser.html#MeshPhongMaterial
  28305. */
  28306. class MeshPhongMaterial extends Material {
  28307. /**
  28308. * Constructs a new mesh phong material.
  28309. *
  28310. * @param {Object} [parameters] - An object with one or more properties
  28311. * defining the material's appearance. Any property of the material
  28312. * (including any property from inherited materials) can be passed
  28313. * in here. Color values can be passed any type of value accepted
  28314. * by {@link Color#set}.
  28315. */
  28316. constructor( parameters ) {
  28317. super();
  28318. /**
  28319. * This flag can be used for type testing.
  28320. *
  28321. * @type {boolean}
  28322. * @readonly
  28323. * @default true
  28324. */
  28325. this.isMeshPhongMaterial = true;
  28326. this.type = 'MeshPhongMaterial';
  28327. /**
  28328. * Color of the material.
  28329. *
  28330. * @type {Color}
  28331. * @default (1,1,1)
  28332. */
  28333. this.color = new Color( 0xffffff ); // diffuse
  28334. /**
  28335. * Specular color of the material. The default color is set to `0x111111` (very dark grey)
  28336. *
  28337. * This defines how shiny the material is and the color of its shine.
  28338. *
  28339. * @type {Color}
  28340. */
  28341. this.specular = new Color( 0x111111 );
  28342. /**
  28343. * How shiny the specular highlight is; a higher value gives a sharper highlight.
  28344. *
  28345. * @type {number}
  28346. * @default 30
  28347. */
  28348. this.shininess = 30;
  28349. /**
  28350. * The color map. May optionally include an alpha channel, typically combined
  28351. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28352. * color is modulated by the diffuse `color`.
  28353. *
  28354. * @type {?Texture}
  28355. * @default null
  28356. */
  28357. this.map = null;
  28358. /**
  28359. * The light map. Requires a second set of UVs.
  28360. *
  28361. * @type {?Texture}
  28362. * @default null
  28363. */
  28364. this.lightMap = null;
  28365. /**
  28366. * Intensity of the baked light.
  28367. *
  28368. * @type {number}
  28369. * @default 1
  28370. */
  28371. this.lightMapIntensity = 1.0;
  28372. /**
  28373. * The red channel of this texture is used as the ambient occlusion map.
  28374. * Requires a second set of UVs.
  28375. *
  28376. * @type {?Texture}
  28377. * @default null
  28378. */
  28379. this.aoMap = null;
  28380. /**
  28381. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28382. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28383. * red channel is also `1`, ambient light is fully occluded on a surface.
  28384. *
  28385. * @type {number}
  28386. * @default 1
  28387. */
  28388. this.aoMapIntensity = 1.0;
  28389. /**
  28390. * Emissive (light) color of the material, essentially a solid color
  28391. * unaffected by other lighting.
  28392. *
  28393. * @type {Color}
  28394. * @default (0,0,0)
  28395. */
  28396. this.emissive = new Color( 0x000000 );
  28397. /**
  28398. * Intensity of the emissive light. Modulates the emissive color.
  28399. *
  28400. * @type {number}
  28401. * @default 1
  28402. */
  28403. this.emissiveIntensity = 1.0;
  28404. /**
  28405. * Set emissive (glow) map. The emissive map color is modulated by the
  28406. * emissive color and the emissive intensity. If you have an emissive map,
  28407. * be sure to set the emissive color to something other than black.
  28408. *
  28409. * @type {?Texture}
  28410. * @default null
  28411. */
  28412. this.emissiveMap = null;
  28413. /**
  28414. * The texture to create a bump map. The black and white values map to the
  28415. * perceived depth in relation to the lights. Bump doesn't actually affect
  28416. * the geometry of the object, only the lighting. If a normal map is defined
  28417. * this will be ignored.
  28418. *
  28419. * @type {?Texture}
  28420. * @default null
  28421. */
  28422. this.bumpMap = null;
  28423. /**
  28424. * How much the bump map affects the material. Typical range is `[0,1]`.
  28425. *
  28426. * @type {number}
  28427. * @default 1
  28428. */
  28429. this.bumpScale = 1;
  28430. /**
  28431. * The texture to create a normal map. The RGB values affect the surface
  28432. * normal for each pixel fragment and change the way the color is lit. Normal
  28433. * maps do not change the actual shape of the surface, only the lighting. In
  28434. * case the material has a normal map authored using the left handed
  28435. * convention, the `y` component of `normalScale` should be negated to compensate
  28436. * for the different handedness.
  28437. *
  28438. * @type {?Texture}
  28439. * @default null
  28440. */
  28441. this.normalMap = null;
  28442. /**
  28443. * The type of normal map.
  28444. *
  28445. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28446. * @default TangentSpaceNormalMap
  28447. */
  28448. this.normalMapType = TangentSpaceNormalMap;
  28449. /**
  28450. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28451. *
  28452. * @type {Vector2}
  28453. * @default (1,1)
  28454. */
  28455. this.normalScale = new Vector2( 1, 1 );
  28456. /**
  28457. * The displacement map affects the position of the mesh's vertices. Unlike
  28458. * other maps which only affect the light and shade of the material the
  28459. * displaced vertices can cast shadows, block other objects, and otherwise
  28460. * act as real geometry. The displacement texture is an image where the value
  28461. * of each pixel (white being the highest) is mapped against, and
  28462. * repositions, the vertices of the mesh.
  28463. *
  28464. * @type {?Texture}
  28465. * @default null
  28466. */
  28467. this.displacementMap = null;
  28468. /**
  28469. * How much the displacement map affects the mesh (where black is no
  28470. * displacement, and white is maximum displacement). Without a displacement
  28471. * map set, this value is not applied.
  28472. *
  28473. * @type {number}
  28474. * @default 0
  28475. */
  28476. this.displacementScale = 1;
  28477. /**
  28478. * The offset of the displacement map's values on the mesh's vertices.
  28479. * The bias is added to the scaled sample of the displacement map.
  28480. * Without a displacement map set, this value is not applied.
  28481. *
  28482. * @type {number}
  28483. * @default 0
  28484. */
  28485. this.displacementBias = 0;
  28486. /**
  28487. * The specular map value affects both how much the specular surface
  28488. * highlight contributes and how much of the environment map affects the
  28489. * surface.
  28490. *
  28491. * @type {?Texture}
  28492. * @default null
  28493. */
  28494. this.specularMap = null;
  28495. /**
  28496. * The alpha map is a grayscale texture that controls the opacity across the
  28497. * surface (black: fully transparent; white: fully opaque).
  28498. *
  28499. * Only the color of the texture is used, ignoring the alpha channel if one
  28500. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28501. * when sampling this texture due to the extra bit of precision provided for
  28502. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28503. * luminance/alpha textures will also still work as expected.
  28504. *
  28505. * @type {?Texture}
  28506. * @default null
  28507. */
  28508. this.alphaMap = null;
  28509. /**
  28510. * The environment map.
  28511. *
  28512. * @type {?Texture}
  28513. * @default null
  28514. */
  28515. this.envMap = null;
  28516. /**
  28517. * The rotation of the environment map in radians.
  28518. *
  28519. * @type {Euler}
  28520. * @default (0,0,0)
  28521. */
  28522. this.envMapRotation = new Euler();
  28523. /**
  28524. * How to combine the result of the surface's color with the environment map, if any.
  28525. *
  28526. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  28527. * blend between the two colors.
  28528. *
  28529. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  28530. * @default MultiplyOperation
  28531. */
  28532. this.combine = MultiplyOperation;
  28533. /**
  28534. * How much the environment map affects the surface.
  28535. * The valid range is between `0` (no reflections) and `1` (full reflections).
  28536. *
  28537. * @type {number}
  28538. * @default 1
  28539. */
  28540. this.reflectivity = 1;
  28541. /**
  28542. * Scales the effect of the environment map by multiplying its color.
  28543. *
  28544. * @type {number}
  28545. * @default 1
  28546. */
  28547. this.envMapIntensity = 1.0;
  28548. /**
  28549. * The index of refraction (IOR) of air (approximately 1) divided by the
  28550. * index of refraction of the material. It is used with environment mapping
  28551. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  28552. * The refraction ratio should not exceed `1`.
  28553. *
  28554. * @type {number}
  28555. * @default 0.98
  28556. */
  28557. this.refractionRatio = 0.98;
  28558. /**
  28559. * Renders the geometry as a wireframe.
  28560. *
  28561. * @type {boolean}
  28562. * @default false
  28563. */
  28564. this.wireframe = false;
  28565. /**
  28566. * Controls the thickness of the wireframe.
  28567. *
  28568. * Can only be used with {@link SVGRenderer}.
  28569. *
  28570. * @type {number}
  28571. * @default 1
  28572. */
  28573. this.wireframeLinewidth = 1;
  28574. /**
  28575. * Defines appearance of wireframe ends.
  28576. *
  28577. * Can only be used with {@link SVGRenderer}.
  28578. *
  28579. * @type {('round'|'bevel'|'miter')}
  28580. * @default 'round'
  28581. */
  28582. this.wireframeLinecap = 'round';
  28583. /**
  28584. * Defines appearance of wireframe joints.
  28585. *
  28586. * Can only be used with {@link SVGRenderer}.
  28587. *
  28588. * @type {('round'|'bevel'|'miter')}
  28589. * @default 'round'
  28590. */
  28591. this.wireframeLinejoin = 'round';
  28592. /**
  28593. * Whether the material is rendered with flat shading or not.
  28594. *
  28595. * @type {boolean}
  28596. * @default false
  28597. */
  28598. this.flatShading = false;
  28599. /**
  28600. * Whether the material is affected by fog or not.
  28601. *
  28602. * @type {boolean}
  28603. * @default true
  28604. */
  28605. this.fog = true;
  28606. this.setValues( parameters );
  28607. }
  28608. copy( source ) {
  28609. super.copy( source );
  28610. this.color.copy( source.color );
  28611. this.specular.copy( source.specular );
  28612. this.shininess = source.shininess;
  28613. this.map = source.map;
  28614. this.lightMap = source.lightMap;
  28615. this.lightMapIntensity = source.lightMapIntensity;
  28616. this.aoMap = source.aoMap;
  28617. this.aoMapIntensity = source.aoMapIntensity;
  28618. this.emissive.copy( source.emissive );
  28619. this.emissiveMap = source.emissiveMap;
  28620. this.emissiveIntensity = source.emissiveIntensity;
  28621. this.bumpMap = source.bumpMap;
  28622. this.bumpScale = source.bumpScale;
  28623. this.normalMap = source.normalMap;
  28624. this.normalMapType = source.normalMapType;
  28625. this.normalScale.copy( source.normalScale );
  28626. this.displacementMap = source.displacementMap;
  28627. this.displacementScale = source.displacementScale;
  28628. this.displacementBias = source.displacementBias;
  28629. this.specularMap = source.specularMap;
  28630. this.alphaMap = source.alphaMap;
  28631. this.envMap = source.envMap;
  28632. this.envMapRotation.copy( source.envMapRotation );
  28633. this.combine = source.combine;
  28634. this.reflectivity = source.reflectivity;
  28635. this.envMapIntensity = source.envMapIntensity;
  28636. this.refractionRatio = source.refractionRatio;
  28637. this.wireframe = source.wireframe;
  28638. this.wireframeLinewidth = source.wireframeLinewidth;
  28639. this.wireframeLinecap = source.wireframeLinecap;
  28640. this.wireframeLinejoin = source.wireframeLinejoin;
  28641. this.flatShading = source.flatShading;
  28642. this.fog = source.fog;
  28643. return this;
  28644. }
  28645. }
  28646. /**
  28647. * A material implementing toon shading.
  28648. *
  28649. * @augments Material
  28650. * @demo scenes/material-browser.html#MeshToonMaterial
  28651. */
  28652. class MeshToonMaterial extends Material {
  28653. /**
  28654. * Constructs a new mesh toon material.
  28655. *
  28656. * @param {Object} [parameters] - An object with one or more properties
  28657. * defining the material's appearance. Any property of the material
  28658. * (including any property from inherited materials) can be passed
  28659. * in here. Color values can be passed any type of value accepted
  28660. * by {@link Color#set}.
  28661. */
  28662. constructor( parameters ) {
  28663. super();
  28664. /**
  28665. * This flag can be used for type testing.
  28666. *
  28667. * @type {boolean}
  28668. * @readonly
  28669. * @default true
  28670. */
  28671. this.isMeshToonMaterial = true;
  28672. this.defines = { 'TOON': '' };
  28673. this.type = 'MeshToonMaterial';
  28674. /**
  28675. * Color of the material.
  28676. *
  28677. * @type {Color}
  28678. * @default (1,1,1)
  28679. */
  28680. this.color = new Color( 0xffffff );
  28681. /**
  28682. * The color map. May optionally include an alpha channel, typically combined
  28683. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28684. * color is modulated by the diffuse `color`.
  28685. *
  28686. * @type {?Texture}
  28687. * @default null
  28688. */
  28689. this.map = null;
  28690. /**
  28691. * Gradient map for toon shading. It's required to set
  28692. * {@link Texture#minFilter} and {@link Texture#magFilter} to {@link NearestFilter}
  28693. * when using this type of texture.
  28694. *
  28695. * @type {?Texture}
  28696. * @default null
  28697. */
  28698. this.gradientMap = null;
  28699. /**
  28700. * The light map. Requires a second set of UVs.
  28701. *
  28702. * @type {?Texture}
  28703. * @default null
  28704. */
  28705. this.lightMap = null;
  28706. /**
  28707. * Intensity of the baked light.
  28708. *
  28709. * @type {number}
  28710. * @default 1
  28711. */
  28712. this.lightMapIntensity = 1.0;
  28713. /**
  28714. * The red channel of this texture is used as the ambient occlusion map.
  28715. * Requires a second set of UVs.
  28716. *
  28717. * @type {?Texture}
  28718. * @default null
  28719. */
  28720. this.aoMap = null;
  28721. /**
  28722. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28723. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28724. * red channel is also `1`, ambient light is fully occluded on a surface.
  28725. *
  28726. * @type {number}
  28727. * @default 1
  28728. */
  28729. this.aoMapIntensity = 1.0;
  28730. /**
  28731. * Emissive (light) color of the material, essentially a solid color
  28732. * unaffected by other lighting.
  28733. *
  28734. * @type {Color}
  28735. * @default (0,0,0)
  28736. */
  28737. this.emissive = new Color( 0x000000 );
  28738. /**
  28739. * Intensity of the emissive light. Modulates the emissive color.
  28740. *
  28741. * @type {number}
  28742. * @default 1
  28743. */
  28744. this.emissiveIntensity = 1.0;
  28745. /**
  28746. * Set emissive (glow) map. The emissive map color is modulated by the
  28747. * emissive color and the emissive intensity. If you have an emissive map,
  28748. * be sure to set the emissive color to something other than black.
  28749. *
  28750. * @type {?Texture}
  28751. * @default null
  28752. */
  28753. this.emissiveMap = null;
  28754. /**
  28755. * The texture to create a bump map. The black and white values map to the
  28756. * perceived depth in relation to the lights. Bump doesn't actually affect
  28757. * the geometry of the object, only the lighting. If a normal map is defined
  28758. * this will be ignored.
  28759. *
  28760. * @type {?Texture}
  28761. * @default null
  28762. */
  28763. this.bumpMap = null;
  28764. /**
  28765. * How much the bump map affects the material. Typical range is `[0,1]`.
  28766. *
  28767. * @type {number}
  28768. * @default 1
  28769. */
  28770. this.bumpScale = 1;
  28771. /**
  28772. * The texture to create a normal map. The RGB values affect the surface
  28773. * normal for each pixel fragment and change the way the color is lit. Normal
  28774. * maps do not change the actual shape of the surface, only the lighting. In
  28775. * case the material has a normal map authored using the left handed
  28776. * convention, the `y` component of `normalScale` should be negated to compensate
  28777. * for the different handedness.
  28778. *
  28779. * @type {?Texture}
  28780. * @default null
  28781. */
  28782. this.normalMap = null;
  28783. /**
  28784. * The type of normal map.
  28785. *
  28786. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28787. * @default TangentSpaceNormalMap
  28788. */
  28789. this.normalMapType = TangentSpaceNormalMap;
  28790. /**
  28791. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28792. *
  28793. * @type {Vector2}
  28794. * @default (1,1)
  28795. */
  28796. this.normalScale = new Vector2( 1, 1 );
  28797. /**
  28798. * The displacement map affects the position of the mesh's vertices. Unlike
  28799. * other maps which only affect the light and shade of the material the
  28800. * displaced vertices can cast shadows, block other objects, and otherwise
  28801. * act as real geometry. The displacement texture is an image where the value
  28802. * of each pixel (white being the highest) is mapped against, and
  28803. * repositions, the vertices of the mesh.
  28804. *
  28805. * @type {?Texture}
  28806. * @default null
  28807. */
  28808. this.displacementMap = null;
  28809. /**
  28810. * How much the displacement map affects the mesh (where black is no
  28811. * displacement, and white is maximum displacement). Without a displacement
  28812. * map set, this value is not applied.
  28813. *
  28814. * @type {number}
  28815. * @default 0
  28816. */
  28817. this.displacementScale = 1;
  28818. /**
  28819. * The offset of the displacement map's values on the mesh's vertices.
  28820. * The bias is added to the scaled sample of the displacement map.
  28821. * Without a displacement map set, this value is not applied.
  28822. *
  28823. * @type {number}
  28824. * @default 0
  28825. */
  28826. this.displacementBias = 0;
  28827. /**
  28828. * The alpha map is a grayscale texture that controls the opacity across the
  28829. * surface (black: fully transparent; white: fully opaque).
  28830. *
  28831. * Only the color of the texture is used, ignoring the alpha channel if one
  28832. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28833. * when sampling this texture due to the extra bit of precision provided for
  28834. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28835. * luminance/alpha textures will also still work as expected.
  28836. *
  28837. * @type {?Texture}
  28838. * @default null
  28839. */
  28840. this.alphaMap = null;
  28841. /**
  28842. * Renders the geometry as a wireframe.
  28843. *
  28844. * @type {boolean}
  28845. * @default false
  28846. */
  28847. this.wireframe = false;
  28848. /**
  28849. * Controls the thickness of the wireframe.
  28850. *
  28851. * Can only be used with {@link SVGRenderer}.
  28852. *
  28853. * @type {number}
  28854. * @default 1
  28855. */
  28856. this.wireframeLinewidth = 1;
  28857. /**
  28858. * Defines appearance of wireframe ends.
  28859. *
  28860. * Can only be used with {@link SVGRenderer}.
  28861. *
  28862. * @type {('round'|'bevel'|'miter')}
  28863. * @default 'round'
  28864. */
  28865. this.wireframeLinecap = 'round';
  28866. /**
  28867. * Defines appearance of wireframe joints.
  28868. *
  28869. * Can only be used with {@link SVGRenderer}.
  28870. *
  28871. * @type {('round'|'bevel'|'miter')}
  28872. * @default 'round'
  28873. */
  28874. this.wireframeLinejoin = 'round';
  28875. /**
  28876. * Whether the material is affected by fog or not.
  28877. *
  28878. * @type {boolean}
  28879. * @default true
  28880. */
  28881. this.fog = true;
  28882. this.setValues( parameters );
  28883. }
  28884. copy( source ) {
  28885. super.copy( source );
  28886. this.color.copy( source.color );
  28887. this.map = source.map;
  28888. this.gradientMap = source.gradientMap;
  28889. this.lightMap = source.lightMap;
  28890. this.lightMapIntensity = source.lightMapIntensity;
  28891. this.aoMap = source.aoMap;
  28892. this.aoMapIntensity = source.aoMapIntensity;
  28893. this.emissive.copy( source.emissive );
  28894. this.emissiveMap = source.emissiveMap;
  28895. this.emissiveIntensity = source.emissiveIntensity;
  28896. this.bumpMap = source.bumpMap;
  28897. this.bumpScale = source.bumpScale;
  28898. this.normalMap = source.normalMap;
  28899. this.normalMapType = source.normalMapType;
  28900. this.normalScale.copy( source.normalScale );
  28901. this.displacementMap = source.displacementMap;
  28902. this.displacementScale = source.displacementScale;
  28903. this.displacementBias = source.displacementBias;
  28904. this.alphaMap = source.alphaMap;
  28905. this.wireframe = source.wireframe;
  28906. this.wireframeLinewidth = source.wireframeLinewidth;
  28907. this.wireframeLinecap = source.wireframeLinecap;
  28908. this.wireframeLinejoin = source.wireframeLinejoin;
  28909. this.fog = source.fog;
  28910. return this;
  28911. }
  28912. }
  28913. /**
  28914. * A material that maps the normal vectors to RGB colors.
  28915. *
  28916. * @augments Material
  28917. * @demo scenes/material-browser.html#MeshNormalMaterial
  28918. */
  28919. class MeshNormalMaterial extends Material {
  28920. /**
  28921. * Constructs a new mesh normal material.
  28922. *
  28923. * @param {Object} [parameters] - An object with one or more properties
  28924. * defining the material's appearance. Any property of the material
  28925. * (including any property from inherited materials) can be passed
  28926. * in here. Color values can be passed any type of value accepted
  28927. * by {@link Color#set}.
  28928. */
  28929. constructor( parameters ) {
  28930. super();
  28931. /**
  28932. * This flag can be used for type testing.
  28933. *
  28934. * @type {boolean}
  28935. * @readonly
  28936. * @default true
  28937. */
  28938. this.isMeshNormalMaterial = true;
  28939. this.type = 'MeshNormalMaterial';
  28940. /**
  28941. * The texture to create a bump map. The black and white values map to the
  28942. * perceived depth in relation to the lights. Bump doesn't actually affect
  28943. * the geometry of the object, only the lighting. If a normal map is defined
  28944. * this will be ignored.
  28945. *
  28946. * @type {?Texture}
  28947. * @default null
  28948. */
  28949. this.bumpMap = null;
  28950. /**
  28951. * How much the bump map affects the material. Typical range is `[0,1]`.
  28952. *
  28953. * @type {number}
  28954. * @default 1
  28955. */
  28956. this.bumpScale = 1;
  28957. /**
  28958. * The texture to create a normal map. The RGB values affect the surface
  28959. * normal for each pixel fragment and change the way the color is lit. Normal
  28960. * maps do not change the actual shape of the surface, only the lighting. In
  28961. * case the material has a normal map authored using the left handed
  28962. * convention, the `y` component of `normalScale` should be negated to compensate
  28963. * for the different handedness.
  28964. *
  28965. * @type {?Texture}
  28966. * @default null
  28967. */
  28968. this.normalMap = null;
  28969. /**
  28970. * The type of normal map.
  28971. *
  28972. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28973. * @default TangentSpaceNormalMap
  28974. */
  28975. this.normalMapType = TangentSpaceNormalMap;
  28976. /**
  28977. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28978. *
  28979. * @type {Vector2}
  28980. * @default (1,1)
  28981. */
  28982. this.normalScale = new Vector2( 1, 1 );
  28983. /**
  28984. * The displacement map affects the position of the mesh's vertices. Unlike
  28985. * other maps which only affect the light and shade of the material the
  28986. * displaced vertices can cast shadows, block other objects, and otherwise
  28987. * act as real geometry. The displacement texture is an image where the value
  28988. * of each pixel (white being the highest) is mapped against, and
  28989. * repositions, the vertices of the mesh.
  28990. *
  28991. * @type {?Texture}
  28992. * @default null
  28993. */
  28994. this.displacementMap = null;
  28995. /**
  28996. * How much the displacement map affects the mesh (where black is no
  28997. * displacement, and white is maximum displacement). Without a displacement
  28998. * map set, this value is not applied.
  28999. *
  29000. * @type {number}
  29001. * @default 0
  29002. */
  29003. this.displacementScale = 1;
  29004. /**
  29005. * The offset of the displacement map's values on the mesh's vertices.
  29006. * The bias is added to the scaled sample of the displacement map.
  29007. * Without a displacement map set, this value is not applied.
  29008. *
  29009. * @type {number}
  29010. * @default 0
  29011. */
  29012. this.displacementBias = 0;
  29013. /**
  29014. * Renders the geometry as a wireframe.
  29015. *
  29016. * @type {boolean}
  29017. * @default false
  29018. */
  29019. this.wireframe = false;
  29020. /**
  29021. * Controls the thickness of the wireframe.
  29022. *
  29023. * WebGL and WebGPU ignore this property and always render
  29024. * 1 pixel wide lines.
  29025. *
  29026. * @type {number}
  29027. * @default 1
  29028. */
  29029. this.wireframeLinewidth = 1;
  29030. /**
  29031. * Whether the material is rendered with flat shading or not.
  29032. *
  29033. * @type {boolean}
  29034. * @default false
  29035. */
  29036. this.flatShading = false;
  29037. this.setValues( parameters );
  29038. }
  29039. copy( source ) {
  29040. super.copy( source );
  29041. this.bumpMap = source.bumpMap;
  29042. this.bumpScale = source.bumpScale;
  29043. this.normalMap = source.normalMap;
  29044. this.normalMapType = source.normalMapType;
  29045. this.normalScale.copy( source.normalScale );
  29046. this.displacementMap = source.displacementMap;
  29047. this.displacementScale = source.displacementScale;
  29048. this.displacementBias = source.displacementBias;
  29049. this.wireframe = source.wireframe;
  29050. this.wireframeLinewidth = source.wireframeLinewidth;
  29051. this.flatShading = source.flatShading;
  29052. return this;
  29053. }
  29054. }
  29055. /**
  29056. * A material for non-shiny surfaces, without specular highlights.
  29057. *
  29058. * The material uses a non-physically based [Lambertian](https://en.wikipedia.org/wiki/Lambertian_reflectance)
  29059. * model for calculating reflectance. This can simulate some surfaces (such
  29060. * as untreated wood or stone) well, but cannot simulate shiny surfaces with
  29061. * specular highlights (such as varnished wood). `MeshLambertMaterial` uses per-fragment
  29062. * shading.
  29063. *
  29064. * Due to the simplicity of the reflectance and illumination models,
  29065. * performance will be greater when using this material over the
  29066. * {@link MeshPhongMaterial}, {@link MeshStandardMaterial} or
  29067. * {@link MeshPhysicalMaterial}, at the cost of some graphical accuracy.
  29068. *
  29069. * @augments Material
  29070. * @demo scenes/material-browser.html#MeshLambertMaterial
  29071. */
  29072. class MeshLambertMaterial extends Material {
  29073. /**
  29074. * Constructs a new mesh lambert material.
  29075. *
  29076. * @param {Object} [parameters] - An object with one or more properties
  29077. * defining the material's appearance. Any property of the material
  29078. * (including any property from inherited materials) can be passed
  29079. * in here. Color values can be passed any type of value accepted
  29080. * by {@link Color#set}.
  29081. */
  29082. constructor( parameters ) {
  29083. super();
  29084. /**
  29085. * This flag can be used for type testing.
  29086. *
  29087. * @type {boolean}
  29088. * @readonly
  29089. * @default true
  29090. */
  29091. this.isMeshLambertMaterial = true;
  29092. this.type = 'MeshLambertMaterial';
  29093. /**
  29094. * Color of the material.
  29095. *
  29096. * @type {Color}
  29097. * @default (1,1,1)
  29098. */
  29099. this.color = new Color( 0xffffff ); // diffuse
  29100. /**
  29101. * The color map. May optionally include an alpha channel, typically combined
  29102. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29103. * color is modulated by the diffuse `color`.
  29104. *
  29105. * @type {?Texture}
  29106. * @default null
  29107. */
  29108. this.map = null;
  29109. /**
  29110. * The light map. Requires a second set of UVs.
  29111. *
  29112. * @type {?Texture}
  29113. * @default null
  29114. */
  29115. this.lightMap = null;
  29116. /**
  29117. * Intensity of the baked light.
  29118. *
  29119. * @type {number}
  29120. * @default 1
  29121. */
  29122. this.lightMapIntensity = 1.0;
  29123. /**
  29124. * The red channel of this texture is used as the ambient occlusion map.
  29125. * Requires a second set of UVs.
  29126. *
  29127. * @type {?Texture}
  29128. * @default null
  29129. */
  29130. this.aoMap = null;
  29131. /**
  29132. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29133. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29134. * red channel is also `1`, ambient light is fully occluded on a surface.
  29135. *
  29136. * @type {number}
  29137. * @default 1
  29138. */
  29139. this.aoMapIntensity = 1.0;
  29140. /**
  29141. * Emissive (light) color of the material, essentially a solid color
  29142. * unaffected by other lighting.
  29143. *
  29144. * @type {Color}
  29145. * @default (0,0,0)
  29146. */
  29147. this.emissive = new Color( 0x000000 );
  29148. /**
  29149. * Intensity of the emissive light. Modulates the emissive color.
  29150. *
  29151. * @type {number}
  29152. * @default 1
  29153. */
  29154. this.emissiveIntensity = 1.0;
  29155. /**
  29156. * Set emissive (glow) map. The emissive map color is modulated by the
  29157. * emissive color and the emissive intensity. If you have an emissive map,
  29158. * be sure to set the emissive color to something other than black.
  29159. *
  29160. * @type {?Texture}
  29161. * @default null
  29162. */
  29163. this.emissiveMap = null;
  29164. /**
  29165. * The texture to create a bump map. The black and white values map to the
  29166. * perceived depth in relation to the lights. Bump doesn't actually affect
  29167. * the geometry of the object, only the lighting. If a normal map is defined
  29168. * this will be ignored.
  29169. *
  29170. * @type {?Texture}
  29171. * @default null
  29172. */
  29173. this.bumpMap = null;
  29174. /**
  29175. * How much the bump map affects the material. Typical range is `[0,1]`.
  29176. *
  29177. * @type {number}
  29178. * @default 1
  29179. */
  29180. this.bumpScale = 1;
  29181. /**
  29182. * The texture to create a normal map. The RGB values affect the surface
  29183. * normal for each pixel fragment and change the way the color is lit. Normal
  29184. * maps do not change the actual shape of the surface, only the lighting. In
  29185. * case the material has a normal map authored using the left handed
  29186. * convention, the `y` component of `normalScale` should be negated to compensate
  29187. * for the different handedness.
  29188. *
  29189. * @type {?Texture}
  29190. * @default null
  29191. */
  29192. this.normalMap = null;
  29193. /**
  29194. * The type of normal map.
  29195. *
  29196. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29197. * @default TangentSpaceNormalMap
  29198. */
  29199. this.normalMapType = TangentSpaceNormalMap;
  29200. /**
  29201. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29202. *
  29203. * @type {Vector2}
  29204. * @default (1,1)
  29205. */
  29206. this.normalScale = new Vector2( 1, 1 );
  29207. /**
  29208. * The displacement map affects the position of the mesh's vertices. Unlike
  29209. * other maps which only affect the light and shade of the material the
  29210. * displaced vertices can cast shadows, block other objects, and otherwise
  29211. * act as real geometry. The displacement texture is an image where the value
  29212. * of each pixel (white being the highest) is mapped against, and
  29213. * repositions, the vertices of the mesh.
  29214. *
  29215. * @type {?Texture}
  29216. * @default null
  29217. */
  29218. this.displacementMap = null;
  29219. /**
  29220. * How much the displacement map affects the mesh (where black is no
  29221. * displacement, and white is maximum displacement). Without a displacement
  29222. * map set, this value is not applied.
  29223. *
  29224. * @type {number}
  29225. * @default 0
  29226. */
  29227. this.displacementScale = 1;
  29228. /**
  29229. * The offset of the displacement map's values on the mesh's vertices.
  29230. * The bias is added to the scaled sample of the displacement map.
  29231. * Without a displacement map set, this value is not applied.
  29232. *
  29233. * @type {number}
  29234. * @default 0
  29235. */
  29236. this.displacementBias = 0;
  29237. /**
  29238. * Specular map used by the material.
  29239. *
  29240. * @type {?Texture}
  29241. * @default null
  29242. */
  29243. this.specularMap = null;
  29244. /**
  29245. * The alpha map is a grayscale texture that controls the opacity across the
  29246. * surface (black: fully transparent; white: fully opaque).
  29247. *
  29248. * Only the color of the texture is used, ignoring the alpha channel if one
  29249. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29250. * when sampling this texture due to the extra bit of precision provided for
  29251. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29252. * luminance/alpha textures will also still work as expected.
  29253. *
  29254. * @type {?Texture}
  29255. * @default null
  29256. */
  29257. this.alphaMap = null;
  29258. /**
  29259. * The environment map.
  29260. *
  29261. * @type {?Texture}
  29262. * @default null
  29263. */
  29264. this.envMap = null;
  29265. /**
  29266. * The rotation of the environment map in radians.
  29267. *
  29268. * @type {Euler}
  29269. * @default (0,0,0)
  29270. */
  29271. this.envMapRotation = new Euler();
  29272. /**
  29273. * How to combine the result of the surface's color with the environment map, if any.
  29274. *
  29275. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  29276. * blend between the two colors.
  29277. *
  29278. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  29279. * @default MultiplyOperation
  29280. */
  29281. this.combine = MultiplyOperation;
  29282. /**
  29283. * How much the environment map affects the surface.
  29284. * The valid range is between `0` (no reflections) and `1` (full reflections).
  29285. *
  29286. * @type {number}
  29287. * @default 1
  29288. */
  29289. this.reflectivity = 1;
  29290. /**
  29291. * Scales the effect of the environment map by multiplying its color.
  29292. *
  29293. * @type {number}
  29294. * @default 1
  29295. */
  29296. this.envMapIntensity = 1.0;
  29297. /**
  29298. * The index of refraction (IOR) of air (approximately 1) divided by the
  29299. * index of refraction of the material. It is used with environment mapping
  29300. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  29301. * The refraction ratio should not exceed `1`.
  29302. *
  29303. * @type {number}
  29304. * @default 0.98
  29305. */
  29306. this.refractionRatio = 0.98;
  29307. /**
  29308. * Renders the geometry as a wireframe.
  29309. *
  29310. * @type {boolean}
  29311. * @default false
  29312. */
  29313. this.wireframe = false;
  29314. /**
  29315. * Controls the thickness of the wireframe.
  29316. *
  29317. * Can only be used with {@link SVGRenderer}.
  29318. *
  29319. * @type {number}
  29320. * @default 1
  29321. */
  29322. this.wireframeLinewidth = 1;
  29323. /**
  29324. * Defines appearance of wireframe ends.
  29325. *
  29326. * Can only be used with {@link SVGRenderer}.
  29327. *
  29328. * @type {('round'|'bevel'|'miter')}
  29329. * @default 'round'
  29330. */
  29331. this.wireframeLinecap = 'round';
  29332. /**
  29333. * Defines appearance of wireframe joints.
  29334. *
  29335. * Can only be used with {@link SVGRenderer}.
  29336. *
  29337. * @type {('round'|'bevel'|'miter')}
  29338. * @default 'round'
  29339. */
  29340. this.wireframeLinejoin = 'round';
  29341. /**
  29342. * Whether the material is rendered with flat shading or not.
  29343. *
  29344. * @type {boolean}
  29345. * @default false
  29346. */
  29347. this.flatShading = false;
  29348. /**
  29349. * Whether the material is affected by fog or not.
  29350. *
  29351. * @type {boolean}
  29352. * @default true
  29353. */
  29354. this.fog = true;
  29355. this.setValues( parameters );
  29356. }
  29357. copy( source ) {
  29358. super.copy( source );
  29359. this.color.copy( source.color );
  29360. this.map = source.map;
  29361. this.lightMap = source.lightMap;
  29362. this.lightMapIntensity = source.lightMapIntensity;
  29363. this.aoMap = source.aoMap;
  29364. this.aoMapIntensity = source.aoMapIntensity;
  29365. this.emissive.copy( source.emissive );
  29366. this.emissiveMap = source.emissiveMap;
  29367. this.emissiveIntensity = source.emissiveIntensity;
  29368. this.bumpMap = source.bumpMap;
  29369. this.bumpScale = source.bumpScale;
  29370. this.normalMap = source.normalMap;
  29371. this.normalMapType = source.normalMapType;
  29372. this.normalScale.copy( source.normalScale );
  29373. this.displacementMap = source.displacementMap;
  29374. this.displacementScale = source.displacementScale;
  29375. this.displacementBias = source.displacementBias;
  29376. this.specularMap = source.specularMap;
  29377. this.alphaMap = source.alphaMap;
  29378. this.envMap = source.envMap;
  29379. this.envMapRotation.copy( source.envMapRotation );
  29380. this.combine = source.combine;
  29381. this.reflectivity = source.reflectivity;
  29382. this.envMapIntensity = source.envMapIntensity;
  29383. this.refractionRatio = source.refractionRatio;
  29384. this.wireframe = source.wireframe;
  29385. this.wireframeLinewidth = source.wireframeLinewidth;
  29386. this.wireframeLinecap = source.wireframeLinecap;
  29387. this.wireframeLinejoin = source.wireframeLinejoin;
  29388. this.flatShading = source.flatShading;
  29389. this.fog = source.fog;
  29390. return this;
  29391. }
  29392. }
  29393. /**
  29394. * A material for drawing geometry by depth. Depth is based off of the camera
  29395. * near and far plane. White is nearest, black is farthest.
  29396. *
  29397. * @augments Material
  29398. * @demo scenes/material-browser.html#MeshDepthMaterial
  29399. */
  29400. class MeshDepthMaterial extends Material {
  29401. /**
  29402. * Constructs a new mesh depth material.
  29403. *
  29404. * @param {Object} [parameters] - An object with one or more properties
  29405. * defining the material's appearance. Any property of the material
  29406. * (including any property from inherited materials) can be passed
  29407. * in here. Color values can be passed any type of value accepted
  29408. * by {@link Color#set}.
  29409. */
  29410. constructor( parameters ) {
  29411. super();
  29412. /**
  29413. * This flag can be used for type testing.
  29414. *
  29415. * @type {boolean}
  29416. * @readonly
  29417. * @default true
  29418. */
  29419. this.isMeshDepthMaterial = true;
  29420. this.type = 'MeshDepthMaterial';
  29421. /**
  29422. * Type for depth packing.
  29423. *
  29424. * @type {(BasicDepthPacking|RGBADepthPacking|RGBDepthPacking|RGDepthPacking)}
  29425. * @default BasicDepthPacking
  29426. */
  29427. this.depthPacking = BasicDepthPacking;
  29428. /**
  29429. * The color map. May optionally include an alpha channel, typically combined
  29430. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29431. *
  29432. * @type {?Texture}
  29433. * @default null
  29434. */
  29435. this.map = null;
  29436. /**
  29437. * The alpha map is a grayscale texture that controls the opacity across the
  29438. * surface (black: fully transparent; white: fully opaque).
  29439. *
  29440. * Only the color of the texture is used, ignoring the alpha channel if one
  29441. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29442. * when sampling this texture due to the extra bit of precision provided for
  29443. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29444. * luminance/alpha textures will also still work as expected.
  29445. *
  29446. * @type {?Texture}
  29447. * @default null
  29448. */
  29449. this.alphaMap = null;
  29450. /**
  29451. * The displacement map affects the position of the mesh's vertices. Unlike
  29452. * other maps which only affect the light and shade of the material the
  29453. * displaced vertices can cast shadows, block other objects, and otherwise
  29454. * act as real geometry. The displacement texture is an image where the value
  29455. * of each pixel (white being the highest) is mapped against, and
  29456. * repositions, the vertices of the mesh.
  29457. *
  29458. * @type {?Texture}
  29459. * @default null
  29460. */
  29461. this.displacementMap = null;
  29462. /**
  29463. * How much the displacement map affects the mesh (where black is no
  29464. * displacement, and white is maximum displacement). Without a displacement
  29465. * map set, this value is not applied.
  29466. *
  29467. * @type {number}
  29468. * @default 0
  29469. */
  29470. this.displacementScale = 1;
  29471. /**
  29472. * The offset of the displacement map's values on the mesh's vertices.
  29473. * The bias is added to the scaled sample of the displacement map.
  29474. * Without a displacement map set, this value is not applied.
  29475. *
  29476. * @type {number}
  29477. * @default 0
  29478. */
  29479. this.displacementBias = 0;
  29480. /**
  29481. * Renders the geometry as a wireframe.
  29482. *
  29483. * @type {boolean}
  29484. * @default false
  29485. */
  29486. this.wireframe = false;
  29487. /**
  29488. * Controls the thickness of the wireframe.
  29489. *
  29490. * WebGL and WebGPU ignore this property and always render
  29491. * 1 pixel wide lines.
  29492. *
  29493. * @type {number}
  29494. * @default 1
  29495. */
  29496. this.wireframeLinewidth = 1;
  29497. this.setValues( parameters );
  29498. }
  29499. copy( source ) {
  29500. super.copy( source );
  29501. this.depthPacking = source.depthPacking;
  29502. this.map = source.map;
  29503. this.alphaMap = source.alphaMap;
  29504. this.displacementMap = source.displacementMap;
  29505. this.displacementScale = source.displacementScale;
  29506. this.displacementBias = source.displacementBias;
  29507. this.wireframe = source.wireframe;
  29508. this.wireframeLinewidth = source.wireframeLinewidth;
  29509. return this;
  29510. }
  29511. }
  29512. /**
  29513. * A material used internally for implementing shadow mapping with
  29514. * point lights.
  29515. *
  29516. * Can also be used to customize the shadow casting of an object by assigning
  29517. * an instance of `MeshDistanceMaterial` to {@link Object3D#customDistanceMaterial}.
  29518. * The following examples demonstrates this approach in order to ensure
  29519. * transparent parts of objects do not cast shadows.
  29520. *
  29521. * @augments Material
  29522. */
  29523. class MeshDistanceMaterial extends Material {
  29524. /**
  29525. * Constructs a new mesh distance material.
  29526. *
  29527. * @param {Object} [parameters] - An object with one or more properties
  29528. * defining the material's appearance. Any property of the material
  29529. * (including any property from inherited materials) can be passed
  29530. * in here. Color values can be passed any type of value accepted
  29531. * by {@link Color#set}.
  29532. */
  29533. constructor( parameters ) {
  29534. super();
  29535. /**
  29536. * This flag can be used for type testing.
  29537. *
  29538. * @type {boolean}
  29539. * @readonly
  29540. * @default true
  29541. */
  29542. this.isMeshDistanceMaterial = true;
  29543. this.type = 'MeshDistanceMaterial';
  29544. /**
  29545. * The color map. May optionally include an alpha channel, typically combined
  29546. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29547. *
  29548. * @type {?Texture}
  29549. * @default null
  29550. */
  29551. this.map = null;
  29552. /**
  29553. * The alpha map is a grayscale texture that controls the opacity across the
  29554. * surface (black: fully transparent; white: fully opaque).
  29555. *
  29556. * Only the color of the texture is used, ignoring the alpha channel if one
  29557. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29558. * when sampling this texture due to the extra bit of precision provided for
  29559. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29560. * luminance/alpha textures will also still work as expected.
  29561. *
  29562. * @type {?Texture}
  29563. * @default null
  29564. */
  29565. this.alphaMap = null;
  29566. /**
  29567. * The displacement map affects the position of the mesh's vertices. Unlike
  29568. * other maps which only affect the light and shade of the material the
  29569. * displaced vertices can cast shadows, block other objects, and otherwise
  29570. * act as real geometry. The displacement texture is an image where the value
  29571. * of each pixel (white being the highest) is mapped against, and
  29572. * repositions, the vertices of the mesh.
  29573. *
  29574. * @type {?Texture}
  29575. * @default null
  29576. */
  29577. this.displacementMap = null;
  29578. /**
  29579. * How much the displacement map affects the mesh (where black is no
  29580. * displacement, and white is maximum displacement). Without a displacement
  29581. * map set, this value is not applied.
  29582. *
  29583. * @type {number}
  29584. * @default 0
  29585. */
  29586. this.displacementScale = 1;
  29587. /**
  29588. * The offset of the displacement map's values on the mesh's vertices.
  29589. * The bias is added to the scaled sample of the displacement map.
  29590. * Without a displacement map set, this value is not applied.
  29591. *
  29592. * @type {number}
  29593. * @default 0
  29594. */
  29595. this.displacementBias = 0;
  29596. this.setValues( parameters );
  29597. }
  29598. copy( source ) {
  29599. super.copy( source );
  29600. this.map = source.map;
  29601. this.alphaMap = source.alphaMap;
  29602. this.displacementMap = source.displacementMap;
  29603. this.displacementScale = source.displacementScale;
  29604. this.displacementBias = source.displacementBias;
  29605. return this;
  29606. }
  29607. }
  29608. /**
  29609. * This material is defined by a MatCap (or Lit Sphere) texture, which encodes the
  29610. * material color and shading.
  29611. *
  29612. * `MeshMatcapMaterial` does not respond to lights since the matcap image file encodes
  29613. * baked lighting. It will cast a shadow onto an object that receives shadows
  29614. * (and shadow clipping works), but it will not self-shadow or receive
  29615. * shadows.
  29616. *
  29617. * @augments Material
  29618. * @demo scenes/material-browser.html#MeshMatcapMaterial
  29619. */
  29620. class MeshMatcapMaterial extends Material {
  29621. /**
  29622. * Constructs a new mesh matcap material.
  29623. *
  29624. * @param {Object} [parameters] - An object with one or more properties
  29625. * defining the material's appearance. Any property of the material
  29626. * (including any property from inherited materials) can be passed
  29627. * in here. Color values can be passed any type of value accepted
  29628. * by {@link Color#set}.
  29629. */
  29630. constructor( parameters ) {
  29631. super();
  29632. /**
  29633. * This flag can be used for type testing.
  29634. *
  29635. * @type {boolean}
  29636. * @readonly
  29637. * @default true
  29638. */
  29639. this.isMeshMatcapMaterial = true;
  29640. this.defines = { 'MATCAP': '' };
  29641. this.type = 'MeshMatcapMaterial';
  29642. /**
  29643. * Color of the material.
  29644. *
  29645. * @type {Color}
  29646. * @default (1,1,1)
  29647. */
  29648. this.color = new Color( 0xffffff ); // diffuse
  29649. /**
  29650. * The matcap map.
  29651. *
  29652. * @type {?Texture}
  29653. * @default null
  29654. */
  29655. this.matcap = null;
  29656. /**
  29657. * The color map. May optionally include an alpha channel, typically combined
  29658. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29659. * color is modulated by the diffuse `color`.
  29660. *
  29661. * @type {?Texture}
  29662. * @default null
  29663. */
  29664. this.map = null;
  29665. /**
  29666. * The texture to create a bump map. The black and white values map to the
  29667. * perceived depth in relation to the lights. Bump doesn't actually affect
  29668. * the geometry of the object, only the lighting. If a normal map is defined
  29669. * this will be ignored.
  29670. *
  29671. * @type {?Texture}
  29672. * @default null
  29673. */
  29674. this.bumpMap = null;
  29675. /**
  29676. * How much the bump map affects the material. Typical range is `[0,1]`.
  29677. *
  29678. * @type {number}
  29679. * @default 1
  29680. */
  29681. this.bumpScale = 1;
  29682. /**
  29683. * The texture to create a normal map. The RGB values affect the surface
  29684. * normal for each pixel fragment and change the way the color is lit. Normal
  29685. * maps do not change the actual shape of the surface, only the lighting. In
  29686. * case the material has a normal map authored using the left handed
  29687. * convention, the `y` component of `normalScale` should be negated to compensate
  29688. * for the different handedness.
  29689. *
  29690. * @type {?Texture}
  29691. * @default null
  29692. */
  29693. this.normalMap = null;
  29694. /**
  29695. * The type of normal map.
  29696. *
  29697. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29698. * @default TangentSpaceNormalMap
  29699. */
  29700. this.normalMapType = TangentSpaceNormalMap;
  29701. /**
  29702. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29703. *
  29704. * @type {Vector2}
  29705. * @default (1,1)
  29706. */
  29707. this.normalScale = new Vector2( 1, 1 );
  29708. /**
  29709. * The displacement map affects the position of the mesh's vertices. Unlike
  29710. * other maps which only affect the light and shade of the material the
  29711. * displaced vertices can cast shadows, block other objects, and otherwise
  29712. * act as real geometry. The displacement texture is an image where the value
  29713. * of each pixel (white being the highest) is mapped against, and
  29714. * repositions, the vertices of the mesh.
  29715. *
  29716. * @type {?Texture}
  29717. * @default null
  29718. */
  29719. this.displacementMap = null;
  29720. /**
  29721. * How much the displacement map affects the mesh (where black is no
  29722. * displacement, and white is maximum displacement). Without a displacement
  29723. * map set, this value is not applied.
  29724. *
  29725. * @type {number}
  29726. * @default 0
  29727. */
  29728. this.displacementScale = 1;
  29729. /**
  29730. * The offset of the displacement map's values on the mesh's vertices.
  29731. * The bias is added to the scaled sample of the displacement map.
  29732. * Without a displacement map set, this value is not applied.
  29733. *
  29734. * @type {number}
  29735. * @default 0
  29736. */
  29737. this.displacementBias = 0;
  29738. /**
  29739. * The alpha map is a grayscale texture that controls the opacity across the
  29740. * surface (black: fully transparent; white: fully opaque).
  29741. *
  29742. * Only the color of the texture is used, ignoring the alpha channel if one
  29743. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29744. * when sampling this texture due to the extra bit of precision provided for
  29745. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29746. * luminance/alpha textures will also still work as expected.
  29747. *
  29748. * @type {?Texture}
  29749. * @default null
  29750. */
  29751. this.alphaMap = null;
  29752. /**
  29753. * Renders the geometry as a wireframe.
  29754. *
  29755. * @type {boolean}
  29756. * @default false
  29757. */
  29758. this.wireframe = false;
  29759. /**
  29760. * Controls the thickness of the wireframe.
  29761. *
  29762. * Can only be used with {@link SVGRenderer}.
  29763. *
  29764. * @type {number}
  29765. * @default 1
  29766. */
  29767. this.wireframeLinewidth = 1;
  29768. /**
  29769. * Whether the material is rendered with flat shading or not.
  29770. *
  29771. * @type {boolean}
  29772. * @default false
  29773. */
  29774. this.flatShading = false;
  29775. /**
  29776. * Whether the material is affected by fog or not.
  29777. *
  29778. * @type {boolean}
  29779. * @default true
  29780. */
  29781. this.fog = true;
  29782. this.setValues( parameters );
  29783. }
  29784. copy( source ) {
  29785. super.copy( source );
  29786. this.defines = { 'MATCAP': '' };
  29787. this.color.copy( source.color );
  29788. this.matcap = source.matcap;
  29789. this.map = source.map;
  29790. this.bumpMap = source.bumpMap;
  29791. this.bumpScale = source.bumpScale;
  29792. this.normalMap = source.normalMap;
  29793. this.normalMapType = source.normalMapType;
  29794. this.normalScale.copy( source.normalScale );
  29795. this.displacementMap = source.displacementMap;
  29796. this.displacementScale = source.displacementScale;
  29797. this.displacementBias = source.displacementBias;
  29798. this.alphaMap = source.alphaMap;
  29799. this.wireframe = source.wireframe;
  29800. this.wireframeLinewidth = source.wireframeLinewidth;
  29801. this.flatShading = source.flatShading;
  29802. this.fog = source.fog;
  29803. return this;
  29804. }
  29805. }
  29806. /**
  29807. * A material for rendering line primitives.
  29808. *
  29809. * Materials define the appearance of renderable 3D objects.
  29810. *
  29811. * ```js
  29812. * const material = new THREE.LineDashedMaterial( {
  29813. * color: 0xffffff,
  29814. * scale: 1,
  29815. * dashSize: 3,
  29816. * gapSize: 1,
  29817. * } );
  29818. * ```
  29819. *
  29820. * @augments LineBasicMaterial
  29821. */
  29822. class LineDashedMaterial extends LineBasicMaterial {
  29823. /**
  29824. * Constructs a new line dashed material.
  29825. *
  29826. * @param {Object} [parameters] - An object with one or more properties
  29827. * defining the material's appearance. Any property of the material
  29828. * (including any property from inherited materials) can be passed
  29829. * in here. Color values can be passed any type of value accepted
  29830. * by {@link Color#set}.
  29831. */
  29832. constructor( parameters ) {
  29833. super();
  29834. /**
  29835. * This flag can be used for type testing.
  29836. *
  29837. * @type {boolean}
  29838. * @readonly
  29839. * @default true
  29840. */
  29841. this.isLineDashedMaterial = true;
  29842. this.type = 'LineDashedMaterial';
  29843. /**
  29844. * The scale of the dashed part of a line.
  29845. *
  29846. * @type {number}
  29847. * @default 1
  29848. */
  29849. this.scale = 1;
  29850. /**
  29851. * The size of the dash. This is both the gap with the stroke.
  29852. *
  29853. * @type {number}
  29854. * @default 3
  29855. */
  29856. this.dashSize = 3;
  29857. /**
  29858. * The size of the gap.
  29859. *
  29860. * @type {number}
  29861. * @default 1
  29862. */
  29863. this.gapSize = 1;
  29864. this.setValues( parameters );
  29865. }
  29866. copy( source ) {
  29867. super.copy( source );
  29868. this.scale = source.scale;
  29869. this.dashSize = source.dashSize;
  29870. this.gapSize = source.gapSize;
  29871. return this;
  29872. }
  29873. }
  29874. /**
  29875. * Converts an array to a specific type.
  29876. *
  29877. * @param {TypedArray|Array} array - The array to convert.
  29878. * @param {TypedArray.constructor} type - The constructor of a typed array that defines the new type.
  29879. * @return {TypedArray} The converted array.
  29880. */
  29881. function convertArray( array, type ) {
  29882. if ( ! array || array.constructor === type ) return array;
  29883. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  29884. return new type( array ); // create typed array
  29885. }
  29886. return Array.prototype.slice.call( array ); // create Array
  29887. }
  29888. /**
  29889. * Returns an array by which times and values can be sorted.
  29890. *
  29891. * @param {Array<number>} times - The keyframe time values.
  29892. * @return {Array<number>} The array.
  29893. */
  29894. function getKeyframeOrder( times ) {
  29895. function compareTime( i, j ) {
  29896. return times[ i ] - times[ j ];
  29897. }
  29898. const n = times.length;
  29899. const result = new Array( n );
  29900. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  29901. result.sort( compareTime );
  29902. return result;
  29903. }
  29904. /**
  29905. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  29906. *
  29907. * @param {Array<number>} values - The values to sort.
  29908. * @param {number} stride - The stride.
  29909. * @param {Array<number>} order - The sort order.
  29910. * @return {Array<number>} The sorted values.
  29911. */
  29912. function sortedArray( values, stride, order ) {
  29913. const nValues = values.length;
  29914. const result = new values.constructor( nValues );
  29915. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  29916. const srcOffset = order[ i ] * stride;
  29917. for ( let j = 0; j !== stride; ++ j ) {
  29918. result[ dstOffset ++ ] = values[ srcOffset + j ];
  29919. }
  29920. }
  29921. return result;
  29922. }
  29923. /**
  29924. * Used for parsing AOS keyframe formats.
  29925. *
  29926. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  29927. * @param {Array<number>} times - This array will be filled with keyframe times by this function.
  29928. * @param {Array<number>} values - This array will be filled with keyframe values by this function.
  29929. * @param {string} valuePropertyName - The name of the property to use.
  29930. */
  29931. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  29932. let i = 1, key = jsonKeys[ 0 ];
  29933. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  29934. key = jsonKeys[ i ++ ];
  29935. }
  29936. if ( key === undefined ) return; // no data
  29937. let value = key[ valuePropertyName ];
  29938. if ( value === undefined ) return; // no data
  29939. if ( Array.isArray( value ) ) {
  29940. do {
  29941. value = key[ valuePropertyName ];
  29942. if ( value !== undefined ) {
  29943. times.push( key.time );
  29944. values.push( ...value ); // push all elements
  29945. }
  29946. key = jsonKeys[ i ++ ];
  29947. } while ( key !== undefined );
  29948. } else if ( value.toArray !== undefined ) {
  29949. // ...assume THREE.Math-ish
  29950. do {
  29951. value = key[ valuePropertyName ];
  29952. if ( value !== undefined ) {
  29953. times.push( key.time );
  29954. value.toArray( values, values.length );
  29955. }
  29956. key = jsonKeys[ i ++ ];
  29957. } while ( key !== undefined );
  29958. } else {
  29959. // otherwise push as-is
  29960. do {
  29961. value = key[ valuePropertyName ];
  29962. if ( value !== undefined ) {
  29963. times.push( key.time );
  29964. values.push( value );
  29965. }
  29966. key = jsonKeys[ i ++ ];
  29967. } while ( key !== undefined );
  29968. }
  29969. }
  29970. /**
  29971. * Creates a new clip, containing only the segment of the original clip between the given frames.
  29972. *
  29973. * @param {AnimationClip} sourceClip - The values to sort.
  29974. * @param {string} name - The name of the clip.
  29975. * @param {number} startFrame - The start frame.
  29976. * @param {number} endFrame - The end frame.
  29977. * @param {number} [fps=30] - The FPS.
  29978. * @return {AnimationClip} The new sub clip.
  29979. */
  29980. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  29981. const clip = sourceClip.clone();
  29982. clip.name = name;
  29983. const tracks = [];
  29984. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  29985. const track = clip.tracks[ i ];
  29986. const valueSize = track.getValueSize();
  29987. const times = [];
  29988. const values = [];
  29989. for ( let j = 0; j < track.times.length; ++ j ) {
  29990. const frame = track.times[ j ] * fps;
  29991. if ( frame < startFrame || frame >= endFrame ) continue;
  29992. times.push( track.times[ j ] );
  29993. for ( let k = 0; k < valueSize; ++ k ) {
  29994. values.push( track.values[ j * valueSize + k ] );
  29995. }
  29996. }
  29997. if ( times.length === 0 ) continue;
  29998. track.times = convertArray( times, track.times.constructor );
  29999. track.values = convertArray( values, track.values.constructor );
  30000. tracks.push( track );
  30001. }
  30002. clip.tracks = tracks;
  30003. // find minimum .times value across all tracks in the trimmed clip
  30004. let minStartTime = Infinity;
  30005. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30006. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  30007. minStartTime = clip.tracks[ i ].times[ 0 ];
  30008. }
  30009. }
  30010. // shift all tracks such that clip begins at t=0
  30011. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30012. clip.tracks[ i ].shift( -1 * minStartTime );
  30013. }
  30014. clip.resetDuration();
  30015. return clip;
  30016. }
  30017. /**
  30018. * Converts the keyframes of the given animation clip to an additive format.
  30019. *
  30020. * @param {AnimationClip} targetClip - The clip to make additive.
  30021. * @param {number} [referenceFrame=0] - The reference frame.
  30022. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30023. * @param {number} [fps=30] - The FPS.
  30024. * @return {AnimationClip} The updated clip which is now additive.
  30025. */
  30026. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30027. if ( fps <= 0 ) fps = 30;
  30028. const numTracks = referenceClip.tracks.length;
  30029. const referenceTime = referenceFrame / fps;
  30030. // Make each track's values relative to the values at the reference frame
  30031. for ( let i = 0; i < numTracks; ++ i ) {
  30032. const referenceTrack = referenceClip.tracks[ i ];
  30033. const referenceTrackType = referenceTrack.ValueTypeName;
  30034. // Skip this track if it's non-numeric
  30035. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  30036. // Find the track in the target clip whose name and type matches the reference track
  30037. const targetTrack = targetClip.tracks.find( function ( track ) {
  30038. return track.name === referenceTrack.name
  30039. && track.ValueTypeName === referenceTrackType;
  30040. } );
  30041. if ( targetTrack === undefined ) continue;
  30042. let referenceOffset = 0;
  30043. const referenceValueSize = referenceTrack.getValueSize();
  30044. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30045. referenceOffset = referenceValueSize / 3;
  30046. }
  30047. let targetOffset = 0;
  30048. const targetValueSize = targetTrack.getValueSize();
  30049. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30050. targetOffset = targetValueSize / 3;
  30051. }
  30052. const lastIndex = referenceTrack.times.length - 1;
  30053. let referenceValue;
  30054. // Find the value to subtract out of the track
  30055. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  30056. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  30057. const startIndex = referenceOffset;
  30058. const endIndex = referenceValueSize - referenceOffset;
  30059. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30060. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  30061. // Reference frame is after the last keyframe, so just use the last keyframe
  30062. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  30063. const endIndex = startIndex + referenceValueSize - referenceOffset;
  30064. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30065. } else {
  30066. // Interpolate to the reference value
  30067. const interpolant = referenceTrack.createInterpolant();
  30068. const startIndex = referenceOffset;
  30069. const endIndex = referenceValueSize - referenceOffset;
  30070. interpolant.evaluate( referenceTime );
  30071. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  30072. }
  30073. // Conjugate the quaternion
  30074. if ( referenceTrackType === 'quaternion' ) {
  30075. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  30076. referenceQuat.toArray( referenceValue );
  30077. }
  30078. // Subtract the reference value from all of the track values
  30079. const numTimes = targetTrack.times.length;
  30080. for ( let j = 0; j < numTimes; ++ j ) {
  30081. const valueStart = j * targetValueSize + targetOffset;
  30082. if ( referenceTrackType === 'quaternion' ) {
  30083. // Multiply the conjugate for quaternion track types
  30084. Quaternion.multiplyQuaternionsFlat(
  30085. targetTrack.values,
  30086. valueStart,
  30087. referenceValue,
  30088. 0,
  30089. targetTrack.values,
  30090. valueStart
  30091. );
  30092. } else {
  30093. const valueEnd = targetValueSize - targetOffset * 2;
  30094. // Subtract each value for all other numeric track types
  30095. for ( let k = 0; k < valueEnd; ++ k ) {
  30096. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  30097. }
  30098. }
  30099. }
  30100. }
  30101. targetClip.blendMode = AdditiveAnimationBlendMode;
  30102. return targetClip;
  30103. }
  30104. /**
  30105. * A class with various methods to assist with animations.
  30106. *
  30107. * @hideconstructor
  30108. */
  30109. class AnimationUtils {
  30110. /**
  30111. * Converts an array to a specific type
  30112. *
  30113. * @static
  30114. * @param {TypedArray|Array} array - The array to convert.
  30115. * @param {TypedArray.constructor} type - The constructor of a type array.
  30116. * @return {TypedArray} The converted array
  30117. */
  30118. static convertArray( array, type ) {
  30119. return convertArray( array, type );
  30120. }
  30121. /**
  30122. * Returns `true` if the given object is a typed array.
  30123. *
  30124. * @static
  30125. * @param {any} object - The object to check.
  30126. * @return {boolean} Whether the given object is a typed array.
  30127. */
  30128. static isTypedArray( object ) {
  30129. return isTypedArray( object );
  30130. }
  30131. /**
  30132. * Returns an array by which times and values can be sorted.
  30133. *
  30134. * @static
  30135. * @param {Array<number>} times - The keyframe time values.
  30136. * @return {Array<number>} The array.
  30137. */
  30138. static getKeyframeOrder( times ) {
  30139. return getKeyframeOrder( times );
  30140. }
  30141. /**
  30142. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30143. *
  30144. * @static
  30145. * @param {Array<number>} values - The values to sort.
  30146. * @param {number} stride - The stride.
  30147. * @param {Array<number>} order - The sort order.
  30148. * @return {Array<number>} The sorted values.
  30149. */
  30150. static sortedArray( values, stride, order ) {
  30151. return sortedArray( values, stride, order );
  30152. }
  30153. /**
  30154. * Used for parsing AOS keyframe formats.
  30155. *
  30156. * @static
  30157. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30158. * @param {Array<number>} times - This array will be filled with keyframe times by this method.
  30159. * @param {Array<number>} values - This array will be filled with keyframe values by this method.
  30160. * @param {string} valuePropertyName - The name of the property to use.
  30161. */
  30162. static flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30163. flattenJSON( jsonKeys, times, values, valuePropertyName );
  30164. }
  30165. /**
  30166. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30167. *
  30168. * @static
  30169. * @param {AnimationClip} sourceClip - The values to sort.
  30170. * @param {string} name - The name of the clip.
  30171. * @param {number} startFrame - The start frame.
  30172. * @param {number} endFrame - The end frame.
  30173. * @param {number} [fps=30] - The FPS.
  30174. * @return {AnimationClip} The new sub clip.
  30175. */
  30176. static subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30177. return subclip( sourceClip, name, startFrame, endFrame, fps );
  30178. }
  30179. /**
  30180. * Converts the keyframes of the given animation clip to an additive format.
  30181. *
  30182. * @static
  30183. * @param {AnimationClip} targetClip - The clip to make additive.
  30184. * @param {number} [referenceFrame=0] - The reference frame.
  30185. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30186. * @param {number} [fps=30] - The FPS.
  30187. * @return {AnimationClip} The updated clip which is now additive.
  30188. */
  30189. static makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30190. return makeClipAdditive( targetClip, referenceFrame, referenceClip, fps );
  30191. }
  30192. }
  30193. /**
  30194. * Abstract base class of interpolants over parametric samples.
  30195. *
  30196. * The parameter domain is one dimensional, typically the time or a path
  30197. * along a curve defined by the data.
  30198. *
  30199. * The sample values can have any dimensionality and derived classes may
  30200. * apply special interpretations to the data.
  30201. *
  30202. * This class provides the interval seek in a Template Method, deferring
  30203. * the actual interpolation to derived classes.
  30204. *
  30205. * Time complexity is O(1) for linear access crossing at most two points
  30206. * and O(log N) for random access, where N is the number of positions.
  30207. *
  30208. * References: {@link http://www.oodesign.com/template-method-pattern.html}
  30209. *
  30210. * @abstract
  30211. */
  30212. class Interpolant {
  30213. /**
  30214. * Constructs a new interpolant.
  30215. *
  30216. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30217. * @param {TypedArray} sampleValues - The sample values.
  30218. * @param {number} sampleSize - The sample size
  30219. * @param {TypedArray} [resultBuffer] - The result buffer.
  30220. */
  30221. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30222. /**
  30223. * The parameter positions.
  30224. *
  30225. * @type {TypedArray}
  30226. */
  30227. this.parameterPositions = parameterPositions;
  30228. /**
  30229. * A cache index.
  30230. *
  30231. * @private
  30232. * @type {number}
  30233. * @default 0
  30234. */
  30235. this._cachedIndex = 0;
  30236. /**
  30237. * The result buffer.
  30238. *
  30239. * @type {TypedArray}
  30240. */
  30241. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor( sampleSize );
  30242. /**
  30243. * The sample values.
  30244. *
  30245. * @type {TypedArray}
  30246. */
  30247. this.sampleValues = sampleValues;
  30248. /**
  30249. * The value size.
  30250. *
  30251. * @type {TypedArray}
  30252. */
  30253. this.valueSize = sampleSize;
  30254. /**
  30255. * The interpolation settings.
  30256. *
  30257. * @type {?Object}
  30258. * @default null
  30259. */
  30260. this.settings = null;
  30261. /**
  30262. * The default settings object.
  30263. *
  30264. * @type {Object}
  30265. */
  30266. this.DefaultSettings_ = {};
  30267. }
  30268. /**
  30269. * Evaluate the interpolant at position `t`.
  30270. *
  30271. * @param {number} t - The interpolation factor.
  30272. * @return {TypedArray} The result buffer.
  30273. */
  30274. evaluate( t ) {
  30275. const pp = this.parameterPositions;
  30276. let i1 = this._cachedIndex,
  30277. t1 = pp[ i1 ],
  30278. t0 = pp[ i1 - 1 ];
  30279. validate_interval: {
  30280. seek: {
  30281. let right;
  30282. linear_scan: {
  30283. //- See http://jsperf.com/comparison-to-undefined/3
  30284. //- slower code:
  30285. //-
  30286. //- if ( t >= t1 || t1 === undefined ) {
  30287. forward_scan: if ( ! ( t < t1 ) ) {
  30288. for ( let giveUpAt = i1 + 2; ; ) {
  30289. if ( t1 === undefined ) {
  30290. if ( t < t0 ) break forward_scan;
  30291. // after end
  30292. i1 = pp.length;
  30293. this._cachedIndex = i1;
  30294. return this.copySampleValue_( i1 - 1 );
  30295. }
  30296. if ( i1 === giveUpAt ) break; // this loop
  30297. t0 = t1;
  30298. t1 = pp[ ++ i1 ];
  30299. if ( t < t1 ) {
  30300. // we have arrived at the sought interval
  30301. break seek;
  30302. }
  30303. }
  30304. // prepare binary search on the right side of the index
  30305. right = pp.length;
  30306. break linear_scan;
  30307. }
  30308. //- slower code:
  30309. //- if ( t < t0 || t0 === undefined ) {
  30310. if ( ! ( t >= t0 ) ) {
  30311. // looping?
  30312. const t1global = pp[ 1 ];
  30313. if ( t < t1global ) {
  30314. i1 = 2; // + 1, using the scan for the details
  30315. t0 = t1global;
  30316. }
  30317. // linear reverse scan
  30318. for ( let giveUpAt = i1 - 2; ; ) {
  30319. if ( t0 === undefined ) {
  30320. // before start
  30321. this._cachedIndex = 0;
  30322. return this.copySampleValue_( 0 );
  30323. }
  30324. if ( i1 === giveUpAt ) break; // this loop
  30325. t1 = t0;
  30326. t0 = pp[ -- i1 - 1 ];
  30327. if ( t >= t0 ) {
  30328. // we have arrived at the sought interval
  30329. break seek;
  30330. }
  30331. }
  30332. // prepare binary search on the left side of the index
  30333. right = i1;
  30334. i1 = 0;
  30335. break linear_scan;
  30336. }
  30337. // the interval is valid
  30338. break validate_interval;
  30339. } // linear scan
  30340. // binary search
  30341. while ( i1 < right ) {
  30342. const mid = ( i1 + right ) >>> 1;
  30343. if ( t < pp[ mid ] ) {
  30344. right = mid;
  30345. } else {
  30346. i1 = mid + 1;
  30347. }
  30348. }
  30349. t1 = pp[ i1 ];
  30350. t0 = pp[ i1 - 1 ];
  30351. // check boundary cases, again
  30352. if ( t0 === undefined ) {
  30353. this._cachedIndex = 0;
  30354. return this.copySampleValue_( 0 );
  30355. }
  30356. if ( t1 === undefined ) {
  30357. i1 = pp.length;
  30358. this._cachedIndex = i1;
  30359. return this.copySampleValue_( i1 - 1 );
  30360. }
  30361. } // seek
  30362. this._cachedIndex = i1;
  30363. this.intervalChanged_( i1, t0, t1 );
  30364. } // validate_interval
  30365. return this.interpolate_( i1, t0, t, t1 );
  30366. }
  30367. /**
  30368. * Returns the interpolation settings.
  30369. *
  30370. * @return {Object} The interpolation settings.
  30371. */
  30372. getSettings_() {
  30373. return this.settings || this.DefaultSettings_;
  30374. }
  30375. /**
  30376. * Copies a sample value to the result buffer.
  30377. *
  30378. * @param {number} index - An index into the sample value buffer.
  30379. * @return {TypedArray} The result buffer.
  30380. */
  30381. copySampleValue_( index ) {
  30382. // copies a sample value to the result buffer
  30383. const result = this.resultBuffer,
  30384. values = this.sampleValues,
  30385. stride = this.valueSize,
  30386. offset = index * stride;
  30387. for ( let i = 0; i !== stride; ++ i ) {
  30388. result[ i ] = values[ offset + i ];
  30389. }
  30390. return result;
  30391. }
  30392. /**
  30393. * Copies a sample value to the result buffer.
  30394. *
  30395. * @abstract
  30396. * @param {number} i1 - An index into the sample value buffer.
  30397. * @param {number} t0 - The previous interpolation factor.
  30398. * @param {number} t - The current interpolation factor.
  30399. * @param {number} t1 - The next interpolation factor.
  30400. * @return {TypedArray} The result buffer.
  30401. */
  30402. interpolate_( /* i1, t0, t, t1 */ ) {
  30403. throw new Error( 'call to abstract method' );
  30404. // implementations shall return this.resultBuffer
  30405. }
  30406. /**
  30407. * Optional method that is executed when the interval has changed.
  30408. *
  30409. * @param {number} i1 - An index into the sample value buffer.
  30410. * @param {number} t0 - The previous interpolation factor.
  30411. * @param {number} t - The current interpolation factor.
  30412. */
  30413. intervalChanged_( /* i1, t0, t1 */ ) {
  30414. // empty
  30415. }
  30416. }
  30417. /**
  30418. * Fast and simple cubic spline interpolant.
  30419. *
  30420. * It was derived from a Hermitian construction setting the first derivative
  30421. * at each sample position to the linear slope between neighboring positions
  30422. * over their parameter interval.
  30423. *
  30424. * @augments Interpolant
  30425. */
  30426. class CubicInterpolant extends Interpolant {
  30427. /**
  30428. * Constructs a new cubic interpolant.
  30429. *
  30430. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30431. * @param {TypedArray} sampleValues - The sample values.
  30432. * @param {number} sampleSize - The sample size
  30433. * @param {TypedArray} [resultBuffer] - The result buffer.
  30434. */
  30435. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30436. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30437. this._weightPrev = -0;
  30438. this._offsetPrev = -0;
  30439. this._weightNext = -0;
  30440. this._offsetNext = -0;
  30441. this.DefaultSettings_ = {
  30442. endingStart: ZeroCurvatureEnding,
  30443. endingEnd: ZeroCurvatureEnding
  30444. };
  30445. }
  30446. intervalChanged_( i1, t0, t1 ) {
  30447. const pp = this.parameterPositions;
  30448. let iPrev = i1 - 2,
  30449. iNext = i1 + 1,
  30450. tPrev = pp[ iPrev ],
  30451. tNext = pp[ iNext ];
  30452. if ( tPrev === undefined ) {
  30453. switch ( this.getSettings_().endingStart ) {
  30454. case ZeroSlopeEnding:
  30455. // f'(t0) = 0
  30456. iPrev = i1;
  30457. tPrev = 2 * t0 - t1;
  30458. break;
  30459. case WrapAroundEnding:
  30460. // use the other end of the curve
  30461. iPrev = pp.length - 2;
  30462. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  30463. break;
  30464. default: // ZeroCurvatureEnding
  30465. // f''(t0) = 0 a.k.a. Natural Spline
  30466. iPrev = i1;
  30467. tPrev = t1;
  30468. }
  30469. }
  30470. if ( tNext === undefined ) {
  30471. switch ( this.getSettings_().endingEnd ) {
  30472. case ZeroSlopeEnding:
  30473. // f'(tN) = 0
  30474. iNext = i1;
  30475. tNext = 2 * t1 - t0;
  30476. break;
  30477. case WrapAroundEnding:
  30478. // use the other end of the curve
  30479. iNext = 1;
  30480. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  30481. break;
  30482. default: // ZeroCurvatureEnding
  30483. // f''(tN) = 0, a.k.a. Natural Spline
  30484. iNext = i1 - 1;
  30485. tNext = t0;
  30486. }
  30487. }
  30488. const halfDt = ( t1 - t0 ) * 0.5,
  30489. stride = this.valueSize;
  30490. this._weightPrev = halfDt / ( t0 - tPrev );
  30491. this._weightNext = halfDt / ( tNext - t1 );
  30492. this._offsetPrev = iPrev * stride;
  30493. this._offsetNext = iNext * stride;
  30494. }
  30495. interpolate_( i1, t0, t, t1 ) {
  30496. const result = this.resultBuffer,
  30497. values = this.sampleValues,
  30498. stride = this.valueSize,
  30499. o1 = i1 * stride, o0 = o1 - stride,
  30500. oP = this._offsetPrev, oN = this._offsetNext,
  30501. wP = this._weightPrev, wN = this._weightNext,
  30502. p = ( t - t0 ) / ( t1 - t0 ),
  30503. pp = p * p,
  30504. ppp = pp * p;
  30505. // evaluate polynomials
  30506. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  30507. const s0 = ( 1 + wP ) * ppp + ( -1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  30508. const s1 = ( -1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  30509. const sN = wN * ppp - wN * pp;
  30510. // combine data linearly
  30511. for ( let i = 0; i !== stride; ++ i ) {
  30512. result[ i ] =
  30513. sP * values[ oP + i ] +
  30514. s0 * values[ o0 + i ] +
  30515. s1 * values[ o1 + i ] +
  30516. sN * values[ oN + i ];
  30517. }
  30518. return result;
  30519. }
  30520. }
  30521. /**
  30522. * A basic linear interpolant.
  30523. *
  30524. * @augments Interpolant
  30525. */
  30526. class LinearInterpolant extends Interpolant {
  30527. /**
  30528. * Constructs a new linear interpolant.
  30529. *
  30530. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30531. * @param {TypedArray} sampleValues - The sample values.
  30532. * @param {number} sampleSize - The sample size
  30533. * @param {TypedArray} [resultBuffer] - The result buffer.
  30534. */
  30535. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30536. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30537. }
  30538. interpolate_( i1, t0, t, t1 ) {
  30539. const result = this.resultBuffer,
  30540. values = this.sampleValues,
  30541. stride = this.valueSize,
  30542. offset1 = i1 * stride,
  30543. offset0 = offset1 - stride,
  30544. weight1 = ( t - t0 ) / ( t1 - t0 ),
  30545. weight0 = 1 - weight1;
  30546. for ( let i = 0; i !== stride; ++ i ) {
  30547. result[ i ] =
  30548. values[ offset0 + i ] * weight0 +
  30549. values[ offset1 + i ] * weight1;
  30550. }
  30551. return result;
  30552. }
  30553. }
  30554. /**
  30555. * Interpolant that evaluates to the sample value at the position preceding
  30556. * the parameter.
  30557. *
  30558. * @augments Interpolant
  30559. */
  30560. class DiscreteInterpolant extends Interpolant {
  30561. /**
  30562. * Constructs a new discrete interpolant.
  30563. *
  30564. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30565. * @param {TypedArray} sampleValues - The sample values.
  30566. * @param {number} sampleSize - The sample size
  30567. * @param {TypedArray} [resultBuffer] - The result buffer.
  30568. */
  30569. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30570. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30571. }
  30572. interpolate_( i1 /*, t0, t, t1 */ ) {
  30573. return this.copySampleValue_( i1 - 1 );
  30574. }
  30575. }
  30576. /**
  30577. * A Bezier interpolant using cubic Bezier curves with 2D control points.
  30578. *
  30579. * This interpolant supports the COLLADA/Maya style of Bezier animation where
  30580. * each keyframe has explicit in/out tangent control points specified as
  30581. * 2D coordinates (time, value).
  30582. *
  30583. * The tangent data must be provided via the `settings` object:
  30584. * - `settings.inTangents`: Float32Array with [time, value] pairs per keyframe per component
  30585. * - `settings.outTangents`: Float32Array with [time, value] pairs per keyframe per component
  30586. *
  30587. * For a track with N keyframes and stride S:
  30588. * - Each tangent array has N * S * 2 values
  30589. * - Layout: [k0_c0_time, k0_c0_value, k0_c1_time, k0_c1_value, ..., k0_cS_time, k0_cS_value,
  30590. * k1_c0_time, k1_c0_value, ...]
  30591. *
  30592. * @augments Interpolant
  30593. */
  30594. class BezierInterpolant extends Interpolant {
  30595. interpolate_( i1, t0, t, t1 ) {
  30596. const result = this.resultBuffer;
  30597. const values = this.sampleValues;
  30598. const stride = this.valueSize;
  30599. const offset1 = i1 * stride;
  30600. const offset0 = offset1 - stride;
  30601. const settings = this.settings || this.DefaultSettings_;
  30602. const inTangents = settings.inTangents;
  30603. const outTangents = settings.outTangents;
  30604. // If no tangent data, fall back to linear interpolation
  30605. if ( ! inTangents || ! outTangents ) {
  30606. const weight1 = ( t - t0 ) / ( t1 - t0 );
  30607. const weight0 = 1 - weight1;
  30608. for ( let i = 0; i !== stride; ++ i ) {
  30609. result[ i ] = values[ offset0 + i ] * weight0 + values[ offset1 + i ] * weight1;
  30610. }
  30611. return result;
  30612. }
  30613. const tangentStride = stride * 2;
  30614. const i0 = i1 - 1;
  30615. for ( let i = 0; i !== stride; ++ i ) {
  30616. const v0 = values[ offset0 + i ];
  30617. const v1 = values[ offset1 + i ];
  30618. // outTangent of previous keyframe (C0)
  30619. const outTangentOffset = i0 * tangentStride + i * 2;
  30620. const c0x = outTangents[ outTangentOffset ];
  30621. const c0y = outTangents[ outTangentOffset + 1 ];
  30622. // inTangent of current keyframe (C1)
  30623. const inTangentOffset = i1 * tangentStride + i * 2;
  30624. const c1x = inTangents[ inTangentOffset ];
  30625. const c1y = inTangents[ inTangentOffset + 1 ];
  30626. // Solve for Bezier parameter s where Bx(s) = t using Newton-Raphson
  30627. let s = ( t - t0 ) / ( t1 - t0 );
  30628. let s2, s3, oneMinusS, oneMinusS2, oneMinusS3;
  30629. for ( let iter = 0; iter < 8; iter ++ ) {
  30630. s2 = s * s;
  30631. s3 = s2 * s;
  30632. oneMinusS = 1 - s;
  30633. oneMinusS2 = oneMinusS * oneMinusS;
  30634. oneMinusS3 = oneMinusS2 * oneMinusS;
  30635. // Bezier X(s) = (1-s)³·t0 + 3(1-s)²s·c0x + 3(1-s)s²·c1x + s³·t1
  30636. const bx = oneMinusS3 * t0 + 3 * oneMinusS2 * s * c0x + 3 * oneMinusS * s2 * c1x + s3 * t1;
  30637. const error = bx - t;
  30638. if ( Math.abs( error ) < 1e-10 ) break;
  30639. // Derivative dX/ds
  30640. const dbx = 3 * oneMinusS2 * ( c0x - t0 ) + 6 * oneMinusS * s * ( c1x - c0x ) + 3 * s2 * ( t1 - c1x );
  30641. if ( Math.abs( dbx ) < 1e-10 ) break;
  30642. s = s - error / dbx;
  30643. s = Math.max( 0, Math.min( 1, s ) );
  30644. }
  30645. // Evaluate Bezier Y(s)
  30646. result[ i ] = oneMinusS3 * v0 + 3 * oneMinusS2 * s * c0y + 3 * oneMinusS * s2 * c1y + s3 * v1;
  30647. }
  30648. return result;
  30649. }
  30650. }
  30651. /**
  30652. * Represents a timed sequence of keyframes, which are composed of lists of
  30653. * times and related values, and which are used to animate a specific property
  30654. * of an object.
  30655. */
  30656. class KeyframeTrack {
  30657. /**
  30658. * Constructs a new keyframe track.
  30659. *
  30660. * @param {string} name - The keyframe track's name.
  30661. * @param {Array<number>} times - A list of keyframe times.
  30662. * @param {Array<number|string|boolean>} values - A list of keyframe values.
  30663. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)} [interpolation] - The interpolation type.
  30664. */
  30665. constructor( name, times, values, interpolation ) {
  30666. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  30667. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  30668. /**
  30669. * The track's name can refer to morph targets or bones or
  30670. * possibly other values within an animated object. See {@link PropertyBinding#parseTrackName}
  30671. * for the forms of strings that can be parsed for property binding.
  30672. *
  30673. * @type {string}
  30674. */
  30675. this.name = name;
  30676. /**
  30677. * The keyframe times.
  30678. *
  30679. * @type {Float32Array}
  30680. */
  30681. this.times = convertArray( times, this.TimeBufferType );
  30682. /**
  30683. * The keyframe values.
  30684. *
  30685. * @type {Float32Array}
  30686. */
  30687. this.values = convertArray( values, this.ValueBufferType );
  30688. this.setInterpolation( interpolation || this.DefaultInterpolation );
  30689. }
  30690. /**
  30691. * Converts the keyframe track to JSON.
  30692. *
  30693. * @static
  30694. * @param {KeyframeTrack} track - The keyframe track to serialize.
  30695. * @return {Object} The serialized keyframe track as JSON.
  30696. */
  30697. static toJSON( track ) {
  30698. const trackType = track.constructor;
  30699. let json;
  30700. // derived classes can define a static toJSON method
  30701. if ( trackType.toJSON !== this.toJSON ) {
  30702. json = trackType.toJSON( track );
  30703. } else {
  30704. // by default, we assume the data can be serialized as-is
  30705. json = {
  30706. 'name': track.name,
  30707. 'times': convertArray( track.times, Array ),
  30708. 'values': convertArray( track.values, Array )
  30709. };
  30710. const interpolation = track.getInterpolation();
  30711. if ( interpolation !== track.DefaultInterpolation ) {
  30712. json.interpolation = interpolation;
  30713. }
  30714. }
  30715. json.type = track.ValueTypeName; // mandatory
  30716. return json;
  30717. }
  30718. /**
  30719. * Factory method for creating a new discrete interpolant.
  30720. *
  30721. * @static
  30722. * @param {TypedArray} [result] - The result buffer.
  30723. * @return {DiscreteInterpolant} The new interpolant.
  30724. */
  30725. InterpolantFactoryMethodDiscrete( result ) {
  30726. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  30727. }
  30728. /**
  30729. * Factory method for creating a new linear interpolant.
  30730. *
  30731. * @static
  30732. * @param {TypedArray} [result] - The result buffer.
  30733. * @return {LinearInterpolant} The new interpolant.
  30734. */
  30735. InterpolantFactoryMethodLinear( result ) {
  30736. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  30737. }
  30738. /**
  30739. * Factory method for creating a new smooth interpolant.
  30740. *
  30741. * @static
  30742. * @param {TypedArray} [result] - The result buffer.
  30743. * @return {CubicInterpolant} The new interpolant.
  30744. */
  30745. InterpolantFactoryMethodSmooth( result ) {
  30746. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  30747. }
  30748. /**
  30749. * Factory method for creating a new Bezier interpolant.
  30750. *
  30751. * The Bezier interpolant requires tangent data to be set via the `settings` property
  30752. * on the track before creating the interpolant. The settings should contain:
  30753. * - `inTangents`: Float32Array with [time, value] pairs per keyframe per component
  30754. * - `outTangents`: Float32Array with [time, value] pairs per keyframe per component
  30755. *
  30756. * @static
  30757. * @param {TypedArray} [result] - The result buffer.
  30758. * @return {BezierInterpolant} The new interpolant.
  30759. */
  30760. InterpolantFactoryMethodBezier( result ) {
  30761. const interpolant = new BezierInterpolant( this.times, this.values, this.getValueSize(), result );
  30762. // Pass tangent data from track settings to interpolant
  30763. if ( this.settings ) {
  30764. interpolant.settings = this.settings;
  30765. }
  30766. return interpolant;
  30767. }
  30768. /**
  30769. * Defines the interpolation factor method for this keyframe track.
  30770. *
  30771. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)} interpolation - The interpolation type.
  30772. * @return {KeyframeTrack} A reference to this keyframe track.
  30773. */
  30774. setInterpolation( interpolation ) {
  30775. let factoryMethod;
  30776. switch ( interpolation ) {
  30777. case InterpolateDiscrete:
  30778. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  30779. break;
  30780. case InterpolateLinear:
  30781. factoryMethod = this.InterpolantFactoryMethodLinear;
  30782. break;
  30783. case InterpolateSmooth:
  30784. factoryMethod = this.InterpolantFactoryMethodSmooth;
  30785. break;
  30786. case InterpolateBezier:
  30787. factoryMethod = this.InterpolantFactoryMethodBezier;
  30788. break;
  30789. }
  30790. if ( factoryMethod === undefined ) {
  30791. const message = 'unsupported interpolation for ' +
  30792. this.ValueTypeName + ' keyframe track named ' + this.name;
  30793. if ( this.createInterpolant === undefined ) {
  30794. // fall back to default, unless the default itself is messed up
  30795. if ( interpolation !== this.DefaultInterpolation ) {
  30796. this.setInterpolation( this.DefaultInterpolation );
  30797. } else {
  30798. throw new Error( message ); // fatal, in this case
  30799. }
  30800. }
  30801. warn( 'KeyframeTrack:', message );
  30802. return this;
  30803. }
  30804. this.createInterpolant = factoryMethod;
  30805. return this;
  30806. }
  30807. /**
  30808. * Returns the current interpolation type.
  30809. *
  30810. * @return {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)} The interpolation type.
  30811. */
  30812. getInterpolation() {
  30813. switch ( this.createInterpolant ) {
  30814. case this.InterpolantFactoryMethodDiscrete:
  30815. return InterpolateDiscrete;
  30816. case this.InterpolantFactoryMethodLinear:
  30817. return InterpolateLinear;
  30818. case this.InterpolantFactoryMethodSmooth:
  30819. return InterpolateSmooth;
  30820. case this.InterpolantFactoryMethodBezier:
  30821. return InterpolateBezier;
  30822. }
  30823. }
  30824. /**
  30825. * Returns the value size.
  30826. *
  30827. * @return {number} The value size.
  30828. */
  30829. getValueSize() {
  30830. return this.values.length / this.times.length;
  30831. }
  30832. /**
  30833. * Moves all keyframes either forward or backward in time.
  30834. *
  30835. * @param {number} timeOffset - The offset to move the time values.
  30836. * @return {KeyframeTrack} A reference to this keyframe track.
  30837. */
  30838. shift( timeOffset ) {
  30839. if ( timeOffset !== 0.0 ) {
  30840. const times = this.times;
  30841. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  30842. times[ i ] += timeOffset;
  30843. }
  30844. }
  30845. return this;
  30846. }
  30847. /**
  30848. * Scale all keyframe times by a factor (useful for frame - seconds conversions).
  30849. *
  30850. * @param {number} timeScale - The time scale.
  30851. * @return {KeyframeTrack} A reference to this keyframe track.
  30852. */
  30853. scale( timeScale ) {
  30854. if ( timeScale !== 1.0 ) {
  30855. const times = this.times;
  30856. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  30857. times[ i ] *= timeScale;
  30858. }
  30859. }
  30860. return this;
  30861. }
  30862. /**
  30863. * Removes keyframes before and after animation without changing any values within the defined time range.
  30864. *
  30865. * Note: The method does not shift around keys to the start of the track time, because for interpolated
  30866. * keys this will change their values
  30867. *
  30868. * @param {number} startTime - The start time.
  30869. * @param {number} endTime - The end time.
  30870. * @return {KeyframeTrack} A reference to this keyframe track.
  30871. */
  30872. trim( startTime, endTime ) {
  30873. const times = this.times,
  30874. nKeys = times.length;
  30875. let from = 0,
  30876. to = nKeys - 1;
  30877. while ( from !== nKeys && times[ from ] < startTime ) {
  30878. ++ from;
  30879. }
  30880. while ( to !== -1 && times[ to ] > endTime ) {
  30881. -- to;
  30882. }
  30883. ++ to; // inclusive -> exclusive bound
  30884. if ( from !== 0 || to !== nKeys ) {
  30885. // empty tracks are forbidden, so keep at least one keyframe
  30886. if ( from >= to ) {
  30887. to = Math.max( to, 1 );
  30888. from = to - 1;
  30889. }
  30890. const stride = this.getValueSize();
  30891. this.times = times.slice( from, to );
  30892. this.values = this.values.slice( from * stride, to * stride );
  30893. }
  30894. return this;
  30895. }
  30896. /**
  30897. * Performs minimal validation on the keyframe track. Returns `true` if the values
  30898. * are valid.
  30899. *
  30900. * @return {boolean} Whether the keyframes are valid or not.
  30901. */
  30902. validate() {
  30903. let valid = true;
  30904. const valueSize = this.getValueSize();
  30905. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  30906. error( 'KeyframeTrack: Invalid value size in track.', this );
  30907. valid = false;
  30908. }
  30909. const times = this.times,
  30910. values = this.values,
  30911. nKeys = times.length;
  30912. if ( nKeys === 0 ) {
  30913. error( 'KeyframeTrack: Track is empty.', this );
  30914. valid = false;
  30915. }
  30916. let prevTime = null;
  30917. for ( let i = 0; i !== nKeys; i ++ ) {
  30918. const currTime = times[ i ];
  30919. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  30920. error( 'KeyframeTrack: Time is not a valid number.', this, i, currTime );
  30921. valid = false;
  30922. break;
  30923. }
  30924. if ( prevTime !== null && prevTime > currTime ) {
  30925. error( 'KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  30926. valid = false;
  30927. break;
  30928. }
  30929. prevTime = currTime;
  30930. }
  30931. if ( values !== undefined ) {
  30932. if ( isTypedArray( values ) ) {
  30933. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  30934. const value = values[ i ];
  30935. if ( isNaN( value ) ) {
  30936. error( 'KeyframeTrack: Value is not a valid number.', this, i, value );
  30937. valid = false;
  30938. break;
  30939. }
  30940. }
  30941. }
  30942. }
  30943. return valid;
  30944. }
  30945. /**
  30946. * Optimizes this keyframe track by removing equivalent sequential keys (which are
  30947. * common in morph target sequences).
  30948. *
  30949. * @return {KeyframeTrack} A reference to this keyframe track.
  30950. */
  30951. optimize() {
  30952. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  30953. // times or values may be shared with other tracks, so overwriting is unsafe
  30954. const times = this.times.slice(),
  30955. values = this.values.slice(),
  30956. stride = this.getValueSize(),
  30957. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  30958. lastIndex = times.length - 1;
  30959. let writeIndex = 1;
  30960. for ( let i = 1; i < lastIndex; ++ i ) {
  30961. let keep = false;
  30962. const time = times[ i ];
  30963. const timeNext = times[ i + 1 ];
  30964. // remove adjacent keyframes scheduled at the same time
  30965. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  30966. if ( ! smoothInterpolation ) {
  30967. // remove unnecessary keyframes same as their neighbors
  30968. const offset = i * stride,
  30969. offsetP = offset - stride,
  30970. offsetN = offset + stride;
  30971. for ( let j = 0; j !== stride; ++ j ) {
  30972. const value = values[ offset + j ];
  30973. if ( value !== values[ offsetP + j ] ||
  30974. value !== values[ offsetN + j ] ) {
  30975. keep = true;
  30976. break;
  30977. }
  30978. }
  30979. } else {
  30980. keep = true;
  30981. }
  30982. }
  30983. // in-place compaction
  30984. if ( keep ) {
  30985. if ( i !== writeIndex ) {
  30986. times[ writeIndex ] = times[ i ];
  30987. const readOffset = i * stride,
  30988. writeOffset = writeIndex * stride;
  30989. for ( let j = 0; j !== stride; ++ j ) {
  30990. values[ writeOffset + j ] = values[ readOffset + j ];
  30991. }
  30992. }
  30993. ++ writeIndex;
  30994. }
  30995. }
  30996. // flush last keyframe (compaction looks ahead)
  30997. if ( lastIndex > 0 ) {
  30998. times[ writeIndex ] = times[ lastIndex ];
  30999. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  31000. values[ writeOffset + j ] = values[ readOffset + j ];
  31001. }
  31002. ++ writeIndex;
  31003. }
  31004. if ( writeIndex !== times.length ) {
  31005. this.times = times.slice( 0, writeIndex );
  31006. this.values = values.slice( 0, writeIndex * stride );
  31007. } else {
  31008. this.times = times;
  31009. this.values = values;
  31010. }
  31011. return this;
  31012. }
  31013. /**
  31014. * Returns a new keyframe track with copied values from this instance.
  31015. *
  31016. * @return {KeyframeTrack} A clone of this instance.
  31017. */
  31018. clone() {
  31019. const times = this.times.slice();
  31020. const values = this.values.slice();
  31021. const TypedKeyframeTrack = this.constructor;
  31022. const track = new TypedKeyframeTrack( this.name, times, values );
  31023. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  31024. track.createInterpolant = this.createInterpolant;
  31025. return track;
  31026. }
  31027. }
  31028. /**
  31029. * The value type name.
  31030. *
  31031. * @type {string}
  31032. * @default ''
  31033. */
  31034. KeyframeTrack.prototype.ValueTypeName = '';
  31035. /**
  31036. * The time buffer type of this keyframe track.
  31037. *
  31038. * @type {TypedArray|Array}
  31039. * @default Float32Array.constructor
  31040. */
  31041. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  31042. /**
  31043. * The value buffer type of this keyframe track.
  31044. *
  31045. * @type {TypedArray|Array}
  31046. * @default Float32Array.constructor
  31047. */
  31048. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  31049. /**
  31050. * The default interpolation type of this keyframe track.
  31051. *
  31052. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)}
  31053. * @default InterpolateLinear
  31054. */
  31055. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  31056. /**
  31057. * A track for boolean keyframe values.
  31058. *
  31059. * @augments KeyframeTrack
  31060. */
  31061. class BooleanKeyframeTrack extends KeyframeTrack {
  31062. /**
  31063. * Constructs a new boolean keyframe track.
  31064. *
  31065. * This keyframe track type has no `interpolation` parameter because the
  31066. * interpolation is always discrete.
  31067. *
  31068. * @param {string} name - The keyframe track's name.
  31069. * @param {Array<number>} times - A list of keyframe times.
  31070. * @param {Array<boolean>} values - A list of keyframe values.
  31071. */
  31072. constructor( name, times, values ) {
  31073. super( name, times, values );
  31074. }
  31075. }
  31076. /**
  31077. * The value type name.
  31078. *
  31079. * @type {string}
  31080. * @default 'bool'
  31081. */
  31082. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  31083. /**
  31084. * The value buffer type of this keyframe track.
  31085. *
  31086. * @type {TypedArray|Array}
  31087. * @default Array.constructor
  31088. */
  31089. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  31090. /**
  31091. * The default interpolation type of this keyframe track.
  31092. *
  31093. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31094. * @default InterpolateDiscrete
  31095. */
  31096. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31097. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31098. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31099. /**
  31100. * A track for color keyframe values.
  31101. *
  31102. * @augments KeyframeTrack
  31103. */
  31104. class ColorKeyframeTrack extends KeyframeTrack {
  31105. /**
  31106. * Constructs a new color keyframe track.
  31107. *
  31108. * @param {string} name - The keyframe track's name.
  31109. * @param {Array<number>} times - A list of keyframe times.
  31110. * @param {Array<number>} values - A list of keyframe values.
  31111. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31112. */
  31113. constructor( name, times, values, interpolation ) {
  31114. super( name, times, values, interpolation );
  31115. }
  31116. }
  31117. /**
  31118. * The value type name.
  31119. *
  31120. * @type {string}
  31121. * @default 'color'
  31122. */
  31123. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  31124. /**
  31125. * A track for numeric keyframe values.
  31126. *
  31127. * @augments KeyframeTrack
  31128. */
  31129. class NumberKeyframeTrack extends KeyframeTrack {
  31130. /**
  31131. * Constructs a new number keyframe track.
  31132. *
  31133. * @param {string} name - The keyframe track's name.
  31134. * @param {Array<number>} times - A list of keyframe times.
  31135. * @param {Array<number>} values - A list of keyframe values.
  31136. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31137. */
  31138. constructor( name, times, values, interpolation ) {
  31139. super( name, times, values, interpolation );
  31140. }
  31141. }
  31142. /**
  31143. * The value type name.
  31144. *
  31145. * @type {string}
  31146. * @default 'number'
  31147. */
  31148. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  31149. /**
  31150. * Spherical linear unit quaternion interpolant.
  31151. *
  31152. * @augments Interpolant
  31153. */
  31154. class QuaternionLinearInterpolant extends Interpolant {
  31155. /**
  31156. * Constructs a new SLERP interpolant.
  31157. *
  31158. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31159. * @param {TypedArray} sampleValues - The sample values.
  31160. * @param {number} sampleSize - The sample size
  31161. * @param {TypedArray} [resultBuffer] - The result buffer.
  31162. */
  31163. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31164. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31165. }
  31166. interpolate_( i1, t0, t, t1 ) {
  31167. const result = this.resultBuffer,
  31168. values = this.sampleValues,
  31169. stride = this.valueSize,
  31170. alpha = ( t - t0 ) / ( t1 - t0 );
  31171. let offset = i1 * stride;
  31172. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  31173. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  31174. }
  31175. return result;
  31176. }
  31177. }
  31178. /**
  31179. * A track for Quaternion keyframe values.
  31180. *
  31181. * @augments KeyframeTrack
  31182. */
  31183. class QuaternionKeyframeTrack extends KeyframeTrack {
  31184. /**
  31185. * Constructs a new Quaternion keyframe track.
  31186. *
  31187. * @param {string} name - The keyframe track's name.
  31188. * @param {Array<number>} times - A list of keyframe times.
  31189. * @param {Array<number>} values - A list of keyframe values.
  31190. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31191. */
  31192. constructor( name, times, values, interpolation ) {
  31193. super( name, times, values, interpolation );
  31194. }
  31195. /**
  31196. * Overwritten so the method returns Quaternion based interpolant.
  31197. *
  31198. * @static
  31199. * @param {TypedArray} [result] - The result buffer.
  31200. * @return {QuaternionLinearInterpolant} The new interpolant.
  31201. */
  31202. InterpolantFactoryMethodLinear( result ) {
  31203. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31204. }
  31205. }
  31206. /**
  31207. * The value type name.
  31208. *
  31209. * @type {string}
  31210. * @default 'quaternion'
  31211. */
  31212. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  31213. // ValueBufferType is inherited
  31214. // DefaultInterpolation is inherited;
  31215. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31216. /**
  31217. * A track for string keyframe values.
  31218. *
  31219. * @augments KeyframeTrack
  31220. */
  31221. class StringKeyframeTrack extends KeyframeTrack {
  31222. /**
  31223. * Constructs a new string keyframe track.
  31224. *
  31225. * This keyframe track type has no `interpolation` parameter because the
  31226. * interpolation is always discrete.
  31227. *
  31228. * @param {string} name - The keyframe track's name.
  31229. * @param {Array<number>} times - A list of keyframe times.
  31230. * @param {Array<string>} values - A list of keyframe values.
  31231. */
  31232. constructor( name, times, values ) {
  31233. super( name, times, values );
  31234. }
  31235. }
  31236. /**
  31237. * The value type name.
  31238. *
  31239. * @type {string}
  31240. * @default 'string'
  31241. */
  31242. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  31243. /**
  31244. * The value buffer type of this keyframe track.
  31245. *
  31246. * @type {TypedArray|Array}
  31247. * @default Array.constructor
  31248. */
  31249. StringKeyframeTrack.prototype.ValueBufferType = Array;
  31250. /**
  31251. * The default interpolation type of this keyframe track.
  31252. *
  31253. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31254. * @default InterpolateDiscrete
  31255. */
  31256. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31257. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31258. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31259. /**
  31260. * A track for vector keyframe values.
  31261. *
  31262. * @augments KeyframeTrack
  31263. */
  31264. class VectorKeyframeTrack extends KeyframeTrack {
  31265. /**
  31266. * Constructs a new vector keyframe track.
  31267. *
  31268. * @param {string} name - The keyframe track's name.
  31269. * @param {Array<number>} times - A list of keyframe times.
  31270. * @param {Array<number>} values - A list of keyframe values.
  31271. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31272. */
  31273. constructor( name, times, values, interpolation ) {
  31274. super( name, times, values, interpolation );
  31275. }
  31276. }
  31277. /**
  31278. * The value type name.
  31279. *
  31280. * @type {string}
  31281. * @default 'vector'
  31282. */
  31283. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  31284. /**
  31285. * A reusable set of keyframe tracks which represent an animation.
  31286. */
  31287. class AnimationClip {
  31288. /**
  31289. * Constructs a new animation clip.
  31290. *
  31291. * Note: Instead of instantiating an AnimationClip directly with the constructor, you can
  31292. * use the static interface of this class for creating clips. In most cases though, animation clips
  31293. * will automatically be created by loaders when importing animated 3D assets.
  31294. *
  31295. * @param {string} [name=''] - The clip's name.
  31296. * @param {number} [duration=-1] - The clip's duration in seconds. If a negative value is passed,
  31297. * the duration will be calculated from the passed keyframes.
  31298. * @param {Array<KeyframeTrack>} tracks - An array of keyframe tracks.
  31299. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode=NormalAnimationBlendMode] - Defines how the animation
  31300. * is blended/combined when two or more animations are simultaneously played.
  31301. */
  31302. constructor( name = '', duration = -1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  31303. /**
  31304. * The clip's name.
  31305. *
  31306. * @type {string}
  31307. */
  31308. this.name = name;
  31309. /**
  31310. * An array of keyframe tracks.
  31311. *
  31312. * @type {Array<KeyframeTrack>}
  31313. */
  31314. this.tracks = tracks;
  31315. /**
  31316. * The clip's duration in seconds.
  31317. *
  31318. * @type {number}
  31319. */
  31320. this.duration = duration;
  31321. /**
  31322. * Defines how the animation is blended/combined when two or more animations
  31323. * are simultaneously played.
  31324. *
  31325. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  31326. */
  31327. this.blendMode = blendMode;
  31328. /**
  31329. * The UUID of the animation clip.
  31330. *
  31331. * @type {string}
  31332. * @readonly
  31333. */
  31334. this.uuid = generateUUID();
  31335. /**
  31336. * An object that can be used to store custom data about the animation clip.
  31337. * It should not hold references to functions as these will not be cloned.
  31338. *
  31339. * @type {Object}
  31340. */
  31341. this.userData = {};
  31342. // this means it should figure out its duration by scanning the tracks
  31343. if ( this.duration < 0 ) {
  31344. this.resetDuration();
  31345. }
  31346. }
  31347. /**
  31348. * Factory method for creating an animation clip from the given JSON.
  31349. *
  31350. * @static
  31351. * @param {Object} json - The serialized animation clip.
  31352. * @return {AnimationClip} The new animation clip.
  31353. */
  31354. static parse( json ) {
  31355. const tracks = [],
  31356. jsonTracks = json.tracks,
  31357. frameTime = 1.0 / ( json.fps || 1.0 );
  31358. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  31359. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  31360. }
  31361. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  31362. clip.uuid = json.uuid;
  31363. clip.userData = JSON.parse( json.userData || '{}' );
  31364. return clip;
  31365. }
  31366. /**
  31367. * Serializes the given animation clip into JSON.
  31368. *
  31369. * @static
  31370. * @param {AnimationClip} clip - The animation clip to serialize.
  31371. * @return {Object} The JSON object.
  31372. */
  31373. static toJSON( clip ) {
  31374. const tracks = [],
  31375. clipTracks = clip.tracks;
  31376. const json = {
  31377. 'name': clip.name,
  31378. 'duration': clip.duration,
  31379. 'tracks': tracks,
  31380. 'uuid': clip.uuid,
  31381. 'blendMode': clip.blendMode,
  31382. 'userData': JSON.stringify( clip.userData ),
  31383. };
  31384. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  31385. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  31386. }
  31387. return json;
  31388. }
  31389. /**
  31390. * Returns a new animation clip from the passed morph targets array of a
  31391. * geometry, taking a name and the number of frames per second.
  31392. *
  31393. * Note: The fps parameter is required, but the animation speed can be
  31394. * overridden via {@link AnimationAction#setDuration}.
  31395. *
  31396. * @static
  31397. * @param {string} name - The name of the animation clip.
  31398. * @param {Array<Object>} morphTargetSequence - A sequence of morph targets.
  31399. * @param {number} fps - The Frames-Per-Second value.
  31400. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31401. * @return {AnimationClip} The new animation clip.
  31402. */
  31403. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  31404. const numMorphTargets = morphTargetSequence.length;
  31405. const tracks = [];
  31406. for ( let i = 0; i < numMorphTargets; i ++ ) {
  31407. let times = [];
  31408. let values = [];
  31409. times.push(
  31410. ( i + numMorphTargets - 1 ) % numMorphTargets,
  31411. i,
  31412. ( i + 1 ) % numMorphTargets );
  31413. values.push( 0, 1, 0 );
  31414. const order = getKeyframeOrder( times );
  31415. times = sortedArray( times, 1, order );
  31416. values = sortedArray( values, 1, order );
  31417. // if there is a key at the first frame, duplicate it as the
  31418. // last frame as well for perfect loop.
  31419. if ( ! noLoop && times[ 0 ] === 0 ) {
  31420. times.push( numMorphTargets );
  31421. values.push( values[ 0 ] );
  31422. }
  31423. tracks.push(
  31424. new NumberKeyframeTrack(
  31425. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  31426. times, values
  31427. ).scale( 1.0 / fps ) );
  31428. }
  31429. return new this( name, -1, tracks );
  31430. }
  31431. /**
  31432. * Searches for an animation clip by name, taking as its first parameter
  31433. * either an array of clips, or a mesh or geometry that contains an
  31434. * array named "animations" property.
  31435. *
  31436. * @static
  31437. * @param {(Array<AnimationClip>|Object3D)} objectOrClipArray - The array or object to search through.
  31438. * @param {string} name - The name to search for.
  31439. * @return {?AnimationClip} The found animation clip. Returns `null` if no clip has been found.
  31440. */
  31441. static findByName( objectOrClipArray, name ) {
  31442. let clipArray = objectOrClipArray;
  31443. if ( ! Array.isArray( objectOrClipArray ) ) {
  31444. const o = objectOrClipArray;
  31445. clipArray = o.geometry && o.geometry.animations || o.animations;
  31446. }
  31447. for ( let i = 0; i < clipArray.length; i ++ ) {
  31448. if ( clipArray[ i ].name === name ) {
  31449. return clipArray[ i ];
  31450. }
  31451. }
  31452. return null;
  31453. }
  31454. /**
  31455. * Returns an array of new AnimationClips created from the morph target
  31456. * sequences of a geometry, trying to sort morph target names into
  31457. * animation-group-based patterns like "Walk_001, Walk_002, Run_001, Run_002...".
  31458. *
  31459. * See {@link MD2Loader#parse} as an example for how the method should be used.
  31460. *
  31461. * @static
  31462. * @param {Array<Object>} morphTargets - A sequence of morph targets.
  31463. * @param {number} fps - The Frames-Per-Second value.
  31464. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31465. * @return {Array<AnimationClip>} An array of new animation clips.
  31466. */
  31467. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  31468. const animationToMorphTargets = {};
  31469. // tested with https://regex101.com/ on trick sequences
  31470. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  31471. const pattern = /^([\w-]*?)([\d]+)$/;
  31472. // sort morph target names into animation groups based
  31473. // patterns like Walk_001, Walk_002, Run_001, Run_002
  31474. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  31475. const morphTarget = morphTargets[ i ];
  31476. const parts = morphTarget.name.match( pattern );
  31477. if ( parts && parts.length > 1 ) {
  31478. const name = parts[ 1 ];
  31479. let animationMorphTargets = animationToMorphTargets[ name ];
  31480. if ( ! animationMorphTargets ) {
  31481. animationToMorphTargets[ name ] = animationMorphTargets = [];
  31482. }
  31483. animationMorphTargets.push( morphTarget );
  31484. }
  31485. }
  31486. const clips = [];
  31487. for ( const name in animationToMorphTargets ) {
  31488. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  31489. }
  31490. return clips;
  31491. }
  31492. /**
  31493. * Parses the `animation.hierarchy` format and returns a new animation clip.
  31494. *
  31495. * @static
  31496. * @deprecated since r175.
  31497. * @param {Object} animation - A serialized animation clip as JSON.
  31498. * @param {Array<Bone>} bones - An array of bones.
  31499. * @return {?AnimationClip} The new animation clip.
  31500. */
  31501. static parseAnimation( animation, bones ) {
  31502. warn( 'AnimationClip: parseAnimation() is deprecated and will be removed with r185' );
  31503. if ( ! animation ) {
  31504. error( 'AnimationClip: No animation in JSONLoader data.' );
  31505. return null;
  31506. }
  31507. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  31508. // only return track if there are actually keys.
  31509. if ( animationKeys.length !== 0 ) {
  31510. const times = [];
  31511. const values = [];
  31512. flattenJSON( animationKeys, times, values, propertyName );
  31513. // empty keys are filtered out, so check again
  31514. if ( times.length !== 0 ) {
  31515. destTracks.push( new trackType( trackName, times, values ) );
  31516. }
  31517. }
  31518. };
  31519. const tracks = [];
  31520. const clipName = animation.name || 'default';
  31521. const fps = animation.fps || 30;
  31522. const blendMode = animation.blendMode;
  31523. // automatic length determination in AnimationClip.
  31524. let duration = animation.length || -1;
  31525. const hierarchyTracks = animation.hierarchy || [];
  31526. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  31527. const animationKeys = hierarchyTracks[ h ].keys;
  31528. // skip empty tracks
  31529. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  31530. // process morph targets
  31531. if ( animationKeys[ 0 ].morphTargets ) {
  31532. // figure out all morph targets used in this track
  31533. const morphTargetNames = {};
  31534. let k;
  31535. for ( k = 0; k < animationKeys.length; k ++ ) {
  31536. if ( animationKeys[ k ].morphTargets ) {
  31537. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  31538. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = -1;
  31539. }
  31540. }
  31541. }
  31542. // create a track for each morph target with all zero
  31543. // morphTargetInfluences except for the keys in which
  31544. // the morphTarget is named.
  31545. for ( const morphTargetName in morphTargetNames ) {
  31546. const times = [];
  31547. const values = [];
  31548. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  31549. const animationKey = animationKeys[ k ];
  31550. times.push( animationKey.time );
  31551. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  31552. }
  31553. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  31554. }
  31555. duration = morphTargetNames.length * fps;
  31556. } else {
  31557. // ...assume skeletal animation
  31558. const boneName = '.bones[' + bones[ h ].name + ']';
  31559. addNonemptyTrack(
  31560. VectorKeyframeTrack, boneName + '.position',
  31561. animationKeys, 'pos', tracks );
  31562. addNonemptyTrack(
  31563. QuaternionKeyframeTrack, boneName + '.quaternion',
  31564. animationKeys, 'rot', tracks );
  31565. addNonemptyTrack(
  31566. VectorKeyframeTrack, boneName + '.scale',
  31567. animationKeys, 'scl', tracks );
  31568. }
  31569. }
  31570. if ( tracks.length === 0 ) {
  31571. return null;
  31572. }
  31573. const clip = new this( clipName, duration, tracks, blendMode );
  31574. return clip;
  31575. }
  31576. /**
  31577. * Sets the duration of this clip to the duration of its longest keyframe track.
  31578. *
  31579. * @return {AnimationClip} A reference to this animation clip.
  31580. */
  31581. resetDuration() {
  31582. const tracks = this.tracks;
  31583. let duration = 0;
  31584. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  31585. const track = this.tracks[ i ];
  31586. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  31587. }
  31588. this.duration = duration;
  31589. return this;
  31590. }
  31591. /**
  31592. * Trims all tracks to the clip's duration.
  31593. *
  31594. * @return {AnimationClip} A reference to this animation clip.
  31595. */
  31596. trim() {
  31597. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31598. this.tracks[ i ].trim( 0, this.duration );
  31599. }
  31600. return this;
  31601. }
  31602. /**
  31603. * Performs minimal validation on each track in the clip. Returns `true` if all
  31604. * tracks are valid.
  31605. *
  31606. * @return {boolean} Whether the clip's keyframes are valid or not.
  31607. */
  31608. validate() {
  31609. let valid = true;
  31610. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31611. valid = valid && this.tracks[ i ].validate();
  31612. }
  31613. return valid;
  31614. }
  31615. /**
  31616. * Optimizes each track by removing equivalent sequential keys (which are
  31617. * common in morph target sequences).
  31618. *
  31619. * @return {AnimationClip} A reference to this animation clip.
  31620. */
  31621. optimize() {
  31622. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31623. this.tracks[ i ].optimize();
  31624. }
  31625. return this;
  31626. }
  31627. /**
  31628. * Returns a new animation clip with copied values from this instance.
  31629. *
  31630. * @return {AnimationClip} A clone of this instance.
  31631. */
  31632. clone() {
  31633. const tracks = [];
  31634. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31635. tracks.push( this.tracks[ i ].clone() );
  31636. }
  31637. const clip = new this.constructor( this.name, this.duration, tracks, this.blendMode );
  31638. clip.userData = JSON.parse( JSON.stringify( this.userData ) );
  31639. return clip;
  31640. }
  31641. /**
  31642. * Serializes this animation clip into JSON.
  31643. *
  31644. * @return {Object} The JSON object.
  31645. */
  31646. toJSON() {
  31647. return this.constructor.toJSON( this );
  31648. }
  31649. }
  31650. function getTrackTypeForValueTypeName( typeName ) {
  31651. switch ( typeName.toLowerCase() ) {
  31652. case 'scalar':
  31653. case 'double':
  31654. case 'float':
  31655. case 'number':
  31656. case 'integer':
  31657. return NumberKeyframeTrack;
  31658. case 'vector':
  31659. case 'vector2':
  31660. case 'vector3':
  31661. case 'vector4':
  31662. return VectorKeyframeTrack;
  31663. case 'color':
  31664. return ColorKeyframeTrack;
  31665. case 'quaternion':
  31666. return QuaternionKeyframeTrack;
  31667. case 'bool':
  31668. case 'boolean':
  31669. return BooleanKeyframeTrack;
  31670. case 'string':
  31671. return StringKeyframeTrack;
  31672. }
  31673. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  31674. }
  31675. function parseKeyframeTrack( json ) {
  31676. if ( json.type === undefined ) {
  31677. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  31678. }
  31679. const trackType = getTrackTypeForValueTypeName( json.type );
  31680. if ( json.times === undefined ) {
  31681. const times = [], values = [];
  31682. flattenJSON( json.keys, times, values, 'value' );
  31683. json.times = times;
  31684. json.values = values;
  31685. }
  31686. // derived classes can define a static parse method
  31687. if ( trackType.parse !== undefined ) {
  31688. return trackType.parse( json );
  31689. } else {
  31690. // by default, we assume a constructor compatible with the base
  31691. return new trackType( json.name, json.times, json.values, json.interpolation );
  31692. }
  31693. }
  31694. /**
  31695. * @class
  31696. * @classdesc A simple caching system, used internally by {@link FileLoader}.
  31697. * To enable caching across all loaders that use {@link FileLoader}, add `THREE.Cache.enabled = true.` once in your app.
  31698. * @hideconstructor
  31699. */
  31700. const Cache = {
  31701. /**
  31702. * Whether caching is enabled or not.
  31703. *
  31704. * @static
  31705. * @type {boolean}
  31706. * @default false
  31707. */
  31708. enabled: false,
  31709. /**
  31710. * A dictionary that holds cached files.
  31711. *
  31712. * @static
  31713. * @type {Object<string,Object>}
  31714. */
  31715. files: {},
  31716. /**
  31717. * Adds a cache entry with a key to reference the file. If this key already
  31718. * holds a file, it is overwritten.
  31719. *
  31720. * @static
  31721. * @param {string} key - The key to reference the cached file.
  31722. * @param {Object} file - The file to be cached.
  31723. */
  31724. add: function ( key, file ) {
  31725. if ( this.enabled === false ) return;
  31726. if ( isBlobURL( key ) ) return;
  31727. // log( 'Cache', 'Adding key:', key );
  31728. this.files[ key ] = file;
  31729. },
  31730. /**
  31731. * Gets the cached value for the given key.
  31732. *
  31733. * @static
  31734. * @param {string} key - The key to reference the cached file.
  31735. * @return {Object|undefined} The cached file. If the key does not exist `undefined` is returned.
  31736. */
  31737. get: function ( key ) {
  31738. if ( this.enabled === false ) return;
  31739. if ( isBlobURL( key ) ) return;
  31740. // log( 'Cache', 'Checking key:', key );
  31741. return this.files[ key ];
  31742. },
  31743. /**
  31744. * Removes the cached file associated with the given key.
  31745. *
  31746. * @static
  31747. * @param {string} key - The key to reference the cached file.
  31748. */
  31749. remove: function ( key ) {
  31750. delete this.files[ key ];
  31751. },
  31752. /**
  31753. * Remove all values from the cache.
  31754. *
  31755. * @static
  31756. */
  31757. clear: function () {
  31758. this.files = {};
  31759. }
  31760. };
  31761. /**
  31762. * Returns true if the given cache key contains the blob: scheme.
  31763. *
  31764. * @private
  31765. * @param {string} key - The cache key.
  31766. * @return {boolean} Whether the given cache key contains the blob: scheme or not.
  31767. */
  31768. function isBlobURL( key ) {
  31769. try {
  31770. const urlString = key.slice( key.indexOf( ':' ) + 1 ); // remove type identifier
  31771. const url = new URL( urlString );
  31772. return url.protocol === 'blob:';
  31773. } catch ( e ) {
  31774. // If the string is not a valid URL, it throws an error
  31775. return false;
  31776. }
  31777. }
  31778. /**
  31779. * Handles and keeps track of loaded and pending data. A default global
  31780. * instance of this class is created and used by loaders if not supplied
  31781. * manually.
  31782. *
  31783. * In general that should be sufficient, however there are times when it can
  31784. * be useful to have separate loaders - for example if you want to show
  31785. * separate loading bars for objects and textures.
  31786. *
  31787. * ```js
  31788. * const manager = new THREE.LoadingManager();
  31789. * manager.onLoad = () => console.log( 'Loading complete!' );
  31790. *
  31791. * const loader1 = new OBJLoader( manager );
  31792. * const loader2 = new ColladaLoader( manager );
  31793. * ```
  31794. */
  31795. class LoadingManager {
  31796. /**
  31797. * Constructs a new loading manager.
  31798. *
  31799. * @param {Function} [onLoad] - Executes when all items have been loaded.
  31800. * @param {Function} [onProgress] - Executes when single items have been loaded.
  31801. * @param {Function} [onError] - Executes when an error occurs.
  31802. */
  31803. constructor( onLoad, onProgress, onError ) {
  31804. const scope = this;
  31805. let isLoading = false;
  31806. let itemsLoaded = 0;
  31807. let itemsTotal = 0;
  31808. let urlModifier = undefined;
  31809. const handlers = [];
  31810. // Refer to #5689 for the reason why we don't set .onStart
  31811. // in the constructor
  31812. /**
  31813. * Executes when an item starts loading.
  31814. *
  31815. * @type {Function|undefined}
  31816. * @default undefined
  31817. */
  31818. this.onStart = undefined;
  31819. /**
  31820. * Executes when all items have been loaded.
  31821. *
  31822. * @type {Function|undefined}
  31823. * @default undefined
  31824. */
  31825. this.onLoad = onLoad;
  31826. /**
  31827. * Executes when single items have been loaded.
  31828. *
  31829. * @type {Function|undefined}
  31830. * @default undefined
  31831. */
  31832. this.onProgress = onProgress;
  31833. /**
  31834. * Executes when an error occurs.
  31835. *
  31836. * @type {Function|undefined}
  31837. * @default undefined
  31838. */
  31839. this.onError = onError;
  31840. /**
  31841. * Used for aborting ongoing requests in loaders using this manager.
  31842. *
  31843. * @private
  31844. * @type {AbortController | null}
  31845. */
  31846. this._abortController = null;
  31847. /**
  31848. * This should be called by any loader using the manager when the loader
  31849. * starts loading an item.
  31850. *
  31851. * @param {string} url - The URL to load.
  31852. */
  31853. this.itemStart = function ( url ) {
  31854. itemsTotal ++;
  31855. if ( isLoading === false ) {
  31856. if ( scope.onStart !== undefined ) {
  31857. scope.onStart( url, itemsLoaded, itemsTotal );
  31858. }
  31859. }
  31860. isLoading = true;
  31861. };
  31862. /**
  31863. * This should be called by any loader using the manager when the loader
  31864. * ended loading an item.
  31865. *
  31866. * @param {string} url - The URL of the loaded item.
  31867. */
  31868. this.itemEnd = function ( url ) {
  31869. itemsLoaded ++;
  31870. if ( scope.onProgress !== undefined ) {
  31871. scope.onProgress( url, itemsLoaded, itemsTotal );
  31872. }
  31873. if ( itemsLoaded === itemsTotal ) {
  31874. isLoading = false;
  31875. if ( scope.onLoad !== undefined ) {
  31876. scope.onLoad();
  31877. }
  31878. }
  31879. };
  31880. /**
  31881. * This should be called by any loader using the manager when the loader
  31882. * encounters an error when loading an item.
  31883. *
  31884. * @param {string} url - The URL of the item that produces an error.
  31885. */
  31886. this.itemError = function ( url ) {
  31887. if ( scope.onError !== undefined ) {
  31888. scope.onError( url );
  31889. }
  31890. };
  31891. /**
  31892. * Given a URL, uses the URL modifier callback (if any) and returns a
  31893. * resolved URL. If no URL modifier is set, returns the original URL.
  31894. *
  31895. * @param {string} url - The URL to load.
  31896. * @return {string} The resolved URL.
  31897. */
  31898. this.resolveURL = function ( url ) {
  31899. if ( urlModifier ) {
  31900. return urlModifier( url );
  31901. }
  31902. return url;
  31903. };
  31904. /**
  31905. * If provided, the callback will be passed each resource URL before a
  31906. * request is sent. The callback may return the original URL, or a new URL to
  31907. * override loading behavior. This behavior can be used to load assets from
  31908. * .ZIP files, drag-and-drop APIs, and Data URIs.
  31909. *
  31910. * ```js
  31911. * const blobs = {'fish.gltf': blob1, 'diffuse.png': blob2, 'normal.png': blob3};
  31912. *
  31913. * const manager = new THREE.LoadingManager();
  31914. *
  31915. * // Initialize loading manager with URL callback.
  31916. * const objectURLs = [];
  31917. * manager.setURLModifier( ( url ) => {
  31918. *
  31919. * url = URL.createObjectURL( blobs[ url ] );
  31920. * objectURLs.push( url );
  31921. * return url;
  31922. *
  31923. * } );
  31924. *
  31925. * // Load as usual, then revoke the blob URLs.
  31926. * const loader = new GLTFLoader( manager );
  31927. * loader.load( 'fish.gltf', (gltf) => {
  31928. *
  31929. * scene.add( gltf.scene );
  31930. * objectURLs.forEach( ( url ) => URL.revokeObjectURL( url ) );
  31931. *
  31932. * } );
  31933. * ```
  31934. *
  31935. * @param {function(string):string} transform - URL modifier callback. Called with an URL and must return a resolved URL.
  31936. * @return {LoadingManager} A reference to this loading manager.
  31937. */
  31938. this.setURLModifier = function ( transform ) {
  31939. urlModifier = transform;
  31940. return this;
  31941. };
  31942. /**
  31943. * Registers a loader with the given regular expression. Can be used to
  31944. * define what loader should be used in order to load specific files. A
  31945. * typical use case is to overwrite the default loader for textures.
  31946. *
  31947. * ```js
  31948. * // add handler for TGA textures
  31949. * manager.addHandler( /\.tga$/i, new TGALoader() );
  31950. * ```
  31951. *
  31952. * @param {string} regex - A regular expression.
  31953. * @param {Loader} loader - A loader that should handle matched cases.
  31954. * @return {LoadingManager} A reference to this loading manager.
  31955. */
  31956. this.addHandler = function ( regex, loader ) {
  31957. handlers.push( regex, loader );
  31958. return this;
  31959. };
  31960. /**
  31961. * Removes the loader for the given regular expression.
  31962. *
  31963. * @param {string} regex - A regular expression.
  31964. * @return {LoadingManager} A reference to this loading manager.
  31965. */
  31966. this.removeHandler = function ( regex ) {
  31967. const index = handlers.indexOf( regex );
  31968. if ( index !== -1 ) {
  31969. handlers.splice( index, 2 );
  31970. }
  31971. return this;
  31972. };
  31973. /**
  31974. * Can be used to retrieve the registered loader for the given file path.
  31975. *
  31976. * @param {string} file - The file path.
  31977. * @return {?Loader} The registered loader. Returns `null` if no loader was found.
  31978. */
  31979. this.getHandler = function ( file ) {
  31980. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  31981. const regex = handlers[ i ];
  31982. const loader = handlers[ i + 1 ];
  31983. if ( regex.global ) regex.lastIndex = 0; // see #17920
  31984. if ( regex.test( file ) ) {
  31985. return loader;
  31986. }
  31987. }
  31988. return null;
  31989. };
  31990. /**
  31991. * Can be used to abort ongoing loading requests in loaders using this manager.
  31992. * The abort only works if the loaders implement {@link Loader#abort} and `AbortSignal.any()`
  31993. * is supported in the browser.
  31994. *
  31995. * @return {LoadingManager} A reference to this loading manager.
  31996. */
  31997. this.abort = function () {
  31998. this.abortController.abort();
  31999. this._abortController = null;
  32000. return this;
  32001. };
  32002. }
  32003. // TODO: Revert this back to a single member variable once this issue has been fixed
  32004. // https://github.com/cloudflare/workerd/issues/3657
  32005. /**
  32006. * Used for aborting ongoing requests in loaders using this manager.
  32007. *
  32008. * @type {AbortController}
  32009. */
  32010. get abortController() {
  32011. if ( ! this._abortController ) {
  32012. this._abortController = new AbortController();
  32013. }
  32014. return this._abortController;
  32015. }
  32016. }
  32017. /**
  32018. * The global default loading manager.
  32019. *
  32020. * @constant
  32021. * @type {LoadingManager}
  32022. */
  32023. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  32024. /**
  32025. * Abstract base class for loaders.
  32026. *
  32027. * @abstract
  32028. */
  32029. class Loader {
  32030. /**
  32031. * Constructs a new loader.
  32032. *
  32033. * @param {LoadingManager} [manager] - The loading manager.
  32034. */
  32035. constructor( manager ) {
  32036. /**
  32037. * The loading manager.
  32038. *
  32039. * @type {LoadingManager}
  32040. * @default DefaultLoadingManager
  32041. */
  32042. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  32043. /**
  32044. * The crossOrigin string to implement CORS for loading the url from a
  32045. * different domain that allows CORS.
  32046. *
  32047. * @type {string}
  32048. * @default 'anonymous'
  32049. */
  32050. this.crossOrigin = 'anonymous';
  32051. /**
  32052. * Whether the XMLHttpRequest uses credentials.
  32053. *
  32054. * @type {boolean}
  32055. * @default false
  32056. */
  32057. this.withCredentials = false;
  32058. /**
  32059. * The base path from which the asset will be loaded.
  32060. *
  32061. * @type {string}
  32062. */
  32063. this.path = '';
  32064. /**
  32065. * The base path from which additional resources like textures will be loaded.
  32066. *
  32067. * @type {string}
  32068. */
  32069. this.resourcePath = '';
  32070. /**
  32071. * The [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header)
  32072. * used in HTTP request.
  32073. *
  32074. * @type {Object<string, any>}
  32075. */
  32076. this.requestHeader = {};
  32077. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  32078. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  32079. }
  32080. }
  32081. /**
  32082. * This method needs to be implemented by all concrete loaders. It holds the
  32083. * logic for loading assets from the backend.
  32084. *
  32085. * @abstract
  32086. * @param {string} url - The path/URL of the file to be loaded.
  32087. * @param {Function} onLoad - Executed when the loading process has been finished.
  32088. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32089. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32090. */
  32091. load( /* url, onLoad, onProgress, onError */ ) {}
  32092. /**
  32093. * A async version of {@link Loader#load}.
  32094. *
  32095. * @param {string} url - The path/URL of the file to be loaded.
  32096. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32097. * @return {Promise} A Promise that resolves when the asset has been loaded.
  32098. */
  32099. loadAsync( url, onProgress ) {
  32100. const scope = this;
  32101. return new Promise( function ( resolve, reject ) {
  32102. scope.load( url, resolve, onProgress, reject );
  32103. } );
  32104. }
  32105. /**
  32106. * This method needs to be implemented by all concrete loaders. It holds the
  32107. * logic for parsing the asset into three.js entities.
  32108. *
  32109. * @abstract
  32110. * @param {any} data - The data to parse.
  32111. */
  32112. parse( /* data */ ) {}
  32113. /**
  32114. * Sets the `crossOrigin` String to implement CORS for loading the URL
  32115. * from a different domain that allows CORS.
  32116. *
  32117. * @param {string} crossOrigin - The `crossOrigin` value.
  32118. * @return {Loader} A reference to this instance.
  32119. */
  32120. setCrossOrigin( crossOrigin ) {
  32121. this.crossOrigin = crossOrigin;
  32122. return this;
  32123. }
  32124. /**
  32125. * Whether the XMLHttpRequest uses credentials such as cookies, authorization
  32126. * headers or TLS client certificates, see [XMLHttpRequest.withCredentials](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials).
  32127. *
  32128. * Note: This setting has no effect if you are loading files locally or from the same domain.
  32129. *
  32130. * @param {boolean} value - The `withCredentials` value.
  32131. * @return {Loader} A reference to this instance.
  32132. */
  32133. setWithCredentials( value ) {
  32134. this.withCredentials = value;
  32135. return this;
  32136. }
  32137. /**
  32138. * Sets the base path for the asset.
  32139. *
  32140. * @param {string} path - The base path.
  32141. * @return {Loader} A reference to this instance.
  32142. */
  32143. setPath( path ) {
  32144. this.path = path;
  32145. return this;
  32146. }
  32147. /**
  32148. * Sets the base path for dependent resources like textures.
  32149. *
  32150. * @param {string} resourcePath - The resource path.
  32151. * @return {Loader} A reference to this instance.
  32152. */
  32153. setResourcePath( resourcePath ) {
  32154. this.resourcePath = resourcePath;
  32155. return this;
  32156. }
  32157. /**
  32158. * Sets the given request header.
  32159. *
  32160. * @param {Object} requestHeader - A [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header)
  32161. * for configuring the HTTP request.
  32162. * @return {Loader} A reference to this instance.
  32163. */
  32164. setRequestHeader( requestHeader ) {
  32165. this.requestHeader = requestHeader;
  32166. return this;
  32167. }
  32168. /**
  32169. * This method can be implemented in loaders for aborting ongoing requests.
  32170. *
  32171. * @abstract
  32172. * @return {Loader} A reference to this instance.
  32173. */
  32174. abort() {
  32175. return this;
  32176. }
  32177. }
  32178. /**
  32179. * Callback for onProgress in loaders.
  32180. *
  32181. * @callback onProgressCallback
  32182. * @param {ProgressEvent} event - An instance of `ProgressEvent` that represents the current loading status.
  32183. */
  32184. /**
  32185. * Callback for onError in loaders.
  32186. *
  32187. * @callback onErrorCallback
  32188. * @param {Error} error - The error which occurred during the loading process.
  32189. */
  32190. /**
  32191. * The default material name that is used by loaders
  32192. * when creating materials for loaded 3D objects.
  32193. *
  32194. * Note: Not all loaders might honor this setting.
  32195. *
  32196. * @static
  32197. * @type {string}
  32198. * @default '__DEFAULT'
  32199. */
  32200. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  32201. const loading = {};
  32202. class HttpError extends Error {
  32203. constructor( message, response ) {
  32204. super( message );
  32205. this.response = response;
  32206. }
  32207. }
  32208. /**
  32209. * A low level class for loading resources with the Fetch API, used internally by
  32210. * most loaders. It can also be used directly to load any file type that does
  32211. * not have a loader.
  32212. *
  32213. * This loader supports caching. If you want to use it, add `THREE.Cache.enabled = true;`
  32214. * once to your application.
  32215. *
  32216. * ```js
  32217. * const loader = new THREE.FileLoader();
  32218. * const data = await loader.loadAsync( 'example.txt' );
  32219. * ```
  32220. *
  32221. * @augments Loader
  32222. */
  32223. class FileLoader extends Loader {
  32224. /**
  32225. * Constructs a new file loader.
  32226. *
  32227. * @param {LoadingManager} [manager] - The loading manager.
  32228. */
  32229. constructor( manager ) {
  32230. super( manager );
  32231. /**
  32232. * The expected mime type. Valid values can be found
  32233. * [here](https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#mimetype)
  32234. *
  32235. * @type {string}
  32236. */
  32237. this.mimeType = '';
  32238. /**
  32239. * The expected response type.
  32240. *
  32241. * @type {('arraybuffer'|'blob'|'document'|'json'|'')}
  32242. * @default ''
  32243. */
  32244. this.responseType = '';
  32245. /**
  32246. * Used for aborting requests.
  32247. *
  32248. * @private
  32249. * @type {AbortController}
  32250. */
  32251. this._abortController = new AbortController();
  32252. }
  32253. /**
  32254. * Starts loading from the given URL and pass the loaded response to the `onLoad()` callback.
  32255. *
  32256. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32257. * @param {function(any)} onLoad - Executed when the loading process has been finished.
  32258. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32259. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32260. * @return {any|undefined} The cached resource if available.
  32261. */
  32262. load( url, onLoad, onProgress, onError ) {
  32263. if ( url === undefined ) url = '';
  32264. if ( this.path !== undefined ) url = this.path + url;
  32265. url = this.manager.resolveURL( url );
  32266. const cached = Cache.get( `file:${url}` );
  32267. if ( cached !== undefined ) {
  32268. this.manager.itemStart( url );
  32269. setTimeout( () => {
  32270. if ( onLoad ) onLoad( cached );
  32271. this.manager.itemEnd( url );
  32272. }, 0 );
  32273. return cached;
  32274. }
  32275. // Check if request is duplicate
  32276. if ( loading[ url ] !== undefined ) {
  32277. loading[ url ].push( {
  32278. onLoad: onLoad,
  32279. onProgress: onProgress,
  32280. onError: onError
  32281. } );
  32282. return;
  32283. }
  32284. // Initialise array for duplicate requests
  32285. loading[ url ] = [];
  32286. loading[ url ].push( {
  32287. onLoad: onLoad,
  32288. onProgress: onProgress,
  32289. onError: onError,
  32290. } );
  32291. // create request
  32292. const req = new Request( url, {
  32293. headers: new Headers( this.requestHeader ),
  32294. credentials: this.withCredentials ? 'include' : 'same-origin',
  32295. signal: ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal
  32296. } );
  32297. // record states ( avoid data race )
  32298. const mimeType = this.mimeType;
  32299. const responseType = this.responseType;
  32300. // start the fetch
  32301. fetch( req )
  32302. .then( response => {
  32303. if ( response.status === 200 || response.status === 0 ) {
  32304. // Some browsers return HTTP Status 0 when using non-http protocol
  32305. // e.g. 'file://' or 'data://'. Handle as success.
  32306. if ( response.status === 0 ) {
  32307. warn( 'FileLoader: HTTP Status 0 received.' );
  32308. }
  32309. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  32310. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  32311. return response;
  32312. }
  32313. const callbacks = loading[ url ];
  32314. const reader = response.body.getReader();
  32315. // Nginx needs X-File-Size check
  32316. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  32317. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  32318. const total = contentLength ? parseInt( contentLength ) : 0;
  32319. const lengthComputable = total !== 0;
  32320. let loaded = 0;
  32321. // periodically read data into the new stream tracking while download progress
  32322. const stream = new ReadableStream( {
  32323. start( controller ) {
  32324. readData();
  32325. function readData() {
  32326. reader.read().then( ( { done, value } ) => {
  32327. if ( done ) {
  32328. controller.close();
  32329. } else {
  32330. loaded += value.byteLength;
  32331. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  32332. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32333. const callback = callbacks[ i ];
  32334. if ( callback.onProgress ) callback.onProgress( event );
  32335. }
  32336. controller.enqueue( value );
  32337. readData();
  32338. }
  32339. }, ( e ) => {
  32340. controller.error( e );
  32341. } );
  32342. }
  32343. }
  32344. } );
  32345. return new Response( stream );
  32346. } else {
  32347. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  32348. }
  32349. } )
  32350. .then( response => {
  32351. switch ( responseType ) {
  32352. case 'arraybuffer':
  32353. return response.arrayBuffer();
  32354. case 'blob':
  32355. return response.blob();
  32356. case 'document':
  32357. return response.text()
  32358. .then( text => {
  32359. const parser = new DOMParser();
  32360. return parser.parseFromString( text, mimeType );
  32361. } );
  32362. case 'json':
  32363. return response.json();
  32364. default:
  32365. if ( mimeType === '' ) {
  32366. return response.text();
  32367. } else {
  32368. // sniff encoding
  32369. const re = /charset="?([^;"\s]*)"?/i;
  32370. const exec = re.exec( mimeType );
  32371. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  32372. const decoder = new TextDecoder( label );
  32373. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  32374. }
  32375. }
  32376. } )
  32377. .then( data => {
  32378. // Add to cache only on HTTP success, so that we do not cache
  32379. // error response bodies as proper responses to requests.
  32380. Cache.add( `file:${url}`, data );
  32381. const callbacks = loading[ url ];
  32382. delete loading[ url ];
  32383. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32384. const callback = callbacks[ i ];
  32385. if ( callback.onLoad ) callback.onLoad( data );
  32386. }
  32387. } )
  32388. .catch( err => {
  32389. // Abort errors and other errors are handled the same
  32390. const callbacks = loading[ url ];
  32391. if ( callbacks === undefined ) {
  32392. // When onLoad was called and url was deleted in `loading`
  32393. this.manager.itemError( url );
  32394. throw err;
  32395. }
  32396. delete loading[ url ];
  32397. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32398. const callback = callbacks[ i ];
  32399. if ( callback.onError ) callback.onError( err );
  32400. }
  32401. this.manager.itemError( url );
  32402. } )
  32403. .finally( () => {
  32404. this.manager.itemEnd( url );
  32405. } );
  32406. this.manager.itemStart( url );
  32407. }
  32408. /**
  32409. * Sets the expected response type.
  32410. *
  32411. * @param {('arraybuffer'|'blob'|'document'|'json'|'')} value - The response type.
  32412. * @return {FileLoader} A reference to this file loader.
  32413. */
  32414. setResponseType( value ) {
  32415. this.responseType = value;
  32416. return this;
  32417. }
  32418. /**
  32419. * Sets the expected mime type of the loaded file.
  32420. *
  32421. * @param {string} value - The mime type.
  32422. * @return {FileLoader} A reference to this file loader.
  32423. */
  32424. setMimeType( value ) {
  32425. this.mimeType = value;
  32426. return this;
  32427. }
  32428. /**
  32429. * Aborts ongoing fetch requests.
  32430. *
  32431. * @return {FileLoader} A reference to this instance.
  32432. */
  32433. abort() {
  32434. this._abortController.abort();
  32435. this._abortController = new AbortController();
  32436. return this;
  32437. }
  32438. }
  32439. /**
  32440. * Class for loading animation clips in the JSON format. The files are internally
  32441. * loaded via {@link FileLoader}.
  32442. *
  32443. * ```js
  32444. * const loader = new THREE.AnimationLoader();
  32445. * const animations = await loader.loadAsync( 'animations/animation.js' );
  32446. * ```
  32447. *
  32448. * @augments Loader
  32449. */
  32450. class AnimationLoader extends Loader {
  32451. /**
  32452. * Constructs a new animation loader.
  32453. *
  32454. * @param {LoadingManager} [manager] - The loading manager.
  32455. */
  32456. constructor( manager ) {
  32457. super( manager );
  32458. }
  32459. /**
  32460. * Starts loading from the given URL and pass the loaded animations as an array
  32461. * holding instances of {@link AnimationClip} to the `onLoad()` callback.
  32462. *
  32463. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32464. * @param {function(Array<AnimationClip>)} onLoad - Executed when the loading process has been finished.
  32465. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32466. * @param {onErrorCallback} onError - Executed when errors occur.
  32467. */
  32468. load( url, onLoad, onProgress, onError ) {
  32469. const scope = this;
  32470. const loader = new FileLoader( this.manager );
  32471. loader.setPath( this.path );
  32472. loader.setRequestHeader( this.requestHeader );
  32473. loader.setWithCredentials( this.withCredentials );
  32474. loader.load( url, function ( text ) {
  32475. try {
  32476. onLoad( scope.parse( JSON.parse( text ) ) );
  32477. } catch ( e ) {
  32478. if ( onError ) {
  32479. onError( e );
  32480. } else {
  32481. error( e );
  32482. }
  32483. scope.manager.itemError( url );
  32484. }
  32485. }, onProgress, onError );
  32486. }
  32487. /**
  32488. * Parses the given JSON object and returns an array of animation clips.
  32489. *
  32490. * @param {Object} json - The serialized animation clips.
  32491. * @return {Array<AnimationClip>} The parsed animation clips.
  32492. */
  32493. parse( json ) {
  32494. const animations = [];
  32495. for ( let i = 0; i < json.length; i ++ ) {
  32496. const clip = AnimationClip.parse( json[ i ] );
  32497. animations.push( clip );
  32498. }
  32499. return animations;
  32500. }
  32501. }
  32502. /**
  32503. * Abstract base class for loading compressed texture formats S3TC, ASTC or ETC.
  32504. * Textures are internally loaded via {@link FileLoader}.
  32505. *
  32506. * Derived classes have to implement the `parse()` method which holds the parsing
  32507. * for the respective format.
  32508. *
  32509. * @abstract
  32510. * @augments Loader
  32511. */
  32512. class CompressedTextureLoader extends Loader {
  32513. /**
  32514. * Constructs a new compressed texture loader.
  32515. *
  32516. * @param {LoadingManager} [manager] - The loading manager.
  32517. */
  32518. constructor( manager ) {
  32519. super( manager );
  32520. }
  32521. /**
  32522. * Starts loading from the given URL and passes the loaded compressed texture
  32523. * to the `onLoad()` callback. The method also returns a new texture object which can
  32524. * directly be used for material creation. If you do it this way, the texture
  32525. * may pop up in your scene once the respective loading process is finished.
  32526. *
  32527. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32528. * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished.
  32529. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32530. * @param {onErrorCallback} onError - Executed when errors occur.
  32531. * @return {CompressedTexture} The compressed texture.
  32532. */
  32533. load( url, onLoad, onProgress, onError ) {
  32534. const scope = this;
  32535. const images = [];
  32536. const texture = new CompressedTexture();
  32537. const loader = new FileLoader( this.manager );
  32538. loader.setPath( this.path );
  32539. loader.setResponseType( 'arraybuffer' );
  32540. loader.setRequestHeader( this.requestHeader );
  32541. loader.setWithCredentials( scope.withCredentials );
  32542. let loaded = 0;
  32543. function loadTexture( i ) {
  32544. loader.load( url[ i ], function ( buffer ) {
  32545. const texDatas = scope.parse( buffer, true );
  32546. images[ i ] = {
  32547. width: texDatas.width,
  32548. height: texDatas.height,
  32549. format: texDatas.format,
  32550. mipmaps: texDatas.mipmaps
  32551. };
  32552. loaded += 1;
  32553. if ( loaded === 6 ) {
  32554. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  32555. texture.image = images;
  32556. texture.format = texDatas.format;
  32557. texture.needsUpdate = true;
  32558. if ( onLoad ) onLoad( texture );
  32559. }
  32560. }, onProgress, onError );
  32561. }
  32562. if ( Array.isArray( url ) ) {
  32563. for ( let i = 0, il = url.length; i < il; ++ i ) {
  32564. loadTexture( i );
  32565. }
  32566. } else {
  32567. // compressed cubemap texture stored in a single DDS file
  32568. loader.load( url, function ( buffer ) {
  32569. const texDatas = scope.parse( buffer, true );
  32570. if ( texDatas.isCubemap ) {
  32571. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  32572. for ( let f = 0; f < faces; f ++ ) {
  32573. images[ f ] = { mipmaps: [] };
  32574. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  32575. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  32576. images[ f ].format = texDatas.format;
  32577. images[ f ].width = texDatas.width;
  32578. images[ f ].height = texDatas.height;
  32579. }
  32580. }
  32581. texture.image = images;
  32582. } else {
  32583. texture.image.width = texDatas.width;
  32584. texture.image.height = texDatas.height;
  32585. texture.mipmaps = texDatas.mipmaps;
  32586. }
  32587. if ( texDatas.mipmapCount === 1 ) {
  32588. texture.minFilter = LinearFilter;
  32589. }
  32590. texture.format = texDatas.format;
  32591. texture.needsUpdate = true;
  32592. if ( onLoad ) onLoad( texture );
  32593. }, onProgress, onError );
  32594. }
  32595. return texture;
  32596. }
  32597. }
  32598. const _loading = new WeakMap();
  32599. /**
  32600. * A loader for loading images. The class loads images with the HTML `Image` API.
  32601. *
  32602. * ```js
  32603. * const loader = new THREE.ImageLoader();
  32604. * const image = await loader.loadAsync( 'image.png' );
  32605. * ```
  32606. * Please note that `ImageLoader` has dropped support for progress
  32607. * events in `r84`. For an `ImageLoader` that supports progress events, see
  32608. * [this thread](https://github.com/mrdoob/three.js/issues/10439#issuecomment-275785639).
  32609. *
  32610. * @augments Loader
  32611. */
  32612. class ImageLoader extends Loader {
  32613. /**
  32614. * Constructs a new image loader.
  32615. *
  32616. * @param {LoadingManager} [manager] - The loading manager.
  32617. */
  32618. constructor( manager ) {
  32619. super( manager );
  32620. }
  32621. /**
  32622. * Starts loading from the given URL and passes the loaded image
  32623. * to the `onLoad()` callback. The method also returns a new `Image` object which can
  32624. * directly be used for texture creation. If you do it this way, the texture
  32625. * may pop up in your scene once the respective loading process is finished.
  32626. *
  32627. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32628. * @param {function(Image)} onLoad - Executed when the loading process has been finished.
  32629. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32630. * @param {onErrorCallback} onError - Executed when errors occur.
  32631. * @return {Image} The image.
  32632. */
  32633. load( url, onLoad, onProgress, onError ) {
  32634. if ( this.path !== undefined ) url = this.path + url;
  32635. url = this.manager.resolveURL( url );
  32636. const scope = this;
  32637. const cached = Cache.get( `image:${url}` );
  32638. if ( cached !== undefined ) {
  32639. if ( cached.complete === true ) {
  32640. scope.manager.itemStart( url );
  32641. setTimeout( function () {
  32642. if ( onLoad ) onLoad( cached );
  32643. scope.manager.itemEnd( url );
  32644. }, 0 );
  32645. } else {
  32646. let arr = _loading.get( cached );
  32647. if ( arr === undefined ) {
  32648. arr = [];
  32649. _loading.set( cached, arr );
  32650. }
  32651. arr.push( { onLoad, onError } );
  32652. }
  32653. return cached;
  32654. }
  32655. const image = createElementNS( 'img' );
  32656. function onImageLoad() {
  32657. removeEventListeners();
  32658. if ( onLoad ) onLoad( this );
  32659. //
  32660. const callbacks = _loading.get( this ) || [];
  32661. for ( let i = 0; i < callbacks.length; i ++ ) {
  32662. const callback = callbacks[ i ];
  32663. if ( callback.onLoad ) callback.onLoad( this );
  32664. }
  32665. _loading.delete( this );
  32666. scope.manager.itemEnd( url );
  32667. }
  32668. function onImageError( event ) {
  32669. removeEventListeners();
  32670. if ( onError ) onError( event );
  32671. Cache.remove( `image:${url}` );
  32672. //
  32673. const callbacks = _loading.get( this ) || [];
  32674. for ( let i = 0; i < callbacks.length; i ++ ) {
  32675. const callback = callbacks[ i ];
  32676. if ( callback.onError ) callback.onError( event );
  32677. }
  32678. _loading.delete( this );
  32679. scope.manager.itemError( url );
  32680. scope.manager.itemEnd( url );
  32681. }
  32682. function removeEventListeners() {
  32683. image.removeEventListener( 'load', onImageLoad, false );
  32684. image.removeEventListener( 'error', onImageError, false );
  32685. }
  32686. image.addEventListener( 'load', onImageLoad, false );
  32687. image.addEventListener( 'error', onImageError, false );
  32688. if ( url.slice( 0, 5 ) !== 'data:' ) {
  32689. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  32690. }
  32691. Cache.add( `image:${url}`, image );
  32692. scope.manager.itemStart( url );
  32693. image.src = url;
  32694. return image;
  32695. }
  32696. }
  32697. /**
  32698. * Class for loading cube textures. Images are internally loaded via {@link ImageLoader}.
  32699. *
  32700. * The loader returns an instance of {@link CubeTexture} and expects the cube map to
  32701. * be defined as six separate images representing the sides of a cube. Other cube map definitions
  32702. * like vertical and horizontal cross, column and row layouts are not supported.
  32703. *
  32704. * Note that, by convention, cube maps are specified in a coordinate system
  32705. * in which positive-x is to the right when looking up the positive-z axis --
  32706. * in other words, using a left-handed coordinate system. Since three.js uses
  32707. * a right-handed coordinate system, environment maps used in three.js will
  32708. * have pos-x and neg-x swapped.
  32709. *
  32710. * The loaded cube texture is in sRGB color space. Meaning {@link Texture#colorSpace}
  32711. * is set to `SRGBColorSpace` by default.
  32712. *
  32713. * ```js
  32714. * const loader = new THREE.CubeTextureLoader().setPath( 'textures/cubeMaps/' );
  32715. * const cubeTexture = await loader.loadAsync( [
  32716. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  32717. * ] );
  32718. * scene.background = cubeTexture;
  32719. * ```
  32720. *
  32721. * @augments Loader
  32722. */
  32723. class CubeTextureLoader extends Loader {
  32724. /**
  32725. * Constructs a new cube texture loader.
  32726. *
  32727. * @param {LoadingManager} [manager] - The loading manager.
  32728. */
  32729. constructor( manager ) {
  32730. super( manager );
  32731. }
  32732. /**
  32733. * Starts loading from the given URL and pass the fully loaded cube texture
  32734. * to the `onLoad()` callback. The method also returns a new cube texture object which can
  32735. * directly be used for material creation. If you do it this way, the cube texture
  32736. * may pop up in your scene once the respective loading process is finished.
  32737. *
  32738. * @param {Array<string>} urls - Array of 6 URLs to images, one for each side of the
  32739. * cube texture. The urls should be specified in the following order: pos-x,
  32740. * neg-x, pos-y, neg-y, pos-z, neg-z. An array of data URIs are allowed as well.
  32741. * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished.
  32742. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32743. * @param {onErrorCallback} onError - Executed when errors occur.
  32744. * @return {CubeTexture} The cube texture.
  32745. */
  32746. load( urls, onLoad, onProgress, onError ) {
  32747. const texture = new CubeTexture();
  32748. texture.colorSpace = SRGBColorSpace;
  32749. const loader = new ImageLoader( this.manager );
  32750. loader.setCrossOrigin( this.crossOrigin );
  32751. loader.setPath( this.path );
  32752. let loaded = 0;
  32753. function loadTexture( i ) {
  32754. loader.load( urls[ i ], function ( image ) {
  32755. texture.images[ i ] = image;
  32756. loaded ++;
  32757. if ( loaded === 6 ) {
  32758. texture.needsUpdate = true;
  32759. if ( onLoad ) onLoad( texture );
  32760. }
  32761. }, undefined, onError );
  32762. }
  32763. for ( let i = 0; i < urls.length; ++ i ) {
  32764. loadTexture( i );
  32765. }
  32766. return texture;
  32767. }
  32768. }
  32769. /**
  32770. * Abstract base class for loading binary texture formats RGBE, EXR or TGA.
  32771. * Textures are internally loaded via {@link FileLoader}.
  32772. *
  32773. * Derived classes have to implement the `parse()` method which holds the parsing
  32774. * for the respective format.
  32775. *
  32776. * @abstract
  32777. * @augments Loader
  32778. */
  32779. class DataTextureLoader extends Loader {
  32780. /**
  32781. * Constructs a new data texture loader.
  32782. *
  32783. * @param {LoadingManager} [manager] - The loading manager.
  32784. */
  32785. constructor( manager ) {
  32786. super( manager );
  32787. }
  32788. /**
  32789. * Starts loading from the given URL and passes the loaded data texture
  32790. * to the `onLoad()` callback. The method also returns a new texture object which can
  32791. * directly be used for material creation. If you do it this way, the texture
  32792. * may pop up in your scene once the respective loading process is finished.
  32793. *
  32794. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32795. * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished.
  32796. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32797. * @param {onErrorCallback} onError - Executed when errors occur.
  32798. * @return {DataTexture} The data texture.
  32799. */
  32800. load( url, onLoad, onProgress, onError ) {
  32801. const scope = this;
  32802. const texture = new DataTexture();
  32803. const loader = new FileLoader( this.manager );
  32804. loader.setResponseType( 'arraybuffer' );
  32805. loader.setRequestHeader( this.requestHeader );
  32806. loader.setPath( this.path );
  32807. loader.setWithCredentials( scope.withCredentials );
  32808. loader.load( url, function ( buffer ) {
  32809. let texData;
  32810. try {
  32811. texData = scope.parse( buffer );
  32812. } catch ( e ) {
  32813. if ( onError !== undefined ) {
  32814. onError( e );
  32815. } else {
  32816. error( e );
  32817. return;
  32818. }
  32819. }
  32820. if ( texData.image !== undefined ) {
  32821. texture.image = texData.image;
  32822. } else if ( texData.data !== undefined ) {
  32823. texture.image.width = texData.width;
  32824. texture.image.height = texData.height;
  32825. texture.image.data = texData.data;
  32826. }
  32827. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  32828. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  32829. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  32830. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  32831. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  32832. if ( texData.colorSpace !== undefined ) {
  32833. texture.colorSpace = texData.colorSpace;
  32834. }
  32835. if ( texData.flipY !== undefined ) {
  32836. texture.flipY = texData.flipY;
  32837. }
  32838. if ( texData.format !== undefined ) {
  32839. texture.format = texData.format;
  32840. }
  32841. if ( texData.type !== undefined ) {
  32842. texture.type = texData.type;
  32843. }
  32844. if ( texData.mipmaps !== undefined ) {
  32845. texture.mipmaps = texData.mipmaps;
  32846. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  32847. }
  32848. if ( texData.mipmapCount === 1 ) {
  32849. texture.minFilter = LinearFilter;
  32850. }
  32851. if ( texData.generateMipmaps !== undefined ) {
  32852. texture.generateMipmaps = texData.generateMipmaps;
  32853. }
  32854. texture.needsUpdate = true;
  32855. if ( onLoad ) onLoad( texture, texData );
  32856. }, onProgress, onError );
  32857. return texture;
  32858. }
  32859. }
  32860. /**
  32861. * Class for loading textures. Images are internally
  32862. * loaded via {@link ImageLoader}.
  32863. *
  32864. * ```js
  32865. * const loader = new THREE.TextureLoader();
  32866. * const texture = await loader.loadAsync( 'textures/land_ocean_ice_cloud_2048.jpg' );
  32867. *
  32868. * const material = new THREE.MeshBasicMaterial( { map:texture } );
  32869. * ```
  32870. * Please note that `TextureLoader` has dropped support for progress
  32871. * events in `r84`. For a `TextureLoader` that supports progress events, see
  32872. * [this thread](https://github.com/mrdoob/three.js/issues/10439#issuecomment-293260145).
  32873. *
  32874. * @augments Loader
  32875. */
  32876. class TextureLoader extends Loader {
  32877. /**
  32878. * Constructs a new texture loader.
  32879. *
  32880. * @param {LoadingManager} [manager] - The loading manager.
  32881. */
  32882. constructor( manager ) {
  32883. super( manager );
  32884. }
  32885. /**
  32886. * Starts loading from the given URL and pass the fully loaded texture
  32887. * to the `onLoad()` callback. The method also returns a new texture object which can
  32888. * directly be used for material creation. If you do it this way, the texture
  32889. * may pop up in your scene once the respective loading process is finished.
  32890. *
  32891. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32892. * @param {function(Texture)} onLoad - Executed when the loading process has been finished.
  32893. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32894. * @param {onErrorCallback} onError - Executed when errors occur.
  32895. * @return {Texture} The texture.
  32896. */
  32897. load( url, onLoad, onProgress, onError ) {
  32898. const texture = new Texture();
  32899. const loader = new ImageLoader( this.manager );
  32900. loader.setCrossOrigin( this.crossOrigin );
  32901. loader.setPath( this.path );
  32902. loader.load( url, function ( image ) {
  32903. texture.image = image;
  32904. texture.needsUpdate = true;
  32905. if ( onLoad !== undefined ) {
  32906. onLoad( texture );
  32907. }
  32908. }, onProgress, onError );
  32909. return texture;
  32910. }
  32911. }
  32912. /**
  32913. * Abstract base class for lights - all other light types inherit the
  32914. * properties and methods described here.
  32915. *
  32916. * @abstract
  32917. * @augments Object3D
  32918. */
  32919. class Light extends Object3D {
  32920. /**
  32921. * Constructs a new light.
  32922. *
  32923. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  32924. * @param {number} [intensity=1] - The light's strength/intensity.
  32925. */
  32926. constructor( color, intensity = 1 ) {
  32927. super();
  32928. /**
  32929. * This flag can be used for type testing.
  32930. *
  32931. * @type {boolean}
  32932. * @readonly
  32933. * @default true
  32934. */
  32935. this.isLight = true;
  32936. this.type = 'Light';
  32937. /**
  32938. * The light's color.
  32939. *
  32940. * @type {Color}
  32941. */
  32942. this.color = new Color( color );
  32943. /**
  32944. * The light's intensity.
  32945. *
  32946. * @type {number}
  32947. * @default 1
  32948. */
  32949. this.intensity = intensity;
  32950. }
  32951. /**
  32952. * Frees the GPU-related resources allocated by this instance. Call this
  32953. * method whenever this instance is no longer used in your app.
  32954. */
  32955. dispose() {
  32956. this.dispatchEvent( { type: 'dispose' } );
  32957. }
  32958. copy( source, recursive ) {
  32959. super.copy( source, recursive );
  32960. this.color.copy( source.color );
  32961. this.intensity = source.intensity;
  32962. return this;
  32963. }
  32964. toJSON( meta ) {
  32965. const data = super.toJSON( meta );
  32966. data.object.color = this.color.getHex();
  32967. data.object.intensity = this.intensity;
  32968. return data;
  32969. }
  32970. }
  32971. /**
  32972. * A light source positioned directly above the scene, with color fading from
  32973. * the sky color to the ground color.
  32974. *
  32975. * This light cannot be used to cast shadows.
  32976. *
  32977. * ```js
  32978. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  32979. * scene.add( light );
  32980. * ```
  32981. *
  32982. * @augments Light
  32983. */
  32984. class HemisphereLight extends Light {
  32985. /**
  32986. * Constructs a new hemisphere light.
  32987. *
  32988. * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color.
  32989. * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color.
  32990. * @param {number} [intensity=1] - The light's strength/intensity.
  32991. */
  32992. constructor( skyColor, groundColor, intensity ) {
  32993. super( skyColor, intensity );
  32994. /**
  32995. * This flag can be used for type testing.
  32996. *
  32997. * @type {boolean}
  32998. * @readonly
  32999. * @default true
  33000. */
  33001. this.isHemisphereLight = true;
  33002. this.type = 'HemisphereLight';
  33003. this.position.copy( Object3D.DEFAULT_UP );
  33004. this.updateMatrix();
  33005. /**
  33006. * The light's ground color.
  33007. *
  33008. * @type {Color}
  33009. */
  33010. this.groundColor = new Color( groundColor );
  33011. }
  33012. copy( source, recursive ) {
  33013. super.copy( source, recursive );
  33014. this.groundColor.copy( source.groundColor );
  33015. return this;
  33016. }
  33017. toJSON( meta ) {
  33018. const data = super.toJSON( meta );
  33019. data.object.groundColor = this.groundColor.getHex();
  33020. return data;
  33021. }
  33022. }
  33023. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  33024. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  33025. const _lookTarget = /*@__PURE__*/ new Vector3();
  33026. /**
  33027. * Abstract base class for light shadow classes. These classes
  33028. * represent the shadow configuration for different light types.
  33029. *
  33030. * @abstract
  33031. */
  33032. class LightShadow {
  33033. /**
  33034. * Constructs a new light shadow.
  33035. *
  33036. * @param {Camera} camera - The light's view of the world.
  33037. */
  33038. constructor( camera ) {
  33039. /**
  33040. * The light's view of the world.
  33041. *
  33042. * @type {Camera}
  33043. */
  33044. this.camera = camera;
  33045. /**
  33046. * The intensity of the shadow. The default is `1`.
  33047. * Valid values are in the range `[0, 1]`.
  33048. *
  33049. * @type {number}
  33050. * @default 1
  33051. */
  33052. this.intensity = 1;
  33053. /**
  33054. * Shadow map bias, how much to add or subtract from the normalized depth
  33055. * when deciding whether a surface is in shadow.
  33056. *
  33057. * The default is `0`. Very tiny adjustments here (in the order of `0.0001`)
  33058. * may help reduce artifacts in shadows.
  33059. *
  33060. * @type {number}
  33061. * @default 0
  33062. */
  33063. this.bias = 0;
  33064. /**
  33065. * A node version of `bias`. Only supported with `WebGPURenderer`.
  33066. *
  33067. * If a bias node is defined, `bias` has no effect.
  33068. *
  33069. * @type {?Node<float>}
  33070. * @default null
  33071. */
  33072. this.biasNode = null;
  33073. /**
  33074. * Defines how much the position used to query the shadow map is offset along
  33075. * the object normal. The default is `0`. Increasing this value can be used to
  33076. * reduce shadow acne especially in large scenes where light shines onto
  33077. * geometry at a shallow angle. The cost is that shadows may appear distorted.
  33078. *
  33079. * @type {number}
  33080. * @default 0
  33081. */
  33082. this.normalBias = 0;
  33083. /**
  33084. * Setting this to values greater than 1 will blur the edges of the shadow.
  33085. * High values will cause unwanted banding effects in the shadows - a greater
  33086. * map size will allow for a higher value to be used here before these effects
  33087. * become visible.
  33088. *
  33089. * The property has no effect when the shadow map type is `BasicShadowMap`.
  33090. *
  33091. * @type {number}
  33092. * @default 1
  33093. */
  33094. this.radius = 1;
  33095. /**
  33096. * The amount of samples to use when blurring a VSM shadow map.
  33097. *
  33098. * @type {number}
  33099. * @default 8
  33100. */
  33101. this.blurSamples = 8;
  33102. /**
  33103. * Defines the width and height of the shadow map. Higher values give better quality
  33104. * shadows at the cost of computation time. Values must be powers of two.
  33105. *
  33106. * @type {Vector2}
  33107. * @default (512,512)
  33108. */
  33109. this.mapSize = new Vector2( 512, 512 );
  33110. /**
  33111. * The type of shadow texture. The default is `UnsignedByteType`.
  33112. *
  33113. * @type {number}
  33114. * @default UnsignedByteType
  33115. */
  33116. this.mapType = UnsignedByteType;
  33117. /**
  33118. * The depth map generated using the internal camera; a location beyond a
  33119. * pixel's depth is in shadow. Computed internally during rendering.
  33120. *
  33121. * @type {?RenderTarget}
  33122. * @default null
  33123. */
  33124. this.map = null;
  33125. /**
  33126. * The distribution map generated using the internal camera; an occlusion is
  33127. * calculated based on the distribution of depths. Computed internally during
  33128. * rendering.
  33129. *
  33130. * @type {?RenderTarget}
  33131. * @default null
  33132. */
  33133. this.mapPass = null;
  33134. /**
  33135. * Model to shadow camera space, to compute location and depth in shadow map.
  33136. * This is computed internally during rendering.
  33137. *
  33138. * @type {Matrix4}
  33139. */
  33140. this.matrix = new Matrix4();
  33141. /**
  33142. * Enables automatic updates of the light's shadow. If you do not require dynamic
  33143. * lighting / shadows, you may set this to `false`.
  33144. *
  33145. * @type {boolean}
  33146. * @default true
  33147. */
  33148. this.autoUpdate = true;
  33149. /**
  33150. * When set to `true`, shadow maps will be updated in the next `render` call.
  33151. * If you have set {@link LightShadow#autoUpdate} to `false`, you will need to
  33152. * set this property to `true` and then make a render call to update the light's shadow.
  33153. *
  33154. * @type {boolean}
  33155. * @default false
  33156. */
  33157. this.needsUpdate = false;
  33158. this._frustum = new Frustum();
  33159. this._frameExtents = new Vector2( 1, 1 );
  33160. this._viewportCount = 1;
  33161. this._viewports = [
  33162. new Vector4( 0, 0, 1, 1 )
  33163. ];
  33164. }
  33165. /**
  33166. * Used internally by the renderer to get the number of viewports that need
  33167. * to be rendered for this shadow.
  33168. *
  33169. * @return {number} The viewport count.
  33170. */
  33171. getViewportCount() {
  33172. return this._viewportCount;
  33173. }
  33174. /**
  33175. * Gets the shadow cameras frustum. Used internally by the renderer to cull objects.
  33176. *
  33177. * @return {Frustum} The shadow camera frustum.
  33178. */
  33179. getFrustum() {
  33180. return this._frustum;
  33181. }
  33182. /**
  33183. * Update the matrices for the camera and shadow, used internally by the renderer.
  33184. *
  33185. * @param {Light} light - The light for which the shadow is being rendered.
  33186. */
  33187. updateMatrices( light ) {
  33188. const shadowCamera = this.camera;
  33189. const shadowMatrix = this.matrix;
  33190. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  33191. shadowCamera.position.copy( _lightPositionWorld );
  33192. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  33193. shadowCamera.lookAt( _lookTarget );
  33194. shadowCamera.updateMatrixWorld();
  33195. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  33196. this._frustum.setFromProjectionMatrix( _projScreenMatrix, shadowCamera.coordinateSystem, shadowCamera.reversedDepth );
  33197. if ( shadowCamera.coordinateSystem === WebGPUCoordinateSystem || shadowCamera.reversedDepth ) {
  33198. shadowMatrix.set(
  33199. 0.5, 0.0, 0.0, 0.5,
  33200. 0.0, 0.5, 0.0, 0.5,
  33201. 0.0, 0.0, 1.0, 0.0, // Identity Z (preserving the correct [0, 1] range from the projection matrix)
  33202. 0.0, 0.0, 0.0, 1.0
  33203. );
  33204. } else {
  33205. shadowMatrix.set(
  33206. 0.5, 0.0, 0.0, 0.5,
  33207. 0.0, 0.5, 0.0, 0.5,
  33208. 0.0, 0.0, 0.5, 0.5,
  33209. 0.0, 0.0, 0.0, 1.0
  33210. );
  33211. }
  33212. shadowMatrix.multiply( _projScreenMatrix );
  33213. }
  33214. /**
  33215. * Returns a viewport definition for the given viewport index.
  33216. *
  33217. * @param {number} viewportIndex - The viewport index.
  33218. * @return {Vector4} The viewport.
  33219. */
  33220. getViewport( viewportIndex ) {
  33221. return this._viewports[ viewportIndex ];
  33222. }
  33223. /**
  33224. * Returns the frame extends.
  33225. *
  33226. * @return {Vector2} The frame extends.
  33227. */
  33228. getFrameExtents() {
  33229. return this._frameExtents;
  33230. }
  33231. /**
  33232. * Frees the GPU-related resources allocated by this instance. Call this
  33233. * method whenever this instance is no longer used in your app.
  33234. */
  33235. dispose() {
  33236. if ( this.map ) {
  33237. this.map.dispose();
  33238. }
  33239. if ( this.mapPass ) {
  33240. this.mapPass.dispose();
  33241. }
  33242. }
  33243. /**
  33244. * Copies the values of the given light shadow instance to this instance.
  33245. *
  33246. * @param {LightShadow} source - The light shadow to copy.
  33247. * @return {LightShadow} A reference to this light shadow instance.
  33248. */
  33249. copy( source ) {
  33250. this.camera = source.camera.clone();
  33251. this.intensity = source.intensity;
  33252. this.bias = source.bias;
  33253. this.radius = source.radius;
  33254. this.autoUpdate = source.autoUpdate;
  33255. this.needsUpdate = source.needsUpdate;
  33256. this.normalBias = source.normalBias;
  33257. this.blurSamples = source.blurSamples;
  33258. this.mapSize.copy( source.mapSize );
  33259. this.biasNode = source.biasNode;
  33260. return this;
  33261. }
  33262. /**
  33263. * Returns a new light shadow instance with copied values from this instance.
  33264. *
  33265. * @return {LightShadow} A clone of this instance.
  33266. */
  33267. clone() {
  33268. return new this.constructor().copy( this );
  33269. }
  33270. /**
  33271. * Serializes the light shadow into JSON.
  33272. *
  33273. * @return {Object} A JSON object representing the serialized light shadow.
  33274. * @see {@link ObjectLoader#parse}
  33275. */
  33276. toJSON() {
  33277. const object = {};
  33278. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  33279. if ( this.bias !== 0 ) object.bias = this.bias;
  33280. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  33281. if ( this.radius !== 1 ) object.radius = this.radius;
  33282. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  33283. object.camera = this.camera.toJSON( false ).object;
  33284. delete object.camera.matrix;
  33285. return object;
  33286. }
  33287. }
  33288. const _position$2 = /*@__PURE__*/ new Vector3();
  33289. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  33290. const _scale$2 = /*@__PURE__*/ new Vector3();
  33291. /**
  33292. * Abstract base class for cameras. This class should always be inherited
  33293. * when you build a new camera.
  33294. *
  33295. * @abstract
  33296. * @augments Object3D
  33297. */
  33298. class Camera extends Object3D {
  33299. /**
  33300. * Constructs a new camera.
  33301. */
  33302. constructor() {
  33303. super();
  33304. /**
  33305. * This flag can be used for type testing.
  33306. *
  33307. * @type {boolean}
  33308. * @readonly
  33309. * @default true
  33310. */
  33311. this.isCamera = true;
  33312. this.type = 'Camera';
  33313. /**
  33314. * The inverse of the camera's world matrix.
  33315. *
  33316. * @type {Matrix4}
  33317. */
  33318. this.matrixWorldInverse = new Matrix4();
  33319. /**
  33320. * The camera's projection matrix.
  33321. *
  33322. * @type {Matrix4}
  33323. */
  33324. this.projectionMatrix = new Matrix4();
  33325. /**
  33326. * The inverse of the camera's projection matrix.
  33327. *
  33328. * @type {Matrix4}
  33329. */
  33330. this.projectionMatrixInverse = new Matrix4();
  33331. /**
  33332. * The coordinate system in which the camera is used.
  33333. *
  33334. * @type {(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  33335. */
  33336. this.coordinateSystem = WebGLCoordinateSystem;
  33337. this._reversedDepth = false;
  33338. }
  33339. /**
  33340. * The flag that indicates whether the camera uses a reversed depth buffer.
  33341. *
  33342. * @type {boolean}
  33343. * @default false
  33344. */
  33345. get reversedDepth() {
  33346. return this._reversedDepth;
  33347. }
  33348. copy( source, recursive ) {
  33349. super.copy( source, recursive );
  33350. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  33351. this.projectionMatrix.copy( source.projectionMatrix );
  33352. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  33353. this.coordinateSystem = source.coordinateSystem;
  33354. return this;
  33355. }
  33356. /**
  33357. * Returns a vector representing the ("look") direction of the 3D object in world space.
  33358. *
  33359. * This method is overwritten since cameras have a different forward vector compared to other
  33360. * 3D objects. A camera looks down its local, negative z-axis by default.
  33361. *
  33362. * @param {Vector3} target - The target vector the result is stored to.
  33363. * @return {Vector3} The 3D object's direction in world space.
  33364. */
  33365. getWorldDirection( target ) {
  33366. return super.getWorldDirection( target ).negate();
  33367. }
  33368. updateMatrixWorld( force ) {
  33369. super.updateMatrixWorld( force );
  33370. // exclude scale from view matrix to be glTF conform
  33371. this.matrixWorld.decompose( _position$2, _quaternion$2, _scale$2 );
  33372. if ( _scale$2.x === 1 && _scale$2.y === 1 && _scale$2.z === 1 ) {
  33373. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  33374. } else {
  33375. this.matrixWorldInverse.compose( _position$2, _quaternion$2, _scale$2.set( 1, 1, 1 ) ).invert();
  33376. }
  33377. }
  33378. updateWorldMatrix( updateParents, updateChildren ) {
  33379. super.updateWorldMatrix( updateParents, updateChildren );
  33380. // exclude scale from view matrix to be glTF conform
  33381. this.matrixWorld.decompose( _position$2, _quaternion$2, _scale$2 );
  33382. if ( _scale$2.x === 1 && _scale$2.y === 1 && _scale$2.z === 1 ) {
  33383. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  33384. } else {
  33385. this.matrixWorldInverse.compose( _position$2, _quaternion$2, _scale$2.set( 1, 1, 1 ) ).invert();
  33386. }
  33387. }
  33388. clone() {
  33389. return new this.constructor().copy( this );
  33390. }
  33391. }
  33392. const _v3$1 = /*@__PURE__*/ new Vector3();
  33393. const _minTarget = /*@__PURE__*/ new Vector2();
  33394. const _maxTarget = /*@__PURE__*/ new Vector2();
  33395. /**
  33396. * Camera that uses [perspective projection](https://en.wikipedia.org/wiki/Perspective_(graphical)).
  33397. *
  33398. * This projection mode is designed to mimic the way the human eye sees. It
  33399. * is the most common projection mode used for rendering a 3D scene.
  33400. *
  33401. * ```js
  33402. * const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 );
  33403. * scene.add( camera );
  33404. * ```
  33405. *
  33406. * @augments Camera
  33407. */
  33408. class PerspectiveCamera extends Camera {
  33409. /**
  33410. * Constructs a new perspective camera.
  33411. *
  33412. * @param {number} [fov=50] - The vertical field of view.
  33413. * @param {number} [aspect=1] - The aspect ratio.
  33414. * @param {number} [near=0.1] - The camera's near plane.
  33415. * @param {number} [far=2000] - The camera's far plane.
  33416. */
  33417. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  33418. super();
  33419. /**
  33420. * This flag can be used for type testing.
  33421. *
  33422. * @type {boolean}
  33423. * @readonly
  33424. * @default true
  33425. */
  33426. this.isPerspectiveCamera = true;
  33427. this.type = 'PerspectiveCamera';
  33428. /**
  33429. * The vertical field of view, from bottom to top of view,
  33430. * in degrees.
  33431. *
  33432. * @type {number}
  33433. * @default 50
  33434. */
  33435. this.fov = fov;
  33436. /**
  33437. * The zoom factor of the camera.
  33438. *
  33439. * @type {number}
  33440. * @default 1
  33441. */
  33442. this.zoom = 1;
  33443. /**
  33444. * The camera's near plane. The valid range is greater than `0`
  33445. * and less than the current value of {@link PerspectiveCamera#far}.
  33446. *
  33447. * Note that, unlike for the {@link OrthographicCamera}, `0` is <em>not</em> a
  33448. * valid value for a perspective camera's near plane.
  33449. *
  33450. * @type {number}
  33451. * @default 0.1
  33452. */
  33453. this.near = near;
  33454. /**
  33455. * The camera's far plane. Must be greater than the
  33456. * current value of {@link PerspectiveCamera#near}.
  33457. *
  33458. * @type {number}
  33459. * @default 2000
  33460. */
  33461. this.far = far;
  33462. /**
  33463. * Object distance used for stereoscopy and depth-of-field effects. This
  33464. * parameter does not influence the projection matrix unless a
  33465. * {@link StereoCamera} is being used.
  33466. *
  33467. * @type {number}
  33468. * @default 10
  33469. */
  33470. this.focus = 10;
  33471. /**
  33472. * The aspect ratio, usually the canvas width / canvas height.
  33473. *
  33474. * @type {number}
  33475. * @default 1
  33476. */
  33477. this.aspect = aspect;
  33478. /**
  33479. * Represents the frustum window specification. This property should not be edited
  33480. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  33481. *
  33482. * @type {?Object}
  33483. * @default null
  33484. */
  33485. this.view = null;
  33486. /**
  33487. * Film size used for the larger axis. Default is `35` (millimeters). This
  33488. * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset}
  33489. * is set to a nonzero value.
  33490. *
  33491. * @type {number}
  33492. * @default 35
  33493. */
  33494. this.filmGauge = 35;
  33495. /**
  33496. * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}.
  33497. *
  33498. * @type {number}
  33499. * @default 0
  33500. */
  33501. this.filmOffset = 0;
  33502. this.updateProjectionMatrix();
  33503. }
  33504. copy( source, recursive ) {
  33505. super.copy( source, recursive );
  33506. this.fov = source.fov;
  33507. this.zoom = source.zoom;
  33508. this.near = source.near;
  33509. this.far = source.far;
  33510. this.focus = source.focus;
  33511. this.aspect = source.aspect;
  33512. this.view = source.view === null ? null : Object.assign( {}, source.view );
  33513. this.filmGauge = source.filmGauge;
  33514. this.filmOffset = source.filmOffset;
  33515. return this;
  33516. }
  33517. /**
  33518. * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}.
  33519. *
  33520. * The default film gauge is 35, so that the focal length can be specified for
  33521. * a 35mm (full frame) camera.
  33522. *
  33523. * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
  33524. */
  33525. setFocalLength( focalLength ) {
  33526. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  33527. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  33528. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  33529. this.updateProjectionMatrix();
  33530. }
  33531. /**
  33532. * Returns the focal length from the current {@link PerspectiveCamera#fov} and
  33533. * {@link PerspectiveCamera#filmGauge}.
  33534. *
  33535. * @return {number} The computed focal length.
  33536. */
  33537. getFocalLength() {
  33538. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  33539. return 0.5 * this.getFilmHeight() / vExtentSlope;
  33540. }
  33541. /**
  33542. * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}.
  33543. *
  33544. * @return {number} The effective FOV.
  33545. */
  33546. getEffectiveFOV() {
  33547. return RAD2DEG * 2 * Math.atan(
  33548. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  33549. }
  33550. /**
  33551. * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  33552. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  33553. *
  33554. * @return {number} The film width.
  33555. */
  33556. getFilmWidth() {
  33557. // film not completely covered in portrait format (aspect < 1)
  33558. return this.filmGauge * Math.min( this.aspect, 1 );
  33559. }
  33560. /**
  33561. * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  33562. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  33563. *
  33564. * @return {number} The film width.
  33565. */
  33566. getFilmHeight() {
  33567. // film not completely covered in landscape format (aspect > 1)
  33568. return this.filmGauge / Math.max( this.aspect, 1 );
  33569. }
  33570. /**
  33571. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  33572. * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle.
  33573. *
  33574. * @param {number} distance - The viewing distance.
  33575. * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector.
  33576. * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector.
  33577. */
  33578. getViewBounds( distance, minTarget, maxTarget ) {
  33579. _v3$1.set( -1, -1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  33580. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  33581. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  33582. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  33583. }
  33584. /**
  33585. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  33586. *
  33587. * @param {number} distance - The viewing distance.
  33588. * @param {Vector2} target - The target vector that is used to store result where x is width and y is height.
  33589. * @returns {Vector2} The view size.
  33590. */
  33591. getViewSize( distance, target ) {
  33592. this.getViewBounds( distance, _minTarget, _maxTarget );
  33593. return target.subVectors( _maxTarget, _minTarget );
  33594. }
  33595. /**
  33596. * Sets an offset in a larger frustum. This is useful for multi-window or
  33597. * multi-monitor/multi-machine setups.
  33598. *
  33599. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  33600. * the monitors are in grid like this
  33601. *```
  33602. * +---+---+---+
  33603. * | A | B | C |
  33604. * +---+---+---+
  33605. * | D | E | F |
  33606. * +---+---+---+
  33607. *```
  33608. * then for each monitor you would call it like this:
  33609. *```js
  33610. * const w = 1920;
  33611. * const h = 1080;
  33612. * const fullWidth = w * 3;
  33613. * const fullHeight = h * 2;
  33614. *
  33615. * // --A--
  33616. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  33617. * // --B--
  33618. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  33619. * // --C--
  33620. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  33621. * // --D--
  33622. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  33623. * // --E--
  33624. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  33625. * // --F--
  33626. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  33627. * ```
  33628. *
  33629. * Note there is no reason monitors have to be the same size or in a grid.
  33630. *
  33631. * @param {number} fullWidth - The full width of multiview setup.
  33632. * @param {number} fullHeight - The full height of multiview setup.
  33633. * @param {number} x - The horizontal offset of the subcamera.
  33634. * @param {number} y - The vertical offset of the subcamera.
  33635. * @param {number} width - The width of subcamera.
  33636. * @param {number} height - The height of subcamera.
  33637. */
  33638. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  33639. this.aspect = fullWidth / fullHeight;
  33640. if ( this.view === null ) {
  33641. this.view = {
  33642. enabled: true,
  33643. fullWidth: 1,
  33644. fullHeight: 1,
  33645. offsetX: 0,
  33646. offsetY: 0,
  33647. width: 1,
  33648. height: 1
  33649. };
  33650. }
  33651. this.view.enabled = true;
  33652. this.view.fullWidth = fullWidth;
  33653. this.view.fullHeight = fullHeight;
  33654. this.view.offsetX = x;
  33655. this.view.offsetY = y;
  33656. this.view.width = width;
  33657. this.view.height = height;
  33658. this.updateProjectionMatrix();
  33659. }
  33660. /**
  33661. * Removes the view offset from the projection matrix.
  33662. */
  33663. clearViewOffset() {
  33664. if ( this.view !== null ) {
  33665. this.view.enabled = false;
  33666. }
  33667. this.updateProjectionMatrix();
  33668. }
  33669. /**
  33670. * Updates the camera's projection matrix. Must be called after any change of
  33671. * camera properties.
  33672. */
  33673. updateProjectionMatrix() {
  33674. const near = this.near;
  33675. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  33676. let height = 2 * top;
  33677. let width = this.aspect * height;
  33678. let left = -0.5 * width;
  33679. const view = this.view;
  33680. if ( this.view !== null && this.view.enabled ) {
  33681. const fullWidth = view.fullWidth,
  33682. fullHeight = view.fullHeight;
  33683. left += view.offsetX * width / fullWidth;
  33684. top -= view.offsetY * height / fullHeight;
  33685. width *= view.width / fullWidth;
  33686. height *= view.height / fullHeight;
  33687. }
  33688. const skew = this.filmOffset;
  33689. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  33690. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem, this.reversedDepth );
  33691. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  33692. }
  33693. toJSON( meta ) {
  33694. const data = super.toJSON( meta );
  33695. data.object.fov = this.fov;
  33696. data.object.zoom = this.zoom;
  33697. data.object.near = this.near;
  33698. data.object.far = this.far;
  33699. data.object.focus = this.focus;
  33700. data.object.aspect = this.aspect;
  33701. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  33702. data.object.filmGauge = this.filmGauge;
  33703. data.object.filmOffset = this.filmOffset;
  33704. return data;
  33705. }
  33706. }
  33707. /**
  33708. * Represents the shadow configuration of directional lights.
  33709. *
  33710. * @augments LightShadow
  33711. */
  33712. class SpotLightShadow extends LightShadow {
  33713. /**
  33714. * Constructs a new spot light shadow.
  33715. */
  33716. constructor() {
  33717. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  33718. /**
  33719. * This flag can be used for type testing.
  33720. *
  33721. * @type {boolean}
  33722. * @readonly
  33723. * @default true
  33724. */
  33725. this.isSpotLightShadow = true;
  33726. /**
  33727. * Used to focus the shadow camera. The camera's field of view is set as a
  33728. * percentage of the spotlight's field-of-view. Range is `[0, 1]`.
  33729. *
  33730. * @type {number}
  33731. * @default 1
  33732. */
  33733. this.focus = 1;
  33734. /**
  33735. * Texture aspect ratio.
  33736. *
  33737. * @type {number}
  33738. * @default 1
  33739. */
  33740. this.aspect = 1;
  33741. }
  33742. updateMatrices( light ) {
  33743. const camera = this.camera;
  33744. const fov = RAD2DEG * 2 * light.angle * this.focus;
  33745. const aspect = ( this.mapSize.width / this.mapSize.height ) * this.aspect;
  33746. const far = light.distance || camera.far;
  33747. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  33748. camera.fov = fov;
  33749. camera.aspect = aspect;
  33750. camera.far = far;
  33751. camera.updateProjectionMatrix();
  33752. }
  33753. super.updateMatrices( light );
  33754. }
  33755. copy( source ) {
  33756. super.copy( source );
  33757. this.focus = source.focus;
  33758. return this;
  33759. }
  33760. }
  33761. /**
  33762. * This light gets emitted from a single point in one direction, along a cone
  33763. * that increases in size the further from the light it gets.
  33764. *
  33765. * This light can cast shadows - see the {@link SpotLightShadow} for details.
  33766. *
  33767. * ```js
  33768. * // white spotlight shining from the side, modulated by a texture
  33769. * const spotLight = new THREE.SpotLight( 0xffffff );
  33770. * spotLight.position.set( 100, 1000, 100 );
  33771. * spotLight.map = new THREE.TextureLoader().load( url );
  33772. *
  33773. * spotLight.castShadow = true;
  33774. * spotLight.shadow.mapSize.width = 1024;
  33775. * spotLight.shadow.mapSize.height = 1024;
  33776. * spotLight.shadow.camera.near = 500;
  33777. * spotLight.shadow.camera.far = 4000;
  33778. * spotLight.shadow.camera.fov = 30;s
  33779. * ```
  33780. *
  33781. * @augments Light
  33782. */
  33783. class SpotLight extends Light {
  33784. /**
  33785. * Constructs a new spot light.
  33786. *
  33787. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33788. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33789. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33790. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33791. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  33792. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33793. */
  33794. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  33795. super( color, intensity );
  33796. /**
  33797. * This flag can be used for type testing.
  33798. *
  33799. * @type {boolean}
  33800. * @readonly
  33801. * @default true
  33802. */
  33803. this.isSpotLight = true;
  33804. this.type = 'SpotLight';
  33805. this.position.copy( Object3D.DEFAULT_UP );
  33806. this.updateMatrix();
  33807. /**
  33808. * The spot light points from its position to the
  33809. * target's position.
  33810. *
  33811. * For the target's position to be changed to anything other
  33812. * than the default, it must be added to the scene.
  33813. *
  33814. * It is also possible to set the target to be another 3D object
  33815. * in the scene. The light will now track the target object.
  33816. *
  33817. * @type {Object3D}
  33818. */
  33819. this.target = new Object3D();
  33820. /**
  33821. * Maximum range of the light. `0` means no limit.
  33822. *
  33823. * @type {number}
  33824. * @default 0
  33825. */
  33826. this.distance = distance;
  33827. /**
  33828. * Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33829. *
  33830. * @type {number}
  33831. * @default Math.PI/3
  33832. */
  33833. this.angle = angle;
  33834. /**
  33835. * Percent of the spotlight cone that is attenuated due to penumbra.
  33836. * Value range is `[0,1]`.
  33837. *
  33838. * @type {number}
  33839. * @default 0
  33840. */
  33841. this.penumbra = penumbra;
  33842. /**
  33843. * The amount the light dims along the distance of the light. In context of
  33844. * physically-correct rendering the default value should not be changed.
  33845. *
  33846. * @type {number}
  33847. * @default 2
  33848. */
  33849. this.decay = decay;
  33850. /**
  33851. * A texture used to modulate the color of the light. The spot light
  33852. * color is mixed with the RGB value of this texture, with a ratio
  33853. * corresponding to its alpha value. The cookie-like masking effect is
  33854. * reproduced using pixel values (0, 0, 0, 1-cookie_value).
  33855. *
  33856. * *Warning*: This property is disabled if {@link Object3D#castShadow} is set to `false`.
  33857. *
  33858. * @type {?Texture}
  33859. * @default null
  33860. */
  33861. this.map = null;
  33862. /**
  33863. * This property holds the light's shadow configuration.
  33864. *
  33865. * @type {SpotLightShadow}
  33866. */
  33867. this.shadow = new SpotLightShadow();
  33868. }
  33869. /**
  33870. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33871. * Changing the power will also change the light's intensity.
  33872. *
  33873. * @type {number}
  33874. */
  33875. get power() {
  33876. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33877. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  33878. return this.intensity * Math.PI;
  33879. }
  33880. set power( power ) {
  33881. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33882. this.intensity = power / Math.PI;
  33883. }
  33884. dispose() {
  33885. super.dispose();
  33886. this.shadow.dispose();
  33887. }
  33888. copy( source, recursive ) {
  33889. super.copy( source, recursive );
  33890. this.distance = source.distance;
  33891. this.angle = source.angle;
  33892. this.penumbra = source.penumbra;
  33893. this.decay = source.decay;
  33894. this.target = source.target.clone();
  33895. this.map = source.map;
  33896. this.shadow = source.shadow.clone();
  33897. return this;
  33898. }
  33899. toJSON( meta ) {
  33900. const data = super.toJSON( meta );
  33901. data.object.distance = this.distance;
  33902. data.object.angle = this.angle;
  33903. data.object.decay = this.decay;
  33904. data.object.penumbra = this.penumbra;
  33905. data.object.target = this.target.uuid;
  33906. if ( this.map && this.map.isTexture ) data.object.map = this.map.toJSON( meta ).uuid;
  33907. data.object.shadow = this.shadow.toJSON();
  33908. return data;
  33909. }
  33910. }
  33911. /**
  33912. * Represents the shadow configuration of point lights.
  33913. *
  33914. * @augments LightShadow
  33915. */
  33916. class PointLightShadow extends LightShadow {
  33917. /**
  33918. * Constructs a new point light shadow.
  33919. */
  33920. constructor() {
  33921. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  33922. /**
  33923. * This flag can be used for type testing.
  33924. *
  33925. * @type {boolean}
  33926. * @readonly
  33927. * @default true
  33928. */
  33929. this.isPointLightShadow = true;
  33930. }
  33931. }
  33932. /**
  33933. * A light that gets emitted from a single point in all directions. A common
  33934. * use case for this is to replicate the light emitted from a bare
  33935. * lightbulb.
  33936. *
  33937. * This light can cast shadows - see the {@link PointLightShadow} for details.
  33938. *
  33939. * ```js
  33940. * const light = new THREE.PointLight( 0xff0000, 1, 100 );
  33941. * light.position.set( 50, 50, 50 );
  33942. * scene.add( light );
  33943. * ```
  33944. *
  33945. * @augments Light
  33946. */
  33947. class PointLight extends Light {
  33948. /**
  33949. * Constructs a new point light.
  33950. *
  33951. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33952. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33953. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33954. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33955. */
  33956. constructor( color, intensity, distance = 0, decay = 2 ) {
  33957. super( color, intensity );
  33958. /**
  33959. * This flag can be used for type testing.
  33960. *
  33961. * @type {boolean}
  33962. * @readonly
  33963. * @default true
  33964. */
  33965. this.isPointLight = true;
  33966. this.type = 'PointLight';
  33967. /**
  33968. * When distance is zero, light will attenuate according to inverse-square
  33969. * law to infinite distance. When distance is non-zero, light will attenuate
  33970. * according to inverse-square law until near the distance cutoff, where it
  33971. * will then attenuate quickly and smoothly to 0. Inherently, cutoffs are not
  33972. * physically correct.
  33973. *
  33974. * @type {number}
  33975. * @default 0
  33976. */
  33977. this.distance = distance;
  33978. /**
  33979. * The amount the light dims along the distance of the light. In context of
  33980. * physically-correct rendering the default value should not be changed.
  33981. *
  33982. * @type {number}
  33983. * @default 2
  33984. */
  33985. this.decay = decay;
  33986. /**
  33987. * This property holds the light's shadow configuration.
  33988. *
  33989. * @type {PointLightShadow}
  33990. */
  33991. this.shadow = new PointLightShadow();
  33992. }
  33993. /**
  33994. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33995. * Changing the power will also change the light's intensity.
  33996. *
  33997. * @type {number}
  33998. */
  33999. get power() {
  34000. // compute the light's luminous power (in lumens) from its intensity (in candela)
  34001. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  34002. return this.intensity * 4 * Math.PI;
  34003. }
  34004. set power( power ) {
  34005. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  34006. this.intensity = power / ( 4 * Math.PI );
  34007. }
  34008. dispose() {
  34009. super.dispose();
  34010. this.shadow.dispose();
  34011. }
  34012. copy( source, recursive ) {
  34013. super.copy( source, recursive );
  34014. this.distance = source.distance;
  34015. this.decay = source.decay;
  34016. this.shadow = source.shadow.clone();
  34017. return this;
  34018. }
  34019. toJSON( meta ) {
  34020. const data = super.toJSON( meta );
  34021. data.object.distance = this.distance;
  34022. data.object.decay = this.decay;
  34023. data.object.shadow = this.shadow.toJSON();
  34024. return data;
  34025. }
  34026. }
  34027. /**
  34028. * Camera that uses [orthographic projection](https://en.wikipedia.org/wiki/Orthographic_projection).
  34029. *
  34030. * In this projection mode, an object's size in the rendered image stays
  34031. * constant regardless of its distance from the camera. This can be useful
  34032. * for rendering 2D scenes and UI elements, amongst other things.
  34033. *
  34034. * ```js
  34035. * const camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 );
  34036. * scene.add( camera );
  34037. * ```
  34038. *
  34039. * @augments Camera
  34040. */
  34041. class OrthographicCamera extends Camera {
  34042. /**
  34043. * Constructs a new orthographic camera.
  34044. *
  34045. * @param {number} [left=-1] - The left plane of the camera's frustum.
  34046. * @param {number} [right=1] - The right plane of the camera's frustum.
  34047. * @param {number} [top=1] - The top plane of the camera's frustum.
  34048. * @param {number} [bottom=-1] - The bottom plane of the camera's frustum.
  34049. * @param {number} [near=0.1] - The camera's near plane.
  34050. * @param {number} [far=2000] - The camera's far plane.
  34051. */
  34052. constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) {
  34053. super();
  34054. /**
  34055. * This flag can be used for type testing.
  34056. *
  34057. * @type {boolean}
  34058. * @readonly
  34059. * @default true
  34060. */
  34061. this.isOrthographicCamera = true;
  34062. this.type = 'OrthographicCamera';
  34063. /**
  34064. * The zoom factor of the camera.
  34065. *
  34066. * @type {number}
  34067. * @default 1
  34068. */
  34069. this.zoom = 1;
  34070. /**
  34071. * Represents the frustum window specification. This property should not be edited
  34072. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  34073. *
  34074. * @type {?Object}
  34075. * @default null
  34076. */
  34077. this.view = null;
  34078. /**
  34079. * The left plane of the camera's frustum.
  34080. *
  34081. * @type {number}
  34082. * @default -1
  34083. */
  34084. this.left = left;
  34085. /**
  34086. * The right plane of the camera's frustum.
  34087. *
  34088. * @type {number}
  34089. * @default 1
  34090. */
  34091. this.right = right;
  34092. /**
  34093. * The top plane of the camera's frustum.
  34094. *
  34095. * @type {number}
  34096. * @default 1
  34097. */
  34098. this.top = top;
  34099. /**
  34100. * The bottom plane of the camera's frustum.
  34101. *
  34102. * @type {number}
  34103. * @default -1
  34104. */
  34105. this.bottom = bottom;
  34106. /**
  34107. * The camera's near plane. The valid range is greater than `0`
  34108. * and less than the current value of {@link OrthographicCamera#far}.
  34109. *
  34110. * Note that, unlike for the {@link PerspectiveCamera}, `0` is a
  34111. * valid value for an orthographic camera's near plane.
  34112. *
  34113. * @type {number}
  34114. * @default 0.1
  34115. */
  34116. this.near = near;
  34117. /**
  34118. * The camera's far plane. Must be greater than the
  34119. * current value of {@link OrthographicCamera#near}.
  34120. *
  34121. * @type {number}
  34122. * @default 2000
  34123. */
  34124. this.far = far;
  34125. this.updateProjectionMatrix();
  34126. }
  34127. copy( source, recursive ) {
  34128. super.copy( source, recursive );
  34129. this.left = source.left;
  34130. this.right = source.right;
  34131. this.top = source.top;
  34132. this.bottom = source.bottom;
  34133. this.near = source.near;
  34134. this.far = source.far;
  34135. this.zoom = source.zoom;
  34136. this.view = source.view === null ? null : Object.assign( {}, source.view );
  34137. return this;
  34138. }
  34139. /**
  34140. * Sets an offset in a larger frustum. This is useful for multi-window or
  34141. * multi-monitor/multi-machine setups.
  34142. *
  34143. * @param {number} fullWidth - The full width of multiview setup.
  34144. * @param {number} fullHeight - The full height of multiview setup.
  34145. * @param {number} x - The horizontal offset of the subcamera.
  34146. * @param {number} y - The vertical offset of the subcamera.
  34147. * @param {number} width - The width of subcamera.
  34148. * @param {number} height - The height of subcamera.
  34149. * @see {@link PerspectiveCamera#setViewOffset}
  34150. */
  34151. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  34152. if ( this.view === null ) {
  34153. this.view = {
  34154. enabled: true,
  34155. fullWidth: 1,
  34156. fullHeight: 1,
  34157. offsetX: 0,
  34158. offsetY: 0,
  34159. width: 1,
  34160. height: 1
  34161. };
  34162. }
  34163. this.view.enabled = true;
  34164. this.view.fullWidth = fullWidth;
  34165. this.view.fullHeight = fullHeight;
  34166. this.view.offsetX = x;
  34167. this.view.offsetY = y;
  34168. this.view.width = width;
  34169. this.view.height = height;
  34170. this.updateProjectionMatrix();
  34171. }
  34172. /**
  34173. * Removes the view offset from the projection matrix.
  34174. */
  34175. clearViewOffset() {
  34176. if ( this.view !== null ) {
  34177. this.view.enabled = false;
  34178. }
  34179. this.updateProjectionMatrix();
  34180. }
  34181. /**
  34182. * Updates the camera's projection matrix. Must be called after any change of
  34183. * camera properties.
  34184. */
  34185. updateProjectionMatrix() {
  34186. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  34187. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  34188. const cx = ( this.right + this.left ) / 2;
  34189. const cy = ( this.top + this.bottom ) / 2;
  34190. let left = cx - dx;
  34191. let right = cx + dx;
  34192. let top = cy + dy;
  34193. let bottom = cy - dy;
  34194. if ( this.view !== null && this.view.enabled ) {
  34195. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  34196. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  34197. left += scaleW * this.view.offsetX;
  34198. right = left + scaleW * this.view.width;
  34199. top -= scaleH * this.view.offsetY;
  34200. bottom = top - scaleH * this.view.height;
  34201. }
  34202. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem, this.reversedDepth );
  34203. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  34204. }
  34205. toJSON( meta ) {
  34206. const data = super.toJSON( meta );
  34207. data.object.zoom = this.zoom;
  34208. data.object.left = this.left;
  34209. data.object.right = this.right;
  34210. data.object.top = this.top;
  34211. data.object.bottom = this.bottom;
  34212. data.object.near = this.near;
  34213. data.object.far = this.far;
  34214. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  34215. return data;
  34216. }
  34217. }
  34218. /**
  34219. * Represents the shadow configuration of directional lights.
  34220. *
  34221. * @augments LightShadow
  34222. */
  34223. class DirectionalLightShadow extends LightShadow {
  34224. /**
  34225. * Constructs a new directional light shadow.
  34226. */
  34227. constructor() {
  34228. super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) );
  34229. /**
  34230. * This flag can be used for type testing.
  34231. *
  34232. * @type {boolean}
  34233. * @readonly
  34234. * @default true
  34235. */
  34236. this.isDirectionalLightShadow = true;
  34237. }
  34238. }
  34239. /**
  34240. * A light that gets emitted in a specific direction. This light will behave
  34241. * as though it is infinitely far away and the rays produced from it are all
  34242. * parallel. The common use case for this is to simulate daylight; the sun is
  34243. * far enough away that its position can be considered to be infinite, and
  34244. * all light rays coming from it are parallel.
  34245. *
  34246. * A common point of confusion for directional lights is that setting the
  34247. * rotation has no effect. This is because three.js's DirectionalLight is the
  34248. * equivalent to what is often called a 'Target Direct Light' in other
  34249. * applications.
  34250. *
  34251. * This means that its direction is calculated as pointing from the light's
  34252. * {@link Object3D#position} to the {@link DirectionalLight#target} position
  34253. * (as opposed to a 'Free Direct Light' that just has a rotation
  34254. * component).
  34255. *
  34256. * This light can cast shadows - see the {@link DirectionalLightShadow} for details.
  34257. *
  34258. * ```js
  34259. * // White directional light at half intensity shining from the top.
  34260. * const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  34261. * scene.add( directionalLight );
  34262. * ```
  34263. *
  34264. * @augments Light
  34265. */
  34266. class DirectionalLight extends Light {
  34267. /**
  34268. * Constructs a new directional light.
  34269. *
  34270. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34271. * @param {number} [intensity=1] - The light's strength/intensity.
  34272. */
  34273. constructor( color, intensity ) {
  34274. super( color, intensity );
  34275. /**
  34276. * This flag can be used for type testing.
  34277. *
  34278. * @type {boolean}
  34279. * @readonly
  34280. * @default true
  34281. */
  34282. this.isDirectionalLight = true;
  34283. this.type = 'DirectionalLight';
  34284. this.position.copy( Object3D.DEFAULT_UP );
  34285. this.updateMatrix();
  34286. /**
  34287. * The directional light points from its position to the
  34288. * target's position.
  34289. *
  34290. * For the target's position to be changed to anything other
  34291. * than the default, it must be added to the scene.
  34292. *
  34293. * It is also possible to set the target to be another 3D object
  34294. * in the scene. The light will now track the target object.
  34295. *
  34296. * @type {Object3D}
  34297. */
  34298. this.target = new Object3D();
  34299. /**
  34300. * This property holds the light's shadow configuration.
  34301. *
  34302. * @type {DirectionalLightShadow}
  34303. */
  34304. this.shadow = new DirectionalLightShadow();
  34305. }
  34306. dispose() {
  34307. super.dispose();
  34308. this.shadow.dispose();
  34309. }
  34310. copy( source ) {
  34311. super.copy( source );
  34312. this.target = source.target.clone();
  34313. this.shadow = source.shadow.clone();
  34314. return this;
  34315. }
  34316. toJSON( meta ) {
  34317. const data = super.toJSON( meta );
  34318. data.object.shadow = this.shadow.toJSON();
  34319. data.object.target = this.target.uuid;
  34320. return data;
  34321. }
  34322. }
  34323. /**
  34324. * This light globally illuminates all objects in the scene equally.
  34325. *
  34326. * It cannot be used to cast shadows as it does not have a direction.
  34327. *
  34328. * ```js
  34329. * const light = new THREE.AmbientLight( 0x404040 ); // soft white light
  34330. * scene.add( light );
  34331. * ```
  34332. *
  34333. * @augments Light
  34334. */
  34335. class AmbientLight extends Light {
  34336. /**
  34337. * Constructs a new ambient light.
  34338. *
  34339. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34340. * @param {number} [intensity=1] - The light's strength/intensity.
  34341. */
  34342. constructor( color, intensity ) {
  34343. super( color, intensity );
  34344. /**
  34345. * This flag can be used for type testing.
  34346. *
  34347. * @type {boolean}
  34348. * @readonly
  34349. * @default true
  34350. */
  34351. this.isAmbientLight = true;
  34352. this.type = 'AmbientLight';
  34353. }
  34354. }
  34355. /**
  34356. * This class emits light uniformly across the face a rectangular plane.
  34357. * This light type can be used to simulate light sources such as bright
  34358. * windows or strip lighting.
  34359. *
  34360. * Important Notes:
  34361. *
  34362. * - There is no shadow support.
  34363. * - Only PBR materials are supported.
  34364. * - You have to include `RectAreaLightUniformsLib` (`WebGLRenderer`) or `RectAreaLightTexturesLib` (`WebGPURenderer`)
  34365. * into your app and init the uniforms/textures.
  34366. *
  34367. * ```js
  34368. * RectAreaLightUniformsLib.init(); // only relevant for WebGLRenderer
  34369. * THREE.RectAreaLightNode.setLTC( RectAreaLightTexturesLib.init() ); // only relevant for WebGPURenderer
  34370. *
  34371. * const intensity = 1; const width = 10; const height = 10;
  34372. * const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height );
  34373. * rectLight.position.set( 5, 5, 0 );
  34374. * rectLight.lookAt( 0, 0, 0 );
  34375. * scene.add( rectLight )
  34376. * ```
  34377. *
  34378. * @augments Light
  34379. */
  34380. class RectAreaLight extends Light {
  34381. /**
  34382. * Constructs a new area light.
  34383. *
  34384. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34385. * @param {number} [intensity=1] - The light's strength/intensity.
  34386. * @param {number} [width=10] - The width of the light.
  34387. * @param {number} [height=10] - The height of the light.
  34388. */
  34389. constructor( color, intensity, width = 10, height = 10 ) {
  34390. super( color, intensity );
  34391. /**
  34392. * This flag can be used for type testing.
  34393. *
  34394. * @type {boolean}
  34395. * @readonly
  34396. * @default true
  34397. */
  34398. this.isRectAreaLight = true;
  34399. this.type = 'RectAreaLight';
  34400. /**
  34401. * The width of the light.
  34402. *
  34403. * @type {number}
  34404. * @default 10
  34405. */
  34406. this.width = width;
  34407. /**
  34408. * The height of the light.
  34409. *
  34410. * @type {number}
  34411. * @default 10
  34412. */
  34413. this.height = height;
  34414. }
  34415. /**
  34416. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  34417. * Changing the power will also change the light's intensity.
  34418. *
  34419. * @type {number}
  34420. */
  34421. get power() {
  34422. // compute the light's luminous power (in lumens) from its intensity (in nits)
  34423. return this.intensity * this.width * this.height * Math.PI;
  34424. }
  34425. set power( power ) {
  34426. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  34427. this.intensity = power / ( this.width * this.height * Math.PI );
  34428. }
  34429. copy( source ) {
  34430. super.copy( source );
  34431. this.width = source.width;
  34432. this.height = source.height;
  34433. return this;
  34434. }
  34435. toJSON( meta ) {
  34436. const data = super.toJSON( meta );
  34437. data.object.width = this.width;
  34438. data.object.height = this.height;
  34439. return data;
  34440. }
  34441. }
  34442. /**
  34443. * Represents a third-order spherical harmonics (SH). Light probes use this class
  34444. * to encode lighting information.
  34445. *
  34446. * - Primary reference: {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf}
  34447. * - Secondary reference: {@link https://www.ppsloan.org/publications/StupidSH36.pdf}
  34448. */
  34449. class SphericalHarmonics3 {
  34450. /**
  34451. * Constructs a new spherical harmonics.
  34452. */
  34453. constructor() {
  34454. /**
  34455. * This flag can be used for type testing.
  34456. *
  34457. * @type {boolean}
  34458. * @readonly
  34459. * @default true
  34460. */
  34461. this.isSphericalHarmonics3 = true;
  34462. /**
  34463. * An array holding the (9) SH coefficients.
  34464. *
  34465. * @type {Array<Vector3>}
  34466. */
  34467. this.coefficients = [];
  34468. for ( let i = 0; i < 9; i ++ ) {
  34469. this.coefficients.push( new Vector3() );
  34470. }
  34471. }
  34472. /**
  34473. * Sets the given SH coefficients to this instance by copying
  34474. * the values.
  34475. *
  34476. * @param {Array<Vector3>} coefficients - The SH coefficients.
  34477. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34478. */
  34479. set( coefficients ) {
  34480. for ( let i = 0; i < 9; i ++ ) {
  34481. this.coefficients[ i ].copy( coefficients[ i ] );
  34482. }
  34483. return this;
  34484. }
  34485. /**
  34486. * Sets all SH coefficients to `0`.
  34487. *
  34488. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34489. */
  34490. zero() {
  34491. for ( let i = 0; i < 9; i ++ ) {
  34492. this.coefficients[ i ].set( 0, 0, 0 );
  34493. }
  34494. return this;
  34495. }
  34496. /**
  34497. * Returns the radiance in the direction of the given normal.
  34498. *
  34499. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34500. * @param {Vector3} target - The target vector that is used to store the method's result.
  34501. * @return {Vector3} The radiance.
  34502. */
  34503. getAt( normal, target ) {
  34504. // normal is assumed to be unit length
  34505. const x = normal.x, y = normal.y, z = normal.z;
  34506. const coeff = this.coefficients;
  34507. // band 0
  34508. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  34509. // band 1
  34510. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  34511. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  34512. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  34513. // band 2
  34514. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  34515. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  34516. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  34517. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  34518. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  34519. return target;
  34520. }
  34521. /**
  34522. * Returns the irradiance (radiance convolved with cosine lobe) in the
  34523. * direction of the given normal.
  34524. *
  34525. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34526. * @param {Vector3} target - The target vector that is used to store the method's result.
  34527. * @return {Vector3} The irradiance.
  34528. */
  34529. getIrradianceAt( normal, target ) {
  34530. // normal is assumed to be unit length
  34531. const x = normal.x, y = normal.y, z = normal.z;
  34532. const coeff = this.coefficients;
  34533. // band 0
  34534. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  34535. // band 1
  34536. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  34537. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  34538. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  34539. // band 2
  34540. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  34541. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  34542. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  34543. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  34544. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  34545. return target;
  34546. }
  34547. /**
  34548. * Adds the given SH to this instance.
  34549. *
  34550. * @param {SphericalHarmonics3} sh - The SH to add.
  34551. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34552. */
  34553. add( sh ) {
  34554. for ( let i = 0; i < 9; i ++ ) {
  34555. this.coefficients[ i ].add( sh.coefficients[ i ] );
  34556. }
  34557. return this;
  34558. }
  34559. /**
  34560. * A convenience method for performing {@link SphericalHarmonics3#add} and
  34561. * {@link SphericalHarmonics3#scale} at once.
  34562. *
  34563. * @param {SphericalHarmonics3} sh - The SH to add.
  34564. * @param {number} s - The scale factor.
  34565. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34566. */
  34567. addScaledSH( sh, s ) {
  34568. for ( let i = 0; i < 9; i ++ ) {
  34569. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  34570. }
  34571. return this;
  34572. }
  34573. /**
  34574. * Scales this SH by the given scale factor.
  34575. *
  34576. * @param {number} s - The scale factor.
  34577. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34578. */
  34579. scale( s ) {
  34580. for ( let i = 0; i < 9; i ++ ) {
  34581. this.coefficients[ i ].multiplyScalar( s );
  34582. }
  34583. return this;
  34584. }
  34585. /**
  34586. * Linear interpolates between the given SH and this instance by the given
  34587. * alpha factor.
  34588. *
  34589. * @param {SphericalHarmonics3} sh - The SH to interpolate with.
  34590. * @param {number} alpha - The alpha factor.
  34591. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34592. */
  34593. lerp( sh, alpha ) {
  34594. for ( let i = 0; i < 9; i ++ ) {
  34595. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  34596. }
  34597. return this;
  34598. }
  34599. /**
  34600. * Returns `true` if this spherical harmonics is equal with the given one.
  34601. *
  34602. * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality.
  34603. * @return {boolean} Whether this spherical harmonics is equal with the given one.
  34604. */
  34605. equals( sh ) {
  34606. for ( let i = 0; i < 9; i ++ ) {
  34607. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  34608. return false;
  34609. }
  34610. }
  34611. return true;
  34612. }
  34613. /**
  34614. * Copies the values of the given spherical harmonics to this instance.
  34615. *
  34616. * @param {SphericalHarmonics3} sh - The spherical harmonics to copy.
  34617. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34618. */
  34619. copy( sh ) {
  34620. return this.set( sh.coefficients );
  34621. }
  34622. /**
  34623. * Returns a new spherical harmonics with copied values from this instance.
  34624. *
  34625. * @return {SphericalHarmonics3} A clone of this instance.
  34626. */
  34627. clone() {
  34628. return new this.constructor().copy( this );
  34629. }
  34630. /**
  34631. * Sets the SH coefficients of this instance from the given array.
  34632. *
  34633. * @param {Array<number>} array - An array holding the SH coefficients.
  34634. * @param {number} [offset=0] - The array offset where to start copying.
  34635. * @return {SphericalHarmonics3} A clone of this instance.
  34636. */
  34637. fromArray( array, offset = 0 ) {
  34638. const coefficients = this.coefficients;
  34639. for ( let i = 0; i < 9; i ++ ) {
  34640. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  34641. }
  34642. return this;
  34643. }
  34644. /**
  34645. * Returns an array with the SH coefficients, or copies them into the provided
  34646. * array. The coefficients are represented as numbers.
  34647. *
  34648. * @param {Array<number>} [array=[]] - The target array.
  34649. * @param {number} [offset=0] - The array offset where to start copying.
  34650. * @return {Array<number>} An array with flat SH coefficients.
  34651. */
  34652. toArray( array = [], offset = 0 ) {
  34653. const coefficients = this.coefficients;
  34654. for ( let i = 0; i < 9; i ++ ) {
  34655. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  34656. }
  34657. return array;
  34658. }
  34659. /**
  34660. * Computes the SH basis for the given normal vector.
  34661. *
  34662. * @param {Vector3} normal - The normal.
  34663. * @param {Array<number>} shBasis - The target array holding the SH basis.
  34664. */
  34665. static getBasisAt( normal, shBasis ) {
  34666. // normal is assumed to be unit length
  34667. const x = normal.x, y = normal.y, z = normal.z;
  34668. // band 0
  34669. shBasis[ 0 ] = 0.282095;
  34670. // band 1
  34671. shBasis[ 1 ] = 0.488603 * y;
  34672. shBasis[ 2 ] = 0.488603 * z;
  34673. shBasis[ 3 ] = 0.488603 * x;
  34674. // band 2
  34675. shBasis[ 4 ] = 1.092548 * x * y;
  34676. shBasis[ 5 ] = 1.092548 * y * z;
  34677. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  34678. shBasis[ 7 ] = 1.092548 * x * z;
  34679. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  34680. }
  34681. }
  34682. /**
  34683. * Light probes are an alternative way of adding light to a 3D scene. Unlike
  34684. * classical light sources (e.g. directional, point or spot lights), light
  34685. * probes do not emit light. Instead they store information about light
  34686. * passing through 3D space. During rendering, the light that hits a 3D
  34687. * object is approximated by using the data from the light probe.
  34688. *
  34689. * Light probes are usually created from (radiance) environment maps. The
  34690. * class {@link LightProbeGenerator} can be used to create light probes from
  34691. * cube textures or render targets. However, light estimation data could also
  34692. * be provided in other forms e.g. by WebXR. This enables the rendering of
  34693. * augmented reality content that reacts to real world lighting.
  34694. *
  34695. * The current probe implementation in three.js supports so-called diffuse
  34696. * light probes. This type of light probe is functionally equivalent to an
  34697. * irradiance environment map.
  34698. *
  34699. * @augments Light
  34700. */
  34701. class LightProbe extends Light {
  34702. /**
  34703. * Constructs a new light probe.
  34704. *
  34705. * @param {SphericalHarmonics3} sh - The spherical harmonics which represents encoded lighting information.
  34706. * @param {number} [intensity=1] - The light's strength/intensity.
  34707. */
  34708. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  34709. super( undefined, intensity );
  34710. /**
  34711. * This flag can be used for type testing.
  34712. *
  34713. * @type {boolean}
  34714. * @readonly
  34715. * @default true
  34716. */
  34717. this.isLightProbe = true;
  34718. /**
  34719. * A light probe uses spherical harmonics to encode lighting information.
  34720. *
  34721. * @type {SphericalHarmonics3}
  34722. */
  34723. this.sh = sh;
  34724. }
  34725. copy( source ) {
  34726. super.copy( source );
  34727. this.sh.copy( source.sh );
  34728. return this;
  34729. }
  34730. toJSON( meta ) {
  34731. const data = super.toJSON( meta );
  34732. data.object.sh = this.sh.toArray();
  34733. return data;
  34734. }
  34735. }
  34736. /**
  34737. * Class for loading materials. The files are internally
  34738. * loaded via {@link FileLoader}.
  34739. *
  34740. * ```js
  34741. * const loader = new THREE.MaterialLoader();
  34742. * const material = await loader.loadAsync( 'material.json' );
  34743. * ```
  34744. * This loader does not support node materials. Use {@link NodeMaterialLoader} instead.
  34745. *
  34746. * @augments Loader
  34747. */
  34748. class MaterialLoader extends Loader {
  34749. /**
  34750. * Constructs a new material loader.
  34751. *
  34752. * @param {LoadingManager} [manager] - The loading manager.
  34753. */
  34754. constructor( manager ) {
  34755. super( manager );
  34756. /**
  34757. * A dictionary holding textures used by the material.
  34758. *
  34759. * @type {Object<string,Texture>}
  34760. */
  34761. this.textures = {};
  34762. }
  34763. /**
  34764. * Starts loading from the given URL and pass the loaded material to the `onLoad()` callback.
  34765. *
  34766. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34767. * @param {function(Material)} onLoad - Executed when the loading process has been finished.
  34768. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34769. * @param {onErrorCallback} onError - Executed when errors occur.
  34770. */
  34771. load( url, onLoad, onProgress, onError ) {
  34772. const scope = this;
  34773. const loader = new FileLoader( scope.manager );
  34774. loader.setPath( scope.path );
  34775. loader.setRequestHeader( scope.requestHeader );
  34776. loader.setWithCredentials( scope.withCredentials );
  34777. loader.load( url, function ( text ) {
  34778. try {
  34779. onLoad( scope.parse( JSON.parse( text ) ) );
  34780. } catch ( e ) {
  34781. if ( onError ) {
  34782. onError( e );
  34783. } else {
  34784. error( e );
  34785. }
  34786. scope.manager.itemError( url );
  34787. }
  34788. }, onProgress, onError );
  34789. }
  34790. /**
  34791. * Parses the given JSON object and returns a material.
  34792. *
  34793. * @param {Object} json - The serialized material.
  34794. * @return {Material} The parsed material.
  34795. */
  34796. parse( json ) {
  34797. const textures = this.textures;
  34798. function getTexture( name ) {
  34799. if ( textures[ name ] === undefined ) {
  34800. warn( 'MaterialLoader: Undefined texture', name );
  34801. }
  34802. return textures[ name ];
  34803. }
  34804. const material = this.createMaterialFromType( json.type );
  34805. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  34806. if ( json.name !== undefined ) material.name = json.name;
  34807. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  34808. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  34809. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  34810. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  34811. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  34812. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  34813. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  34814. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  34815. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  34816. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  34817. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  34818. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  34819. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  34820. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  34821. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  34822. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  34823. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  34824. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  34825. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  34826. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  34827. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  34828. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  34829. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  34830. if ( json.fog !== undefined ) material.fog = json.fog;
  34831. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  34832. if ( json.blending !== undefined ) material.blending = json.blending;
  34833. if ( json.combine !== undefined ) material.combine = json.combine;
  34834. if ( json.side !== undefined ) material.side = json.side;
  34835. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  34836. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  34837. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  34838. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  34839. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  34840. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  34841. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  34842. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  34843. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  34844. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  34845. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  34846. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  34847. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  34848. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  34849. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  34850. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  34851. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  34852. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  34853. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  34854. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  34855. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  34856. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  34857. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  34858. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  34859. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  34860. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  34861. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  34862. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  34863. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  34864. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  34865. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  34866. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  34867. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  34868. if ( json.scale !== undefined ) material.scale = json.scale;
  34869. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  34870. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  34871. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  34872. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  34873. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  34874. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  34875. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  34876. if ( json.allowOverride !== undefined ) material.allowOverride = json.allowOverride;
  34877. if ( json.visible !== undefined ) material.visible = json.visible;
  34878. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  34879. if ( json.userData !== undefined ) material.userData = json.userData;
  34880. if ( json.vertexColors !== undefined ) {
  34881. if ( typeof json.vertexColors === 'number' ) {
  34882. material.vertexColors = json.vertexColors > 0;
  34883. } else {
  34884. material.vertexColors = json.vertexColors;
  34885. }
  34886. }
  34887. // Shader Material
  34888. if ( json.uniforms !== undefined ) {
  34889. for ( const name in json.uniforms ) {
  34890. const uniform = json.uniforms[ name ];
  34891. material.uniforms[ name ] = {};
  34892. switch ( uniform.type ) {
  34893. case 't':
  34894. material.uniforms[ name ].value = getTexture( uniform.value );
  34895. break;
  34896. case 'c':
  34897. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  34898. break;
  34899. case 'v2':
  34900. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  34901. break;
  34902. case 'v3':
  34903. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  34904. break;
  34905. case 'v4':
  34906. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  34907. break;
  34908. case 'm3':
  34909. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  34910. break;
  34911. case 'm4':
  34912. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  34913. break;
  34914. default:
  34915. material.uniforms[ name ].value = uniform.value;
  34916. }
  34917. }
  34918. }
  34919. if ( json.defines !== undefined ) material.defines = json.defines;
  34920. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  34921. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  34922. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  34923. if ( json.extensions !== undefined ) {
  34924. for ( const key in json.extensions ) {
  34925. material.extensions[ key ] = json.extensions[ key ];
  34926. }
  34927. }
  34928. if ( json.lights !== undefined ) material.lights = json.lights;
  34929. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  34930. // for PointsMaterial
  34931. if ( json.size !== undefined ) material.size = json.size;
  34932. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  34933. // maps
  34934. if ( json.map !== undefined ) material.map = getTexture( json.map );
  34935. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  34936. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  34937. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  34938. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  34939. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  34940. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  34941. if ( json.normalScale !== undefined ) {
  34942. let normalScale = json.normalScale;
  34943. if ( Array.isArray( normalScale ) === false ) {
  34944. // Blender exporter used to export a scalar. See #7459
  34945. normalScale = [ normalScale, normalScale ];
  34946. }
  34947. material.normalScale = new Vector2().fromArray( normalScale );
  34948. }
  34949. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  34950. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  34951. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  34952. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  34953. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  34954. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  34955. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  34956. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  34957. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  34958. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  34959. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  34960. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  34961. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  34962. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  34963. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  34964. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  34965. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  34966. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  34967. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  34968. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  34969. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  34970. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  34971. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  34972. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  34973. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  34974. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  34975. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  34976. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  34977. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  34978. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  34979. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  34980. return material;
  34981. }
  34982. /**
  34983. * Textures are not embedded in the material JSON so they have
  34984. * to be injected before the loading process starts.
  34985. *
  34986. * @param {Object} value - A dictionary holding textures for material properties.
  34987. * @return {MaterialLoader} A reference to this material loader.
  34988. */
  34989. setTextures( value ) {
  34990. this.textures = value;
  34991. return this;
  34992. }
  34993. /**
  34994. * Creates a material for the given type.
  34995. *
  34996. * @param {string} type - The material type.
  34997. * @return {Material} The new material.
  34998. */
  34999. createMaterialFromType( type ) {
  35000. return MaterialLoader.createMaterialFromType( type );
  35001. }
  35002. /**
  35003. * Creates a material for the given type.
  35004. *
  35005. * @static
  35006. * @param {string} type - The material type.
  35007. * @return {Material} The new material.
  35008. */
  35009. static createMaterialFromType( type ) {
  35010. const materialLib = {
  35011. ShadowMaterial,
  35012. SpriteMaterial,
  35013. RawShaderMaterial,
  35014. ShaderMaterial,
  35015. PointsMaterial,
  35016. MeshPhysicalMaterial,
  35017. MeshStandardMaterial,
  35018. MeshPhongMaterial,
  35019. MeshToonMaterial,
  35020. MeshNormalMaterial,
  35021. MeshLambertMaterial,
  35022. MeshDepthMaterial,
  35023. MeshDistanceMaterial,
  35024. MeshBasicMaterial,
  35025. MeshMatcapMaterial,
  35026. LineDashedMaterial,
  35027. LineBasicMaterial,
  35028. Material
  35029. };
  35030. return new materialLib[ type ]();
  35031. }
  35032. }
  35033. /**
  35034. * A class with loader utility functions.
  35035. */
  35036. class LoaderUtils {
  35037. /**
  35038. * Extracts the base URL from the given URL.
  35039. *
  35040. * @param {string} url -The URL to extract the base URL from.
  35041. * @return {string} The extracted base URL.
  35042. */
  35043. static extractUrlBase( url ) {
  35044. const index = url.lastIndexOf( '/' );
  35045. if ( index === -1 ) return './';
  35046. return url.slice( 0, index + 1 );
  35047. }
  35048. /**
  35049. * Resolves relative URLs against the given path. Absolute paths, data urls,
  35050. * and blob URLs will be returned as is. Invalid URLs will return an empty
  35051. * string.
  35052. *
  35053. * @param {string} url -The URL to resolve.
  35054. * @param {string} path - The base path for relative URLs to be resolved against.
  35055. * @return {string} The resolved URL.
  35056. */
  35057. static resolveURL( url, path ) {
  35058. // Invalid URL
  35059. if ( typeof url !== 'string' || url === '' ) return '';
  35060. // Host Relative URL
  35061. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  35062. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  35063. }
  35064. // Absolute URL http://,https://,//
  35065. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  35066. // Data URI
  35067. if ( /^data:.*,.*$/i.test( url ) ) return url;
  35068. // Blob URL
  35069. if ( /^blob:.*$/i.test( url ) ) return url;
  35070. // Relative URL
  35071. return path + url;
  35072. }
  35073. }
  35074. /**
  35075. * An instanced version of a geometry.
  35076. */
  35077. class InstancedBufferGeometry extends BufferGeometry {
  35078. /**
  35079. * Constructs a new instanced buffer geometry.
  35080. */
  35081. constructor() {
  35082. super();
  35083. /**
  35084. * This flag can be used for type testing.
  35085. *
  35086. * @type {boolean}
  35087. * @readonly
  35088. * @default true
  35089. */
  35090. this.isInstancedBufferGeometry = true;
  35091. this.type = 'InstancedBufferGeometry';
  35092. /**
  35093. * The instance count.
  35094. *
  35095. * @type {number}
  35096. * @default Infinity
  35097. */
  35098. this.instanceCount = Infinity;
  35099. }
  35100. copy( source ) {
  35101. super.copy( source );
  35102. this.instanceCount = source.instanceCount;
  35103. return this;
  35104. }
  35105. toJSON() {
  35106. const data = super.toJSON();
  35107. data.instanceCount = this.instanceCount;
  35108. data.isInstancedBufferGeometry = true;
  35109. return data;
  35110. }
  35111. }
  35112. /**
  35113. * Class for loading geometries. The files are internally
  35114. * loaded via {@link FileLoader}.
  35115. *
  35116. * ```js
  35117. * const loader = new THREE.BufferGeometryLoader();
  35118. * const geometry = await loader.loadAsync( 'models/json/pressure.json' );
  35119. *
  35120. * const material = new THREE.MeshBasicMaterial( { color: 0xF5F5F5 } );
  35121. * const object = new THREE.Mesh( geometry, material );
  35122. * scene.add( object );
  35123. * ```
  35124. *
  35125. * @augments Loader
  35126. */
  35127. class BufferGeometryLoader extends Loader {
  35128. /**
  35129. * Constructs a new geometry loader.
  35130. *
  35131. * @param {LoadingManager} [manager] - The loading manager.
  35132. */
  35133. constructor( manager ) {
  35134. super( manager );
  35135. }
  35136. /**
  35137. * Starts loading from the given URL and pass the loaded geometry to the `onLoad()` callback.
  35138. *
  35139. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35140. * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
  35141. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35142. * @param {onErrorCallback} onError - Executed when errors occur.
  35143. */
  35144. load( url, onLoad, onProgress, onError ) {
  35145. const scope = this;
  35146. const loader = new FileLoader( scope.manager );
  35147. loader.setPath( scope.path );
  35148. loader.setRequestHeader( scope.requestHeader );
  35149. loader.setWithCredentials( scope.withCredentials );
  35150. loader.load( url, function ( text ) {
  35151. try {
  35152. onLoad( scope.parse( JSON.parse( text ) ) );
  35153. } catch ( e ) {
  35154. if ( onError ) {
  35155. onError( e );
  35156. } else {
  35157. error( e );
  35158. }
  35159. scope.manager.itemError( url );
  35160. }
  35161. }, onProgress, onError );
  35162. }
  35163. /**
  35164. * Parses the given JSON object and returns a geometry.
  35165. *
  35166. * @param {Object} json - The serialized geometry.
  35167. * @return {BufferGeometry} The parsed geometry.
  35168. */
  35169. parse( json ) {
  35170. const interleavedBufferMap = {};
  35171. const arrayBufferMap = {};
  35172. function getInterleavedBuffer( json, uuid ) {
  35173. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  35174. const interleavedBuffers = json.interleavedBuffers;
  35175. const interleavedBuffer = interleavedBuffers[ uuid ];
  35176. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  35177. const array = getTypedArray( interleavedBuffer.type, buffer );
  35178. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  35179. ib.uuid = interleavedBuffer.uuid;
  35180. interleavedBufferMap[ uuid ] = ib;
  35181. return ib;
  35182. }
  35183. function getArrayBuffer( json, uuid ) {
  35184. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  35185. const arrayBuffers = json.arrayBuffers;
  35186. const arrayBuffer = arrayBuffers[ uuid ];
  35187. const ab = new Uint32Array( arrayBuffer ).buffer;
  35188. arrayBufferMap[ uuid ] = ab;
  35189. return ab;
  35190. }
  35191. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  35192. const index = json.data.index;
  35193. if ( index !== undefined ) {
  35194. const typedArray = getTypedArray( index.type, index.array );
  35195. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  35196. }
  35197. const attributes = json.data.attributes;
  35198. for ( const key in attributes ) {
  35199. const attribute = attributes[ key ];
  35200. let bufferAttribute;
  35201. if ( attribute.isInterleavedBufferAttribute ) {
  35202. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  35203. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  35204. } else {
  35205. const typedArray = getTypedArray( attribute.type, attribute.array );
  35206. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  35207. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  35208. }
  35209. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  35210. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  35211. geometry.setAttribute( key, bufferAttribute );
  35212. }
  35213. const morphAttributes = json.data.morphAttributes;
  35214. if ( morphAttributes ) {
  35215. for ( const key in morphAttributes ) {
  35216. const attributeArray = morphAttributes[ key ];
  35217. const array = [];
  35218. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  35219. const attribute = attributeArray[ i ];
  35220. let bufferAttribute;
  35221. if ( attribute.isInterleavedBufferAttribute ) {
  35222. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  35223. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  35224. } else {
  35225. const typedArray = getTypedArray( attribute.type, attribute.array );
  35226. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  35227. }
  35228. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  35229. array.push( bufferAttribute );
  35230. }
  35231. geometry.morphAttributes[ key ] = array;
  35232. }
  35233. }
  35234. const morphTargetsRelative = json.data.morphTargetsRelative;
  35235. if ( morphTargetsRelative ) {
  35236. geometry.morphTargetsRelative = true;
  35237. }
  35238. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  35239. if ( groups !== undefined ) {
  35240. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  35241. const group = groups[ i ];
  35242. geometry.addGroup( group.start, group.count, group.materialIndex );
  35243. }
  35244. }
  35245. const boundingSphere = json.data.boundingSphere;
  35246. if ( boundingSphere !== undefined ) {
  35247. geometry.boundingSphere = new Sphere().fromJSON( boundingSphere );
  35248. }
  35249. if ( json.name ) geometry.name = json.name;
  35250. if ( json.userData ) geometry.userData = json.userData;
  35251. return geometry;
  35252. }
  35253. }
  35254. /**
  35255. * A loader for loading a JSON resource in the [JSON Object/Scene format](https://github.com/mrdoob/three.js/wiki/JSON-Object-Scene-format-4).
  35256. * The files are internally loaded via {@link FileLoader}.
  35257. *
  35258. * ```js
  35259. * const loader = new THREE.ObjectLoader();
  35260. * const obj = await loader.loadAsync( 'models/json/example.json' );
  35261. * scene.add( obj );
  35262. *
  35263. * // Alternatively, to parse a previously loaded JSON structure
  35264. * const object = await loader.parseAsync( a_json_object );
  35265. * scene.add( object );
  35266. * ```
  35267. *
  35268. * @augments Loader
  35269. */
  35270. class ObjectLoader extends Loader {
  35271. /**
  35272. * Constructs a new object loader.
  35273. *
  35274. * @param {LoadingManager} [manager] - The loading manager.
  35275. */
  35276. constructor( manager ) {
  35277. super( manager );
  35278. }
  35279. /**
  35280. * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback.
  35281. *
  35282. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35283. * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
  35284. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35285. * @param {onErrorCallback} onError - Executed when errors occur.
  35286. */
  35287. load( url, onLoad, onProgress, onError ) {
  35288. const scope = this;
  35289. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  35290. this.resourcePath = this.resourcePath || path;
  35291. const loader = new FileLoader( this.manager );
  35292. loader.setPath( this.path );
  35293. loader.setRequestHeader( this.requestHeader );
  35294. loader.setWithCredentials( this.withCredentials );
  35295. loader.load( url, function ( text ) {
  35296. let json = null;
  35297. try {
  35298. json = JSON.parse( text );
  35299. } catch ( error ) {
  35300. if ( onError !== undefined ) onError( error );
  35301. error( 'ObjectLoader: Can\'t parse ' + url + '.', error.message );
  35302. return;
  35303. }
  35304. const metadata = json.metadata;
  35305. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  35306. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  35307. error( 'ObjectLoader: Can\'t load ' + url );
  35308. return;
  35309. }
  35310. scope.parse( json, onLoad );
  35311. }, onProgress, onError );
  35312. }
  35313. /**
  35314. * Async version of {@link ObjectLoader#load}.
  35315. *
  35316. * @async
  35317. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35318. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35319. * @return {Promise<Object3D>} A Promise that resolves with the loaded 3D object.
  35320. */
  35321. async loadAsync( url, onProgress ) {
  35322. const scope = this;
  35323. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  35324. this.resourcePath = this.resourcePath || path;
  35325. const loader = new FileLoader( this.manager );
  35326. loader.setPath( this.path );
  35327. loader.setRequestHeader( this.requestHeader );
  35328. loader.setWithCredentials( this.withCredentials );
  35329. const text = await loader.loadAsync( url, onProgress );
  35330. let json;
  35331. try {
  35332. json = JSON.parse( text );
  35333. } catch ( e ) {
  35334. throw new Error( 'ObjectLoader: Can\'t parse ' + url + '. ' + e.message );
  35335. }
  35336. const metadata = json.metadata;
  35337. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  35338. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  35339. }
  35340. return await scope.parseAsync( json );
  35341. }
  35342. /**
  35343. * Parses the given JSON. This is used internally by {@link ObjectLoader#load}
  35344. * but can also be used directly to parse a previously loaded JSON structure.
  35345. *
  35346. * @param {Object} json - The serialized 3D object.
  35347. * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded.
  35348. * @return {Object3D} The parsed 3D object.
  35349. */
  35350. parse( json, onLoad ) {
  35351. const animations = this.parseAnimations( json.animations );
  35352. const shapes = this.parseShapes( json.shapes );
  35353. const geometries = this.parseGeometries( json.geometries, shapes );
  35354. const images = this.parseImages( json.images, function () {
  35355. if ( onLoad !== undefined ) onLoad( object );
  35356. } );
  35357. const textures = this.parseTextures( json.textures, images );
  35358. const materials = this.parseMaterials( json.materials, textures );
  35359. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  35360. const skeletons = this.parseSkeletons( json.skeletons, object );
  35361. this.bindSkeletons( object, skeletons );
  35362. this.bindLightTargets( object );
  35363. //
  35364. if ( onLoad !== undefined ) {
  35365. let hasImages = false;
  35366. for ( const uuid in images ) {
  35367. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  35368. hasImages = true;
  35369. break;
  35370. }
  35371. }
  35372. if ( hasImages === false ) onLoad( object );
  35373. }
  35374. return object;
  35375. }
  35376. /**
  35377. * Async version of {@link ObjectLoader#parse}.
  35378. *
  35379. * @param {Object} json - The serialized 3D object.
  35380. * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
  35381. */
  35382. async parseAsync( json ) {
  35383. const animations = this.parseAnimations( json.animations );
  35384. const shapes = this.parseShapes( json.shapes );
  35385. const geometries = this.parseGeometries( json.geometries, shapes );
  35386. const images = await this.parseImagesAsync( json.images );
  35387. const textures = this.parseTextures( json.textures, images );
  35388. const materials = this.parseMaterials( json.materials, textures );
  35389. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  35390. const skeletons = this.parseSkeletons( json.skeletons, object );
  35391. this.bindSkeletons( object, skeletons );
  35392. this.bindLightTargets( object );
  35393. return object;
  35394. }
  35395. // internals
  35396. parseShapes( json ) {
  35397. const shapes = {};
  35398. if ( json !== undefined ) {
  35399. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35400. const shape = new Shape().fromJSON( json[ i ] );
  35401. shapes[ shape.uuid ] = shape;
  35402. }
  35403. }
  35404. return shapes;
  35405. }
  35406. parseSkeletons( json, object ) {
  35407. const skeletons = {};
  35408. const bones = {};
  35409. // generate bone lookup table
  35410. object.traverse( function ( child ) {
  35411. if ( child.isBone ) bones[ child.uuid ] = child;
  35412. } );
  35413. // create skeletons
  35414. if ( json !== undefined ) {
  35415. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35416. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  35417. skeletons[ skeleton.uuid ] = skeleton;
  35418. }
  35419. }
  35420. return skeletons;
  35421. }
  35422. parseGeometries( json, shapes ) {
  35423. const geometries = {};
  35424. if ( json !== undefined ) {
  35425. const bufferGeometryLoader = new BufferGeometryLoader();
  35426. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35427. let geometry;
  35428. const data = json[ i ];
  35429. switch ( data.type ) {
  35430. case 'BufferGeometry':
  35431. case 'InstancedBufferGeometry':
  35432. geometry = bufferGeometryLoader.parse( data );
  35433. break;
  35434. default:
  35435. if ( data.type in Geometries ) {
  35436. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  35437. } else {
  35438. warn( `ObjectLoader: Unsupported geometry type "${ data.type }"` );
  35439. }
  35440. }
  35441. geometry.uuid = data.uuid;
  35442. if ( data.name !== undefined ) geometry.name = data.name;
  35443. if ( data.userData !== undefined ) geometry.userData = data.userData;
  35444. geometries[ data.uuid ] = geometry;
  35445. }
  35446. }
  35447. return geometries;
  35448. }
  35449. parseMaterials( json, textures ) {
  35450. const cache = {}; // MultiMaterial
  35451. const materials = {};
  35452. if ( json !== undefined ) {
  35453. const loader = new MaterialLoader();
  35454. loader.setTextures( textures );
  35455. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35456. const data = json[ i ];
  35457. if ( cache[ data.uuid ] === undefined ) {
  35458. cache[ data.uuid ] = loader.parse( data );
  35459. }
  35460. materials[ data.uuid ] = cache[ data.uuid ];
  35461. }
  35462. }
  35463. return materials;
  35464. }
  35465. parseAnimations( json ) {
  35466. const animations = {};
  35467. if ( json !== undefined ) {
  35468. for ( let i = 0; i < json.length; i ++ ) {
  35469. const data = json[ i ];
  35470. const clip = AnimationClip.parse( data );
  35471. animations[ clip.uuid ] = clip;
  35472. }
  35473. }
  35474. return animations;
  35475. }
  35476. parseImages( json, onLoad ) {
  35477. const scope = this;
  35478. const images = {};
  35479. let loader;
  35480. function loadImage( url ) {
  35481. scope.manager.itemStart( url );
  35482. return loader.load( url, function () {
  35483. scope.manager.itemEnd( url );
  35484. }, undefined, function () {
  35485. scope.manager.itemError( url );
  35486. scope.manager.itemEnd( url );
  35487. } );
  35488. }
  35489. function deserializeImage( image ) {
  35490. if ( typeof image === 'string' ) {
  35491. const url = image;
  35492. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35493. return loadImage( path );
  35494. } else {
  35495. if ( image.data ) {
  35496. return {
  35497. data: getTypedArray( image.type, image.data ),
  35498. width: image.width,
  35499. height: image.height
  35500. };
  35501. } else {
  35502. return null;
  35503. }
  35504. }
  35505. }
  35506. if ( json !== undefined && json.length > 0 ) {
  35507. const manager = new LoadingManager( onLoad );
  35508. loader = new ImageLoader( manager );
  35509. loader.setCrossOrigin( this.crossOrigin );
  35510. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35511. const image = json[ i ];
  35512. const url = image.url;
  35513. if ( Array.isArray( url ) ) {
  35514. // load array of images e.g CubeTexture
  35515. const imageArray = [];
  35516. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35517. const currentUrl = url[ j ];
  35518. const deserializedImage = deserializeImage( currentUrl );
  35519. if ( deserializedImage !== null ) {
  35520. if ( deserializedImage instanceof HTMLImageElement ) {
  35521. imageArray.push( deserializedImage );
  35522. } else {
  35523. // special case: handle array of data textures for cube textures
  35524. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35525. }
  35526. }
  35527. }
  35528. images[ image.uuid ] = new Source( imageArray );
  35529. } else {
  35530. // load single image
  35531. const deserializedImage = deserializeImage( image.url );
  35532. images[ image.uuid ] = new Source( deserializedImage );
  35533. }
  35534. }
  35535. }
  35536. return images;
  35537. }
  35538. async parseImagesAsync( json ) {
  35539. const scope = this;
  35540. const images = {};
  35541. let loader;
  35542. async function deserializeImage( image ) {
  35543. if ( typeof image === 'string' ) {
  35544. const url = image;
  35545. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35546. return await loader.loadAsync( path );
  35547. } else {
  35548. if ( image.data ) {
  35549. return {
  35550. data: getTypedArray( image.type, image.data ),
  35551. width: image.width,
  35552. height: image.height
  35553. };
  35554. } else {
  35555. return null;
  35556. }
  35557. }
  35558. }
  35559. if ( json !== undefined && json.length > 0 ) {
  35560. loader = new ImageLoader( this.manager );
  35561. loader.setCrossOrigin( this.crossOrigin );
  35562. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35563. const image = json[ i ];
  35564. const url = image.url;
  35565. if ( Array.isArray( url ) ) {
  35566. // load array of images e.g CubeTexture
  35567. const imageArray = [];
  35568. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35569. const currentUrl = url[ j ];
  35570. const deserializedImage = await deserializeImage( currentUrl );
  35571. if ( deserializedImage !== null ) {
  35572. if ( deserializedImage instanceof HTMLImageElement ) {
  35573. imageArray.push( deserializedImage );
  35574. } else {
  35575. // special case: handle array of data textures for cube textures
  35576. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35577. }
  35578. }
  35579. }
  35580. images[ image.uuid ] = new Source( imageArray );
  35581. } else {
  35582. // load single image
  35583. const deserializedImage = await deserializeImage( image.url );
  35584. images[ image.uuid ] = new Source( deserializedImage );
  35585. }
  35586. }
  35587. }
  35588. return images;
  35589. }
  35590. parseTextures( json, images ) {
  35591. function parseConstant( value, type ) {
  35592. if ( typeof value === 'number' ) return value;
  35593. warn( 'ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  35594. return type[ value ];
  35595. }
  35596. const textures = {};
  35597. if ( json !== undefined ) {
  35598. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35599. const data = json[ i ];
  35600. if ( data.image === undefined ) {
  35601. warn( 'ObjectLoader: No "image" specified for', data.uuid );
  35602. }
  35603. if ( images[ data.image ] === undefined ) {
  35604. warn( 'ObjectLoader: Undefined image', data.image );
  35605. }
  35606. const source = images[ data.image ];
  35607. const image = source.data;
  35608. let texture;
  35609. if ( Array.isArray( image ) ) {
  35610. texture = new CubeTexture();
  35611. if ( image.length === 6 ) texture.needsUpdate = true;
  35612. } else {
  35613. if ( image && image.data ) {
  35614. texture = new DataTexture();
  35615. } else {
  35616. texture = new Texture();
  35617. }
  35618. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  35619. }
  35620. texture.source = source;
  35621. texture.uuid = data.uuid;
  35622. if ( data.name !== undefined ) texture.name = data.name;
  35623. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  35624. if ( data.channel !== undefined ) texture.channel = data.channel;
  35625. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  35626. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  35627. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  35628. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  35629. if ( data.wrap !== undefined ) {
  35630. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  35631. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  35632. }
  35633. if ( data.format !== undefined ) texture.format = data.format;
  35634. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  35635. if ( data.type !== undefined ) texture.type = data.type;
  35636. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  35637. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  35638. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  35639. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  35640. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  35641. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  35642. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  35643. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  35644. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  35645. if ( data.userData !== undefined ) texture.userData = data.userData;
  35646. textures[ data.uuid ] = texture;
  35647. }
  35648. }
  35649. return textures;
  35650. }
  35651. parseObject( data, geometries, materials, textures, animations ) {
  35652. let object;
  35653. function getGeometry( name ) {
  35654. if ( geometries[ name ] === undefined ) {
  35655. warn( 'ObjectLoader: Undefined geometry', name );
  35656. }
  35657. return geometries[ name ];
  35658. }
  35659. function getMaterial( name ) {
  35660. if ( name === undefined ) return undefined;
  35661. if ( Array.isArray( name ) ) {
  35662. const array = [];
  35663. for ( let i = 0, l = name.length; i < l; i ++ ) {
  35664. const uuid = name[ i ];
  35665. if ( materials[ uuid ] === undefined ) {
  35666. warn( 'ObjectLoader: Undefined material', uuid );
  35667. }
  35668. array.push( materials[ uuid ] );
  35669. }
  35670. return array;
  35671. }
  35672. if ( materials[ name ] === undefined ) {
  35673. warn( 'ObjectLoader: Undefined material', name );
  35674. }
  35675. return materials[ name ];
  35676. }
  35677. function getTexture( uuid ) {
  35678. if ( textures[ uuid ] === undefined ) {
  35679. warn( 'ObjectLoader: Undefined texture', uuid );
  35680. }
  35681. return textures[ uuid ];
  35682. }
  35683. let geometry, material;
  35684. switch ( data.type ) {
  35685. case 'Scene':
  35686. object = new Scene();
  35687. if ( data.background !== undefined ) {
  35688. if ( Number.isInteger( data.background ) ) {
  35689. object.background = new Color( data.background );
  35690. } else {
  35691. object.background = getTexture( data.background );
  35692. }
  35693. }
  35694. if ( data.environment !== undefined ) {
  35695. object.environment = getTexture( data.environment );
  35696. }
  35697. if ( data.fog !== undefined ) {
  35698. if ( data.fog.type === 'Fog' ) {
  35699. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  35700. } else if ( data.fog.type === 'FogExp2' ) {
  35701. object.fog = new FogExp2( data.fog.color, data.fog.density );
  35702. }
  35703. if ( data.fog.name !== '' ) {
  35704. object.fog.name = data.fog.name;
  35705. }
  35706. }
  35707. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  35708. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  35709. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  35710. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  35711. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  35712. break;
  35713. case 'PerspectiveCamera':
  35714. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  35715. if ( data.focus !== undefined ) object.focus = data.focus;
  35716. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35717. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  35718. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  35719. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35720. break;
  35721. case 'OrthographicCamera':
  35722. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  35723. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35724. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35725. break;
  35726. case 'AmbientLight':
  35727. object = new AmbientLight( data.color, data.intensity );
  35728. break;
  35729. case 'DirectionalLight':
  35730. object = new DirectionalLight( data.color, data.intensity );
  35731. object.target = data.target || '';
  35732. break;
  35733. case 'PointLight':
  35734. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  35735. break;
  35736. case 'RectAreaLight':
  35737. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  35738. break;
  35739. case 'SpotLight':
  35740. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  35741. object.target = data.target || '';
  35742. break;
  35743. case 'HemisphereLight':
  35744. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  35745. break;
  35746. case 'LightProbe':
  35747. const sh = new SphericalHarmonics3().fromArray( data.sh );
  35748. object = new LightProbe( sh, data.intensity );
  35749. break;
  35750. case 'SkinnedMesh':
  35751. geometry = getGeometry( data.geometry );
  35752. material = getMaterial( data.material );
  35753. object = new SkinnedMesh( geometry, material );
  35754. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  35755. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  35756. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  35757. break;
  35758. case 'Mesh':
  35759. geometry = getGeometry( data.geometry );
  35760. material = getMaterial( data.material );
  35761. object = new Mesh( geometry, material );
  35762. break;
  35763. case 'InstancedMesh':
  35764. geometry = getGeometry( data.geometry );
  35765. material = getMaterial( data.material );
  35766. const count = data.count;
  35767. const instanceMatrix = data.instanceMatrix;
  35768. const instanceColor = data.instanceColor;
  35769. object = new InstancedMesh( geometry, material, count );
  35770. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  35771. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  35772. break;
  35773. case 'BatchedMesh':
  35774. geometry = getGeometry( data.geometry );
  35775. material = getMaterial( data.material );
  35776. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  35777. object.geometry = geometry;
  35778. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  35779. object.sortObjects = data.sortObjects;
  35780. object._drawRanges = data.drawRanges;
  35781. object._reservedRanges = data.reservedRanges;
  35782. object._geometryInfo = data.geometryInfo.map( info => {
  35783. let box = null;
  35784. let sphere = null;
  35785. if ( info.boundingBox !== undefined ) {
  35786. box = new Box3().fromJSON( info.boundingBox );
  35787. }
  35788. if ( info.boundingSphere !== undefined ) {
  35789. sphere = new Sphere().fromJSON( info.boundingSphere );
  35790. }
  35791. return {
  35792. ...info,
  35793. boundingBox: box,
  35794. boundingSphere: sphere
  35795. };
  35796. } );
  35797. object._instanceInfo = data.instanceInfo;
  35798. object._availableInstanceIds = data._availableInstanceIds;
  35799. object._availableGeometryIds = data._availableGeometryIds;
  35800. object._nextIndexStart = data.nextIndexStart;
  35801. object._nextVertexStart = data.nextVertexStart;
  35802. object._geometryCount = data.geometryCount;
  35803. object._maxInstanceCount = data.maxInstanceCount;
  35804. object._maxVertexCount = data.maxVertexCount;
  35805. object._maxIndexCount = data.maxIndexCount;
  35806. object._geometryInitialized = data.geometryInitialized;
  35807. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  35808. object._indirectTexture = getTexture( data.indirectTexture.uuid );
  35809. if ( data.colorsTexture !== undefined ) {
  35810. object._colorsTexture = getTexture( data.colorsTexture.uuid );
  35811. }
  35812. if ( data.boundingSphere !== undefined ) {
  35813. object.boundingSphere = new Sphere().fromJSON( data.boundingSphere );
  35814. }
  35815. if ( data.boundingBox !== undefined ) {
  35816. object.boundingBox = new Box3().fromJSON( data.boundingBox );
  35817. }
  35818. break;
  35819. case 'LOD':
  35820. object = new LOD();
  35821. break;
  35822. case 'Line':
  35823. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  35824. break;
  35825. case 'LineLoop':
  35826. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  35827. break;
  35828. case 'LineSegments':
  35829. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  35830. break;
  35831. case 'PointCloud':
  35832. case 'Points':
  35833. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  35834. break;
  35835. case 'Sprite':
  35836. object = new Sprite( getMaterial( data.material ) );
  35837. break;
  35838. case 'Group':
  35839. object = new Group();
  35840. break;
  35841. case 'Bone':
  35842. object = new Bone();
  35843. break;
  35844. default:
  35845. object = new Object3D();
  35846. }
  35847. object.uuid = data.uuid;
  35848. if ( data.name !== undefined ) object.name = data.name;
  35849. if ( data.matrix !== undefined ) {
  35850. object.matrix.fromArray( data.matrix );
  35851. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  35852. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  35853. } else {
  35854. if ( data.position !== undefined ) object.position.fromArray( data.position );
  35855. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  35856. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  35857. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  35858. }
  35859. if ( data.up !== undefined ) object.up.fromArray( data.up );
  35860. if ( data.pivot !== undefined ) object.pivot = new Vector3().fromArray( data.pivot );
  35861. if ( data.morphTargetDictionary !== undefined ) object.morphTargetDictionary = Object.assign( {}, data.morphTargetDictionary );
  35862. if ( data.morphTargetInfluences !== undefined ) object.morphTargetInfluences = data.morphTargetInfluences.slice();
  35863. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  35864. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  35865. if ( data.shadow ) {
  35866. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  35867. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  35868. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  35869. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  35870. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  35871. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  35872. }
  35873. if ( data.visible !== undefined ) object.visible = data.visible;
  35874. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  35875. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  35876. if ( data.static !== undefined ) object.static = data.static;
  35877. if ( data.userData !== undefined ) object.userData = data.userData;
  35878. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  35879. if ( data.children !== undefined ) {
  35880. const children = data.children;
  35881. for ( let i = 0; i < children.length; i ++ ) {
  35882. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  35883. }
  35884. }
  35885. if ( data.animations !== undefined ) {
  35886. const objectAnimations = data.animations;
  35887. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  35888. const uuid = objectAnimations[ i ];
  35889. object.animations.push( animations[ uuid ] );
  35890. }
  35891. }
  35892. if ( data.type === 'LOD' ) {
  35893. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  35894. const levels = data.levels;
  35895. for ( let l = 0; l < levels.length; l ++ ) {
  35896. const level = levels[ l ];
  35897. const child = object.getObjectByProperty( 'uuid', level.object );
  35898. if ( child !== undefined ) {
  35899. object.addLevel( child, level.distance, level.hysteresis );
  35900. }
  35901. }
  35902. }
  35903. return object;
  35904. }
  35905. bindSkeletons( object, skeletons ) {
  35906. if ( Object.keys( skeletons ).length === 0 ) return;
  35907. object.traverse( function ( child ) {
  35908. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  35909. const skeleton = skeletons[ child.skeleton ];
  35910. if ( skeleton === undefined ) {
  35911. warn( 'ObjectLoader: No skeleton found with UUID:', child.skeleton );
  35912. } else {
  35913. child.bind( skeleton, child.bindMatrix );
  35914. }
  35915. }
  35916. } );
  35917. }
  35918. bindLightTargets( object ) {
  35919. object.traverse( function ( child ) {
  35920. if ( child.isDirectionalLight || child.isSpotLight ) {
  35921. const uuid = child.target;
  35922. const target = object.getObjectByProperty( 'uuid', uuid );
  35923. if ( target !== undefined ) {
  35924. child.target = target;
  35925. } else {
  35926. child.target = new Object3D();
  35927. }
  35928. }
  35929. } );
  35930. }
  35931. }
  35932. const TEXTURE_MAPPING = {
  35933. UVMapping: UVMapping,
  35934. CubeReflectionMapping: CubeReflectionMapping,
  35935. CubeRefractionMapping: CubeRefractionMapping,
  35936. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  35937. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  35938. CubeUVReflectionMapping: CubeUVReflectionMapping
  35939. };
  35940. const TEXTURE_WRAPPING = {
  35941. RepeatWrapping: RepeatWrapping,
  35942. ClampToEdgeWrapping: ClampToEdgeWrapping,
  35943. MirroredRepeatWrapping: MirroredRepeatWrapping
  35944. };
  35945. const TEXTURE_FILTER = {
  35946. NearestFilter: NearestFilter,
  35947. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  35948. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  35949. LinearFilter: LinearFilter,
  35950. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  35951. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  35952. };
  35953. const _errorMap = new WeakMap();
  35954. /**
  35955. * A loader for loading images as an [ImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap).
  35956. * An `ImageBitmap` provides an asynchronous and resource efficient pathway to prepare
  35957. * textures for rendering.
  35958. *
  35959. * Note that {@link Texture#flipY} and {@link Texture#premultiplyAlpha} are ignored with image bitmaps.
  35960. * These options need to be configured via {@link ImageBitmapLoader#setOptions} prior to loading,
  35961. * unlike regular images which can be configured on the Texture to set these options on GPU upload instead.
  35962. *
  35963. * To match the default behaviour of {@link Texture}, the following options are needed:
  35964. *
  35965. * ```js
  35966. * { imageOrientation: 'flipY', premultiplyAlpha: 'none' }
  35967. * ```
  35968. *
  35969. * Also note that unlike {@link FileLoader}, this loader will only avoid multiple concurrent requests to the same URL if {@link Cache} is enabled.
  35970. *
  35971. * ```js
  35972. * const loader = new THREE.ImageBitmapLoader();
  35973. * loader.setOptions( { imageOrientation: 'flipY' } ); // set options if needed
  35974. * const imageBitmap = await loader.loadAsync( 'image.png' );
  35975. *
  35976. * const texture = new THREE.Texture( imageBitmap );
  35977. * texture.needsUpdate = true;
  35978. * ```
  35979. *
  35980. * @augments Loader
  35981. */
  35982. class ImageBitmapLoader extends Loader {
  35983. /**
  35984. * Constructs a new image bitmap loader.
  35985. *
  35986. * @param {LoadingManager} [manager] - The loading manager.
  35987. */
  35988. constructor( manager ) {
  35989. super( manager );
  35990. /**
  35991. * This flag can be used for type testing.
  35992. *
  35993. * @type {boolean}
  35994. * @readonly
  35995. * @default true
  35996. */
  35997. this.isImageBitmapLoader = true;
  35998. if ( typeof createImageBitmap === 'undefined' ) {
  35999. warn( 'ImageBitmapLoader: createImageBitmap() not supported.' );
  36000. }
  36001. if ( typeof fetch === 'undefined' ) {
  36002. warn( 'ImageBitmapLoader: fetch() not supported.' );
  36003. }
  36004. /**
  36005. * Represents the loader options.
  36006. *
  36007. * @type {Object}
  36008. * @default {premultiplyAlpha:'none'}
  36009. */
  36010. this.options = { premultiplyAlpha: 'none' };
  36011. /**
  36012. * Used for aborting requests.
  36013. *
  36014. * @private
  36015. * @type {AbortController}
  36016. */
  36017. this._abortController = new AbortController();
  36018. }
  36019. /**
  36020. * Sets the given loader options. The structure of the object must match the `options` parameter of
  36021. * [createImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap).
  36022. *
  36023. * @param {Object} options - The loader options to set.
  36024. * @return {ImageBitmapLoader} A reference to this image bitmap loader.
  36025. */
  36026. setOptions( options ) {
  36027. this.options = options;
  36028. return this;
  36029. }
  36030. /**
  36031. * Starts loading from the given URL and pass the loaded image bitmap to the `onLoad()` callback.
  36032. *
  36033. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  36034. * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished.
  36035. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  36036. * @param {onErrorCallback} onError - Executed when errors occur.
  36037. * @return {ImageBitmap|undefined} The image bitmap.
  36038. */
  36039. load( url, onLoad, onProgress, onError ) {
  36040. if ( url === undefined ) url = '';
  36041. if ( this.path !== undefined ) url = this.path + url;
  36042. url = this.manager.resolveURL( url );
  36043. const scope = this;
  36044. const cached = Cache.get( `image-bitmap:${url}` );
  36045. if ( cached !== undefined ) {
  36046. scope.manager.itemStart( url );
  36047. // If cached is a promise, wait for it to resolve
  36048. if ( cached.then ) {
  36049. cached.then( imageBitmap => {
  36050. // check if there is an error for the cached promise
  36051. if ( _errorMap.has( cached ) === true ) {
  36052. if ( onError ) onError( _errorMap.get( cached ) );
  36053. scope.manager.itemError( url );
  36054. scope.manager.itemEnd( url );
  36055. } else {
  36056. if ( onLoad ) onLoad( imageBitmap );
  36057. scope.manager.itemEnd( url );
  36058. return imageBitmap;
  36059. }
  36060. } );
  36061. return;
  36062. }
  36063. // If cached is not a promise (i.e., it's already an imageBitmap)
  36064. setTimeout( function () {
  36065. if ( onLoad ) onLoad( cached );
  36066. scope.manager.itemEnd( url );
  36067. }, 0 );
  36068. return cached;
  36069. }
  36070. const fetchOptions = {};
  36071. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  36072. fetchOptions.headers = this.requestHeader;
  36073. fetchOptions.signal = ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal;
  36074. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  36075. return res.blob();
  36076. } ).then( function ( blob ) {
  36077. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  36078. } ).then( function ( imageBitmap ) {
  36079. Cache.add( `image-bitmap:${url}`, imageBitmap );
  36080. if ( onLoad ) onLoad( imageBitmap );
  36081. scope.manager.itemEnd( url );
  36082. return imageBitmap;
  36083. } ).catch( function ( e ) {
  36084. if ( onError ) onError( e );
  36085. _errorMap.set( promise, e );
  36086. Cache.remove( `image-bitmap:${url}` );
  36087. scope.manager.itemError( url );
  36088. scope.manager.itemEnd( url );
  36089. } );
  36090. Cache.add( `image-bitmap:${url}`, promise );
  36091. scope.manager.itemStart( url );
  36092. }
  36093. /**
  36094. * Aborts ongoing fetch requests.
  36095. *
  36096. * @return {ImageBitmapLoader} A reference to this instance.
  36097. */
  36098. abort() {
  36099. this._abortController.abort();
  36100. this._abortController = new AbortController();
  36101. return this;
  36102. }
  36103. }
  36104. let _context;
  36105. /**
  36106. * Manages the global audio context in the engine.
  36107. *
  36108. * @hideconstructor
  36109. */
  36110. class AudioContext {
  36111. /**
  36112. * Returns the global native audio context.
  36113. *
  36114. * @return {Window.AudioContext} The native audio context.
  36115. */
  36116. static getContext() {
  36117. if ( _context === undefined ) {
  36118. _context = new ( window.AudioContext || window.webkitAudioContext )();
  36119. }
  36120. return _context;
  36121. }
  36122. /**
  36123. * Allows to set the global native audio context from outside.
  36124. *
  36125. * @param {Window.AudioContext} value - The native context to set.
  36126. */
  36127. static setContext( value ) {
  36128. _context = value;
  36129. }
  36130. }
  36131. /**
  36132. * Class for loading audio buffers. Audios are internally
  36133. * loaded via {@link FileLoader}.
  36134. *
  36135. * ```js
  36136. * const audioListener = new THREE.AudioListener();
  36137. * const ambientSound = new THREE.Audio( audioListener );
  36138. *
  36139. * const loader = new THREE.AudioLoader();
  36140. * const audioBuffer = await loader.loadAsync( 'audio/ambient_ocean.ogg' );
  36141. *
  36142. * ambientSound.setBuffer( audioBuffer );
  36143. * ambientSound.play();
  36144. * ```
  36145. *
  36146. * @augments Loader
  36147. */
  36148. class AudioLoader extends Loader {
  36149. /**
  36150. * Constructs a new audio loader.
  36151. *
  36152. * @param {LoadingManager} [manager] - The loading manager.
  36153. */
  36154. constructor( manager ) {
  36155. super( manager );
  36156. }
  36157. /**
  36158. * Starts loading from the given URL and passes the loaded audio buffer
  36159. * to the `onLoad()` callback.
  36160. *
  36161. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  36162. * @param {function(AudioBuffer)} onLoad - Executed when the loading process has been finished.
  36163. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  36164. * @param {onErrorCallback} onError - Executed when errors occur.
  36165. */
  36166. load( url, onLoad, onProgress, onError ) {
  36167. const scope = this;
  36168. const loader = new FileLoader( this.manager );
  36169. loader.setResponseType( 'arraybuffer' );
  36170. loader.setPath( this.path );
  36171. loader.setRequestHeader( this.requestHeader );
  36172. loader.setWithCredentials( this.withCredentials );
  36173. loader.load( url, function ( buffer ) {
  36174. try {
  36175. // Create a copy of the buffer. The `decodeAudioData` method
  36176. // detaches the buffer when complete, preventing reuse.
  36177. const bufferCopy = buffer.slice( 0 );
  36178. const context = AudioContext.getContext();
  36179. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  36180. onLoad( audioBuffer );
  36181. } ).catch( handleError );
  36182. } catch ( e ) {
  36183. handleError( e );
  36184. }
  36185. }, onProgress, onError );
  36186. function handleError( e ) {
  36187. if ( onError ) {
  36188. onError( e );
  36189. } else {
  36190. error( e );
  36191. }
  36192. scope.manager.itemError( url );
  36193. }
  36194. }
  36195. }
  36196. const _eyeRight = /*@__PURE__*/ new Matrix4();
  36197. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  36198. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  36199. /**
  36200. * A special type of camera that uses two perspective cameras with
  36201. * stereoscopic projection. Can be used for rendering stereo effects
  36202. * like [3D Anaglyph](https://en.wikipedia.org/wiki/Anaglyph_3D) or
  36203. * [Parallax Barrier](https://en.wikipedia.org/wiki/parallax_barrier).
  36204. */
  36205. class StereoCamera {
  36206. /**
  36207. * Constructs a new stereo camera.
  36208. */
  36209. constructor() {
  36210. /**
  36211. * The type property is used for detecting the object type
  36212. * in context of serialization/deserialization.
  36213. *
  36214. * @type {string}
  36215. * @readonly
  36216. */
  36217. this.type = 'StereoCamera';
  36218. /**
  36219. * The aspect.
  36220. *
  36221. * @type {number}
  36222. * @default 1
  36223. */
  36224. this.aspect = 1;
  36225. /**
  36226. * The eye separation which represents the distance
  36227. * between the left and right camera.
  36228. *
  36229. * @type {number}
  36230. * @default 0.064
  36231. */
  36232. this.eyeSep = 0.064;
  36233. /**
  36234. * The camera representing the left eye. This is added to layer `1` so objects to be
  36235. * rendered by the left camera must also be added to this layer.
  36236. *
  36237. * @type {PerspectiveCamera}
  36238. */
  36239. this.cameraL = new PerspectiveCamera();
  36240. this.cameraL.layers.enable( 1 );
  36241. this.cameraL.matrixAutoUpdate = false;
  36242. /**
  36243. * The camera representing the right eye. This is added to layer `2` so objects to be
  36244. * rendered by the right camera must also be added to this layer.
  36245. *
  36246. * @type {PerspectiveCamera}
  36247. */
  36248. this.cameraR = new PerspectiveCamera();
  36249. this.cameraR.layers.enable( 2 );
  36250. this.cameraR.matrixAutoUpdate = false;
  36251. this._cache = {
  36252. focus: null,
  36253. fov: null,
  36254. aspect: null,
  36255. near: null,
  36256. far: null,
  36257. zoom: null,
  36258. eyeSep: null
  36259. };
  36260. }
  36261. /**
  36262. * Updates the stereo camera based on the given perspective camera.
  36263. *
  36264. * @param {PerspectiveCamera} camera - The perspective camera.
  36265. */
  36266. update( camera ) {
  36267. const cache = this._cache;
  36268. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  36269. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  36270. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  36271. if ( needsUpdate ) {
  36272. cache.focus = camera.focus;
  36273. cache.fov = camera.fov;
  36274. cache.aspect = camera.aspect * this.aspect;
  36275. cache.near = camera.near;
  36276. cache.far = camera.far;
  36277. cache.zoom = camera.zoom;
  36278. cache.eyeSep = this.eyeSep;
  36279. // Off-axis stereoscopic effect based on
  36280. // http://paulbourke.net/stereographics/stereorender/
  36281. _projectionMatrix.copy( camera.projectionMatrix );
  36282. const eyeSepHalf = cache.eyeSep / 2;
  36283. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  36284. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  36285. let xmin, xmax;
  36286. // translate xOffset
  36287. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  36288. _eyeRight.elements[ 12 ] = eyeSepHalf;
  36289. // for left eye
  36290. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  36291. xmax = ymax * cache.aspect + eyeSepOnProjection;
  36292. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  36293. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  36294. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  36295. // for right eye
  36296. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  36297. xmax = ymax * cache.aspect - eyeSepOnProjection;
  36298. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  36299. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  36300. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  36301. }
  36302. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  36303. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  36304. }
  36305. }
  36306. const fov = -90; // negative fov is not an error
  36307. const aspect = 1;
  36308. /**
  36309. * A special type of camera that is positioned in 3D space to render its surroundings into a
  36310. * cube render target. The render target can then be used as an environment map for rendering
  36311. * realtime reflections in your scene.
  36312. *
  36313. * ```js
  36314. * // Create cube render target
  36315. * const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 256, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter } );
  36316. *
  36317. * // Create cube camera
  36318. * const cubeCamera = new THREE.CubeCamera( 1, 100000, cubeRenderTarget );
  36319. * scene.add( cubeCamera );
  36320. *
  36321. * // Create car
  36322. * const chromeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: cubeRenderTarget.texture } );
  36323. * const car = new THREE.Mesh( carGeometry, chromeMaterial );
  36324. * scene.add( car );
  36325. *
  36326. * // Update the render target cube
  36327. * car.visible = false;
  36328. * cubeCamera.position.copy( car.position );
  36329. * cubeCamera.update( renderer, scene );
  36330. *
  36331. * // Render the scene
  36332. * car.visible = true;
  36333. * renderer.render( scene, camera );
  36334. * ```
  36335. *
  36336. * @augments Object3D
  36337. */
  36338. class CubeCamera extends Object3D {
  36339. /**
  36340. * Constructs a new cube camera.
  36341. *
  36342. * @param {number} near - The camera's near plane.
  36343. * @param {number} far - The camera's far plane.
  36344. * @param {WebGLCubeRenderTarget} renderTarget - The cube render target.
  36345. */
  36346. constructor( near, far, renderTarget ) {
  36347. super();
  36348. this.type = 'CubeCamera';
  36349. /**
  36350. * A reference to the cube render target.
  36351. *
  36352. * @type {WebGLCubeRenderTarget}
  36353. */
  36354. this.renderTarget = renderTarget;
  36355. /**
  36356. * The current active coordinate system.
  36357. *
  36358. * @type {?(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  36359. * @default null
  36360. */
  36361. this.coordinateSystem = null;
  36362. /**
  36363. * The current active mipmap level
  36364. *
  36365. * @type {number}
  36366. * @default 0
  36367. */
  36368. this.activeMipmapLevel = 0;
  36369. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  36370. cameraPX.layers = this.layers;
  36371. this.add( cameraPX );
  36372. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  36373. cameraNX.layers = this.layers;
  36374. this.add( cameraNX );
  36375. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  36376. cameraPY.layers = this.layers;
  36377. this.add( cameraPY );
  36378. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  36379. cameraNY.layers = this.layers;
  36380. this.add( cameraNY );
  36381. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  36382. cameraPZ.layers = this.layers;
  36383. this.add( cameraPZ );
  36384. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  36385. cameraNZ.layers = this.layers;
  36386. this.add( cameraNZ );
  36387. }
  36388. /**
  36389. * Must be called when the coordinate system of the cube camera is changed.
  36390. */
  36391. updateCoordinateSystem() {
  36392. const coordinateSystem = this.coordinateSystem;
  36393. const cameras = this.children.concat();
  36394. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  36395. for ( const camera of cameras ) this.remove( camera );
  36396. if ( coordinateSystem === WebGLCoordinateSystem ) {
  36397. cameraPX.up.set( 0, 1, 0 );
  36398. cameraPX.lookAt( 1, 0, 0 );
  36399. cameraNX.up.set( 0, 1, 0 );
  36400. cameraNX.lookAt( -1, 0, 0 );
  36401. cameraPY.up.set( 0, 0, -1 );
  36402. cameraPY.lookAt( 0, 1, 0 );
  36403. cameraNY.up.set( 0, 0, 1 );
  36404. cameraNY.lookAt( 0, -1, 0 );
  36405. cameraPZ.up.set( 0, 1, 0 );
  36406. cameraPZ.lookAt( 0, 0, 1 );
  36407. cameraNZ.up.set( 0, 1, 0 );
  36408. cameraNZ.lookAt( 0, 0, -1 );
  36409. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  36410. cameraPX.up.set( 0, -1, 0 );
  36411. cameraPX.lookAt( -1, 0, 0 );
  36412. cameraNX.up.set( 0, -1, 0 );
  36413. cameraNX.lookAt( 1, 0, 0 );
  36414. cameraPY.up.set( 0, 0, 1 );
  36415. cameraPY.lookAt( 0, 1, 0 );
  36416. cameraNY.up.set( 0, 0, -1 );
  36417. cameraNY.lookAt( 0, -1, 0 );
  36418. cameraPZ.up.set( 0, -1, 0 );
  36419. cameraPZ.lookAt( 0, 0, 1 );
  36420. cameraNZ.up.set( 0, -1, 0 );
  36421. cameraNZ.lookAt( 0, 0, -1 );
  36422. } else {
  36423. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  36424. }
  36425. for ( const camera of cameras ) {
  36426. this.add( camera );
  36427. camera.updateMatrixWorld();
  36428. }
  36429. }
  36430. /**
  36431. * Calling this method will render the given scene with the given renderer
  36432. * into the cube render target of the camera.
  36433. *
  36434. * @param {(Renderer|WebGLRenderer)} renderer - The renderer.
  36435. * @param {Scene} scene - The scene to render.
  36436. */
  36437. update( renderer, scene ) {
  36438. if ( this.parent === null ) this.updateMatrixWorld();
  36439. const { renderTarget, activeMipmapLevel } = this;
  36440. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  36441. this.coordinateSystem = renderer.coordinateSystem;
  36442. this.updateCoordinateSystem();
  36443. }
  36444. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  36445. const currentRenderTarget = renderer.getRenderTarget();
  36446. const currentActiveCubeFace = renderer.getActiveCubeFace();
  36447. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  36448. const currentXrEnabled = renderer.xr.enabled;
  36449. renderer.xr.enabled = false;
  36450. const generateMipmaps = renderTarget.texture.generateMipmaps;
  36451. renderTarget.texture.generateMipmaps = false;
  36452. // https://github.com/mrdoob/three.js/issues/31413#issuecomment-3095966812
  36453. let reversedDepthBuffer = false;
  36454. if ( renderer.isWebGLRenderer === true ) {
  36455. reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  36456. } else {
  36457. reversedDepthBuffer = renderer.reversedDepthBuffer;
  36458. }
  36459. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  36460. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36461. renderer.render( scene, cameraPX );
  36462. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  36463. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36464. renderer.render( scene, cameraNX );
  36465. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  36466. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36467. renderer.render( scene, cameraPY );
  36468. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  36469. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36470. renderer.render( scene, cameraNY );
  36471. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  36472. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36473. renderer.render( scene, cameraPZ );
  36474. // mipmaps are generated during the last call of render()
  36475. // at this point, all sides of the cube render target are defined
  36476. renderTarget.texture.generateMipmaps = generateMipmaps;
  36477. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  36478. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36479. renderer.render( scene, cameraNZ );
  36480. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  36481. renderer.xr.enabled = currentXrEnabled;
  36482. renderTarget.texture.needsPMREMUpdate = true;
  36483. }
  36484. }
  36485. /**
  36486. * This type of camera can be used in order to efficiently render a scene with a
  36487. * predefined set of cameras. This is an important performance aspect for
  36488. * rendering VR scenes.
  36489. *
  36490. * An instance of `ArrayCamera` always has an array of sub cameras. It's mandatory
  36491. * to define for each sub camera the `viewport` property which determines the
  36492. * part of the viewport that is rendered with this camera.
  36493. *
  36494. * @augments PerspectiveCamera
  36495. */
  36496. class ArrayCamera extends PerspectiveCamera {
  36497. /**
  36498. * Constructs a new array camera.
  36499. *
  36500. * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras.
  36501. */
  36502. constructor( array = [] ) {
  36503. super();
  36504. /**
  36505. * This flag can be used for type testing.
  36506. *
  36507. * @type {boolean}
  36508. * @readonly
  36509. * @default true
  36510. */
  36511. this.isArrayCamera = true;
  36512. /**
  36513. * Whether this camera is used with multiview rendering or not.
  36514. *
  36515. * @type {boolean}
  36516. * @readonly
  36517. * @default false
  36518. */
  36519. this.isMultiViewCamera = false;
  36520. /**
  36521. * An array of perspective sub cameras.
  36522. *
  36523. * @type {Array<PerspectiveCamera>}
  36524. */
  36525. this.cameras = array;
  36526. }
  36527. }
  36528. /**
  36529. * This class is an alternative to {@link Clock} with a different API design and behavior.
  36530. * The goal is to avoid the conceptual flaws that became apparent in `Clock` over time.
  36531. *
  36532. * - `Timer` has an `update()` method that updates its internal state. That makes it possible to
  36533. * call `getDelta()` and `getElapsed()` multiple times per simulation step without getting different values.
  36534. * - The class can make use of the Page Visibility API to avoid large time delta values when the app
  36535. * is inactive (e.g. tab switched or browser hidden).
  36536. *
  36537. * ```js
  36538. * const timer = new Timer();
  36539. * timer.connect( document ); // use Page Visibility API
  36540. * ```
  36541. */
  36542. class Timer {
  36543. /**
  36544. * Constructs a new timer.
  36545. */
  36546. constructor() {
  36547. this._previousTime = 0;
  36548. this._currentTime = 0;
  36549. this._startTime = performance.now();
  36550. this._delta = 0;
  36551. this._elapsed = 0;
  36552. this._timescale = 1;
  36553. this._document = null;
  36554. this._pageVisibilityHandler = null;
  36555. }
  36556. /**
  36557. * Connect the timer to the given document.Calling this method is not mandatory to
  36558. * use the timer but enables the usage of the Page Visibility API to avoid large time
  36559. * delta values.
  36560. *
  36561. * @param {Document} document - The document.
  36562. */
  36563. connect( document ) {
  36564. this._document = document;
  36565. // use Page Visibility API to avoid large time delta values
  36566. if ( document.hidden !== undefined ) {
  36567. this._pageVisibilityHandler = handleVisibilityChange.bind( this );
  36568. document.addEventListener( 'visibilitychange', this._pageVisibilityHandler, false );
  36569. }
  36570. }
  36571. /**
  36572. * Disconnects the timer from the DOM and also disables the usage of the Page Visibility API.
  36573. */
  36574. disconnect() {
  36575. if ( this._pageVisibilityHandler !== null ) {
  36576. this._document.removeEventListener( 'visibilitychange', this._pageVisibilityHandler );
  36577. this._pageVisibilityHandler = null;
  36578. }
  36579. this._document = null;
  36580. }
  36581. /**
  36582. * Returns the time delta in seconds.
  36583. *
  36584. * @return {number} The time delta in second.
  36585. */
  36586. getDelta() {
  36587. return this._delta / 1000;
  36588. }
  36589. /**
  36590. * Returns the elapsed time in seconds.
  36591. *
  36592. * @return {number} The elapsed time in second.
  36593. */
  36594. getElapsed() {
  36595. return this._elapsed / 1000;
  36596. }
  36597. /**
  36598. * Returns the timescale.
  36599. *
  36600. * @return {number} The timescale.
  36601. */
  36602. getTimescale() {
  36603. return this._timescale;
  36604. }
  36605. /**
  36606. * Sets the given timescale which scale the time delta computation
  36607. * in `update()`.
  36608. *
  36609. * @param {number} timescale - The timescale to set.
  36610. * @return {Timer} A reference to this timer.
  36611. */
  36612. setTimescale( timescale ) {
  36613. this._timescale = timescale;
  36614. return this;
  36615. }
  36616. /**
  36617. * Resets the time computation for the current simulation step.
  36618. *
  36619. * @return {Timer} A reference to this timer.
  36620. */
  36621. reset() {
  36622. this._currentTime = performance.now() - this._startTime;
  36623. return this;
  36624. }
  36625. /**
  36626. * Can be used to free all internal resources. Usually called when
  36627. * the timer instance isn't required anymore.
  36628. */
  36629. dispose() {
  36630. this.disconnect();
  36631. }
  36632. /**
  36633. * Updates the internal state of the timer. This method should be called
  36634. * once per simulation step and before you perform queries against the timer
  36635. * (e.g. via `getDelta()`).
  36636. *
  36637. * @param {number} timestamp - The current time in milliseconds. Can be obtained
  36638. * from the `requestAnimationFrame` callback argument. If not provided, the current
  36639. * time will be determined with `performance.now`.
  36640. * @return {Timer} A reference to this timer.
  36641. */
  36642. update( timestamp ) {
  36643. if ( this._pageVisibilityHandler !== null && this._document.hidden === true ) {
  36644. this._delta = 0;
  36645. } else {
  36646. this._previousTime = this._currentTime;
  36647. this._currentTime = ( timestamp !== undefined ? timestamp : performance.now() ) - this._startTime;
  36648. this._delta = ( this._currentTime - this._previousTime ) * this._timescale;
  36649. this._elapsed += this._delta; // _elapsed is the accumulation of all previous deltas
  36650. }
  36651. return this;
  36652. }
  36653. }
  36654. function handleVisibilityChange() {
  36655. if ( this._document.hidden === false ) this.reset();
  36656. }
  36657. const _position$1 = /*@__PURE__*/ new Vector3();
  36658. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  36659. const _scale$1 = /*@__PURE__*/ new Vector3();
  36660. const _forward = /*@__PURE__*/ new Vector3();
  36661. const _up = /*@__PURE__*/ new Vector3();
  36662. /**
  36663. * The class represents a virtual listener of the all positional and non-positional audio effects
  36664. * in the scene. A three.js application usually creates a single listener. It is a mandatory
  36665. * constructor parameter for audios entities like {@link Audio} and {@link PositionalAudio}.
  36666. *
  36667. * In most cases, the listener object is a child of the camera. So the 3D transformation of the
  36668. * camera represents the 3D transformation of the listener.
  36669. *
  36670. * @augments Object3D
  36671. */
  36672. class AudioListener extends Object3D {
  36673. /**
  36674. * Constructs a new audio listener.
  36675. */
  36676. constructor() {
  36677. super();
  36678. this.type = 'AudioListener';
  36679. /**
  36680. * The native audio context.
  36681. *
  36682. * @type {AudioContext}
  36683. * @readonly
  36684. */
  36685. this.context = AudioContext.getContext();
  36686. /**
  36687. * The gain node used for volume control.
  36688. *
  36689. * @type {GainNode}
  36690. * @readonly
  36691. */
  36692. this.gain = this.context.createGain();
  36693. this.gain.connect( this.context.destination );
  36694. /**
  36695. * An optional filter.
  36696. *
  36697. * Defined via {@link AudioListener#setFilter}.
  36698. *
  36699. * @type {?AudioNode}
  36700. * @default null
  36701. * @readonly
  36702. */
  36703. this.filter = null;
  36704. /**
  36705. * Time delta values required for `linearRampToValueAtTime()` usage.
  36706. *
  36707. * @type {number}
  36708. * @default 0
  36709. * @readonly
  36710. */
  36711. this.timeDelta = 0;
  36712. // private
  36713. this._timer = new Timer();
  36714. }
  36715. /**
  36716. * Returns the listener's input node.
  36717. *
  36718. * This method is used by other audio nodes to connect to this listener.
  36719. *
  36720. * @return {GainNode} The input node.
  36721. */
  36722. getInput() {
  36723. return this.gain;
  36724. }
  36725. /**
  36726. * Removes the current filter from this listener.
  36727. *
  36728. * @return {AudioListener} A reference to this listener.
  36729. */
  36730. removeFilter() {
  36731. if ( this.filter !== null ) {
  36732. this.gain.disconnect( this.filter );
  36733. this.filter.disconnect( this.context.destination );
  36734. this.gain.connect( this.context.destination );
  36735. this.filter = null;
  36736. }
  36737. return this;
  36738. }
  36739. /**
  36740. * Returns the current set filter.
  36741. *
  36742. * @return {?AudioNode} The filter.
  36743. */
  36744. getFilter() {
  36745. return this.filter;
  36746. }
  36747. /**
  36748. * Sets the given filter to this listener.
  36749. *
  36750. * @param {AudioNode} value - The filter to set.
  36751. * @return {AudioListener} A reference to this listener.
  36752. */
  36753. setFilter( value ) {
  36754. if ( this.filter !== null ) {
  36755. this.gain.disconnect( this.filter );
  36756. this.filter.disconnect( this.context.destination );
  36757. } else {
  36758. this.gain.disconnect( this.context.destination );
  36759. }
  36760. this.filter = value;
  36761. this.gain.connect( this.filter );
  36762. this.filter.connect( this.context.destination );
  36763. return this;
  36764. }
  36765. /**
  36766. * Returns the applications master volume.
  36767. *
  36768. * @return {number} The master volume.
  36769. */
  36770. getMasterVolume() {
  36771. return this.gain.gain.value;
  36772. }
  36773. /**
  36774. * Sets the applications master volume. This volume setting affects
  36775. * all audio nodes in the scene.
  36776. *
  36777. * @param {number} value - The master volume to set.
  36778. * @return {AudioListener} A reference to this listener.
  36779. */
  36780. setMasterVolume( value ) {
  36781. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36782. return this;
  36783. }
  36784. updateMatrixWorld( force ) {
  36785. super.updateMatrixWorld( force );
  36786. this._timer.update();
  36787. const listener = this.context.listener;
  36788. this.timeDelta = this._timer.getDelta();
  36789. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  36790. // the initial forward and up directions must be orthogonal
  36791. _forward.set( 0, 0, -1 ).applyQuaternion( _quaternion$1 );
  36792. _up.set( 0, 1, 0 ).applyQuaternion( _quaternion$1 );
  36793. if ( listener.positionX ) {
  36794. // code path for Chrome (see #14393)
  36795. const endTime = this.context.currentTime + this.timeDelta;
  36796. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  36797. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  36798. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  36799. listener.forwardX.linearRampToValueAtTime( _forward.x, endTime );
  36800. listener.forwardY.linearRampToValueAtTime( _forward.y, endTime );
  36801. listener.forwardZ.linearRampToValueAtTime( _forward.z, endTime );
  36802. listener.upX.linearRampToValueAtTime( _up.x, endTime );
  36803. listener.upY.linearRampToValueAtTime( _up.y, endTime );
  36804. listener.upZ.linearRampToValueAtTime( _up.z, endTime );
  36805. } else {
  36806. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  36807. listener.setOrientation( _forward.x, _forward.y, _forward.z, _up.x, _up.y, _up.z );
  36808. }
  36809. }
  36810. }
  36811. /**
  36812. * Represents a non-positional ( global ) audio object.
  36813. *
  36814. * This and related audio modules make use of the [Web Audio API](https://www.w3.org/TR/webaudio-1.1/).
  36815. *
  36816. * ```js
  36817. * // create an AudioListener and add it to the camera
  36818. * const listener = new THREE.AudioListener();
  36819. * camera.add( listener );
  36820. *
  36821. * // create a global audio source
  36822. * const sound = new THREE.Audio( listener );
  36823. *
  36824. * // load a sound and set it as the Audio object's buffer
  36825. * const audioLoader = new THREE.AudioLoader();
  36826. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  36827. * sound.setBuffer( buffer );
  36828. * sound.setLoop( true );
  36829. * sound.setVolume( 0.5 );
  36830. * sound.play();
  36831. * });
  36832. * ```
  36833. *
  36834. * @augments Object3D
  36835. */
  36836. class Audio extends Object3D {
  36837. /**
  36838. * Constructs a new audio.
  36839. *
  36840. * @param {AudioListener} listener - The global audio listener.
  36841. */
  36842. constructor( listener ) {
  36843. super();
  36844. this.type = 'Audio';
  36845. /**
  36846. * The global audio listener.
  36847. *
  36848. * @type {AudioListener}
  36849. * @readonly
  36850. */
  36851. this.listener = listener;
  36852. /**
  36853. * The audio context.
  36854. *
  36855. * @type {AudioContext}
  36856. * @readonly
  36857. */
  36858. this.context = listener.context;
  36859. /**
  36860. * The gain node used for volume control.
  36861. *
  36862. * @type {GainNode}
  36863. * @readonly
  36864. */
  36865. this.gain = this.context.createGain();
  36866. this.gain.connect( listener.getInput() );
  36867. /**
  36868. * Whether to start playback automatically or not.
  36869. *
  36870. * @type {boolean}
  36871. * @default false
  36872. */
  36873. this.autoplay = false;
  36874. /**
  36875. * A reference to an audio buffer.
  36876. *
  36877. * Defined via {@link Audio#setBuffer}.
  36878. *
  36879. * @type {?AudioBuffer}
  36880. * @default null
  36881. * @readonly
  36882. */
  36883. this.buffer = null;
  36884. /**
  36885. * Modify pitch, measured in cents. +/- 100 is a semitone.
  36886. * +/- 1200 is an octave.
  36887. *
  36888. * Defined via {@link Audio#setDetune}.
  36889. *
  36890. * @type {number}
  36891. * @default 0
  36892. * @readonly
  36893. */
  36894. this.detune = 0;
  36895. /**
  36896. * Whether the audio should loop or not.
  36897. *
  36898. * Defined via {@link Audio#setLoop}.
  36899. *
  36900. * @type {boolean}
  36901. * @default false
  36902. * @readonly
  36903. */
  36904. this.loop = false;
  36905. /**
  36906. * Defines where in the audio buffer the replay should
  36907. * start, in seconds.
  36908. *
  36909. * @type {number}
  36910. * @default 0
  36911. */
  36912. this.loopStart = 0;
  36913. /**
  36914. * Defines where in the audio buffer the replay should
  36915. * stop, in seconds.
  36916. *
  36917. * @type {number}
  36918. * @default 0
  36919. */
  36920. this.loopEnd = 0;
  36921. /**
  36922. * An offset to the time within the audio buffer the playback
  36923. * should begin, in seconds.
  36924. *
  36925. * @type {number}
  36926. * @default 0
  36927. */
  36928. this.offset = 0;
  36929. /**
  36930. * Overrides the default duration of the audio.
  36931. *
  36932. * @type {undefined|number}
  36933. * @default undefined
  36934. */
  36935. this.duration = undefined;
  36936. /**
  36937. * The playback speed.
  36938. *
  36939. * Defined via {@link Audio#setPlaybackRate}.
  36940. *
  36941. * @type {number}
  36942. * @readonly
  36943. * @default 1
  36944. */
  36945. this.playbackRate = 1;
  36946. /**
  36947. * Indicates whether the audio is playing or not.
  36948. *
  36949. * This flag will be automatically set when using {@link Audio#play},
  36950. * {@link Audio#pause}, {@link Audio#stop}.
  36951. *
  36952. * @type {boolean}
  36953. * @readonly
  36954. * @default false
  36955. */
  36956. this.isPlaying = false;
  36957. /**
  36958. * Indicates whether the audio playback can be controlled
  36959. * with method like {@link Audio#play} or {@link Audio#pause}.
  36960. *
  36961. * This flag will be automatically set when audio sources are
  36962. * defined.
  36963. *
  36964. * @type {boolean}
  36965. * @readonly
  36966. * @default true
  36967. */
  36968. this.hasPlaybackControl = true;
  36969. /**
  36970. * Holds a reference to the current audio source.
  36971. *
  36972. * The property is automatically by one of the `set*()` methods.
  36973. *
  36974. * @type {?AudioNode}
  36975. * @readonly
  36976. * @default null
  36977. */
  36978. this.source = null;
  36979. /**
  36980. * Defines the source type.
  36981. *
  36982. * The property is automatically set by one of the `set*()` methods.
  36983. *
  36984. * @type {('empty'|'audioNode'|'mediaNode'|'mediaStreamNode'|'buffer')}
  36985. * @readonly
  36986. * @default 'empty'
  36987. */
  36988. this.sourceType = 'empty';
  36989. this._startedAt = 0;
  36990. this._progress = 0;
  36991. this._connected = false;
  36992. /**
  36993. * Can be used to apply a variety of low-order filters to create
  36994. * more complex sound effects e.g. via `BiquadFilterNode`.
  36995. *
  36996. * The property is automatically set by {@link Audio#setFilters}.
  36997. *
  36998. * @type {Array<AudioNode>}
  36999. * @readonly
  37000. */
  37001. this.filters = [];
  37002. }
  37003. /**
  37004. * Returns the output audio node.
  37005. *
  37006. * @return {GainNode} The output node.
  37007. */
  37008. getOutput() {
  37009. return this.gain;
  37010. }
  37011. /**
  37012. * Sets the given audio node as the source of this instance.
  37013. *
  37014. * {@link Audio#sourceType} is set to `audioNode` and {@link Audio#hasPlaybackControl} to `false`.
  37015. *
  37016. * @param {AudioNode} audioNode - The audio node like an instance of `OscillatorNode`.
  37017. * @return {Audio} A reference to this instance.
  37018. */
  37019. setNodeSource( audioNode ) {
  37020. this.hasPlaybackControl = false;
  37021. this.sourceType = 'audioNode';
  37022. this.source = audioNode;
  37023. this.connect();
  37024. return this;
  37025. }
  37026. /**
  37027. * Sets the given media element as the source of this instance.
  37028. *
  37029. * {@link Audio#sourceType} is set to `mediaNode` and {@link Audio#hasPlaybackControl} to `false`.
  37030. *
  37031. * @param {HTMLMediaElement} mediaElement - The media element.
  37032. * @return {Audio} A reference to this instance.
  37033. */
  37034. setMediaElementSource( mediaElement ) {
  37035. this.hasPlaybackControl = false;
  37036. this.sourceType = 'mediaNode';
  37037. this.source = this.context.createMediaElementSource( mediaElement );
  37038. this.connect();
  37039. return this;
  37040. }
  37041. /**
  37042. * Sets the given media stream as the source of this instance.
  37043. *
  37044. * {@link Audio#sourceType} is set to `mediaStreamNode` and {@link Audio#hasPlaybackControl} to `false`.
  37045. *
  37046. * @param {MediaStream} mediaStream - The media stream.
  37047. * @return {Audio} A reference to this instance.
  37048. */
  37049. setMediaStreamSource( mediaStream ) {
  37050. this.hasPlaybackControl = false;
  37051. this.sourceType = 'mediaStreamNode';
  37052. this.source = this.context.createMediaStreamSource( mediaStream );
  37053. this.connect();
  37054. return this;
  37055. }
  37056. /**
  37057. * Sets the given audio buffer as the source of this instance.
  37058. *
  37059. * {@link Audio#sourceType} is set to `buffer` and {@link Audio#hasPlaybackControl} to `true`.
  37060. *
  37061. * @param {AudioBuffer} audioBuffer - The audio buffer.
  37062. * @return {Audio} A reference to this instance.
  37063. */
  37064. setBuffer( audioBuffer ) {
  37065. this.buffer = audioBuffer;
  37066. this.sourceType = 'buffer';
  37067. if ( this.autoplay ) this.play();
  37068. return this;
  37069. }
  37070. /**
  37071. * Starts the playback of the audio.
  37072. *
  37073. * Can only be used with compatible audio sources that allow playback control.
  37074. *
  37075. * @param {number} [delay=0] - The delay, in seconds, at which the audio should start playing.
  37076. * @return {Audio|undefined} A reference to this instance.
  37077. */
  37078. play( delay = 0 ) {
  37079. if ( this.isPlaying === true ) {
  37080. warn( 'Audio: Audio is already playing.' );
  37081. return;
  37082. }
  37083. if ( this.hasPlaybackControl === false ) {
  37084. warn( 'Audio: this Audio has no playback control.' );
  37085. return;
  37086. }
  37087. this._startedAt = this.context.currentTime + delay;
  37088. const source = this.context.createBufferSource();
  37089. source.buffer = this.buffer;
  37090. source.loop = this.loop;
  37091. source.loopStart = this.loopStart;
  37092. source.loopEnd = this.loopEnd;
  37093. source.onended = this.onEnded.bind( this );
  37094. source.start( this._startedAt, this._progress + this.offset, this.duration );
  37095. this.isPlaying = true;
  37096. this.source = source;
  37097. this.setDetune( this.detune );
  37098. this.setPlaybackRate( this.playbackRate );
  37099. return this.connect();
  37100. }
  37101. /**
  37102. * Pauses the playback of the audio.
  37103. *
  37104. * Can only be used with compatible audio sources that allow playback control.
  37105. *
  37106. * @return {Audio|undefined} A reference to this instance.
  37107. */
  37108. pause() {
  37109. if ( this.hasPlaybackControl === false ) {
  37110. warn( 'Audio: this Audio has no playback control.' );
  37111. return;
  37112. }
  37113. if ( this.isPlaying === true ) {
  37114. // update current progress
  37115. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  37116. if ( this.loop === true ) {
  37117. // ensure _progress does not exceed duration with looped audios
  37118. this._progress = this._progress % ( this.duration || this.buffer.duration );
  37119. }
  37120. this.source.stop();
  37121. this.source.onended = null;
  37122. this.isPlaying = false;
  37123. }
  37124. return this;
  37125. }
  37126. /**
  37127. * Stops the playback of the audio.
  37128. *
  37129. * Can only be used with compatible audio sources that allow playback control.
  37130. *
  37131. * @param {number} [delay=0] - The delay, in seconds, at which the audio should stop playing.
  37132. * @return {Audio|undefined} A reference to this instance.
  37133. */
  37134. stop( delay = 0 ) {
  37135. if ( this.hasPlaybackControl === false ) {
  37136. warn( 'Audio: this Audio has no playback control.' );
  37137. return;
  37138. }
  37139. this._progress = 0;
  37140. if ( this.source !== null ) {
  37141. this.source.stop( this.context.currentTime + delay );
  37142. this.source.onended = null;
  37143. }
  37144. this.isPlaying = false;
  37145. return this;
  37146. }
  37147. /**
  37148. * Connects to the audio source. This is used internally on
  37149. * initialisation and when setting / removing filters.
  37150. *
  37151. * @return {Audio} A reference to this instance.
  37152. */
  37153. connect() {
  37154. if ( this.filters.length > 0 ) {
  37155. this.source.connect( this.filters[ 0 ] );
  37156. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  37157. this.filters[ i - 1 ].connect( this.filters[ i ] );
  37158. }
  37159. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  37160. } else {
  37161. this.source.connect( this.getOutput() );
  37162. }
  37163. this._connected = true;
  37164. return this;
  37165. }
  37166. /**
  37167. * Disconnects to the audio source. This is used internally on
  37168. * initialisation and when setting / removing filters.
  37169. *
  37170. * @return {Audio|undefined} A reference to this instance.
  37171. */
  37172. disconnect() {
  37173. if ( this._connected === false ) {
  37174. return;
  37175. }
  37176. if ( this.filters.length > 0 ) {
  37177. this.source.disconnect( this.filters[ 0 ] );
  37178. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  37179. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  37180. }
  37181. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  37182. } else {
  37183. this.source.disconnect( this.getOutput() );
  37184. }
  37185. this._connected = false;
  37186. return this;
  37187. }
  37188. /**
  37189. * Returns the current set filters.
  37190. *
  37191. * @return {Array<AudioNode>} The list of filters.
  37192. */
  37193. getFilters() {
  37194. return this.filters;
  37195. }
  37196. /**
  37197. * Sets an array of filters and connects them with the audio source.
  37198. *
  37199. * @param {Array<AudioNode>} [value] - A list of filters.
  37200. * @return {Audio} A reference to this instance.
  37201. */
  37202. setFilters( value ) {
  37203. if ( ! value ) value = [];
  37204. if ( this._connected === true ) {
  37205. this.disconnect();
  37206. this.filters = value.slice();
  37207. this.connect();
  37208. } else {
  37209. this.filters = value.slice();
  37210. }
  37211. return this;
  37212. }
  37213. /**
  37214. * Defines the detuning of oscillation in cents.
  37215. *
  37216. * @param {number} value - The detuning of oscillation in cents.
  37217. * @return {Audio} A reference to this instance.
  37218. */
  37219. setDetune( value ) {
  37220. this.detune = value;
  37221. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  37222. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  37223. }
  37224. return this;
  37225. }
  37226. /**
  37227. * Returns the detuning of oscillation in cents.
  37228. *
  37229. * @return {number} The detuning of oscillation in cents.
  37230. */
  37231. getDetune() {
  37232. return this.detune;
  37233. }
  37234. /**
  37235. * Returns the first filter in the list of filters.
  37236. *
  37237. * @return {AudioNode|undefined} The first filter in the list of filters.
  37238. */
  37239. getFilter() {
  37240. return this.getFilters()[ 0 ];
  37241. }
  37242. /**
  37243. * Applies a single filter node to the audio.
  37244. *
  37245. * @param {AudioNode} [filter] - The filter to set.
  37246. * @return {Audio} A reference to this instance.
  37247. */
  37248. setFilter( filter ) {
  37249. return this.setFilters( filter ? [ filter ] : [] );
  37250. }
  37251. /**
  37252. * Sets the playback rate.
  37253. *
  37254. * Can only be used with compatible audio sources that allow playback control.
  37255. *
  37256. * @param {number} [value] - The playback rate to set.
  37257. * @return {Audio|undefined} A reference to this instance.
  37258. */
  37259. setPlaybackRate( value ) {
  37260. if ( this.hasPlaybackControl === false ) {
  37261. warn( 'Audio: this Audio has no playback control.' );
  37262. return;
  37263. }
  37264. this.playbackRate = value;
  37265. if ( this.isPlaying === true ) {
  37266. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  37267. }
  37268. return this;
  37269. }
  37270. /**
  37271. * Returns the current playback rate.
  37272. * @return {number} The playback rate.
  37273. */
  37274. getPlaybackRate() {
  37275. return this.playbackRate;
  37276. }
  37277. /**
  37278. * Automatically called when playback finished.
  37279. */
  37280. onEnded() {
  37281. this.isPlaying = false;
  37282. this._progress = 0;
  37283. }
  37284. /**
  37285. * Returns the loop flag.
  37286. *
  37287. * Can only be used with compatible audio sources that allow playback control.
  37288. *
  37289. * @return {boolean} Whether the audio should loop or not.
  37290. */
  37291. getLoop() {
  37292. if ( this.hasPlaybackControl === false ) {
  37293. warn( 'Audio: this Audio has no playback control.' );
  37294. return false;
  37295. }
  37296. return this.loop;
  37297. }
  37298. /**
  37299. * Sets the loop flag.
  37300. *
  37301. * Can only be used with compatible audio sources that allow playback control.
  37302. *
  37303. * @param {boolean} value - Whether the audio should loop or not.
  37304. * @return {Audio|undefined} A reference to this instance.
  37305. */
  37306. setLoop( value ) {
  37307. if ( this.hasPlaybackControl === false ) {
  37308. warn( 'Audio: this Audio has no playback control.' );
  37309. return;
  37310. }
  37311. this.loop = value;
  37312. if ( this.isPlaying === true ) {
  37313. this.source.loop = this.loop;
  37314. }
  37315. return this;
  37316. }
  37317. /**
  37318. * Sets the loop start value which defines where in the audio buffer the replay should
  37319. * start, in seconds.
  37320. *
  37321. * @param {number} value - The loop start value.
  37322. * @return {Audio} A reference to this instance.
  37323. */
  37324. setLoopStart( value ) {
  37325. this.loopStart = value;
  37326. return this;
  37327. }
  37328. /**
  37329. * Sets the loop end value which defines where in the audio buffer the replay should
  37330. * stop, in seconds.
  37331. *
  37332. * @param {number} value - The loop end value.
  37333. * @return {Audio} A reference to this instance.
  37334. */
  37335. setLoopEnd( value ) {
  37336. this.loopEnd = value;
  37337. return this;
  37338. }
  37339. /**
  37340. * Returns the volume.
  37341. *
  37342. * @return {number} The volume.
  37343. */
  37344. getVolume() {
  37345. return this.gain.gain.value;
  37346. }
  37347. /**
  37348. * Sets the volume.
  37349. *
  37350. * @param {number} value - The volume to set.
  37351. * @return {Audio} A reference to this instance.
  37352. */
  37353. setVolume( value ) {
  37354. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  37355. return this;
  37356. }
  37357. copy( source, recursive ) {
  37358. super.copy( source, recursive );
  37359. if ( source.sourceType !== 'buffer' ) {
  37360. warn( 'Audio: Audio source type cannot be copied.' );
  37361. return this;
  37362. }
  37363. this.autoplay = source.autoplay;
  37364. this.buffer = source.buffer;
  37365. this.detune = source.detune;
  37366. this.loop = source.loop;
  37367. this.loopStart = source.loopStart;
  37368. this.loopEnd = source.loopEnd;
  37369. this.offset = source.offset;
  37370. this.duration = source.duration;
  37371. this.playbackRate = source.playbackRate;
  37372. this.hasPlaybackControl = source.hasPlaybackControl;
  37373. this.sourceType = source.sourceType;
  37374. this.filters = source.filters.slice();
  37375. return this;
  37376. }
  37377. clone( recursive ) {
  37378. return new this.constructor( this.listener ).copy( this, recursive );
  37379. }
  37380. }
  37381. const _position = /*@__PURE__*/ new Vector3();
  37382. const _quaternion = /*@__PURE__*/ new Quaternion();
  37383. const _scale = /*@__PURE__*/ new Vector3();
  37384. const _orientation = /*@__PURE__*/ new Vector3();
  37385. /**
  37386. * Represents a positional audio object.
  37387. *
  37388. * ```js
  37389. * // create an AudioListener and add it to the camera
  37390. * const listener = new THREE.AudioListener();
  37391. * camera.add( listener );
  37392. *
  37393. * // create the PositionalAudio object (passing in the listener)
  37394. * const sound = new THREE.PositionalAudio( listener );
  37395. *
  37396. * // load a sound and set it as the PositionalAudio object's buffer
  37397. * const audioLoader = new THREE.AudioLoader();
  37398. * audioLoader.load( 'sounds/song.ogg', function( buffer ) {
  37399. * sound.setBuffer( buffer );
  37400. * sound.setRefDistance( 20 );
  37401. * sound.play();
  37402. * });
  37403. *
  37404. * // create an object for the sound to play from
  37405. * const sphere = new THREE.SphereGeometry( 20, 32, 16 );
  37406. * const material = new THREE.MeshPhongMaterial( { color: 0xff2200 } );
  37407. * const mesh = new THREE.Mesh( sphere, material );
  37408. * scene.add( mesh );
  37409. *
  37410. * // finally add the sound to the mesh
  37411. * mesh.add( sound );
  37412. *
  37413. * @augments Audio
  37414. */
  37415. class PositionalAudio extends Audio {
  37416. /**
  37417. * Constructs a positional audio.
  37418. *
  37419. * @param {AudioListener} listener - The global audio listener.
  37420. */
  37421. constructor( listener ) {
  37422. super( listener );
  37423. /**
  37424. * The panner node represents the location, direction, and behavior of an audio
  37425. * source in 3D space.
  37426. *
  37427. * @type {PannerNode}
  37428. * @readonly
  37429. */
  37430. this.panner = this.context.createPanner();
  37431. this.panner.panningModel = 'HRTF';
  37432. this.panner.connect( this.gain );
  37433. }
  37434. connect() {
  37435. super.connect();
  37436. this.panner.connect( this.gain );
  37437. return this;
  37438. }
  37439. disconnect() {
  37440. super.disconnect();
  37441. this.panner.disconnect( this.gain );
  37442. return this;
  37443. }
  37444. getOutput() {
  37445. return this.panner;
  37446. }
  37447. /**
  37448. * Returns the current reference distance.
  37449. *
  37450. * @return {number} The reference distance.
  37451. */
  37452. getRefDistance() {
  37453. return this.panner.refDistance;
  37454. }
  37455. /**
  37456. * Defines the reference distance for reducing volume as the audio source moves
  37457. * further from the listener – i.e. the distance at which the volume reduction
  37458. * starts taking effect.
  37459. *
  37460. * @param {number} value - The reference distance to set.
  37461. * @return {PositionalAudio} A reference to this instance.
  37462. */
  37463. setRefDistance( value ) {
  37464. this.panner.refDistance = value;
  37465. return this;
  37466. }
  37467. /**
  37468. * Returns the current rolloff factor.
  37469. *
  37470. * @return {number} The rolloff factor.
  37471. */
  37472. getRolloffFactor() {
  37473. return this.panner.rolloffFactor;
  37474. }
  37475. /**
  37476. * Defines how quickly the volume is reduced as the source moves away from the listener.
  37477. *
  37478. * @param {number} value - The rolloff factor.
  37479. * @return {PositionalAudio} A reference to this instance.
  37480. */
  37481. setRolloffFactor( value ) {
  37482. this.panner.rolloffFactor = value;
  37483. return this;
  37484. }
  37485. /**
  37486. * Returns the current distance model.
  37487. *
  37488. * @return {('linear'|'inverse'|'exponential')} The distance model.
  37489. */
  37490. getDistanceModel() {
  37491. return this.panner.distanceModel;
  37492. }
  37493. /**
  37494. * Defines which algorithm to use to reduce the volume of the audio source
  37495. * as it moves away from the listener.
  37496. *
  37497. * Read [the spec](https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype)
  37498. * for more details.
  37499. *
  37500. * @param {('linear'|'inverse'|'exponential')} value - The distance model to set.
  37501. * @return {PositionalAudio} A reference to this instance.
  37502. */
  37503. setDistanceModel( value ) {
  37504. this.panner.distanceModel = value;
  37505. return this;
  37506. }
  37507. /**
  37508. * Returns the current max distance.
  37509. *
  37510. * @return {number} The max distance.
  37511. */
  37512. getMaxDistance() {
  37513. return this.panner.maxDistance;
  37514. }
  37515. /**
  37516. * Defines the maximum distance between the audio source and the listener,
  37517. * after which the volume is not reduced any further.
  37518. *
  37519. * This value is used only by the `linear` distance model.
  37520. *
  37521. * @param {number} value - The max distance.
  37522. * @return {PositionalAudio} A reference to this instance.
  37523. */
  37524. setMaxDistance( value ) {
  37525. this.panner.maxDistance = value;
  37526. return this;
  37527. }
  37528. /**
  37529. * Sets the directional cone in which the audio can be listened.
  37530. *
  37531. * @param {number} coneInnerAngle - An angle, in degrees, of a cone inside of which there will be no volume reduction.
  37532. * @param {number} coneOuterAngle - An angle, in degrees, of a cone outside of which the volume will be reduced by a constant value, defined by the `coneOuterGain` parameter.
  37533. * @param {number} coneOuterGain - The amount of volume reduction outside the cone defined by the `coneOuterAngle`. When set to `0`, no sound can be heard.
  37534. * @return {PositionalAudio} A reference to this instance.
  37535. */
  37536. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  37537. this.panner.coneInnerAngle = coneInnerAngle;
  37538. this.panner.coneOuterAngle = coneOuterAngle;
  37539. this.panner.coneOuterGain = coneOuterGain;
  37540. return this;
  37541. }
  37542. updateMatrixWorld( force ) {
  37543. super.updateMatrixWorld( force );
  37544. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  37545. this.matrixWorld.decompose( _position, _quaternion, _scale );
  37546. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  37547. const panner = this.panner;
  37548. if ( panner.positionX ) {
  37549. // code path for Chrome and Firefox (see #14393)
  37550. const endTime = this.context.currentTime + this.listener.timeDelta;
  37551. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  37552. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  37553. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  37554. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  37555. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  37556. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  37557. } else {
  37558. panner.setPosition( _position.x, _position.y, _position.z );
  37559. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  37560. }
  37561. }
  37562. }
  37563. /**
  37564. * This class can be used to analyse audio data.
  37565. *
  37566. * ```js
  37567. * // create an AudioListener and add it to the camera
  37568. * const listener = new THREE.AudioListener();
  37569. * camera.add( listener );
  37570. *
  37571. * // create an Audio source
  37572. * const sound = new THREE.Audio( listener );
  37573. *
  37574. * // load a sound and set it as the Audio object's buffer
  37575. * const audioLoader = new THREE.AudioLoader();
  37576. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  37577. * sound.setBuffer( buffer );
  37578. * sound.setLoop(true);
  37579. * sound.setVolume(0.5);
  37580. * sound.play();
  37581. * });
  37582. *
  37583. * // create an AudioAnalyser, passing in the sound and desired fftSize
  37584. * const analyser = new THREE.AudioAnalyser( sound, 32 );
  37585. *
  37586. * // get the average frequency of the sound
  37587. * const data = analyser.getAverageFrequency();
  37588. * ```
  37589. */
  37590. class AudioAnalyser {
  37591. /**
  37592. * Constructs a new audio analyzer.
  37593. *
  37594. * @param {Audio} audio - The audio to analyze.
  37595. * @param {number} [fftSize=2048] - The window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data.
  37596. */
  37597. constructor( audio, fftSize = 2048 ) {
  37598. /**
  37599. * The global audio listener.
  37600. *
  37601. * @type {AnalyserNode}
  37602. */
  37603. this.analyser = audio.context.createAnalyser();
  37604. this.analyser.fftSize = fftSize;
  37605. /**
  37606. * Holds the analyzed data.
  37607. *
  37608. * @type {Uint8Array}
  37609. */
  37610. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  37611. audio.getOutput().connect( this.analyser );
  37612. }
  37613. /**
  37614. * Returns an array with frequency data of the audio.
  37615. *
  37616. * Each item in the array represents the decibel value for a specific frequency.
  37617. * The frequencies are spread linearly from 0 to 1/2 of the sample rate.
  37618. * For example, for 48000 sample rate, the last item of the array will represent
  37619. * the decibel value for 24000 Hz.
  37620. *
  37621. * @return {Uint8Array} The frequency data.
  37622. */
  37623. getFrequencyData() {
  37624. this.analyser.getByteFrequencyData( this.data );
  37625. return this.data;
  37626. }
  37627. /**
  37628. * Returns the average of the frequencies returned by {@link AudioAnalyser#getFrequencyData}.
  37629. *
  37630. * @return {number} The average frequency.
  37631. */
  37632. getAverageFrequency() {
  37633. let value = 0;
  37634. const data = this.getFrequencyData();
  37635. for ( let i = 0; i < data.length; i ++ ) {
  37636. value += data[ i ];
  37637. }
  37638. return value / data.length;
  37639. }
  37640. }
  37641. /**
  37642. * Buffered scene graph property that allows weighted accumulation; used internally.
  37643. */
  37644. class PropertyMixer {
  37645. /**
  37646. * Constructs a new property mixer.
  37647. *
  37648. * @param {PropertyBinding} binding - The property binding.
  37649. * @param {string} typeName - The keyframe track type name.
  37650. * @param {number} valueSize - The keyframe track value size.
  37651. */
  37652. constructor( binding, typeName, valueSize ) {
  37653. /**
  37654. * The property binding.
  37655. *
  37656. * @type {PropertyBinding}
  37657. */
  37658. this.binding = binding;
  37659. /**
  37660. * The keyframe track value size.
  37661. *
  37662. * @type {number}
  37663. */
  37664. this.valueSize = valueSize;
  37665. let mixFunction,
  37666. mixFunctionAdditive,
  37667. setIdentity;
  37668. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  37669. //
  37670. // interpolators can use .buffer as their .result
  37671. // the data then goes to 'incoming'
  37672. //
  37673. // 'accu0' and 'accu1' are used frame-interleaved for
  37674. // the cumulative result and are compared to detect
  37675. // changes
  37676. //
  37677. // 'orig' stores the original state of the property
  37678. //
  37679. // 'add' is used for additive cumulative results
  37680. //
  37681. // 'work' is optional and is only present for quaternion types. It is used
  37682. // to store intermediate quaternion multiplication results
  37683. switch ( typeName ) {
  37684. case 'quaternion':
  37685. mixFunction = this._slerp;
  37686. mixFunctionAdditive = this._slerpAdditive;
  37687. setIdentity = this._setAdditiveIdentityQuaternion;
  37688. this.buffer = new Float64Array( valueSize * 6 );
  37689. this._workIndex = 5;
  37690. break;
  37691. case 'string':
  37692. case 'bool':
  37693. mixFunction = this._select;
  37694. // Use the regular mix function and for additive on these types,
  37695. // additive is not relevant for non-numeric types
  37696. mixFunctionAdditive = this._select;
  37697. setIdentity = this._setAdditiveIdentityOther;
  37698. this.buffer = new Array( valueSize * 5 );
  37699. break;
  37700. default:
  37701. mixFunction = this._lerp;
  37702. mixFunctionAdditive = this._lerpAdditive;
  37703. setIdentity = this._setAdditiveIdentityNumeric;
  37704. this.buffer = new Float64Array( valueSize * 5 );
  37705. }
  37706. this._mixBufferRegion = mixFunction;
  37707. this._mixBufferRegionAdditive = mixFunctionAdditive;
  37708. this._setIdentity = setIdentity;
  37709. this._origIndex = 3;
  37710. this._addIndex = 4;
  37711. /**
  37712. * Accumulated weight of the property binding.
  37713. *
  37714. * @type {number}
  37715. * @default 0
  37716. */
  37717. this.cumulativeWeight = 0;
  37718. /**
  37719. * Accumulated additive weight of the property binding.
  37720. *
  37721. * @type {number}
  37722. * @default 0
  37723. */
  37724. this.cumulativeWeightAdditive = 0;
  37725. /**
  37726. * Number of active keyframe tracks currently using this property binding.
  37727. *
  37728. * @type {number}
  37729. * @default 0
  37730. */
  37731. this.useCount = 0;
  37732. /**
  37733. * Number of keyframe tracks referencing this property binding.
  37734. *
  37735. * @type {number}
  37736. * @default 0
  37737. */
  37738. this.referenceCount = 0;
  37739. }
  37740. /**
  37741. * Accumulates data in the `incoming` region into `accu<i>`.
  37742. *
  37743. * @param {number} accuIndex - The accumulation index.
  37744. * @param {number} weight - The weight.
  37745. */
  37746. accumulate( accuIndex, weight ) {
  37747. // note: happily accumulating nothing when weight = 0, the caller knows
  37748. // the weight and shouldn't have made the call in the first place
  37749. const buffer = this.buffer,
  37750. stride = this.valueSize,
  37751. offset = accuIndex * stride + stride;
  37752. let currentWeight = this.cumulativeWeight;
  37753. if ( currentWeight === 0 ) {
  37754. // accuN := incoming * weight
  37755. for ( let i = 0; i !== stride; ++ i ) {
  37756. buffer[ offset + i ] = buffer[ i ];
  37757. }
  37758. currentWeight = weight;
  37759. } else {
  37760. // accuN := accuN + incoming * weight
  37761. currentWeight += weight;
  37762. const mix = weight / currentWeight;
  37763. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  37764. }
  37765. this.cumulativeWeight = currentWeight;
  37766. }
  37767. /**
  37768. * Accumulates data in the `incoming` region into `add`.
  37769. *
  37770. * @param {number} weight - The weight.
  37771. */
  37772. accumulateAdditive( weight ) {
  37773. const buffer = this.buffer,
  37774. stride = this.valueSize,
  37775. offset = stride * this._addIndex;
  37776. if ( this.cumulativeWeightAdditive === 0 ) {
  37777. // add = identity
  37778. this._setIdentity();
  37779. }
  37780. // add := add + incoming * weight
  37781. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  37782. this.cumulativeWeightAdditive += weight;
  37783. }
  37784. /**
  37785. * Applies the state of `accu<i>` to the binding when accus differ.
  37786. *
  37787. * @param {number} accuIndex - The accumulation index.
  37788. */
  37789. apply( accuIndex ) {
  37790. const stride = this.valueSize,
  37791. buffer = this.buffer,
  37792. offset = accuIndex * stride + stride,
  37793. weight = this.cumulativeWeight,
  37794. weightAdditive = this.cumulativeWeightAdditive,
  37795. binding = this.binding;
  37796. this.cumulativeWeight = 0;
  37797. this.cumulativeWeightAdditive = 0;
  37798. if ( weight < 1 ) {
  37799. // accuN := accuN + original * ( 1 - cumulativeWeight )
  37800. const originalValueOffset = stride * this._origIndex;
  37801. this._mixBufferRegion(
  37802. buffer, offset, originalValueOffset, 1 - weight, stride );
  37803. }
  37804. if ( weightAdditive > 0 ) {
  37805. // accuN := accuN + additive accuN
  37806. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  37807. }
  37808. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  37809. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  37810. // value has changed -> update scene graph
  37811. binding.setValue( buffer, offset );
  37812. break;
  37813. }
  37814. }
  37815. }
  37816. /**
  37817. * Remembers the state of the bound property and copy it to both accus.
  37818. */
  37819. saveOriginalState() {
  37820. const binding = this.binding;
  37821. const buffer = this.buffer,
  37822. stride = this.valueSize,
  37823. originalValueOffset = stride * this._origIndex;
  37824. binding.getValue( buffer, originalValueOffset );
  37825. // accu[0..1] := orig -- initially detect changes against the original
  37826. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  37827. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  37828. }
  37829. // Add to identity for additive
  37830. this._setIdentity();
  37831. this.cumulativeWeight = 0;
  37832. this.cumulativeWeightAdditive = 0;
  37833. }
  37834. /**
  37835. * Applies the state previously taken via {@link PropertyMixer#saveOriginalState} to the binding.
  37836. */
  37837. restoreOriginalState() {
  37838. const originalValueOffset = this.valueSize * 3;
  37839. this.binding.setValue( this.buffer, originalValueOffset );
  37840. }
  37841. // internals
  37842. _setAdditiveIdentityNumeric() {
  37843. const startIndex = this._addIndex * this.valueSize;
  37844. const endIndex = startIndex + this.valueSize;
  37845. for ( let i = startIndex; i < endIndex; i ++ ) {
  37846. this.buffer[ i ] = 0;
  37847. }
  37848. }
  37849. _setAdditiveIdentityQuaternion() {
  37850. this._setAdditiveIdentityNumeric();
  37851. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  37852. }
  37853. _setAdditiveIdentityOther() {
  37854. const startIndex = this._origIndex * this.valueSize;
  37855. const targetIndex = this._addIndex * this.valueSize;
  37856. for ( let i = 0; i < this.valueSize; i ++ ) {
  37857. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  37858. }
  37859. }
  37860. // mix functions
  37861. _select( buffer, dstOffset, srcOffset, t, stride ) {
  37862. if ( t >= 0.5 ) {
  37863. for ( let i = 0; i !== stride; ++ i ) {
  37864. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  37865. }
  37866. }
  37867. }
  37868. _slerp( buffer, dstOffset, srcOffset, t ) {
  37869. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  37870. }
  37871. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37872. const workOffset = this._workIndex * stride;
  37873. // Store result in intermediate buffer offset
  37874. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  37875. // Slerp to the intermediate result
  37876. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  37877. }
  37878. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  37879. const s = 1 - t;
  37880. for ( let i = 0; i !== stride; ++ i ) {
  37881. const j = dstOffset + i;
  37882. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  37883. }
  37884. }
  37885. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37886. for ( let i = 0; i !== stride; ++ i ) {
  37887. const j = dstOffset + i;
  37888. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  37889. }
  37890. }
  37891. }
  37892. // Characters [].:/ are reserved for track binding syntax.
  37893. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  37894. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  37895. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  37896. // only latin characters, and the unicode \p{L} is not yet supported. So
  37897. // instead, we exclude reserved characters and match everything else.
  37898. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  37899. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  37900. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  37901. // be matched to parse the rest of the track name.
  37902. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  37903. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  37904. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  37905. // Object on target node, and accessor. May not contain reserved
  37906. // characters. Accessor may contain any character except closing bracket.
  37907. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  37908. // Property and accessor. May not contain reserved characters. Accessor may
  37909. // contain any non-bracket characters.
  37910. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  37911. const _trackRe = new RegExp( ''
  37912. + '^'
  37913. + _directoryRe
  37914. + _nodeRe
  37915. + _objectRe
  37916. + _propertyRe
  37917. + '$'
  37918. );
  37919. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  37920. class Composite {
  37921. constructor( targetGroup, path, optionalParsedPath ) {
  37922. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  37923. this._targetGroup = targetGroup;
  37924. this._bindings = targetGroup.subscribe_( path, parsedPath );
  37925. }
  37926. getValue( array, offset ) {
  37927. this.bind(); // bind all binding
  37928. const firstValidIndex = this._targetGroup.nCachedObjects_,
  37929. binding = this._bindings[ firstValidIndex ];
  37930. // and only call .getValue on the first
  37931. if ( binding !== undefined ) binding.getValue( array, offset );
  37932. }
  37933. setValue( array, offset ) {
  37934. const bindings = this._bindings;
  37935. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37936. bindings[ i ].setValue( array, offset );
  37937. }
  37938. }
  37939. bind() {
  37940. const bindings = this._bindings;
  37941. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37942. bindings[ i ].bind();
  37943. }
  37944. }
  37945. unbind() {
  37946. const bindings = this._bindings;
  37947. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37948. bindings[ i ].unbind();
  37949. }
  37950. }
  37951. }
  37952. // Note: This class uses a State pattern on a per-method basis:
  37953. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  37954. // prototype version of these methods with one that represents
  37955. // the bound state. When the property is not found, the methods
  37956. // become no-ops.
  37957. /**
  37958. * This holds a reference to a real property in the scene graph; used internally.
  37959. */
  37960. class PropertyBinding {
  37961. /**
  37962. * Constructs a new property binding.
  37963. *
  37964. * @param {Object} rootNode - The root node.
  37965. * @param {string} path - The path.
  37966. * @param {?Object} [parsedPath] - The parsed path.
  37967. */
  37968. constructor( rootNode, path, parsedPath ) {
  37969. /**
  37970. * The object path to the animated property.
  37971. *
  37972. * @type {string}
  37973. */
  37974. this.path = path;
  37975. /**
  37976. * An object holding information about the path.
  37977. *
  37978. * @type {Object}
  37979. */
  37980. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  37981. /**
  37982. * The object owns the animated property.
  37983. *
  37984. * @type {?Object}
  37985. */
  37986. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  37987. /**
  37988. * The root node.
  37989. *
  37990. * @type {Object3D|Skeleton}
  37991. */
  37992. this.rootNode = rootNode;
  37993. // initial state of these methods that calls 'bind'
  37994. this.getValue = this._getValue_unbound;
  37995. this.setValue = this._setValue_unbound;
  37996. }
  37997. /**
  37998. * Factory method for creating a property binding from the given parameters.
  37999. *
  38000. * @static
  38001. * @param {Object} root - The root node.
  38002. * @param {string} path - The path.
  38003. * @param {?Object} [parsedPath] - The parsed path.
  38004. * @return {PropertyBinding|Composite} The created property binding or composite.
  38005. */
  38006. static create( root, path, parsedPath ) {
  38007. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  38008. return new PropertyBinding( root, path, parsedPath );
  38009. } else {
  38010. return new PropertyBinding.Composite( root, path, parsedPath );
  38011. }
  38012. }
  38013. /**
  38014. * Replaces spaces with underscores and removes unsupported characters from
  38015. * node names, to ensure compatibility with parseTrackName().
  38016. *
  38017. * @param {string} name - Node name to be sanitized.
  38018. * @return {string} The sanitized node name.
  38019. */
  38020. static sanitizeNodeName( name ) {
  38021. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  38022. }
  38023. /**
  38024. * Parses the given track name (an object path to an animated property) and
  38025. * returns an object with information about the path. Matches strings in the following forms:
  38026. *
  38027. * - nodeName.property
  38028. * - nodeName.property[accessor]
  38029. * - nodeName.material.property[accessor]
  38030. * - uuid.property[accessor]
  38031. * - uuid.objectName[objectIndex].propertyName[propertyIndex]
  38032. * - parentName/nodeName.property
  38033. * - parentName/parentName/nodeName.property[index]
  38034. * - .bone[Armature.DEF_cog].position
  38035. * - scene:helium_balloon_model:helium_balloon_model.position
  38036. *
  38037. * @static
  38038. * @param {string} trackName - The track name to parse.
  38039. * @return {Object} The parsed track name as an object.
  38040. */
  38041. static parseTrackName( trackName ) {
  38042. const matches = _trackRe.exec( trackName );
  38043. if ( matches === null ) {
  38044. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  38045. }
  38046. const results = {
  38047. // directoryName: matches[ 1 ], // (tschw) currently unused
  38048. nodeName: matches[ 2 ],
  38049. objectName: matches[ 3 ],
  38050. objectIndex: matches[ 4 ],
  38051. propertyName: matches[ 5 ], // required
  38052. propertyIndex: matches[ 6 ]
  38053. };
  38054. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  38055. if ( lastDot !== undefined && lastDot !== -1 ) {
  38056. const objectName = results.nodeName.substring( lastDot + 1 );
  38057. // Object names must be checked against an allowlist. Otherwise, there
  38058. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  38059. // 'bar' could be the objectName, or part of a nodeName (which can
  38060. // include '.' characters).
  38061. if ( _supportedObjectNames.indexOf( objectName ) !== -1 ) {
  38062. results.nodeName = results.nodeName.substring( 0, lastDot );
  38063. results.objectName = objectName;
  38064. }
  38065. }
  38066. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  38067. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  38068. }
  38069. return results;
  38070. }
  38071. /**
  38072. * Searches for a node in the hierarchy of the given root object by the given
  38073. * node name.
  38074. *
  38075. * @static
  38076. * @param {Object} root - The root object.
  38077. * @param {string|number} nodeName - The name of the node.
  38078. * @return {?Object} The found node. Returns `null` if no object was found.
  38079. */
  38080. static findNode( root, nodeName ) {
  38081. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  38082. return root;
  38083. }
  38084. // search into skeleton bones.
  38085. if ( root.skeleton ) {
  38086. const bone = root.skeleton.getBoneByName( nodeName );
  38087. if ( bone !== undefined ) {
  38088. return bone;
  38089. }
  38090. }
  38091. // search into node subtree.
  38092. if ( root.children ) {
  38093. const searchNodeSubtree = function ( children ) {
  38094. for ( let i = 0; i < children.length; i ++ ) {
  38095. const childNode = children[ i ];
  38096. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  38097. return childNode;
  38098. }
  38099. const result = searchNodeSubtree( childNode.children );
  38100. if ( result ) return result;
  38101. }
  38102. return null;
  38103. };
  38104. const subTreeNode = searchNodeSubtree( root.children );
  38105. if ( subTreeNode ) {
  38106. return subTreeNode;
  38107. }
  38108. }
  38109. return null;
  38110. }
  38111. // these are used to "bind" a nonexistent property
  38112. _getValue_unavailable() {}
  38113. _setValue_unavailable() {}
  38114. // Getters
  38115. _getValue_direct( buffer, offset ) {
  38116. buffer[ offset ] = this.targetObject[ this.propertyName ];
  38117. }
  38118. _getValue_array( buffer, offset ) {
  38119. const source = this.resolvedProperty;
  38120. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  38121. buffer[ offset ++ ] = source[ i ];
  38122. }
  38123. }
  38124. _getValue_arrayElement( buffer, offset ) {
  38125. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  38126. }
  38127. _getValue_toArray( buffer, offset ) {
  38128. this.resolvedProperty.toArray( buffer, offset );
  38129. }
  38130. // Direct
  38131. _setValue_direct( buffer, offset ) {
  38132. this.targetObject[ this.propertyName ] = buffer[ offset ];
  38133. }
  38134. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  38135. this.targetObject[ this.propertyName ] = buffer[ offset ];
  38136. this.targetObject.needsUpdate = true;
  38137. }
  38138. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38139. this.targetObject[ this.propertyName ] = buffer[ offset ];
  38140. this.targetObject.matrixWorldNeedsUpdate = true;
  38141. }
  38142. // EntireArray
  38143. _setValue_array( buffer, offset ) {
  38144. const dest = this.resolvedProperty;
  38145. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  38146. dest[ i ] = buffer[ offset ++ ];
  38147. }
  38148. }
  38149. _setValue_array_setNeedsUpdate( buffer, offset ) {
  38150. const dest = this.resolvedProperty;
  38151. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  38152. dest[ i ] = buffer[ offset ++ ];
  38153. }
  38154. this.targetObject.needsUpdate = true;
  38155. }
  38156. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38157. const dest = this.resolvedProperty;
  38158. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  38159. dest[ i ] = buffer[ offset ++ ];
  38160. }
  38161. this.targetObject.matrixWorldNeedsUpdate = true;
  38162. }
  38163. // ArrayElement
  38164. _setValue_arrayElement( buffer, offset ) {
  38165. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  38166. }
  38167. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  38168. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  38169. this.targetObject.needsUpdate = true;
  38170. }
  38171. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38172. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  38173. this.targetObject.matrixWorldNeedsUpdate = true;
  38174. }
  38175. // HasToFromArray
  38176. _setValue_fromArray( buffer, offset ) {
  38177. this.resolvedProperty.fromArray( buffer, offset );
  38178. }
  38179. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  38180. this.resolvedProperty.fromArray( buffer, offset );
  38181. this.targetObject.needsUpdate = true;
  38182. }
  38183. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38184. this.resolvedProperty.fromArray( buffer, offset );
  38185. this.targetObject.matrixWorldNeedsUpdate = true;
  38186. }
  38187. _getValue_unbound( targetArray, offset ) {
  38188. this.bind();
  38189. this.getValue( targetArray, offset );
  38190. }
  38191. _setValue_unbound( sourceArray, offset ) {
  38192. this.bind();
  38193. this.setValue( sourceArray, offset );
  38194. }
  38195. /**
  38196. * Creates a getter / setter pair for the property tracked by this binding.
  38197. */
  38198. bind() {
  38199. let targetObject = this.node;
  38200. const parsedPath = this.parsedPath;
  38201. const objectName = parsedPath.objectName;
  38202. const propertyName = parsedPath.propertyName;
  38203. let propertyIndex = parsedPath.propertyIndex;
  38204. if ( ! targetObject ) {
  38205. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  38206. this.node = targetObject;
  38207. }
  38208. // set fail state so we can just 'return' on error
  38209. this.getValue = this._getValue_unavailable;
  38210. this.setValue = this._setValue_unavailable;
  38211. // ensure there is a value node
  38212. if ( ! targetObject ) {
  38213. warn( 'PropertyBinding: No target node found for track: ' + this.path + '.' );
  38214. return;
  38215. }
  38216. if ( objectName ) {
  38217. let objectIndex = parsedPath.objectIndex;
  38218. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  38219. switch ( objectName ) {
  38220. case 'materials':
  38221. if ( ! targetObject.material ) {
  38222. error( 'PropertyBinding: Can not bind to material as node does not have a material.', this );
  38223. return;
  38224. }
  38225. if ( ! targetObject.material.materials ) {
  38226. error( 'PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  38227. return;
  38228. }
  38229. targetObject = targetObject.material.materials;
  38230. break;
  38231. case 'bones':
  38232. if ( ! targetObject.skeleton ) {
  38233. error( 'PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  38234. return;
  38235. }
  38236. // potential future optimization: skip this if propertyIndex is already an integer
  38237. // and convert the integer string to a true integer.
  38238. targetObject = targetObject.skeleton.bones;
  38239. // support resolving morphTarget names into indices.
  38240. for ( let i = 0; i < targetObject.length; i ++ ) {
  38241. if ( targetObject[ i ].name === objectIndex ) {
  38242. objectIndex = i;
  38243. break;
  38244. }
  38245. }
  38246. break;
  38247. case 'map':
  38248. if ( 'map' in targetObject ) {
  38249. targetObject = targetObject.map;
  38250. break;
  38251. }
  38252. if ( ! targetObject.material ) {
  38253. error( 'PropertyBinding: Can not bind to material as node does not have a material.', this );
  38254. return;
  38255. }
  38256. if ( ! targetObject.material.map ) {
  38257. error( 'PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  38258. return;
  38259. }
  38260. targetObject = targetObject.material.map;
  38261. break;
  38262. default:
  38263. if ( targetObject[ objectName ] === undefined ) {
  38264. error( 'PropertyBinding: Can not bind to objectName of node undefined.', this );
  38265. return;
  38266. }
  38267. targetObject = targetObject[ objectName ];
  38268. }
  38269. if ( objectIndex !== undefined ) {
  38270. if ( targetObject[ objectIndex ] === undefined ) {
  38271. error( 'PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  38272. return;
  38273. }
  38274. targetObject = targetObject[ objectIndex ];
  38275. }
  38276. }
  38277. // resolve property
  38278. const nodeProperty = targetObject[ propertyName ];
  38279. if ( nodeProperty === undefined ) {
  38280. const nodeName = parsedPath.nodeName;
  38281. error( 'PropertyBinding: Trying to update property for track: ' + nodeName +
  38282. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  38283. return;
  38284. }
  38285. // determine versioning scheme
  38286. let versioning = this.Versioning.None;
  38287. this.targetObject = targetObject;
  38288. if ( targetObject.isMaterial === true ) {
  38289. versioning = this.Versioning.NeedsUpdate;
  38290. } else if ( targetObject.isObject3D === true ) {
  38291. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  38292. }
  38293. // determine how the property gets bound
  38294. let bindingType = this.BindingType.Direct;
  38295. if ( propertyIndex !== undefined ) {
  38296. // access a sub element of the property array (only primitives are supported right now)
  38297. if ( propertyName === 'morphTargetInfluences' ) {
  38298. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  38299. // support resolving morphTarget names into indices.
  38300. if ( ! targetObject.geometry ) {
  38301. error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  38302. return;
  38303. }
  38304. if ( ! targetObject.geometry.morphAttributes ) {
  38305. error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  38306. return;
  38307. }
  38308. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  38309. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  38310. }
  38311. }
  38312. bindingType = this.BindingType.ArrayElement;
  38313. this.resolvedProperty = nodeProperty;
  38314. this.propertyIndex = propertyIndex;
  38315. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  38316. // must use copy for Object3D.Euler/Quaternion
  38317. bindingType = this.BindingType.HasFromToArray;
  38318. this.resolvedProperty = nodeProperty;
  38319. } else if ( Array.isArray( nodeProperty ) ) {
  38320. bindingType = this.BindingType.EntireArray;
  38321. this.resolvedProperty = nodeProperty;
  38322. } else {
  38323. this.propertyName = propertyName;
  38324. }
  38325. // select getter / setter
  38326. this.getValue = this.GetterByBindingType[ bindingType ];
  38327. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  38328. }
  38329. /**
  38330. * Unbinds the property.
  38331. */
  38332. unbind() {
  38333. this.node = null;
  38334. // back to the prototype version of getValue / setValue
  38335. // note: avoiding to mutate the shape of 'this' via 'delete'
  38336. this.getValue = this._getValue_unbound;
  38337. this.setValue = this._setValue_unbound;
  38338. }
  38339. }
  38340. PropertyBinding.Composite = Composite;
  38341. PropertyBinding.prototype.BindingType = {
  38342. Direct: 0,
  38343. EntireArray: 1,
  38344. ArrayElement: 2,
  38345. HasFromToArray: 3
  38346. };
  38347. PropertyBinding.prototype.Versioning = {
  38348. None: 0,
  38349. NeedsUpdate: 1,
  38350. MatrixWorldNeedsUpdate: 2
  38351. };
  38352. PropertyBinding.prototype.GetterByBindingType = [
  38353. PropertyBinding.prototype._getValue_direct,
  38354. PropertyBinding.prototype._getValue_array,
  38355. PropertyBinding.prototype._getValue_arrayElement,
  38356. PropertyBinding.prototype._getValue_toArray,
  38357. ];
  38358. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  38359. [
  38360. // Direct
  38361. PropertyBinding.prototype._setValue_direct,
  38362. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  38363. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  38364. ], [
  38365. // EntireArray
  38366. PropertyBinding.prototype._setValue_array,
  38367. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  38368. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  38369. ], [
  38370. // ArrayElement
  38371. PropertyBinding.prototype._setValue_arrayElement,
  38372. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  38373. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  38374. ], [
  38375. // HasToFromArray
  38376. PropertyBinding.prototype._setValue_fromArray,
  38377. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  38378. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  38379. ]
  38380. ];
  38381. /**
  38382. * A group of objects that receives a shared animation state.
  38383. *
  38384. * Usage:
  38385. *
  38386. * - Add objects you would otherwise pass as 'root' to the
  38387. * constructor or the .clipAction method of AnimationMixer.
  38388. * - Instead pass this object as 'root'.
  38389. * - You can also add and remove objects later when the mixer is running.
  38390. *
  38391. * Note:
  38392. *
  38393. * - Objects of this class appear as one object to the mixer,
  38394. * so cache control of the individual objects must be done on the group.
  38395. *
  38396. * Limitation:
  38397. *
  38398. * - The animated properties must be compatible among the all objects in the group.
  38399. * - A single property can either be controlled through a target group or directly, but not both.
  38400. */
  38401. class AnimationObjectGroup {
  38402. /**
  38403. * Constructs a new animation group.
  38404. *
  38405. * @param {...Object3D} arguments - An arbitrary number of 3D objects that share the same animation state.
  38406. */
  38407. constructor() {
  38408. /**
  38409. * This flag can be used for type testing.
  38410. *
  38411. * @type {boolean}
  38412. * @readonly
  38413. * @default true
  38414. */
  38415. this.isAnimationObjectGroup = true;
  38416. /**
  38417. * The UUID of the 3D object.
  38418. *
  38419. * @type {string}
  38420. * @readonly
  38421. */
  38422. this.uuid = generateUUID();
  38423. // cached objects followed by the active ones
  38424. this._objects = Array.prototype.slice.call( arguments );
  38425. this.nCachedObjects_ = 0; // threshold
  38426. // note: read by PropertyBinding.Composite
  38427. const indices = {};
  38428. this._indicesByUUID = indices; // for bookkeeping
  38429. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38430. indices[ arguments[ i ].uuid ] = i;
  38431. }
  38432. this._paths = []; // inside: string
  38433. this._parsedPaths = []; // inside: { we don't care, here }
  38434. this._bindings = []; // inside: Array< PropertyBinding >
  38435. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  38436. const scope = this;
  38437. this.stats = {
  38438. objects: {
  38439. get total() {
  38440. return scope._objects.length;
  38441. },
  38442. get inUse() {
  38443. return this.total - scope.nCachedObjects_;
  38444. }
  38445. },
  38446. get bindingsPerObject() {
  38447. return scope._bindings.length;
  38448. }
  38449. };
  38450. }
  38451. /**
  38452. * Adds an arbitrary number of objects to this animation group.
  38453. *
  38454. * @param {...Object3D} arguments - The 3D objects to add.
  38455. */
  38456. add() {
  38457. const objects = this._objects,
  38458. indicesByUUID = this._indicesByUUID,
  38459. paths = this._paths,
  38460. parsedPaths = this._parsedPaths,
  38461. bindings = this._bindings,
  38462. nBindings = bindings.length;
  38463. let knownObject = undefined,
  38464. nObjects = objects.length,
  38465. nCachedObjects = this.nCachedObjects_;
  38466. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38467. const object = arguments[ i ],
  38468. uuid = object.uuid;
  38469. let index = indicesByUUID[ uuid ];
  38470. if ( index === undefined ) {
  38471. // unknown object -> add it to the ACTIVE region
  38472. index = nObjects ++;
  38473. indicesByUUID[ uuid ] = index;
  38474. objects.push( object );
  38475. // accounting is done, now do the same for all bindings
  38476. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38477. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  38478. }
  38479. } else if ( index < nCachedObjects ) {
  38480. knownObject = objects[ index ];
  38481. // move existing object to the ACTIVE region
  38482. const firstActiveIndex = -- nCachedObjects,
  38483. lastCachedObject = objects[ firstActiveIndex ];
  38484. indicesByUUID[ lastCachedObject.uuid ] = index;
  38485. objects[ index ] = lastCachedObject;
  38486. indicesByUUID[ uuid ] = firstActiveIndex;
  38487. objects[ firstActiveIndex ] = object;
  38488. // accounting is done, now do the same for all bindings
  38489. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38490. const bindingsForPath = bindings[ j ],
  38491. lastCached = bindingsForPath[ firstActiveIndex ];
  38492. let binding = bindingsForPath[ index ];
  38493. bindingsForPath[ index ] = lastCached;
  38494. if ( binding === undefined ) {
  38495. // since we do not bother to create new bindings
  38496. // for objects that are cached, the binding may
  38497. // or may not exist
  38498. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  38499. }
  38500. bindingsForPath[ firstActiveIndex ] = binding;
  38501. }
  38502. } else if ( objects[ index ] !== knownObject ) {
  38503. error( 'AnimationObjectGroup: Different objects with the same UUID ' +
  38504. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  38505. } // else the object is already where we want it to be
  38506. } // for arguments
  38507. this.nCachedObjects_ = nCachedObjects;
  38508. }
  38509. /**
  38510. * Removes an arbitrary number of objects to this animation group
  38511. *
  38512. * @param {...Object3D} arguments - The 3D objects to remove.
  38513. */
  38514. remove() {
  38515. const objects = this._objects,
  38516. indicesByUUID = this._indicesByUUID,
  38517. bindings = this._bindings,
  38518. nBindings = bindings.length;
  38519. let nCachedObjects = this.nCachedObjects_;
  38520. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38521. const object = arguments[ i ],
  38522. uuid = object.uuid,
  38523. index = indicesByUUID[ uuid ];
  38524. if ( index !== undefined && index >= nCachedObjects ) {
  38525. // move existing object into the CACHED region
  38526. const lastCachedIndex = nCachedObjects ++,
  38527. firstActiveObject = objects[ lastCachedIndex ];
  38528. indicesByUUID[ firstActiveObject.uuid ] = index;
  38529. objects[ index ] = firstActiveObject;
  38530. indicesByUUID[ uuid ] = lastCachedIndex;
  38531. objects[ lastCachedIndex ] = object;
  38532. // accounting is done, now do the same for all bindings
  38533. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38534. const bindingsForPath = bindings[ j ],
  38535. firstActive = bindingsForPath[ lastCachedIndex ],
  38536. binding = bindingsForPath[ index ];
  38537. bindingsForPath[ index ] = firstActive;
  38538. bindingsForPath[ lastCachedIndex ] = binding;
  38539. }
  38540. }
  38541. } // for arguments
  38542. this.nCachedObjects_ = nCachedObjects;
  38543. }
  38544. /**
  38545. * Deallocates all memory resources for the passed 3D objects of this animation group.
  38546. *
  38547. * @param {...Object3D} arguments - The 3D objects to uncache.
  38548. */
  38549. uncache() {
  38550. const objects = this._objects,
  38551. indicesByUUID = this._indicesByUUID,
  38552. bindings = this._bindings,
  38553. nBindings = bindings.length;
  38554. let nCachedObjects = this.nCachedObjects_,
  38555. nObjects = objects.length;
  38556. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38557. const object = arguments[ i ],
  38558. uuid = object.uuid,
  38559. index = indicesByUUID[ uuid ];
  38560. if ( index !== undefined ) {
  38561. delete indicesByUUID[ uuid ];
  38562. if ( index < nCachedObjects ) {
  38563. // object is cached, shrink the CACHED region
  38564. const firstActiveIndex = -- nCachedObjects,
  38565. lastCachedObject = objects[ firstActiveIndex ],
  38566. lastIndex = -- nObjects,
  38567. lastObject = objects[ lastIndex ];
  38568. // last cached object takes this object's place
  38569. indicesByUUID[ lastCachedObject.uuid ] = index;
  38570. objects[ index ] = lastCachedObject;
  38571. // last object goes to the activated slot and pop
  38572. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  38573. objects[ firstActiveIndex ] = lastObject;
  38574. objects.pop();
  38575. // accounting is done, now do the same for all bindings
  38576. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38577. const bindingsForPath = bindings[ j ],
  38578. lastCached = bindingsForPath[ firstActiveIndex ],
  38579. last = bindingsForPath[ lastIndex ];
  38580. bindingsForPath[ index ] = lastCached;
  38581. bindingsForPath[ firstActiveIndex ] = last;
  38582. bindingsForPath.pop();
  38583. }
  38584. } else {
  38585. // object is active, just swap with the last and pop
  38586. const lastIndex = -- nObjects,
  38587. lastObject = objects[ lastIndex ];
  38588. if ( lastIndex > 0 ) {
  38589. indicesByUUID[ lastObject.uuid ] = index;
  38590. }
  38591. objects[ index ] = lastObject;
  38592. objects.pop();
  38593. // accounting is done, now do the same for all bindings
  38594. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38595. const bindingsForPath = bindings[ j ];
  38596. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  38597. bindingsForPath.pop();
  38598. }
  38599. } // cached or active
  38600. } // if object is known
  38601. } // for arguments
  38602. this.nCachedObjects_ = nCachedObjects;
  38603. }
  38604. // Internal interface used by befriended PropertyBinding.Composite:
  38605. subscribe_( path, parsedPath ) {
  38606. // returns an array of bindings for the given path that is changed
  38607. // according to the contained objects in the group
  38608. const indicesByPath = this._bindingsIndicesByPath;
  38609. let index = indicesByPath[ path ];
  38610. const bindings = this._bindings;
  38611. if ( index !== undefined ) return bindings[ index ];
  38612. const paths = this._paths,
  38613. parsedPaths = this._parsedPaths,
  38614. objects = this._objects,
  38615. nObjects = objects.length,
  38616. nCachedObjects = this.nCachedObjects_,
  38617. bindingsForPath = new Array( nObjects );
  38618. index = bindings.length;
  38619. indicesByPath[ path ] = index;
  38620. paths.push( path );
  38621. parsedPaths.push( parsedPath );
  38622. bindings.push( bindingsForPath );
  38623. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  38624. const object = objects[ i ];
  38625. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  38626. }
  38627. return bindingsForPath;
  38628. }
  38629. unsubscribe_( path ) {
  38630. // tells the group to forget about a property path and no longer
  38631. // update the array previously obtained with 'subscribe_'
  38632. const indicesByPath = this._bindingsIndicesByPath,
  38633. index = indicesByPath[ path ];
  38634. if ( index !== undefined ) {
  38635. const paths = this._paths,
  38636. parsedPaths = this._parsedPaths,
  38637. bindings = this._bindings,
  38638. lastBindingsIndex = bindings.length - 1,
  38639. lastBindings = bindings[ lastBindingsIndex ],
  38640. lastBindingsPath = path[ lastBindingsIndex ];
  38641. indicesByPath[ lastBindingsPath ] = index;
  38642. bindings[ index ] = lastBindings;
  38643. bindings.pop();
  38644. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  38645. parsedPaths.pop();
  38646. paths[ index ] = paths[ lastBindingsIndex ];
  38647. paths.pop();
  38648. }
  38649. }
  38650. }
  38651. /**
  38652. * An instance of `AnimationAction` schedules the playback of an animation which is
  38653. * stored in {@link AnimationClip}.
  38654. */
  38655. class AnimationAction {
  38656. /**
  38657. * Constructs a new animation action.
  38658. *
  38659. * @param {AnimationMixer} mixer - The mixer that is controlled by this action.
  38660. * @param {AnimationClip} clip - The animation clip that holds the actual keyframes.
  38661. * @param {?Object3D} [localRoot=null] - The root object on which this action is performed.
  38662. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  38663. */
  38664. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  38665. this._mixer = mixer;
  38666. this._clip = clip;
  38667. this._localRoot = localRoot;
  38668. /**
  38669. * Defines how the animation is blended/combined when two or more animations
  38670. * are simultaneously played.
  38671. *
  38672. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  38673. */
  38674. this.blendMode = blendMode;
  38675. const tracks = clip.tracks,
  38676. nTracks = tracks.length,
  38677. interpolants = new Array( nTracks );
  38678. const interpolantSettings = {
  38679. endingStart: ZeroCurvatureEnding,
  38680. endingEnd: ZeroCurvatureEnding
  38681. };
  38682. for ( let i = 0; i !== nTracks; ++ i ) {
  38683. const interpolant = tracks[ i ].createInterpolant( null );
  38684. interpolants[ i ] = interpolant;
  38685. // preserve interpolant settings (like tangent data from BezierInterpolant)
  38686. if ( interpolant.settings ) {
  38687. Object.assign( interpolantSettings, interpolant.settings );
  38688. }
  38689. interpolant.settings = interpolantSettings;
  38690. }
  38691. this._interpolantSettings = interpolantSettings;
  38692. this._interpolants = interpolants; // bound by the mixer
  38693. // inside: PropertyMixer (managed by the mixer)
  38694. this._propertyBindings = new Array( nTracks );
  38695. this._cacheIndex = null; // for the memory manager
  38696. this._byClipCacheIndex = null; // for the memory manager
  38697. this._timeScaleInterpolant = null;
  38698. this._weightInterpolant = null;
  38699. /**
  38700. * The loop mode, set via {@link AnimationAction#setLoop}.
  38701. *
  38702. * @type {(LoopRepeat|LoopOnce|LoopPingPong)}
  38703. * @default LoopRepeat
  38704. */
  38705. this.loop = LoopRepeat;
  38706. this._loopCount = -1;
  38707. // global mixer time when the action is to be started
  38708. // it's set back to 'null' upon start of the action
  38709. this._startTime = null;
  38710. /**
  38711. * The local time of this action (in seconds, starting with `0`).
  38712. *
  38713. * The value gets clamped or wrapped to `[0,clip.duration]` (according to the
  38714. * loop state).
  38715. *
  38716. * @type {number}
  38717. * @default Infinity
  38718. */
  38719. this.time = 0;
  38720. /**
  38721. * Scaling factor for the {@link AnimationAction#time}. A value of `0` causes the
  38722. * animation to pause. Negative values cause the animation to play backwards.
  38723. *
  38724. * @type {number}
  38725. * @default 1
  38726. */
  38727. this.timeScale = 1;
  38728. this._effectiveTimeScale = 1;
  38729. /**
  38730. * The degree of influence of this action (in the interval `[0, 1]`). Values
  38731. * between `0` (no impact) and `1` (full impact) can be used to blend between
  38732. * several actions.
  38733. *
  38734. * @type {number}
  38735. * @default 1
  38736. */
  38737. this.weight = 1;
  38738. this._effectiveWeight = 1;
  38739. /**
  38740. * The number of repetitions of the performed clip over the course of this action.
  38741. * Can be set via {@link AnimationAction#setLoop}.
  38742. *
  38743. * Setting this number has no effect if {@link AnimationAction#loop} is set to
  38744. * `THREE:LoopOnce`.
  38745. *
  38746. * @type {number}
  38747. * @default Infinity
  38748. */
  38749. this.repetitions = Infinity;
  38750. /**
  38751. * If set to `true`, the playback of the action is paused.
  38752. *
  38753. * @type {boolean}
  38754. * @default false
  38755. */
  38756. this.paused = false;
  38757. /**
  38758. * If set to `false`, the action is disabled so it has no impact.
  38759. *
  38760. * When the action is re-enabled, the animation continues from its current
  38761. * time (setting `enabled` to `false` doesn't reset the action).
  38762. *
  38763. * @type {boolean}
  38764. * @default true
  38765. */
  38766. this.enabled = true;
  38767. /**
  38768. * If set to true the animation will automatically be paused on its last frame.
  38769. *
  38770. * If set to false, {@link AnimationAction#enabled} will automatically be switched
  38771. * to `false` when the last loop of the action has finished, so that this action has
  38772. * no further impact.
  38773. *
  38774. * Note: This member has no impact if the action is interrupted (it
  38775. * has only an effect if its last loop has really finished).
  38776. *
  38777. * @type {boolean}
  38778. * @default false
  38779. */
  38780. this.clampWhenFinished = false;
  38781. /**
  38782. * Enables smooth interpolation without separate clips for start, loop and end.
  38783. *
  38784. * @type {boolean}
  38785. * @default true
  38786. */
  38787. this.zeroSlopeAtStart = true;
  38788. /**
  38789. * Enables smooth interpolation without separate clips for start, loop and end.
  38790. *
  38791. * @type {boolean}
  38792. * @default true
  38793. */
  38794. this.zeroSlopeAtEnd = true;
  38795. }
  38796. /**
  38797. * Starts the playback of the animation.
  38798. *
  38799. * @return {AnimationAction} A reference to this animation action.
  38800. */
  38801. play() {
  38802. this._mixer._activateAction( this );
  38803. return this;
  38804. }
  38805. /**
  38806. * Stops the playback of the animation.
  38807. *
  38808. * @return {AnimationAction} A reference to this animation action.
  38809. */
  38810. stop() {
  38811. this._mixer._deactivateAction( this );
  38812. return this.reset();
  38813. }
  38814. /**
  38815. * Resets the playback of the animation.
  38816. *
  38817. * @return {AnimationAction} A reference to this animation action.
  38818. */
  38819. reset() {
  38820. this.paused = false;
  38821. this.enabled = true;
  38822. this.time = 0; // restart clip
  38823. this._loopCount = -1;// forget previous loops
  38824. this._startTime = null;// forget scheduling
  38825. return this.stopFading().stopWarping();
  38826. }
  38827. /**
  38828. * Returns `true` if the animation is running.
  38829. *
  38830. * @return {boolean} Whether the animation is running or not.
  38831. */
  38832. isRunning() {
  38833. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  38834. this._startTime === null && this._mixer._isActiveAction( this );
  38835. }
  38836. /**
  38837. * Returns `true` when {@link AnimationAction#play} has been called.
  38838. *
  38839. * @return {boolean} Whether the animation is scheduled or not.
  38840. */
  38841. isScheduled() {
  38842. return this._mixer._isActiveAction( this );
  38843. }
  38844. /**
  38845. * Defines the time when the animation should start.
  38846. *
  38847. * @param {number} time - The start time in seconds.
  38848. * @return {AnimationAction} A reference to this animation action.
  38849. */
  38850. startAt( time ) {
  38851. this._startTime = time;
  38852. return this;
  38853. }
  38854. /**
  38855. * Configures the loop settings for this action.
  38856. *
  38857. * @param {(LoopRepeat|LoopOnce|LoopPingPong)} mode - The loop mode.
  38858. * @param {number} repetitions - The number of repetitions.
  38859. * @return {AnimationAction} A reference to this animation action.
  38860. */
  38861. setLoop( mode, repetitions ) {
  38862. this.loop = mode;
  38863. this.repetitions = repetitions;
  38864. return this;
  38865. }
  38866. /**
  38867. * Sets the effective weight of this action.
  38868. *
  38869. * An action has no effect and thus an effective weight of zero when the
  38870. * action is disabled.
  38871. *
  38872. * @param {number} weight - The weight to set.
  38873. * @return {AnimationAction} A reference to this animation action.
  38874. */
  38875. setEffectiveWeight( weight ) {
  38876. this.weight = weight;
  38877. // note: same logic as when updated at runtime
  38878. this._effectiveWeight = this.enabled ? weight : 0;
  38879. return this.stopFading();
  38880. }
  38881. /**
  38882. * Returns the effective weight of this action.
  38883. *
  38884. * @return {number} The effective weight.
  38885. */
  38886. getEffectiveWeight() {
  38887. return this._effectiveWeight;
  38888. }
  38889. /**
  38890. * Fades the animation in by increasing its weight gradually from `0` to `1`,
  38891. * within the passed time interval.
  38892. *
  38893. * @param {number} duration - The duration of the fade.
  38894. * @return {AnimationAction} A reference to this animation action.
  38895. */
  38896. fadeIn( duration ) {
  38897. return this._scheduleFading( duration, 0, 1 );
  38898. }
  38899. /**
  38900. * Fades the animation out by decreasing its weight gradually from `1` to `0`,
  38901. * within the passed time interval.
  38902. *
  38903. * @param {number} duration - The duration of the fade.
  38904. * @return {AnimationAction} A reference to this animation action.
  38905. */
  38906. fadeOut( duration ) {
  38907. return this._scheduleFading( duration, 1, 0 );
  38908. }
  38909. /**
  38910. * Causes this action to fade in and the given action to fade out,
  38911. * within the passed time interval.
  38912. *
  38913. * @param {AnimationAction} fadeOutAction - The animation action to fade out.
  38914. * @param {number} duration - The duration of the fade.
  38915. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38916. * @return {AnimationAction} A reference to this animation action.
  38917. */
  38918. crossFadeFrom( fadeOutAction, duration, warp = false ) {
  38919. fadeOutAction.fadeOut( duration );
  38920. this.fadeIn( duration );
  38921. if ( warp === true ) {
  38922. const fadeInDuration = this._clip.duration,
  38923. fadeOutDuration = fadeOutAction._clip.duration,
  38924. startEndRatio = fadeOutDuration / fadeInDuration,
  38925. endStartRatio = fadeInDuration / fadeOutDuration;
  38926. fadeOutAction.warp( 1.0, startEndRatio, duration );
  38927. this.warp( endStartRatio, 1.0, duration );
  38928. }
  38929. return this;
  38930. }
  38931. /**
  38932. * Causes this action to fade out and the given action to fade in,
  38933. * within the passed time interval.
  38934. *
  38935. * @param {AnimationAction} fadeInAction - The animation action to fade in.
  38936. * @param {number} duration - The duration of the fade.
  38937. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38938. * @return {AnimationAction} A reference to this animation action.
  38939. */
  38940. crossFadeTo( fadeInAction, duration, warp = false ) {
  38941. return fadeInAction.crossFadeFrom( this, duration, warp );
  38942. }
  38943. /**
  38944. * Stops any fading which is applied to this action.
  38945. *
  38946. * @return {AnimationAction} A reference to this animation action.
  38947. */
  38948. stopFading() {
  38949. const weightInterpolant = this._weightInterpolant;
  38950. if ( weightInterpolant !== null ) {
  38951. this._weightInterpolant = null;
  38952. this._mixer._takeBackControlInterpolant( weightInterpolant );
  38953. }
  38954. return this;
  38955. }
  38956. /**
  38957. * Sets the effective time scale of this action.
  38958. *
  38959. * An action has no effect and thus an effective time scale of zero when the
  38960. * action is paused.
  38961. *
  38962. * @param {number} timeScale - The time scale to set.
  38963. * @return {AnimationAction} A reference to this animation action.
  38964. */
  38965. setEffectiveTimeScale( timeScale ) {
  38966. this.timeScale = timeScale;
  38967. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  38968. return this.stopWarping();
  38969. }
  38970. /**
  38971. * Returns the effective time scale of this action.
  38972. *
  38973. * @return {number} The effective time scale.
  38974. */
  38975. getEffectiveTimeScale() {
  38976. return this._effectiveTimeScale;
  38977. }
  38978. /**
  38979. * Sets the duration for a single loop of this action.
  38980. *
  38981. * @param {number} duration - The duration to set.
  38982. * @return {AnimationAction} A reference to this animation action.
  38983. */
  38984. setDuration( duration ) {
  38985. this.timeScale = this._clip.duration / duration;
  38986. return this.stopWarping();
  38987. }
  38988. /**
  38989. * Synchronizes this action with the passed other action.
  38990. *
  38991. * @param {AnimationAction} action - The action to sync with.
  38992. * @return {AnimationAction} A reference to this animation action.
  38993. */
  38994. syncWith( action ) {
  38995. this.time = action.time;
  38996. this.timeScale = action.timeScale;
  38997. return this.stopWarping();
  38998. }
  38999. /**
  39000. * Decelerates this animation's speed to `0` within the passed time interval.
  39001. *
  39002. * @param {number} duration - The duration.
  39003. * @return {AnimationAction} A reference to this animation action.
  39004. */
  39005. halt( duration ) {
  39006. return this.warp( this._effectiveTimeScale, 0, duration );
  39007. }
  39008. /**
  39009. * Changes the playback speed, within the passed time interval, by modifying
  39010. * {@link AnimationAction#timeScale} gradually from `startTimeScale` to
  39011. * `endTimeScale`.
  39012. *
  39013. * @param {number} startTimeScale - The start time scale.
  39014. * @param {number} endTimeScale - The end time scale.
  39015. * @param {number} duration - The duration.
  39016. * @return {AnimationAction} A reference to this animation action.
  39017. */
  39018. warp( startTimeScale, endTimeScale, duration ) {
  39019. const mixer = this._mixer,
  39020. now = mixer.time,
  39021. timeScale = this.timeScale;
  39022. let interpolant = this._timeScaleInterpolant;
  39023. if ( interpolant === null ) {
  39024. interpolant = mixer._lendControlInterpolant();
  39025. this._timeScaleInterpolant = interpolant;
  39026. }
  39027. const times = interpolant.parameterPositions,
  39028. values = interpolant.sampleValues;
  39029. times[ 0 ] = now;
  39030. times[ 1 ] = now + duration;
  39031. values[ 0 ] = startTimeScale / timeScale;
  39032. values[ 1 ] = endTimeScale / timeScale;
  39033. return this;
  39034. }
  39035. /**
  39036. * Stops any scheduled warping which is applied to this action.
  39037. *
  39038. * @return {AnimationAction} A reference to this animation action.
  39039. */
  39040. stopWarping() {
  39041. const timeScaleInterpolant = this._timeScaleInterpolant;
  39042. if ( timeScaleInterpolant !== null ) {
  39043. this._timeScaleInterpolant = null;
  39044. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  39045. }
  39046. return this;
  39047. }
  39048. /**
  39049. * Returns the animation mixer of this animation action.
  39050. *
  39051. * @return {AnimationMixer} The animation mixer.
  39052. */
  39053. getMixer() {
  39054. return this._mixer;
  39055. }
  39056. /**
  39057. * Returns the animation clip of this animation action.
  39058. *
  39059. * @return {AnimationClip} The animation clip.
  39060. */
  39061. getClip() {
  39062. return this._clip;
  39063. }
  39064. /**
  39065. * Returns the root object of this animation action.
  39066. *
  39067. * @return {Object3D} The root object.
  39068. */
  39069. getRoot() {
  39070. return this._localRoot || this._mixer._root;
  39071. }
  39072. // Internal
  39073. _update( time, deltaTime, timeDirection, accuIndex ) {
  39074. // called by the mixer
  39075. if ( ! this.enabled ) {
  39076. // call ._updateWeight() to update ._effectiveWeight
  39077. this._updateWeight( time );
  39078. return;
  39079. }
  39080. const startTime = this._startTime;
  39081. if ( startTime !== null ) {
  39082. // check for scheduled start of action
  39083. const timeRunning = ( time - startTime ) * timeDirection;
  39084. if ( timeRunning < 0 || timeDirection === 0 ) {
  39085. deltaTime = 0;
  39086. } else {
  39087. this._startTime = null; // unschedule
  39088. deltaTime = timeDirection * timeRunning;
  39089. }
  39090. }
  39091. // apply time scale and advance time
  39092. deltaTime *= this._updateTimeScale( time );
  39093. const clipTime = this._updateTime( deltaTime );
  39094. // note: _updateTime may disable the action resulting in
  39095. // an effective weight of 0
  39096. const weight = this._updateWeight( time );
  39097. if ( weight > 0 ) {
  39098. const interpolants = this._interpolants;
  39099. const propertyMixers = this._propertyBindings;
  39100. switch ( this.blendMode ) {
  39101. case AdditiveAnimationBlendMode:
  39102. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  39103. interpolants[ j ].evaluate( clipTime );
  39104. propertyMixers[ j ].accumulateAdditive( weight );
  39105. }
  39106. break;
  39107. case NormalAnimationBlendMode:
  39108. default:
  39109. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  39110. interpolants[ j ].evaluate( clipTime );
  39111. propertyMixers[ j ].accumulate( accuIndex, weight );
  39112. }
  39113. }
  39114. }
  39115. }
  39116. _updateWeight( time ) {
  39117. let weight = 0;
  39118. if ( this.enabled ) {
  39119. weight = this.weight;
  39120. const interpolant = this._weightInterpolant;
  39121. if ( interpolant !== null ) {
  39122. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  39123. weight *= interpolantValue;
  39124. if ( time > interpolant.parameterPositions[ 1 ] ) {
  39125. this.stopFading();
  39126. if ( interpolantValue === 0 ) {
  39127. // faded out, disable
  39128. this.enabled = false;
  39129. }
  39130. }
  39131. }
  39132. }
  39133. this._effectiveWeight = weight;
  39134. return weight;
  39135. }
  39136. _updateTimeScale( time ) {
  39137. let timeScale = 0;
  39138. if ( ! this.paused ) {
  39139. timeScale = this.timeScale;
  39140. const interpolant = this._timeScaleInterpolant;
  39141. if ( interpolant !== null ) {
  39142. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  39143. timeScale *= interpolantValue;
  39144. if ( time > interpolant.parameterPositions[ 1 ] ) {
  39145. this.stopWarping();
  39146. if ( timeScale === 0 ) {
  39147. // motion has halted, pause
  39148. this.paused = true;
  39149. } else {
  39150. // warp done - apply final time scale
  39151. this.timeScale = timeScale;
  39152. }
  39153. }
  39154. }
  39155. }
  39156. this._effectiveTimeScale = timeScale;
  39157. return timeScale;
  39158. }
  39159. _updateTime( deltaTime ) {
  39160. const duration = this._clip.duration;
  39161. const loop = this.loop;
  39162. let time = this.time + deltaTime;
  39163. let loopCount = this._loopCount;
  39164. const pingPong = ( loop === LoopPingPong );
  39165. if ( deltaTime === 0 ) {
  39166. if ( loopCount === -1 ) return time;
  39167. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  39168. }
  39169. if ( loop === LoopOnce ) {
  39170. if ( loopCount === -1 ) {
  39171. // just started
  39172. this._loopCount = 0;
  39173. this._setEndings( true, true, false );
  39174. }
  39175. handle_stop: {
  39176. if ( time >= duration ) {
  39177. time = duration;
  39178. } else if ( time < 0 ) {
  39179. time = 0;
  39180. } else {
  39181. this.time = time;
  39182. break handle_stop;
  39183. }
  39184. if ( this.clampWhenFinished ) this.paused = true;
  39185. else this.enabled = false;
  39186. this.time = time;
  39187. this._mixer.dispatchEvent( {
  39188. type: 'finished', action: this,
  39189. direction: deltaTime < 0 ? -1 : 1
  39190. } );
  39191. }
  39192. } else { // repetitive Repeat or PingPong
  39193. if ( loopCount === -1 ) {
  39194. // just started
  39195. if ( deltaTime >= 0 ) {
  39196. loopCount = 0;
  39197. this._setEndings( true, this.repetitions === 0, pingPong );
  39198. } else {
  39199. // when looping in reverse direction, the initial
  39200. // transition through zero counts as a repetition,
  39201. // so leave loopCount at -1
  39202. this._setEndings( this.repetitions === 0, true, pingPong );
  39203. }
  39204. }
  39205. if ( time >= duration || time < 0 ) {
  39206. // wrap around
  39207. const loopDelta = Math.floor( time / duration ); // signed
  39208. time -= duration * loopDelta;
  39209. loopCount += Math.abs( loopDelta );
  39210. const pending = this.repetitions - loopCount;
  39211. if ( pending <= 0 ) {
  39212. // have to stop (switch state, clamp time, fire event)
  39213. if ( this.clampWhenFinished ) this.paused = true;
  39214. else this.enabled = false;
  39215. time = deltaTime > 0 ? duration : 0;
  39216. this.time = time;
  39217. this._mixer.dispatchEvent( {
  39218. type: 'finished', action: this,
  39219. direction: deltaTime > 0 ? 1 : -1
  39220. } );
  39221. } else {
  39222. // keep running
  39223. if ( pending === 1 ) {
  39224. // entering the last round
  39225. const atStart = deltaTime < 0;
  39226. this._setEndings( atStart, ! atStart, pingPong );
  39227. } else {
  39228. this._setEndings( false, false, pingPong );
  39229. }
  39230. this._loopCount = loopCount;
  39231. this.time = time;
  39232. this._mixer.dispatchEvent( {
  39233. type: 'loop', action: this, loopDelta: loopDelta
  39234. } );
  39235. }
  39236. } else {
  39237. this._loopCount = loopCount;
  39238. this.time = time;
  39239. }
  39240. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  39241. // invert time for the "pong round"
  39242. return duration - time;
  39243. }
  39244. }
  39245. return time;
  39246. }
  39247. _setEndings( atStart, atEnd, pingPong ) {
  39248. const settings = this._interpolantSettings;
  39249. if ( pingPong ) {
  39250. settings.endingStart = ZeroSlopeEnding;
  39251. settings.endingEnd = ZeroSlopeEnding;
  39252. } else {
  39253. // assuming for LoopOnce atStart == atEnd == true
  39254. if ( atStart ) {
  39255. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  39256. } else {
  39257. settings.endingStart = WrapAroundEnding;
  39258. }
  39259. if ( atEnd ) {
  39260. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  39261. } else {
  39262. settings.endingEnd = WrapAroundEnding;
  39263. }
  39264. }
  39265. }
  39266. _scheduleFading( duration, weightNow, weightThen ) {
  39267. const mixer = this._mixer, now = mixer.time;
  39268. let interpolant = this._weightInterpolant;
  39269. if ( interpolant === null ) {
  39270. interpolant = mixer._lendControlInterpolant();
  39271. this._weightInterpolant = interpolant;
  39272. }
  39273. const times = interpolant.parameterPositions,
  39274. values = interpolant.sampleValues;
  39275. times[ 0 ] = now;
  39276. values[ 0 ] = weightNow;
  39277. times[ 1 ] = now + duration;
  39278. values[ 1 ] = weightThen;
  39279. return this;
  39280. }
  39281. }
  39282. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  39283. /**
  39284. * `AnimationMixer` is a player for animations on a particular object in
  39285. * the scene. When multiple objects in the scene are animated independently,
  39286. * one `AnimationMixer` may be used for each object.
  39287. */
  39288. class AnimationMixer extends EventDispatcher {
  39289. /**
  39290. * Constructs a new animation mixer.
  39291. *
  39292. * @param {Object3D} root - The object whose animations shall be played by this mixer.
  39293. */
  39294. constructor( root ) {
  39295. super();
  39296. this._root = root;
  39297. this._initMemoryManager();
  39298. this._accuIndex = 0;
  39299. /**
  39300. * The global mixer time (in seconds; starting with `0` on the mixer's creation).
  39301. *
  39302. * @type {number}
  39303. * @default 0
  39304. */
  39305. this.time = 0;
  39306. /**
  39307. * A scaling factor for the global time.
  39308. *
  39309. * Note: Setting this member to `0` and later back to `1` is a
  39310. * possibility to pause/unpause all actions that are controlled by this
  39311. * mixer.
  39312. *
  39313. * @type {number}
  39314. * @default 1
  39315. */
  39316. this.timeScale = 1.0;
  39317. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  39318. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  39319. }
  39320. }
  39321. _bindAction( action, prototypeAction ) {
  39322. const root = action._localRoot || this._root,
  39323. tracks = action._clip.tracks,
  39324. nTracks = tracks.length,
  39325. bindings = action._propertyBindings,
  39326. interpolants = action._interpolants,
  39327. rootUuid = root.uuid,
  39328. bindingsByRoot = this._bindingsByRootAndName;
  39329. let bindingsByName = bindingsByRoot[ rootUuid ];
  39330. if ( bindingsByName === undefined ) {
  39331. bindingsByName = {};
  39332. bindingsByRoot[ rootUuid ] = bindingsByName;
  39333. }
  39334. for ( let i = 0; i !== nTracks; ++ i ) {
  39335. const track = tracks[ i ],
  39336. trackName = track.name;
  39337. let binding = bindingsByName[ trackName ];
  39338. if ( binding !== undefined ) {
  39339. ++ binding.referenceCount;
  39340. bindings[ i ] = binding;
  39341. } else {
  39342. binding = bindings[ i ];
  39343. if ( binding !== undefined ) {
  39344. // existing binding, make sure the cache knows
  39345. if ( binding._cacheIndex === null ) {
  39346. ++ binding.referenceCount;
  39347. this._addInactiveBinding( binding, rootUuid, trackName );
  39348. }
  39349. continue;
  39350. }
  39351. const path = prototypeAction && prototypeAction.
  39352. _propertyBindings[ i ].binding.parsedPath;
  39353. binding = new PropertyMixer(
  39354. PropertyBinding.create( root, trackName, path ),
  39355. track.ValueTypeName, track.getValueSize() );
  39356. ++ binding.referenceCount;
  39357. this._addInactiveBinding( binding, rootUuid, trackName );
  39358. bindings[ i ] = binding;
  39359. }
  39360. interpolants[ i ].resultBuffer = binding.buffer;
  39361. }
  39362. }
  39363. _activateAction( action ) {
  39364. if ( ! this._isActiveAction( action ) ) {
  39365. if ( action._cacheIndex === null ) {
  39366. // this action has been forgotten by the cache, but the user
  39367. // appears to be still using it -> rebind
  39368. const rootUuid = ( action._localRoot || this._root ).uuid,
  39369. clipUuid = action._clip.uuid,
  39370. actionsForClip = this._actionsByClip[ clipUuid ];
  39371. this._bindAction( action,
  39372. actionsForClip && actionsForClip.knownActions[ 0 ] );
  39373. this._addInactiveAction( action, clipUuid, rootUuid );
  39374. }
  39375. const bindings = action._propertyBindings;
  39376. // increment reference counts / sort out state
  39377. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39378. const binding = bindings[ i ];
  39379. if ( binding.useCount ++ === 0 ) {
  39380. this._lendBinding( binding );
  39381. binding.saveOriginalState();
  39382. }
  39383. }
  39384. this._lendAction( action );
  39385. }
  39386. }
  39387. _deactivateAction( action ) {
  39388. if ( this._isActiveAction( action ) ) {
  39389. const bindings = action._propertyBindings;
  39390. // decrement reference counts / sort out state
  39391. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39392. const binding = bindings[ i ];
  39393. if ( -- binding.useCount === 0 ) {
  39394. binding.restoreOriginalState();
  39395. this._takeBackBinding( binding );
  39396. }
  39397. }
  39398. this._takeBackAction( action );
  39399. }
  39400. }
  39401. // Memory manager
  39402. _initMemoryManager() {
  39403. this._actions = []; // 'nActiveActions' followed by inactive ones
  39404. this._nActiveActions = 0;
  39405. this._actionsByClip = {};
  39406. // inside:
  39407. // {
  39408. // knownActions: Array< AnimationAction > - used as prototypes
  39409. // actionByRoot: AnimationAction - lookup
  39410. // }
  39411. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  39412. this._nActiveBindings = 0;
  39413. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  39414. this._controlInterpolants = []; // same game as above
  39415. this._nActiveControlInterpolants = 0;
  39416. const scope = this;
  39417. this.stats = {
  39418. actions: {
  39419. get total() {
  39420. return scope._actions.length;
  39421. },
  39422. get inUse() {
  39423. return scope._nActiveActions;
  39424. }
  39425. },
  39426. bindings: {
  39427. get total() {
  39428. return scope._bindings.length;
  39429. },
  39430. get inUse() {
  39431. return scope._nActiveBindings;
  39432. }
  39433. },
  39434. controlInterpolants: {
  39435. get total() {
  39436. return scope._controlInterpolants.length;
  39437. },
  39438. get inUse() {
  39439. return scope._nActiveControlInterpolants;
  39440. }
  39441. }
  39442. };
  39443. }
  39444. // Memory management for AnimationAction objects
  39445. _isActiveAction( action ) {
  39446. const index = action._cacheIndex;
  39447. return index !== null && index < this._nActiveActions;
  39448. }
  39449. _addInactiveAction( action, clipUuid, rootUuid ) {
  39450. const actions = this._actions,
  39451. actionsByClip = this._actionsByClip;
  39452. let actionsForClip = actionsByClip[ clipUuid ];
  39453. if ( actionsForClip === undefined ) {
  39454. actionsForClip = {
  39455. knownActions: [ action ],
  39456. actionByRoot: {}
  39457. };
  39458. action._byClipCacheIndex = 0;
  39459. actionsByClip[ clipUuid ] = actionsForClip;
  39460. } else {
  39461. const knownActions = actionsForClip.knownActions;
  39462. action._byClipCacheIndex = knownActions.length;
  39463. knownActions.push( action );
  39464. }
  39465. action._cacheIndex = actions.length;
  39466. actions.push( action );
  39467. actionsForClip.actionByRoot[ rootUuid ] = action;
  39468. }
  39469. _removeInactiveAction( action ) {
  39470. const actions = this._actions,
  39471. lastInactiveAction = actions[ actions.length - 1 ],
  39472. cacheIndex = action._cacheIndex;
  39473. lastInactiveAction._cacheIndex = cacheIndex;
  39474. actions[ cacheIndex ] = lastInactiveAction;
  39475. actions.pop();
  39476. action._cacheIndex = null;
  39477. const clipUuid = action._clip.uuid,
  39478. actionsByClip = this._actionsByClip,
  39479. actionsForClip = actionsByClip[ clipUuid ],
  39480. knownActionsForClip = actionsForClip.knownActions,
  39481. lastKnownAction =
  39482. knownActionsForClip[ knownActionsForClip.length - 1 ],
  39483. byClipCacheIndex = action._byClipCacheIndex;
  39484. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  39485. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  39486. knownActionsForClip.pop();
  39487. action._byClipCacheIndex = null;
  39488. const actionByRoot = actionsForClip.actionByRoot,
  39489. rootUuid = ( action._localRoot || this._root ).uuid;
  39490. delete actionByRoot[ rootUuid ];
  39491. if ( knownActionsForClip.length === 0 ) {
  39492. delete actionsByClip[ clipUuid ];
  39493. }
  39494. this._removeInactiveBindingsForAction( action );
  39495. }
  39496. _removeInactiveBindingsForAction( action ) {
  39497. const bindings = action._propertyBindings;
  39498. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39499. const binding = bindings[ i ];
  39500. if ( -- binding.referenceCount === 0 ) {
  39501. this._removeInactiveBinding( binding );
  39502. }
  39503. }
  39504. }
  39505. _lendAction( action ) {
  39506. // [ active actions | inactive actions ]
  39507. // [ active actions >| inactive actions ]
  39508. // s a
  39509. // <-swap->
  39510. // a s
  39511. const actions = this._actions,
  39512. prevIndex = action._cacheIndex,
  39513. lastActiveIndex = this._nActiveActions ++,
  39514. firstInactiveAction = actions[ lastActiveIndex ];
  39515. action._cacheIndex = lastActiveIndex;
  39516. actions[ lastActiveIndex ] = action;
  39517. firstInactiveAction._cacheIndex = prevIndex;
  39518. actions[ prevIndex ] = firstInactiveAction;
  39519. }
  39520. _takeBackAction( action ) {
  39521. // [ active actions | inactive actions ]
  39522. // [ active actions |< inactive actions ]
  39523. // a s
  39524. // <-swap->
  39525. // s a
  39526. const actions = this._actions,
  39527. prevIndex = action._cacheIndex,
  39528. firstInactiveIndex = -- this._nActiveActions,
  39529. lastActiveAction = actions[ firstInactiveIndex ];
  39530. action._cacheIndex = firstInactiveIndex;
  39531. actions[ firstInactiveIndex ] = action;
  39532. lastActiveAction._cacheIndex = prevIndex;
  39533. actions[ prevIndex ] = lastActiveAction;
  39534. }
  39535. // Memory management for PropertyMixer objects
  39536. _addInactiveBinding( binding, rootUuid, trackName ) {
  39537. const bindingsByRoot = this._bindingsByRootAndName,
  39538. bindings = this._bindings;
  39539. let bindingByName = bindingsByRoot[ rootUuid ];
  39540. if ( bindingByName === undefined ) {
  39541. bindingByName = {};
  39542. bindingsByRoot[ rootUuid ] = bindingByName;
  39543. }
  39544. bindingByName[ trackName ] = binding;
  39545. binding._cacheIndex = bindings.length;
  39546. bindings.push( binding );
  39547. }
  39548. _removeInactiveBinding( binding ) {
  39549. const bindings = this._bindings,
  39550. propBinding = binding.binding,
  39551. rootUuid = propBinding.rootNode.uuid,
  39552. trackName = propBinding.path,
  39553. bindingsByRoot = this._bindingsByRootAndName,
  39554. bindingByName = bindingsByRoot[ rootUuid ],
  39555. lastInactiveBinding = bindings[ bindings.length - 1 ],
  39556. cacheIndex = binding._cacheIndex;
  39557. lastInactiveBinding._cacheIndex = cacheIndex;
  39558. bindings[ cacheIndex ] = lastInactiveBinding;
  39559. bindings.pop();
  39560. delete bindingByName[ trackName ];
  39561. if ( Object.keys( bindingByName ).length === 0 ) {
  39562. delete bindingsByRoot[ rootUuid ];
  39563. }
  39564. }
  39565. _lendBinding( binding ) {
  39566. const bindings = this._bindings,
  39567. prevIndex = binding._cacheIndex,
  39568. lastActiveIndex = this._nActiveBindings ++,
  39569. firstInactiveBinding = bindings[ lastActiveIndex ];
  39570. binding._cacheIndex = lastActiveIndex;
  39571. bindings[ lastActiveIndex ] = binding;
  39572. firstInactiveBinding._cacheIndex = prevIndex;
  39573. bindings[ prevIndex ] = firstInactiveBinding;
  39574. }
  39575. _takeBackBinding( binding ) {
  39576. const bindings = this._bindings,
  39577. prevIndex = binding._cacheIndex,
  39578. firstInactiveIndex = -- this._nActiveBindings,
  39579. lastActiveBinding = bindings[ firstInactiveIndex ];
  39580. binding._cacheIndex = firstInactiveIndex;
  39581. bindings[ firstInactiveIndex ] = binding;
  39582. lastActiveBinding._cacheIndex = prevIndex;
  39583. bindings[ prevIndex ] = lastActiveBinding;
  39584. }
  39585. // Memory management of Interpolants for weight and time scale
  39586. _lendControlInterpolant() {
  39587. const interpolants = this._controlInterpolants,
  39588. lastActiveIndex = this._nActiveControlInterpolants ++;
  39589. let interpolant = interpolants[ lastActiveIndex ];
  39590. if ( interpolant === undefined ) {
  39591. interpolant = new LinearInterpolant(
  39592. new Float32Array( 2 ), new Float32Array( 2 ),
  39593. 1, _controlInterpolantsResultBuffer );
  39594. interpolant.__cacheIndex = lastActiveIndex;
  39595. interpolants[ lastActiveIndex ] = interpolant;
  39596. }
  39597. return interpolant;
  39598. }
  39599. _takeBackControlInterpolant( interpolant ) {
  39600. const interpolants = this._controlInterpolants,
  39601. prevIndex = interpolant.__cacheIndex,
  39602. firstInactiveIndex = -- this._nActiveControlInterpolants,
  39603. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  39604. interpolant.__cacheIndex = firstInactiveIndex;
  39605. interpolants[ firstInactiveIndex ] = interpolant;
  39606. lastActiveInterpolant.__cacheIndex = prevIndex;
  39607. interpolants[ prevIndex ] = lastActiveInterpolant;
  39608. }
  39609. /**
  39610. * Returns an instance of {@link AnimationAction} for the passed clip.
  39611. *
  39612. * If an action fitting the clip and root parameters doesn't yet exist, it
  39613. * will be created by this method. Calling this method several times with the
  39614. * same clip and root parameters always returns the same action.
  39615. *
  39616. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39617. * @param {Object3D} [optionalRoot] - An alternative root object.
  39618. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  39619. * @return {?AnimationAction} The animation action.
  39620. */
  39621. clipAction( clip, optionalRoot, blendMode ) {
  39622. const root = optionalRoot || this._root,
  39623. rootUuid = root.uuid;
  39624. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  39625. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  39626. const actionsForClip = this._actionsByClip[ clipUuid ];
  39627. let prototypeAction = null;
  39628. if ( blendMode === undefined ) {
  39629. if ( clipObject !== null ) {
  39630. blendMode = clipObject.blendMode;
  39631. } else {
  39632. blendMode = NormalAnimationBlendMode;
  39633. }
  39634. }
  39635. if ( actionsForClip !== undefined ) {
  39636. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  39637. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  39638. return existingAction;
  39639. }
  39640. // we know the clip, so we don't have to parse all
  39641. // the bindings again but can just copy
  39642. prototypeAction = actionsForClip.knownActions[ 0 ];
  39643. // also, take the clip from the prototype action
  39644. if ( clipObject === null )
  39645. clipObject = prototypeAction._clip;
  39646. }
  39647. // clip must be known when specified via string
  39648. if ( clipObject === null ) return null;
  39649. // allocate all resources required to run it
  39650. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  39651. this._bindAction( newAction, prototypeAction );
  39652. // and make the action known to the memory manager
  39653. this._addInactiveAction( newAction, clipUuid, rootUuid );
  39654. return newAction;
  39655. }
  39656. /**
  39657. * Returns an existing animation action for the passed clip.
  39658. *
  39659. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39660. * @param {Object3D} [optionalRoot] - An alternative root object.
  39661. * @return {?AnimationAction} The animation action. Returns `null` if no action was found.
  39662. */
  39663. existingAction( clip, optionalRoot ) {
  39664. const root = optionalRoot || this._root,
  39665. rootUuid = root.uuid,
  39666. clipObject = typeof clip === 'string' ?
  39667. AnimationClip.findByName( root, clip ) : clip,
  39668. clipUuid = clipObject ? clipObject.uuid : clip,
  39669. actionsForClip = this._actionsByClip[ clipUuid ];
  39670. if ( actionsForClip !== undefined ) {
  39671. return actionsForClip.actionByRoot[ rootUuid ] || null;
  39672. }
  39673. return null;
  39674. }
  39675. /**
  39676. * Deactivates all previously scheduled actions on this mixer.
  39677. *
  39678. * @return {AnimationMixer} A reference to this animation mixer.
  39679. */
  39680. stopAllAction() {
  39681. const actions = this._actions,
  39682. nActions = this._nActiveActions;
  39683. for ( let i = nActions - 1; i >= 0; -- i ) {
  39684. actions[ i ].stop();
  39685. }
  39686. return this;
  39687. }
  39688. /**
  39689. * Advances the global mixer time and updates the animation.
  39690. *
  39691. * This is usually done in the render loop by passing the delta
  39692. * time from {@link Clock} or {@link Timer}.
  39693. *
  39694. * @param {number} deltaTime - The delta time in seconds.
  39695. * @return {AnimationMixer} A reference to this animation mixer.
  39696. */
  39697. update( deltaTime ) {
  39698. deltaTime *= this.timeScale;
  39699. const actions = this._actions,
  39700. nActions = this._nActiveActions,
  39701. time = this.time += deltaTime,
  39702. timeDirection = Math.sign( deltaTime ),
  39703. accuIndex = this._accuIndex ^= 1;
  39704. // run active actions
  39705. for ( let i = 0; i !== nActions; ++ i ) {
  39706. const action = actions[ i ];
  39707. action._update( time, deltaTime, timeDirection, accuIndex );
  39708. }
  39709. // update scene graph
  39710. const bindings = this._bindings,
  39711. nBindings = this._nActiveBindings;
  39712. for ( let i = 0; i !== nBindings; ++ i ) {
  39713. bindings[ i ].apply( accuIndex );
  39714. }
  39715. return this;
  39716. }
  39717. /**
  39718. * Sets the global mixer to a specific time and updates the animation accordingly.
  39719. *
  39720. * This is useful when you need to jump to an exact time in an animation. The
  39721. * input parameter will be scaled by {@link AnimationMixer#timeScale}
  39722. *
  39723. * @param {number} time - The time to set in seconds.
  39724. * @return {AnimationMixer} A reference to this animation mixer.
  39725. */
  39726. setTime( time ) {
  39727. this.time = 0; // Zero out time attribute for AnimationMixer object;
  39728. for ( let i = 0; i < this._actions.length; i ++ ) {
  39729. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  39730. }
  39731. return this.update( time ); // Update used to set exact time. Returns "this" AnimationMixer object.
  39732. }
  39733. /**
  39734. * Returns this mixer's root object.
  39735. *
  39736. * @return {Object3D} The mixer's root object.
  39737. */
  39738. getRoot() {
  39739. return this._root;
  39740. }
  39741. /**
  39742. * Deallocates all memory resources for a clip. Before using this method make
  39743. * sure to call {@link AnimationAction#stop} for all related actions.
  39744. *
  39745. * @param {AnimationClip} clip - The clip to uncache.
  39746. */
  39747. uncacheClip( clip ) {
  39748. const actions = this._actions,
  39749. clipUuid = clip.uuid,
  39750. actionsByClip = this._actionsByClip,
  39751. actionsForClip = actionsByClip[ clipUuid ];
  39752. if ( actionsForClip !== undefined ) {
  39753. // note: just calling _removeInactiveAction would mess up the
  39754. // iteration state and also require updating the state we can
  39755. // just throw away
  39756. const actionsToRemove = actionsForClip.knownActions;
  39757. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  39758. const action = actionsToRemove[ i ];
  39759. this._deactivateAction( action );
  39760. const cacheIndex = action._cacheIndex,
  39761. lastInactiveAction = actions[ actions.length - 1 ];
  39762. action._cacheIndex = null;
  39763. action._byClipCacheIndex = null;
  39764. lastInactiveAction._cacheIndex = cacheIndex;
  39765. actions[ cacheIndex ] = lastInactiveAction;
  39766. actions.pop();
  39767. this._removeInactiveBindingsForAction( action );
  39768. }
  39769. delete actionsByClip[ clipUuid ];
  39770. }
  39771. }
  39772. /**
  39773. * Deallocates all memory resources for a root object. Before using this
  39774. * method make sure to call {@link AnimationAction#stop} for all related
  39775. * actions or alternatively {@link AnimationMixer#stopAllAction} when the
  39776. * mixer operates on a single root.
  39777. *
  39778. * @param {Object3D} root - The root object to uncache.
  39779. */
  39780. uncacheRoot( root ) {
  39781. const rootUuid = root.uuid,
  39782. actionsByClip = this._actionsByClip;
  39783. for ( const clipUuid in actionsByClip ) {
  39784. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  39785. action = actionByRoot[ rootUuid ];
  39786. if ( action !== undefined ) {
  39787. this._deactivateAction( action );
  39788. this._removeInactiveAction( action );
  39789. }
  39790. }
  39791. const bindingsByRoot = this._bindingsByRootAndName,
  39792. bindingByName = bindingsByRoot[ rootUuid ];
  39793. if ( bindingByName !== undefined ) {
  39794. for ( const trackName in bindingByName ) {
  39795. const binding = bindingByName[ trackName ];
  39796. binding.restoreOriginalState();
  39797. this._removeInactiveBinding( binding );
  39798. }
  39799. }
  39800. }
  39801. /**
  39802. * Deallocates all memory resources for an action. The action is identified by the
  39803. * given clip and an optional root object. Before using this method make
  39804. * sure to call {@link AnimationAction#stop} to deactivate the action.
  39805. *
  39806. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39807. * @param {Object3D} [optionalRoot] - An alternative root object.
  39808. */
  39809. uncacheAction( clip, optionalRoot ) {
  39810. const action = this.existingAction( clip, optionalRoot );
  39811. if ( action !== null ) {
  39812. this._deactivateAction( action );
  39813. this._removeInactiveAction( action );
  39814. }
  39815. }
  39816. }
  39817. /**
  39818. * Represents a 3D render target.
  39819. *
  39820. * @augments RenderTarget
  39821. */
  39822. class RenderTarget3D extends RenderTarget {
  39823. /**
  39824. * Constructs a new 3D render target.
  39825. *
  39826. * @param {number} [width=1] - The width of the render target.
  39827. * @param {number} [height=1] - The height of the render target.
  39828. * @param {number} [depth=1] - The height of the render target.
  39829. * @param {RenderTarget~Options} [options] - The configuration object.
  39830. */
  39831. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  39832. super( width, height, options );
  39833. /**
  39834. * This flag can be used for type testing.
  39835. *
  39836. * @type {boolean}
  39837. * @readonly
  39838. * @default true
  39839. */
  39840. this.isRenderTarget3D = true;
  39841. this.depth = depth;
  39842. /**
  39843. * Overwritten with a different texture type.
  39844. *
  39845. * @type {Data3DTexture}
  39846. */
  39847. this.texture = new Data3DTexture( null, width, height, depth );
  39848. this._setTextureOptions( options );
  39849. this.texture.isRenderTargetTexture = true;
  39850. }
  39851. }
  39852. /**
  39853. * Represents a uniform which is a global shader variable. They are passed to shader programs.
  39854. *
  39855. * When declaring a uniform of a {@link ShaderMaterial}, it is declared by value or by object.
  39856. * ```js
  39857. * uniforms: {
  39858. * time: { value: 1.0 },
  39859. * resolution: new Uniform( new Vector2() )
  39860. * };
  39861. * ```
  39862. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39863. * in {@link WebGLRenderer}.
  39864. */
  39865. class Uniform {
  39866. /**
  39867. * Constructs a new uniform.
  39868. *
  39869. * @param {any} value - The uniform value.
  39870. */
  39871. constructor( value ) {
  39872. /**
  39873. * The uniform value.
  39874. *
  39875. * @type {any}
  39876. */
  39877. this.value = value;
  39878. }
  39879. /**
  39880. * Returns a new uniform with copied values from this instance.
  39881. * If the value has a `clone()` method, the value is cloned as well.
  39882. *
  39883. * @return {Uniform} A clone of this instance.
  39884. */
  39885. clone() {
  39886. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  39887. }
  39888. }
  39889. let _id = 0;
  39890. /**
  39891. * A class for managing multiple uniforms in a single group. The renderer will process
  39892. * such a definition as a single UBO.
  39893. *
  39894. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39895. * in {@link WebGLRenderer}.
  39896. *
  39897. * @augments EventDispatcher
  39898. */
  39899. class UniformsGroup extends EventDispatcher {
  39900. /**
  39901. * Constructs a new uniforms group.
  39902. */
  39903. constructor() {
  39904. super();
  39905. /**
  39906. * This flag can be used for type testing.
  39907. *
  39908. * @type {boolean}
  39909. * @readonly
  39910. * @default true
  39911. */
  39912. this.isUniformsGroup = true;
  39913. /**
  39914. * The ID of the 3D object.
  39915. *
  39916. * @name UniformsGroup#id
  39917. * @type {number}
  39918. * @readonly
  39919. */
  39920. Object.defineProperty( this, 'id', { value: _id ++ } );
  39921. /**
  39922. * The name of the uniforms group.
  39923. *
  39924. * @type {string}
  39925. */
  39926. this.name = '';
  39927. /**
  39928. * The buffer usage.
  39929. *
  39930. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  39931. * @default StaticDrawUsage
  39932. */
  39933. this.usage = StaticDrawUsage;
  39934. /**
  39935. * An array holding the uniforms.
  39936. *
  39937. * @type {Array<Uniform>}
  39938. */
  39939. this.uniforms = [];
  39940. }
  39941. /**
  39942. * Adds the given uniform to this uniforms group.
  39943. *
  39944. * @param {Uniform} uniform - The uniform to add.
  39945. * @return {UniformsGroup} A reference to this uniforms group.
  39946. */
  39947. add( uniform ) {
  39948. this.uniforms.push( uniform );
  39949. return this;
  39950. }
  39951. /**
  39952. * Removes the given uniform from this uniforms group.
  39953. *
  39954. * @param {Uniform} uniform - The uniform to remove.
  39955. * @return {UniformsGroup} A reference to this uniforms group.
  39956. */
  39957. remove( uniform ) {
  39958. const index = this.uniforms.indexOf( uniform );
  39959. if ( index !== -1 ) this.uniforms.splice( index, 1 );
  39960. return this;
  39961. }
  39962. /**
  39963. * Sets the name of this uniforms group.
  39964. *
  39965. * @param {string} name - The name to set.
  39966. * @return {UniformsGroup} A reference to this uniforms group.
  39967. */
  39968. setName( name ) {
  39969. this.name = name;
  39970. return this;
  39971. }
  39972. /**
  39973. * Sets the usage of this uniforms group.
  39974. *
  39975. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  39976. * @return {UniformsGroup} A reference to this uniforms group.
  39977. */
  39978. setUsage( value ) {
  39979. this.usage = value;
  39980. return this;
  39981. }
  39982. /**
  39983. * Frees the GPU-related resources allocated by this instance. Call this
  39984. * method whenever this instance is no longer used in your app.
  39985. *
  39986. * @fires Texture#dispose
  39987. */
  39988. dispose() {
  39989. this.dispatchEvent( { type: 'dispose' } );
  39990. }
  39991. /**
  39992. * Copies the values of the given uniforms group to this instance.
  39993. *
  39994. * @param {UniformsGroup} source - The uniforms group to copy.
  39995. * @return {UniformsGroup} A reference to this uniforms group.
  39996. */
  39997. copy( source ) {
  39998. this.name = source.name;
  39999. this.usage = source.usage;
  40000. const uniformsSource = source.uniforms;
  40001. this.uniforms.length = 0;
  40002. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  40003. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  40004. for ( let j = 0; j < uniforms.length; j ++ ) {
  40005. this.uniforms.push( uniforms[ j ].clone() );
  40006. }
  40007. }
  40008. return this;
  40009. }
  40010. /**
  40011. * Returns a new uniforms group with copied values from this instance.
  40012. *
  40013. * @return {UniformsGroup} A clone of this instance.
  40014. */
  40015. clone() {
  40016. return new this.constructor().copy( this );
  40017. }
  40018. }
  40019. /**
  40020. * An instanced version of an interleaved buffer.
  40021. *
  40022. * @augments InterleavedBuffer
  40023. */
  40024. class InstancedInterleavedBuffer extends InterleavedBuffer {
  40025. /**
  40026. * Constructs a new instanced interleaved buffer.
  40027. *
  40028. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  40029. * @param {number} stride - The number of typed-array elements per vertex.
  40030. * @param {number} [meshPerAttribute=1] - Defines how often a value of this interleaved buffer should be repeated.
  40031. */
  40032. constructor( array, stride, meshPerAttribute = 1 ) {
  40033. super( array, stride );
  40034. /**
  40035. * This flag can be used for type testing.
  40036. *
  40037. * @type {boolean}
  40038. * @readonly
  40039. * @default true
  40040. */
  40041. this.isInstancedInterleavedBuffer = true;
  40042. /**
  40043. * Defines how often a value of this buffer attribute should be repeated,
  40044. * see {@link InstancedBufferAttribute#meshPerAttribute}.
  40045. *
  40046. * @type {number}
  40047. * @default 1
  40048. */
  40049. this.meshPerAttribute = meshPerAttribute;
  40050. }
  40051. copy( source ) {
  40052. super.copy( source );
  40053. this.meshPerAttribute = source.meshPerAttribute;
  40054. return this;
  40055. }
  40056. clone( data ) {
  40057. const ib = super.clone( data );
  40058. ib.meshPerAttribute = this.meshPerAttribute;
  40059. return ib;
  40060. }
  40061. toJSON( data ) {
  40062. const json = super.toJSON( data );
  40063. json.isInstancedInterleavedBuffer = true;
  40064. json.meshPerAttribute = this.meshPerAttribute;
  40065. return json;
  40066. }
  40067. }
  40068. /**
  40069. * An alternative version of a buffer attribute with more control over the VBO.
  40070. *
  40071. * The renderer does not construct a VBO for this kind of attribute. Instead, it uses
  40072. * whatever VBO is passed in constructor and can later be altered via the `buffer` property.
  40073. *
  40074. * The most common use case for this class is when some kind of GPGPU calculation interferes
  40075. * or even produces the VBOs in question.
  40076. *
  40077. * Notice that this class can only be used with {@link WebGLRenderer}.
  40078. */
  40079. class GLBufferAttribute {
  40080. /**
  40081. * Constructs a new GL buffer attribute.
  40082. *
  40083. * @param {WebGLBuffer} buffer - The native WebGL buffer.
  40084. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  40085. * @param {number} itemSize - The item size.
  40086. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  40087. * @param {number} count - The expected number of vertices in VBO.
  40088. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  40089. */
  40090. constructor( buffer, type, itemSize, elementSize, count, normalized = false ) {
  40091. /**
  40092. * This flag can be used for type testing.
  40093. *
  40094. * @type {boolean}
  40095. * @readonly
  40096. * @default true
  40097. */
  40098. this.isGLBufferAttribute = true;
  40099. /**
  40100. * The name of the buffer attribute.
  40101. *
  40102. * @type {string}
  40103. */
  40104. this.name = '';
  40105. /**
  40106. * The native WebGL buffer.
  40107. *
  40108. * @type {WebGLBuffer}
  40109. */
  40110. this.buffer = buffer;
  40111. /**
  40112. * The native data type.
  40113. *
  40114. * @type {number}
  40115. */
  40116. this.type = type;
  40117. /**
  40118. * The item size, see {@link BufferAttribute#itemSize}.
  40119. *
  40120. * @type {number}
  40121. */
  40122. this.itemSize = itemSize;
  40123. /**
  40124. * The corresponding size (in bytes) for the given `type` parameter.
  40125. *
  40126. * @type {number}
  40127. */
  40128. this.elementSize = elementSize;
  40129. /**
  40130. * The expected number of vertices in VBO.
  40131. *
  40132. * @type {number}
  40133. */
  40134. this.count = count;
  40135. /**
  40136. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  40137. * the values in the GLSL code. For instance, if `buffer` contains data of `gl.UNSIGNED_SHORT`,
  40138. * and `normalized` is `true`, the values `0 - +65535` in the buffer data will be mapped to
  40139. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  40140. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  40141. *
  40142. * @type {boolean}
  40143. */
  40144. this.normalized = normalized;
  40145. /**
  40146. * A version number, incremented every time the `needsUpdate` is set to `true`.
  40147. *
  40148. * @type {number}
  40149. */
  40150. this.version = 0;
  40151. }
  40152. /**
  40153. * Flag to indicate that this attribute has changed and should be re-sent to
  40154. * the GPU. Set this to `true` when you modify the value of the array.
  40155. *
  40156. * @type {number}
  40157. * @default false
  40158. * @param {boolean} value
  40159. */
  40160. set needsUpdate( value ) {
  40161. if ( value === true ) this.version ++;
  40162. }
  40163. /**
  40164. * Sets the given native WebGL buffer.
  40165. *
  40166. * @param {WebGLBuffer} buffer - The buffer to set.
  40167. * @return {BufferAttribute} A reference to this instance.
  40168. */
  40169. setBuffer( buffer ) {
  40170. this.buffer = buffer;
  40171. return this;
  40172. }
  40173. /**
  40174. * Sets the given native data type and element size.
  40175. *
  40176. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  40177. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  40178. * @return {BufferAttribute} A reference to this instance.
  40179. */
  40180. setType( type, elementSize ) {
  40181. this.type = type;
  40182. this.elementSize = elementSize;
  40183. return this;
  40184. }
  40185. /**
  40186. * Sets the item size.
  40187. *
  40188. * @param {number} itemSize - The item size.
  40189. * @return {BufferAttribute} A reference to this instance.
  40190. */
  40191. setItemSize( itemSize ) {
  40192. this.itemSize = itemSize;
  40193. return this;
  40194. }
  40195. /**
  40196. * Sets the count (the expected number of vertices in VBO).
  40197. *
  40198. * @param {number} count - The count.
  40199. * @return {BufferAttribute} A reference to this instance.
  40200. */
  40201. setCount( count ) {
  40202. this.count = count;
  40203. return this;
  40204. }
  40205. }
  40206. const _matrix = /*@__PURE__*/ new Matrix4();
  40207. /**
  40208. * This class is designed to assist with raycasting. Raycasting is used for
  40209. * mouse picking (working out what objects in the 3d space the mouse is over)
  40210. * amongst other things.
  40211. */
  40212. class Raycaster {
  40213. /**
  40214. * Constructs a new raycaster.
  40215. *
  40216. * @param {Vector3} origin - The origin vector where the ray casts from.
  40217. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  40218. * @param {number} [near=0] - All results returned are further away than near. Near can't be negative.
  40219. * @param {number} [far=Infinity] - All results returned are closer than far. Far can't be lower than near.
  40220. */
  40221. constructor( origin, direction, near = 0, far = Infinity ) {
  40222. /**
  40223. * The ray used for raycasting.
  40224. *
  40225. * @type {Ray}
  40226. */
  40227. this.ray = new Ray( origin, direction );
  40228. /**
  40229. * All results returned are further away than near. Near can't be negative.
  40230. *
  40231. * @type {number}
  40232. * @default 0
  40233. */
  40234. this.near = near;
  40235. /**
  40236. * All results returned are closer than far. Far can't be lower than near.
  40237. *
  40238. * @type {number}
  40239. * @default Infinity
  40240. */
  40241. this.far = far;
  40242. /**
  40243. * The camera to use when raycasting against view-dependent objects such as
  40244. * billboarded objects like sprites. This field can be set manually or
  40245. * is set when calling `setFromCamera()`.
  40246. *
  40247. * @type {?Camera}
  40248. * @default null
  40249. */
  40250. this.camera = null;
  40251. /**
  40252. * Allows to selectively ignore 3D objects when performing intersection tests.
  40253. * The following code example ensures that only 3D objects on layer `1` will be
  40254. * honored by raycaster.
  40255. * ```js
  40256. * raycaster.layers.set( 1 );
  40257. * object.layers.enable( 1 );
  40258. * ```
  40259. *
  40260. * @type {Layers}
  40261. */
  40262. this.layers = new Layers();
  40263. /**
  40264. * A parameter object that configures the raycasting. It has the structure:
  40265. *
  40266. * ```
  40267. * {
  40268. * Mesh: {},
  40269. * Line: { threshold: 1 },
  40270. * LOD: {},
  40271. * Points: { threshold: 1 },
  40272. * Sprite: {}
  40273. * }
  40274. * ```
  40275. * Where `threshold` is the precision of the raycaster when intersecting objects, in world units.
  40276. *
  40277. * @type {Object}
  40278. */
  40279. this.params = {
  40280. Mesh: {},
  40281. Line: { threshold: 1 },
  40282. LOD: {},
  40283. Points: { threshold: 1 },
  40284. Sprite: {}
  40285. };
  40286. }
  40287. /**
  40288. * Updates the ray with a new origin and direction by copying the values from the arguments.
  40289. *
  40290. * @param {Vector3} origin - The origin vector where the ray casts from.
  40291. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  40292. */
  40293. set( origin, direction ) {
  40294. // direction is assumed to be normalized (for accurate distance calculations)
  40295. this.ray.set( origin, direction );
  40296. }
  40297. /**
  40298. * Uses the given coordinates and camera to compute a new origin and direction for the internal ray.
  40299. *
  40300. * @param {Vector2} coords - 2D coordinates of the mouse, in normalized device coordinates (NDC).
  40301. * X and Y components should be between `-1` and `1`.
  40302. * @param {Camera} camera - The camera from which the ray should originate.
  40303. */
  40304. setFromCamera( coords, camera ) {
  40305. if ( camera.isPerspectiveCamera ) {
  40306. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  40307. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  40308. this.camera = camera;
  40309. } else if ( camera.isOrthographicCamera ) {
  40310. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  40311. this.ray.direction.set( 0, 0, -1 ).transformDirection( camera.matrixWorld );
  40312. this.camera = camera;
  40313. } else {
  40314. error( 'Raycaster: Unsupported camera type: ' + camera.type );
  40315. }
  40316. }
  40317. /**
  40318. * Uses the given WebXR controller to compute a new origin and direction for the internal ray.
  40319. *
  40320. * @param {WebXRController} controller - The controller to copy the position and direction from.
  40321. * @return {Raycaster} A reference to this raycaster.
  40322. */
  40323. setFromXRController( controller ) {
  40324. _matrix.identity().extractRotation( controller.matrixWorld );
  40325. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  40326. this.ray.direction.set( 0, 0, -1 ).applyMatrix4( _matrix );
  40327. return this;
  40328. }
  40329. /**
  40330. * The intersection point of a raycaster intersection test.
  40331. * @typedef {Object} Raycaster~Intersection
  40332. * @property {number} distance - The distance from the ray's origin to the intersection point.
  40333. * @property {number} distanceToRay - Some 3D objects e.g. {@link Points} provide the distance of the
  40334. * intersection to the nearest point on the ray. For other objects it will be `undefined`.
  40335. * @property {Vector3} point - The intersection point, in world coordinates.
  40336. * @property {Object} face - The face that has been intersected.
  40337. * @property {number} faceIndex - The face index.
  40338. * @property {Object3D} object - The 3D object that has been intersected.
  40339. * @property {Vector2} uv - U,V coordinates at point of intersection.
  40340. * @property {Vector2} uv1 - Second set of U,V coordinates at point of intersection.
  40341. * @property {Vector3} normal - Interpolated normal vector at point of intersection.
  40342. * @property {number} instanceId - The index number of the instance where the ray
  40343. * intersects the {@link InstancedMesh}.
  40344. */
  40345. /**
  40346. * Checks all intersection between the ray and the object with or without the
  40347. * descendants. Intersections are returned sorted by distance, closest first.
  40348. *
  40349. * `Raycaster` delegates to the `raycast()` method of the passed 3D object, when
  40350. * evaluating whether the ray intersects the object or not. This allows meshes to respond
  40351. * differently to ray casting than lines or points.
  40352. *
  40353. * Note that for meshes, faces must be pointed towards the origin of the ray in order
  40354. * to be detected; intersections of the ray passing through the back of a face will not
  40355. * be detected. To raycast against both faces of an object, you'll want to set {@link Material#side}
  40356. * to `THREE.DoubleSide`.
  40357. *
  40358. * @param {Object3D} object - The 3D object to check for intersection with the ray.
  40359. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  40360. * Otherwise it only checks intersection with the object.
  40361. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  40362. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  40363. */
  40364. intersectObject( object, recursive = true, intersects = [] ) {
  40365. intersect( object, this, intersects, recursive );
  40366. intersects.sort( ascSort );
  40367. return intersects;
  40368. }
  40369. /**
  40370. * Checks all intersection between the ray and the objects with or without
  40371. * the descendants. Intersections are returned sorted by distance, closest first.
  40372. *
  40373. * @param {Array<Object3D>} objects - The 3D objects to check for intersection with the ray.
  40374. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  40375. * Otherwise it only checks intersection with the object.
  40376. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  40377. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  40378. */
  40379. intersectObjects( objects, recursive = true, intersects = [] ) {
  40380. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  40381. intersect( objects[ i ], this, intersects, recursive );
  40382. }
  40383. intersects.sort( ascSort );
  40384. return intersects;
  40385. }
  40386. }
  40387. function ascSort( a, b ) {
  40388. return a.distance - b.distance;
  40389. }
  40390. function intersect( object, raycaster, intersects, recursive ) {
  40391. let propagate = true;
  40392. if ( object.layers.test( raycaster.layers ) ) {
  40393. const result = object.raycast( raycaster, intersects );
  40394. if ( result === false ) propagate = false;
  40395. }
  40396. if ( propagate === true && recursive === true ) {
  40397. const children = object.children;
  40398. for ( let i = 0, l = children.length; i < l; i ++ ) {
  40399. intersect( children[ i ], raycaster, intersects, true );
  40400. }
  40401. }
  40402. }
  40403. /**
  40404. * Class for keeping track of time.
  40405. *
  40406. * @deprecated since r183.
  40407. */
  40408. class Clock {
  40409. /**
  40410. * Constructs a new clock.
  40411. *
  40412. * @deprecated since 183.
  40413. * @param {boolean} [autoStart=true] - Whether to automatically start the clock when
  40414. * `getDelta()` is called for the first time.
  40415. */
  40416. constructor( autoStart = true ) {
  40417. /**
  40418. * If set to `true`, the clock starts automatically when `getDelta()` is called
  40419. * for the first time.
  40420. *
  40421. * @type {boolean}
  40422. * @default true
  40423. */
  40424. this.autoStart = autoStart;
  40425. /**
  40426. * Holds the time at which the clock's `start()` method was last called.
  40427. *
  40428. * @type {number}
  40429. * @default 0
  40430. */
  40431. this.startTime = 0;
  40432. /**
  40433. * Holds the time at which the clock's `start()`, `getElapsedTime()` or
  40434. * `getDelta()` methods were last called.
  40435. *
  40436. * @type {number}
  40437. * @default 0
  40438. */
  40439. this.oldTime = 0;
  40440. /**
  40441. * Keeps track of the total time that the clock has been running.
  40442. *
  40443. * @type {number}
  40444. * @default 0
  40445. */
  40446. this.elapsedTime = 0;
  40447. /**
  40448. * Whether the clock is running or not.
  40449. *
  40450. * @type {boolean}
  40451. * @default true
  40452. */
  40453. this.running = false;
  40454. warn( 'THREE.Clock: This module has been deprecated. Please use THREE.Timer instead.' ); // @deprecated, r183
  40455. }
  40456. /**
  40457. * Starts the clock. When `autoStart` is set to `true`, the method is automatically
  40458. * called by the class.
  40459. */
  40460. start() {
  40461. this.startTime = performance.now();
  40462. this.oldTime = this.startTime;
  40463. this.elapsedTime = 0;
  40464. this.running = true;
  40465. }
  40466. /**
  40467. * Stops the clock.
  40468. */
  40469. stop() {
  40470. this.getElapsedTime();
  40471. this.running = false;
  40472. this.autoStart = false;
  40473. }
  40474. /**
  40475. * Returns the elapsed time in seconds.
  40476. *
  40477. * @return {number} The elapsed time.
  40478. */
  40479. getElapsedTime() {
  40480. this.getDelta();
  40481. return this.elapsedTime;
  40482. }
  40483. /**
  40484. * Returns the delta time in seconds.
  40485. *
  40486. * @return {number} The delta time.
  40487. */
  40488. getDelta() {
  40489. let diff = 0;
  40490. if ( this.autoStart && ! this.running ) {
  40491. this.start();
  40492. return 0;
  40493. }
  40494. if ( this.running ) {
  40495. const newTime = performance.now();
  40496. diff = ( newTime - this.oldTime ) / 1000;
  40497. this.oldTime = newTime;
  40498. this.elapsedTime += diff;
  40499. }
  40500. return diff;
  40501. }
  40502. }
  40503. /**
  40504. * This class can be used to represent points in 3D space as
  40505. * [Spherical coordinates](https://en.wikipedia.org/wiki/Spherical_coordinate_system).
  40506. */
  40507. class Spherical {
  40508. /**
  40509. * Constructs a new spherical.
  40510. *
  40511. * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  40512. * @param {number} [phi=0] - The polar angle in radians from the y (up) axis.
  40513. * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis.
  40514. */
  40515. constructor( radius = 1, phi = 0, theta = 0 ) {
  40516. /**
  40517. * The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  40518. *
  40519. * @type {number}
  40520. * @default 1
  40521. */
  40522. this.radius = radius;
  40523. /**
  40524. * The polar angle in radians from the y (up) axis.
  40525. *
  40526. * @type {number}
  40527. * @default 0
  40528. */
  40529. this.phi = phi;
  40530. /**
  40531. * The equator/azimuthal angle in radians around the y (up) axis.
  40532. *
  40533. * @type {number}
  40534. * @default 0
  40535. */
  40536. this.theta = theta;
  40537. }
  40538. /**
  40539. * Sets the spherical components by copying the given values.
  40540. *
  40541. * @param {number} radius - The radius.
  40542. * @param {number} phi - The polar angle.
  40543. * @param {number} theta - The azimuthal angle.
  40544. * @return {Spherical} A reference to this spherical.
  40545. */
  40546. set( radius, phi, theta ) {
  40547. this.radius = radius;
  40548. this.phi = phi;
  40549. this.theta = theta;
  40550. return this;
  40551. }
  40552. /**
  40553. * Copies the values of the given spherical to this instance.
  40554. *
  40555. * @param {Spherical} other - The spherical to copy.
  40556. * @return {Spherical} A reference to this spherical.
  40557. */
  40558. copy( other ) {
  40559. this.radius = other.radius;
  40560. this.phi = other.phi;
  40561. this.theta = other.theta;
  40562. return this;
  40563. }
  40564. /**
  40565. * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi -
  40566. * `0.000001`.
  40567. *
  40568. * @return {Spherical} A reference to this spherical.
  40569. */
  40570. makeSafe() {
  40571. const EPS = 0.000001;
  40572. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  40573. return this;
  40574. }
  40575. /**
  40576. * Sets the spherical components from the given vector which is assumed to hold
  40577. * Cartesian coordinates.
  40578. *
  40579. * @param {Vector3} v - The vector to set.
  40580. * @return {Spherical} A reference to this spherical.
  40581. */
  40582. setFromVector3( v ) {
  40583. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40584. }
  40585. /**
  40586. * Sets the spherical components from the given Cartesian coordinates.
  40587. *
  40588. * @param {number} x - The x value.
  40589. * @param {number} y - The y value.
  40590. * @param {number} z - The z value.
  40591. * @return {Spherical} A reference to this spherical.
  40592. */
  40593. setFromCartesianCoords( x, y, z ) {
  40594. this.radius = Math.sqrt( x * x + y * y + z * z );
  40595. if ( this.radius === 0 ) {
  40596. this.theta = 0;
  40597. this.phi = 0;
  40598. } else {
  40599. this.theta = Math.atan2( x, z );
  40600. this.phi = Math.acos( clamp( y / this.radius, -1, 1 ) );
  40601. }
  40602. return this;
  40603. }
  40604. /**
  40605. * Returns a new spherical with copied values from this instance.
  40606. *
  40607. * @return {Spherical} A clone of this instance.
  40608. */
  40609. clone() {
  40610. return new this.constructor().copy( this );
  40611. }
  40612. }
  40613. /**
  40614. * This class can be used to represent points in 3D space as
  40615. * [Cylindrical coordinates](https://en.wikipedia.org/wiki/Cylindrical_coordinate_system).
  40616. */
  40617. class Cylindrical {
  40618. /**
  40619. * Constructs a new cylindrical.
  40620. *
  40621. * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane.
  40622. * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  40623. * @param {number} [y=0] - The height above the x-z plane.
  40624. */
  40625. constructor( radius = 1, theta = 0, y = 0 ) {
  40626. /**
  40627. * The distance from the origin to a point in the x-z plane.
  40628. *
  40629. * @type {number}
  40630. * @default 1
  40631. */
  40632. this.radius = radius;
  40633. /**
  40634. * A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  40635. *
  40636. * @type {number}
  40637. * @default 0
  40638. */
  40639. this.theta = theta;
  40640. /**
  40641. * The height above the x-z plane.
  40642. *
  40643. * @type {number}
  40644. * @default 0
  40645. */
  40646. this.y = y;
  40647. }
  40648. /**
  40649. * Sets the cylindrical components by copying the given values.
  40650. *
  40651. * @param {number} radius - The radius.
  40652. * @param {number} theta - The theta angle.
  40653. * @param {number} y - The height value.
  40654. * @return {Cylindrical} A reference to this cylindrical.
  40655. */
  40656. set( radius, theta, y ) {
  40657. this.radius = radius;
  40658. this.theta = theta;
  40659. this.y = y;
  40660. return this;
  40661. }
  40662. /**
  40663. * Copies the values of the given cylindrical to this instance.
  40664. *
  40665. * @param {Cylindrical} other - The cylindrical to copy.
  40666. * @return {Cylindrical} A reference to this cylindrical.
  40667. */
  40668. copy( other ) {
  40669. this.radius = other.radius;
  40670. this.theta = other.theta;
  40671. this.y = other.y;
  40672. return this;
  40673. }
  40674. /**
  40675. * Sets the cylindrical components from the given vector which is assumed to hold
  40676. * Cartesian coordinates.
  40677. *
  40678. * @param {Vector3} v - The vector to set.
  40679. * @return {Cylindrical} A reference to this cylindrical.
  40680. */
  40681. setFromVector3( v ) {
  40682. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40683. }
  40684. /**
  40685. * Sets the cylindrical components from the given Cartesian coordinates.
  40686. *
  40687. * @param {number} x - The x value.
  40688. * @param {number} y - The x value.
  40689. * @param {number} z - The x value.
  40690. * @return {Cylindrical} A reference to this cylindrical.
  40691. */
  40692. setFromCartesianCoords( x, y, z ) {
  40693. this.radius = Math.sqrt( x * x + z * z );
  40694. this.theta = Math.atan2( x, z );
  40695. this.y = y;
  40696. return this;
  40697. }
  40698. /**
  40699. * Returns a new cylindrical with copied values from this instance.
  40700. *
  40701. * @return {Cylindrical} A clone of this instance.
  40702. */
  40703. clone() {
  40704. return new this.constructor().copy( this );
  40705. }
  40706. }
  40707. /**
  40708. * Represents a 2x2 matrix.
  40709. *
  40710. * A Note on Row-Major and Column-Major Ordering:
  40711. *
  40712. * The constructor and {@link Matrix2#set} method take arguments in
  40713. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  40714. * order, while internally they are stored in the {@link Matrix2#elements} array in column-major order.
  40715. * This means that calling:
  40716. * ```js
  40717. * const m = new THREE.Matrix2();
  40718. * m.set( 11, 12,
  40719. * 21, 22 );
  40720. * ```
  40721. * will result in the elements array containing:
  40722. * ```js
  40723. * m.elements = [ 11, 21,
  40724. * 12, 22 ];
  40725. * ```
  40726. * and internally all calculations are performed using column-major ordering.
  40727. * However, as the actual ordering makes no difference mathematically and
  40728. * most people are used to thinking about matrices in row-major order, the
  40729. * three.js documentation shows matrices in row-major order. Just bear in
  40730. * mind that if you are reading the source code, you'll have to take the
  40731. * transpose of any matrices outlined here to make sense of the calculations.
  40732. */
  40733. class Matrix2 {
  40734. static {
  40735. /**
  40736. * This flag can be used for type testing.
  40737. *
  40738. * @type {boolean}
  40739. * @readonly
  40740. * @default true
  40741. */
  40742. Matrix2.prototype.isMatrix2 = true;
  40743. }
  40744. /**
  40745. * Constructs a new 2x2 matrix. The arguments are supposed to be
  40746. * in row-major order. If no arguments are provided, the constructor
  40747. * initializes the matrix as an identity matrix.
  40748. *
  40749. * @param {number} [n11] - 1-1 matrix element.
  40750. * @param {number} [n12] - 1-2 matrix element.
  40751. * @param {number} [n21] - 2-1 matrix element.
  40752. * @param {number} [n22] - 2-2 matrix element.
  40753. */
  40754. constructor( n11, n12, n21, n22 ) {
  40755. /**
  40756. * A column-major list of matrix values.
  40757. *
  40758. * @type {Array<number>}
  40759. */
  40760. this.elements = [
  40761. 1, 0,
  40762. 0, 1,
  40763. ];
  40764. if ( n11 !== undefined ) {
  40765. this.set( n11, n12, n21, n22 );
  40766. }
  40767. }
  40768. /**
  40769. * Sets this matrix to the 2x2 identity matrix.
  40770. *
  40771. * @return {Matrix2} A reference to this matrix.
  40772. */
  40773. identity() {
  40774. this.set(
  40775. 1, 0,
  40776. 0, 1,
  40777. );
  40778. return this;
  40779. }
  40780. /**
  40781. * Sets the elements of the matrix from the given array.
  40782. *
  40783. * @param {Array<number>} array - The matrix elements in column-major order.
  40784. * @param {number} [offset=0] - Index of the first element in the array.
  40785. * @return {Matrix2} A reference to this matrix.
  40786. */
  40787. fromArray( array, offset = 0 ) {
  40788. for ( let i = 0; i < 4; i ++ ) {
  40789. this.elements[ i ] = array[ i + offset ];
  40790. }
  40791. return this;
  40792. }
  40793. /**
  40794. * Sets the elements of the matrix.The arguments are supposed to be
  40795. * in row-major order.
  40796. *
  40797. * @param {number} n11 - 1-1 matrix element.
  40798. * @param {number} n12 - 1-2 matrix element.
  40799. * @param {number} n21 - 2-1 matrix element.
  40800. * @param {number} n22 - 2-2 matrix element.
  40801. * @return {Matrix2} A reference to this matrix.
  40802. */
  40803. set( n11, n12, n21, n22 ) {
  40804. const te = this.elements;
  40805. te[ 0 ] = n11; te[ 2 ] = n12;
  40806. te[ 1 ] = n21; te[ 3 ] = n22;
  40807. return this;
  40808. }
  40809. }
  40810. const _vector$4 = /*@__PURE__*/ new Vector2();
  40811. /**
  40812. * Represents an axis-aligned bounding box (AABB) in 2D space.
  40813. */
  40814. class Box2 {
  40815. /**
  40816. * Constructs a new bounding box.
  40817. *
  40818. * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box.
  40819. * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  40820. */
  40821. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  40822. /**
  40823. * This flag can be used for type testing.
  40824. *
  40825. * @type {boolean}
  40826. * @readonly
  40827. * @default true
  40828. */
  40829. this.isBox2 = true;
  40830. /**
  40831. * The lower boundary of the box.
  40832. *
  40833. * @type {Vector2}
  40834. */
  40835. this.min = min;
  40836. /**
  40837. * The upper boundary of the box.
  40838. *
  40839. * @type {Vector2}
  40840. */
  40841. this.max = max;
  40842. }
  40843. /**
  40844. * Sets the lower and upper boundaries of this box.
  40845. * Please note that this method only copies the values from the given objects.
  40846. *
  40847. * @param {Vector2} min - The lower boundary of the box.
  40848. * @param {Vector2} max - The upper boundary of the box.
  40849. * @return {Box2} A reference to this bounding box.
  40850. */
  40851. set( min, max ) {
  40852. this.min.copy( min );
  40853. this.max.copy( max );
  40854. return this;
  40855. }
  40856. /**
  40857. * Sets the upper and lower bounds of this box so it encloses the position data
  40858. * in the given array.
  40859. *
  40860. * @param {Array<Vector2>} points - An array holding 2D position data as instances of {@link Vector2}.
  40861. * @return {Box2} A reference to this bounding box.
  40862. */
  40863. setFromPoints( points ) {
  40864. this.makeEmpty();
  40865. for ( let i = 0, il = points.length; i < il; i ++ ) {
  40866. this.expandByPoint( points[ i ] );
  40867. }
  40868. return this;
  40869. }
  40870. /**
  40871. * Centers this box on the given center vector and sets this box's width, height and
  40872. * depth to the given size values.
  40873. *
  40874. * @param {Vector2} center - The center of the box.
  40875. * @param {Vector2} size - The x and y dimensions of the box.
  40876. * @return {Box2} A reference to this bounding box.
  40877. */
  40878. setFromCenterAndSize( center, size ) {
  40879. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  40880. this.min.copy( center ).sub( halfSize );
  40881. this.max.copy( center ).add( halfSize );
  40882. return this;
  40883. }
  40884. /**
  40885. * Returns a new box with copied values from this instance.
  40886. *
  40887. * @return {Box2} A clone of this instance.
  40888. */
  40889. clone() {
  40890. return new this.constructor().copy( this );
  40891. }
  40892. /**
  40893. * Copies the values of the given box to this instance.
  40894. *
  40895. * @param {Box2} box - The box to copy.
  40896. * @return {Box2} A reference to this bounding box.
  40897. */
  40898. copy( box ) {
  40899. this.min.copy( box.min );
  40900. this.max.copy( box.max );
  40901. return this;
  40902. }
  40903. /**
  40904. * Makes this box empty which means in encloses a zero space in 2D.
  40905. *
  40906. * @return {Box2} A reference to this bounding box.
  40907. */
  40908. makeEmpty() {
  40909. this.min.x = this.min.y = + Infinity;
  40910. this.max.x = this.max.y = - Infinity;
  40911. return this;
  40912. }
  40913. /**
  40914. * Returns true if this box includes zero points within its bounds.
  40915. * Note that a box with equal lower and upper bounds still includes one
  40916. * point, the one both bounds share.
  40917. *
  40918. * @return {boolean} Whether this box is empty or not.
  40919. */
  40920. isEmpty() {
  40921. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  40922. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  40923. }
  40924. /**
  40925. * Returns the center point of this box.
  40926. *
  40927. * @param {Vector2} target - The target vector that is used to store the method's result.
  40928. * @return {Vector2} The center point.
  40929. */
  40930. getCenter( target ) {
  40931. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  40932. }
  40933. /**
  40934. * Returns the dimensions of this box.
  40935. *
  40936. * @param {Vector2} target - The target vector that is used to store the method's result.
  40937. * @return {Vector2} The size.
  40938. */
  40939. getSize( target ) {
  40940. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  40941. }
  40942. /**
  40943. * Expands the boundaries of this box to include the given point.
  40944. *
  40945. * @param {Vector2} point - The point that should be included by the bounding box.
  40946. * @return {Box2} A reference to this bounding box.
  40947. */
  40948. expandByPoint( point ) {
  40949. this.min.min( point );
  40950. this.max.max( point );
  40951. return this;
  40952. }
  40953. /**
  40954. * Expands this box equilaterally by the given vector. The width of this
  40955. * box will be expanded by the x component of the vector in both
  40956. * directions. The height of this box will be expanded by the y component of
  40957. * the vector in both directions.
  40958. *
  40959. * @param {Vector2} vector - The vector that should expand the bounding box.
  40960. * @return {Box2} A reference to this bounding box.
  40961. */
  40962. expandByVector( vector ) {
  40963. this.min.sub( vector );
  40964. this.max.add( vector );
  40965. return this;
  40966. }
  40967. /**
  40968. * Expands each dimension of the box by the given scalar. If negative, the
  40969. * dimensions of the box will be contracted.
  40970. *
  40971. * @param {number} scalar - The scalar value that should expand the bounding box.
  40972. * @return {Box2} A reference to this bounding box.
  40973. */
  40974. expandByScalar( scalar ) {
  40975. this.min.addScalar( - scalar );
  40976. this.max.addScalar( scalar );
  40977. return this;
  40978. }
  40979. /**
  40980. * Returns `true` if the given point lies within or on the boundaries of this box.
  40981. *
  40982. * @param {Vector2} point - The point to test.
  40983. * @return {boolean} Whether the bounding box contains the given point or not.
  40984. */
  40985. containsPoint( point ) {
  40986. return point.x >= this.min.x && point.x <= this.max.x &&
  40987. point.y >= this.min.y && point.y <= this.max.y;
  40988. }
  40989. /**
  40990. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  40991. * If this box and the given one are identical, this function also returns `true`.
  40992. *
  40993. * @param {Box2} box - The bounding box to test.
  40994. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  40995. */
  40996. containsBox( box ) {
  40997. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  40998. this.min.y <= box.min.y && box.max.y <= this.max.y;
  40999. }
  41000. /**
  41001. * Returns a point as a proportion of this box's width and height.
  41002. *
  41003. * @param {Vector2} point - A point in 2D space.
  41004. * @param {Vector2} target - The target vector that is used to store the method's result.
  41005. * @return {Vector2} A point as a proportion of this box's width and height.
  41006. */
  41007. getParameter( point, target ) {
  41008. // This can potentially have a divide by zero if the box
  41009. // has a size dimension of 0.
  41010. return target.set(
  41011. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  41012. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  41013. );
  41014. }
  41015. /**
  41016. * Returns `true` if the given bounding box intersects with this bounding box.
  41017. *
  41018. * @param {Box2} box - The bounding box to test.
  41019. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  41020. */
  41021. intersectsBox( box ) {
  41022. // using 4 splitting planes to rule out intersections
  41023. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  41024. box.max.y >= this.min.y && box.min.y <= this.max.y;
  41025. }
  41026. /**
  41027. * Clamps the given point within the bounds of this box.
  41028. *
  41029. * @param {Vector2} point - The point to clamp.
  41030. * @param {Vector2} target - The target vector that is used to store the method's result.
  41031. * @return {Vector2} The clamped point.
  41032. */
  41033. clampPoint( point, target ) {
  41034. return target.copy( point ).clamp( this.min, this.max );
  41035. }
  41036. /**
  41037. * Returns the euclidean distance from any edge of this box to the specified point. If
  41038. * the given point lies inside of this box, the distance will be `0`.
  41039. *
  41040. * @param {Vector2} point - The point to compute the distance to.
  41041. * @return {number} The euclidean distance.
  41042. */
  41043. distanceToPoint( point ) {
  41044. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  41045. }
  41046. /**
  41047. * Computes the intersection of this bounding box and the given one, setting the upper
  41048. * bound of this box to the lesser of the two boxes' upper bounds and the
  41049. * lower bound of this box to the greater of the two boxes' lower bounds. If
  41050. * there's no overlap, makes this box empty.
  41051. *
  41052. * @param {Box2} box - The bounding box to intersect with.
  41053. * @return {Box2} A reference to this bounding box.
  41054. */
  41055. intersect( box ) {
  41056. this.min.max( box.min );
  41057. this.max.min( box.max );
  41058. if ( this.isEmpty() ) this.makeEmpty();
  41059. return this;
  41060. }
  41061. /**
  41062. * Computes the union of this box and another and the given one, setting the upper
  41063. * bound of this box to the greater of the two boxes' upper bounds and the
  41064. * lower bound of this box to the lesser of the two boxes' lower bounds.
  41065. *
  41066. * @param {Box2} box - The bounding box that will be unioned with this instance.
  41067. * @return {Box2} A reference to this bounding box.
  41068. */
  41069. union( box ) {
  41070. this.min.min( box.min );
  41071. this.max.max( box.max );
  41072. return this;
  41073. }
  41074. /**
  41075. * Adds the given offset to both the upper and lower bounds of this bounding box,
  41076. * effectively moving it in 2D space.
  41077. *
  41078. * @param {Vector2} offset - The offset that should be used to translate the bounding box.
  41079. * @return {Box2} A reference to this bounding box.
  41080. */
  41081. translate( offset ) {
  41082. this.min.add( offset );
  41083. this.max.add( offset );
  41084. return this;
  41085. }
  41086. /**
  41087. * Returns `true` if this bounding box is equal with the given one.
  41088. *
  41089. * @param {Box2} box - The box to test for equality.
  41090. * @return {boolean} Whether this bounding box is equal with the given one.
  41091. */
  41092. equals( box ) {
  41093. return box.min.equals( this.min ) && box.max.equals( this.max );
  41094. }
  41095. }
  41096. const _startP = /*@__PURE__*/ new Vector3();
  41097. const _startEnd = /*@__PURE__*/ new Vector3();
  41098. const _d1 = /*@__PURE__*/ new Vector3();
  41099. const _d2 = /*@__PURE__*/ new Vector3();
  41100. const _r = /*@__PURE__*/ new Vector3();
  41101. const _c1 = /*@__PURE__*/ new Vector3();
  41102. const _c2 = /*@__PURE__*/ new Vector3();
  41103. /**
  41104. * An analytical line segment in 3D space represented by a start and end point.
  41105. */
  41106. class Line3 {
  41107. /**
  41108. * Constructs a new line segment.
  41109. *
  41110. * @param {Vector3} [start=(0,0,0)] - Start of the line segment.
  41111. * @param {Vector3} [end=(0,0,0)] - End of the line segment.
  41112. */
  41113. constructor( start = new Vector3(), end = new Vector3() ) {
  41114. /**
  41115. * Start of the line segment.
  41116. *
  41117. * @type {Vector3}
  41118. */
  41119. this.start = start;
  41120. /**
  41121. * End of the line segment.
  41122. *
  41123. * @type {Vector3}
  41124. */
  41125. this.end = end;
  41126. }
  41127. /**
  41128. * Sets the start and end values by copying the given vectors.
  41129. *
  41130. * @param {Vector3} start - The start point.
  41131. * @param {Vector3} end - The end point.
  41132. * @return {Line3} A reference to this line segment.
  41133. */
  41134. set( start, end ) {
  41135. this.start.copy( start );
  41136. this.end.copy( end );
  41137. return this;
  41138. }
  41139. /**
  41140. * Copies the values of the given line segment to this instance.
  41141. *
  41142. * @param {Line3} line - The line segment to copy.
  41143. * @return {Line3} A reference to this line segment.
  41144. */
  41145. copy( line ) {
  41146. this.start.copy( line.start );
  41147. this.end.copy( line.end );
  41148. return this;
  41149. }
  41150. /**
  41151. * Returns the center of the line segment.
  41152. *
  41153. * @param {Vector3} target - The target vector that is used to store the method's result.
  41154. * @return {Vector3} The center point.
  41155. */
  41156. getCenter( target ) {
  41157. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  41158. }
  41159. /**
  41160. * Returns the delta vector of the line segment's start and end point.
  41161. *
  41162. * @param {Vector3} target - The target vector that is used to store the method's result.
  41163. * @return {Vector3} The delta vector.
  41164. */
  41165. delta( target ) {
  41166. return target.subVectors( this.end, this.start );
  41167. }
  41168. /**
  41169. * Returns the squared Euclidean distance between the line' start and end point.
  41170. *
  41171. * @return {number} The squared Euclidean distance.
  41172. */
  41173. distanceSq() {
  41174. return this.start.distanceToSquared( this.end );
  41175. }
  41176. /**
  41177. * Returns the Euclidean distance between the line' start and end point.
  41178. *
  41179. * @return {number} The Euclidean distance.
  41180. */
  41181. distance() {
  41182. return this.start.distanceTo( this.end );
  41183. }
  41184. /**
  41185. * Returns a vector at a certain position along the line segment.
  41186. *
  41187. * @param {number} t - A value between `[0,1]` to represent a position along the line segment.
  41188. * @param {Vector3} target - The target vector that is used to store the method's result.
  41189. * @return {Vector3} The delta vector.
  41190. */
  41191. at( t, target ) {
  41192. return this.delta( target ).multiplyScalar( t ).add( this.start );
  41193. }
  41194. /**
  41195. * Returns a point parameter based on the closest point as projected on the line segment.
  41196. *
  41197. * @param {Vector3} point - The point for which to return a point parameter.
  41198. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  41199. * @return {number} The point parameter.
  41200. */
  41201. closestPointToPointParameter( point, clampToLine ) {
  41202. _startP.subVectors( point, this.start );
  41203. _startEnd.subVectors( this.end, this.start );
  41204. const startEnd2 = _startEnd.dot( _startEnd );
  41205. const startEnd_startP = _startEnd.dot( _startP );
  41206. let t = startEnd_startP / startEnd2;
  41207. if ( clampToLine ) {
  41208. t = clamp( t, 0, 1 );
  41209. }
  41210. return t;
  41211. }
  41212. /**
  41213. * Returns the closest point on the line for a given point.
  41214. *
  41215. * @param {Vector3} point - The point to compute the closest point on the line for.
  41216. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  41217. * @param {Vector3} target - The target vector that is used to store the method's result.
  41218. * @return {Vector3} The closest point on the line.
  41219. */
  41220. closestPointToPoint( point, clampToLine, target ) {
  41221. const t = this.closestPointToPointParameter( point, clampToLine );
  41222. return this.delta( target ).multiplyScalar( t ).add( this.start );
  41223. }
  41224. /**
  41225. * Returns the closest squared distance between this line segment and the given one.
  41226. *
  41227. * @param {Line3} line - The line segment to compute the closest squared distance to.
  41228. * @param {Vector3} [c1] - The closest point on this line segment.
  41229. * @param {Vector3} [c2] - The closest point on the given line segment.
  41230. * @return {number} The squared distance between this line segment and the given one.
  41231. */
  41232. distanceSqToLine3( line, c1 = _c1, c2 = _c2 ) {
  41233. // from Real-Time Collision Detection by Christer Ericson, chapter 5.1.9
  41234. // Computes closest points C1 and C2 of S1(s)=P1+s*(Q1-P1) and
  41235. // S2(t)=P2+t*(Q2-P2), returning s and t. Function result is squared
  41236. // distance between between S1(s) and S2(t)
  41237. const EPSILON = 1e-8 * 1e-8; // must be squared since we compare squared length
  41238. let s, t;
  41239. const p1 = this.start;
  41240. const p2 = line.start;
  41241. const q1 = this.end;
  41242. const q2 = line.end;
  41243. _d1.subVectors( q1, p1 ); // Direction vector of segment S1
  41244. _d2.subVectors( q2, p2 ); // Direction vector of segment S2
  41245. _r.subVectors( p1, p2 );
  41246. const a = _d1.dot( _d1 ); // Squared length of segment S1, always nonnegative
  41247. const e = _d2.dot( _d2 ); // Squared length of segment S2, always nonnegative
  41248. const f = _d2.dot( _r );
  41249. // Check if either or both segments degenerate into points
  41250. if ( a <= EPSILON && e <= EPSILON ) {
  41251. // Both segments degenerate into points
  41252. c1.copy( p1 );
  41253. c2.copy( p2 );
  41254. c1.sub( c2 );
  41255. return c1.dot( c1 );
  41256. }
  41257. if ( a <= EPSILON ) {
  41258. // First segment degenerates into a point
  41259. s = 0;
  41260. t = f / e; // s = 0 => t = (b*s + f) / e = f / e
  41261. t = clamp( t, 0, 1 );
  41262. } else {
  41263. const c = _d1.dot( _r );
  41264. if ( e <= EPSILON ) {
  41265. // Second segment degenerates into a point
  41266. t = 0;
  41267. s = clamp( - c / a, 0, 1 ); // t = 0 => s = (b*t - c) / a = -c / a
  41268. } else {
  41269. // The general nondegenerate case starts here
  41270. const b = _d1.dot( _d2 );
  41271. const denom = a * e - b * b; // Always nonnegative
  41272. // If segments not parallel, compute closest point on L1 to L2 and
  41273. // clamp to segment S1. Else pick arbitrary s (here 0)
  41274. if ( denom !== 0 ) {
  41275. s = clamp( ( b * f - c * e ) / denom, 0, 1 );
  41276. } else {
  41277. s = 0;
  41278. }
  41279. // Compute point on L2 closest to S1(s) using
  41280. // t = Dot((P1 + D1*s) - P2,D2) / Dot(D2,D2) = (b*s + f) / e
  41281. t = ( b * s + f ) / e;
  41282. // If t in [0,1] done. Else clamp t, recompute s for the new value
  41283. // of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a
  41284. // and clamp s to [0, 1]
  41285. if ( t < 0 ) {
  41286. t = 0.;
  41287. s = clamp( - c / a, 0, 1 );
  41288. } else if ( t > 1 ) {
  41289. t = 1;
  41290. s = clamp( ( b - c ) / a, 0, 1 );
  41291. }
  41292. }
  41293. }
  41294. c1.copy( p1 ).addScaledVector( _d1, s );
  41295. c2.copy( p2 ).addScaledVector( _d2, t );
  41296. return c1.distanceToSquared( c2 );
  41297. }
  41298. /**
  41299. * Applies a 4x4 transformation matrix to this line segment.
  41300. *
  41301. * @param {Matrix4} matrix - The transformation matrix.
  41302. * @return {Line3} A reference to this line segment.
  41303. */
  41304. applyMatrix4( matrix ) {
  41305. this.start.applyMatrix4( matrix );
  41306. this.end.applyMatrix4( matrix );
  41307. return this;
  41308. }
  41309. /**
  41310. * Returns `true` if this line segment is equal with the given one.
  41311. *
  41312. * @param {Line3} line - The line segment to test for equality.
  41313. * @return {boolean} Whether this line segment is equal with the given one.
  41314. */
  41315. equals( line ) {
  41316. return line.start.equals( this.start ) && line.end.equals( this.end );
  41317. }
  41318. /**
  41319. * Returns a new line segment with copied values from this instance.
  41320. *
  41321. * @return {Line3} A clone of this instance.
  41322. */
  41323. clone() {
  41324. return new this.constructor().copy( this );
  41325. }
  41326. }
  41327. const _vector$3 = /*@__PURE__*/ new Vector3();
  41328. /**
  41329. * This displays a cone shaped helper object for a {@link SpotLight}.
  41330. *
  41331. * When the spot light or its target are transformed or light properties are
  41332. * changed, it's necessary to call the `update()` method of the respective helper.
  41333. *
  41334. * ```js
  41335. * const spotLight = new THREE.SpotLight( 0xffffff );
  41336. * spotLight.position.set( 10, 10, 10 );
  41337. * scene.add( spotLight );
  41338. *
  41339. * const spotLightHelper = new THREE.SpotLightHelper( spotLight );
  41340. * scene.add( spotLightHelper );
  41341. * ```
  41342. *
  41343. * @augments Object3D
  41344. */
  41345. class SpotLightHelper extends Object3D {
  41346. /**
  41347. * Constructs a new spot light helper.
  41348. *
  41349. * @param {HemisphereLight} light - The light to be visualized.
  41350. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41351. * the color of the light.
  41352. */
  41353. constructor( light, color ) {
  41354. super();
  41355. /**
  41356. * The light being visualized.
  41357. *
  41358. * @type {SpotLight}
  41359. */
  41360. this.light = light;
  41361. this.matrixAutoUpdate = false;
  41362. /**
  41363. * The color parameter passed in the constructor.
  41364. * If not set, the helper will take the color of the light.
  41365. *
  41366. * @type {number|Color|string}
  41367. */
  41368. this.color = color;
  41369. this.type = 'SpotLightHelper';
  41370. const geometry = new BufferGeometry();
  41371. const positions = [
  41372. 0, 0, 0, 0, 0, 1,
  41373. 0, 0, 0, 1, 0, 1,
  41374. 0, 0, 0, -1, 0, 1,
  41375. 0, 0, 0, 0, 1, 1,
  41376. 0, 0, 0, 0, -1, 1
  41377. ];
  41378. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  41379. const p1 = ( i / l ) * Math.PI * 2;
  41380. const p2 = ( j / l ) * Math.PI * 2;
  41381. positions.push(
  41382. Math.cos( p1 ), Math.sin( p1 ), 1,
  41383. Math.cos( p2 ), Math.sin( p2 ), 1
  41384. );
  41385. }
  41386. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41387. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  41388. this.cone = new LineSegments( geometry, material );
  41389. this.add( this.cone );
  41390. this.update();
  41391. }
  41392. /**
  41393. * Frees the GPU-related resources allocated by this instance. Call this
  41394. * method whenever this instance is no longer used in your app.
  41395. */
  41396. dispose() {
  41397. this.cone.geometry.dispose();
  41398. this.cone.material.dispose();
  41399. }
  41400. /**
  41401. * Updates the helper to match the position and direction of the
  41402. * light being visualized.
  41403. */
  41404. update() {
  41405. this.light.updateWorldMatrix( true, false );
  41406. this.light.target.updateWorldMatrix( true, false );
  41407. // update the local matrix based on the parent and light target transforms
  41408. if ( this.parent ) {
  41409. this.parent.updateWorldMatrix( true );
  41410. this.matrix
  41411. .copy( this.parent.matrixWorld )
  41412. .invert()
  41413. .multiply( this.light.matrixWorld );
  41414. } else {
  41415. this.matrix.copy( this.light.matrixWorld );
  41416. }
  41417. this.matrixWorld.copy( this.light.matrixWorld );
  41418. const coneLength = this.light.distance ? this.light.distance : 1000;
  41419. const coneWidth = coneLength * Math.tan( this.light.angle );
  41420. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  41421. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  41422. this.cone.lookAt( _vector$3 );
  41423. if ( this.color !== undefined ) {
  41424. this.cone.material.color.set( this.color );
  41425. } else {
  41426. this.cone.material.color.copy( this.light.color );
  41427. }
  41428. }
  41429. }
  41430. const _vector$2 = /*@__PURE__*/ new Vector3();
  41431. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  41432. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  41433. /**
  41434. * A helper object to assist with visualizing a {@link Skeleton}.
  41435. *
  41436. * ```js
  41437. * const helper = new THREE.SkeletonHelper( skinnedMesh );
  41438. * scene.add( helper );
  41439. * ```
  41440. *
  41441. * @augments LineSegments
  41442. */
  41443. class SkeletonHelper extends LineSegments {
  41444. /**
  41445. * Constructs a new skeleton helper.
  41446. *
  41447. * @param {Object3D} object - Usually an instance of {@link SkinnedMesh}. However, any 3D object
  41448. * can be used if it represents a hierarchy of bones (see {@link Bone}).
  41449. */
  41450. constructor( object ) {
  41451. const bones = getBoneList( object );
  41452. const geometry = new BufferGeometry();
  41453. const vertices = [];
  41454. const colors = [];
  41455. for ( let i = 0; i < bones.length; i ++ ) {
  41456. const bone = bones[ i ];
  41457. if ( bone.parent && bone.parent.isBone ) {
  41458. vertices.push( 0, 0, 0 );
  41459. vertices.push( 0, 0, 0 );
  41460. colors.push( 0, 0, 0 );
  41461. colors.push( 0, 0, 0 );
  41462. }
  41463. }
  41464. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41465. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41466. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  41467. super( geometry, material );
  41468. /**
  41469. * This flag can be used for type testing.
  41470. *
  41471. * @type {boolean}
  41472. * @readonly
  41473. * @default true
  41474. */
  41475. this.isSkeletonHelper = true;
  41476. this.type = 'SkeletonHelper';
  41477. /**
  41478. * The object being visualized.
  41479. *
  41480. * @type {Object3D}
  41481. */
  41482. this.root = object;
  41483. /**
  41484. * The list of bones that the helper visualizes.
  41485. *
  41486. * @type {Array<Bone>}
  41487. */
  41488. this.bones = bones;
  41489. this.matrix = object.matrixWorld;
  41490. this.matrixAutoUpdate = false;
  41491. // colors
  41492. const color1 = new Color( 0x0000ff );
  41493. const color2 = new Color( 0x00ff00 );
  41494. this.setColors( color1, color2 );
  41495. }
  41496. updateMatrixWorld( force ) {
  41497. const bones = this.bones;
  41498. const geometry = this.geometry;
  41499. const position = geometry.getAttribute( 'position' );
  41500. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  41501. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  41502. const bone = bones[ i ];
  41503. if ( bone.parent && bone.parent.isBone ) {
  41504. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  41505. _vector$2.setFromMatrixPosition( _boneMatrix );
  41506. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  41507. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  41508. _vector$2.setFromMatrixPosition( _boneMatrix );
  41509. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  41510. j += 2;
  41511. }
  41512. }
  41513. geometry.getAttribute( 'position' ).needsUpdate = true;
  41514. super.updateMatrixWorld( force );
  41515. }
  41516. /**
  41517. * Defines the colors of the helper.
  41518. *
  41519. * @param {Color} color1 - The first line color for each bone.
  41520. * @param {Color} color2 - The second line color for each bone.
  41521. * @return {SkeletonHelper} A reference to this helper.
  41522. */
  41523. setColors( color1, color2 ) {
  41524. const geometry = this.geometry;
  41525. const colorAttribute = geometry.getAttribute( 'color' );
  41526. for ( let i = 0; i < colorAttribute.count; i += 2 ) {
  41527. colorAttribute.setXYZ( i, color1.r, color1.g, color1.b );
  41528. colorAttribute.setXYZ( i + 1, color2.r, color2.g, color2.b );
  41529. }
  41530. colorAttribute.needsUpdate = true;
  41531. return this;
  41532. }
  41533. /**
  41534. * Frees the GPU-related resources allocated by this instance. Call this
  41535. * method whenever this instance is no longer used in your app.
  41536. */
  41537. dispose() {
  41538. this.geometry.dispose();
  41539. this.material.dispose();
  41540. }
  41541. }
  41542. function getBoneList( object ) {
  41543. const boneList = [];
  41544. if ( object.isBone === true ) {
  41545. boneList.push( object );
  41546. }
  41547. for ( let i = 0; i < object.children.length; i ++ ) {
  41548. boneList.push( ...getBoneList( object.children[ i ] ) );
  41549. }
  41550. return boneList;
  41551. }
  41552. /**
  41553. * This displays a helper object consisting of a spherical mesh for
  41554. * visualizing an instance of {@link PointLight}.
  41555. *
  41556. * ```js
  41557. * const pointLight = new THREE.PointLight( 0xff0000, 1, 100 );
  41558. * pointLight.position.set( 10, 10, 10 );
  41559. * scene.add( pointLight );
  41560. *
  41561. * const sphereSize = 1;
  41562. * const pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
  41563. * scene.add( pointLightHelper );
  41564. * ```
  41565. *
  41566. * @augments Mesh
  41567. */
  41568. class PointLightHelper extends Mesh {
  41569. /**
  41570. * Constructs a new point light helper.
  41571. *
  41572. * @param {PointLight} light - The light to be visualized.
  41573. * @param {number} [sphereSize=1] - The size of the sphere helper.
  41574. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41575. * the color of the light.
  41576. */
  41577. constructor( light, sphereSize, color ) {
  41578. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  41579. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41580. super( geometry, material );
  41581. /**
  41582. * The light being visualized.
  41583. *
  41584. * @type {PointLight}
  41585. */
  41586. this.light = light;
  41587. /**
  41588. * The color parameter passed in the constructor.
  41589. * If not set, the helper will take the color of the light.
  41590. *
  41591. * @type {number|Color|string}
  41592. */
  41593. this.color = color;
  41594. this.type = 'PointLightHelper';
  41595. this.matrix = this.light.matrixWorld;
  41596. this.matrixAutoUpdate = false;
  41597. this.update();
  41598. }
  41599. /**
  41600. * Frees the GPU-related resources allocated by this instance. Call this
  41601. * method whenever this instance is no longer used in your app.
  41602. */
  41603. dispose() {
  41604. this.geometry.dispose();
  41605. this.material.dispose();
  41606. }
  41607. /**
  41608. * Updates the helper to match the position of the
  41609. * light being visualized.
  41610. */
  41611. update() {
  41612. this.light.updateWorldMatrix( true, false );
  41613. if ( this.color !== undefined ) {
  41614. this.material.color.set( this.color );
  41615. } else {
  41616. this.material.color.copy( this.light.color );
  41617. }
  41618. /*
  41619. const d = this.light.distance;
  41620. if ( d === 0.0 ) {
  41621. this.lightDistance.visible = false;
  41622. } else {
  41623. this.lightDistance.visible = true;
  41624. this.lightDistance.scale.set( d, d, d );
  41625. }
  41626. */
  41627. }
  41628. }
  41629. const _vector$1 = /*@__PURE__*/ new Vector3();
  41630. const _color1 = /*@__PURE__*/ new Color();
  41631. const _color2 = /*@__PURE__*/ new Color();
  41632. /**
  41633. * Creates a visual aid consisting of a spherical mesh for a
  41634. * given {@link HemisphereLight}.
  41635. *
  41636. * When the hemisphere light is transformed or its light properties are changed,
  41637. * it's necessary to call the `update()` method of the respective helper.
  41638. *
  41639. * ```js
  41640. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  41641. * const helper = new THREE.HemisphereLightHelper( light, 5 );
  41642. * scene.add( helper );
  41643. * ```
  41644. *
  41645. * @augments Object3D
  41646. */
  41647. class HemisphereLightHelper extends Object3D {
  41648. /**
  41649. * Constructs a new hemisphere light helper.
  41650. *
  41651. * @param {HemisphereLight} light - The light to be visualized.
  41652. * @param {number} [size=1] - The size of the mesh used to visualize the light.
  41653. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41654. * the color of the light.
  41655. */
  41656. constructor( light, size, color ) {
  41657. super();
  41658. /**
  41659. * The light being visualized.
  41660. *
  41661. * @type {HemisphereLight}
  41662. */
  41663. this.light = light;
  41664. this.matrix = light.matrixWorld;
  41665. this.matrixAutoUpdate = false;
  41666. /**
  41667. * The color parameter passed in the constructor.
  41668. * If not set, the helper will take the color of the light.
  41669. *
  41670. * @type {number|Color|string}
  41671. */
  41672. this.color = color;
  41673. this.type = 'HemisphereLightHelper';
  41674. const geometry = new OctahedronGeometry( size );
  41675. geometry.rotateY( Math.PI * 0.5 );
  41676. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41677. if ( this.color === undefined ) this.material.vertexColors = true;
  41678. const position = geometry.getAttribute( 'position' );
  41679. const colors = new Float32Array( position.count * 3 );
  41680. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  41681. this.add( new Mesh( geometry, this.material ) );
  41682. this.update();
  41683. }
  41684. /**
  41685. * Frees the GPU-related resources allocated by this instance. Call this
  41686. * method whenever this instance is no longer used in your app.
  41687. */
  41688. dispose() {
  41689. this.children[ 0 ].geometry.dispose();
  41690. this.children[ 0 ].material.dispose();
  41691. }
  41692. /**
  41693. * Updates the helper to match the position and direction of the
  41694. * light being visualized.
  41695. */
  41696. update() {
  41697. const mesh = this.children[ 0 ];
  41698. if ( this.color !== undefined ) {
  41699. this.material.color.set( this.color );
  41700. } else {
  41701. const colors = mesh.geometry.getAttribute( 'color' );
  41702. _color1.copy( this.light.color );
  41703. _color2.copy( this.light.groundColor );
  41704. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  41705. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  41706. colors.setXYZ( i, color.r, color.g, color.b );
  41707. }
  41708. colors.needsUpdate = true;
  41709. }
  41710. this.light.updateWorldMatrix( true, false );
  41711. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  41712. }
  41713. }
  41714. /**
  41715. * The helper is an object to define grids. Grids are two-dimensional
  41716. * arrays of lines.
  41717. *
  41718. * ```js
  41719. * const size = 10;
  41720. * const divisions = 10;
  41721. *
  41722. * const gridHelper = new THREE.GridHelper( size, divisions );
  41723. * scene.add( gridHelper );
  41724. * ```
  41725. *
  41726. * @augments LineSegments
  41727. */
  41728. class GridHelper extends LineSegments {
  41729. /**
  41730. * Constructs a new grid helper.
  41731. *
  41732. * @param {number} [size=10] - The size of the grid.
  41733. * @param {number} [divisions=10] - The number of divisions across the grid.
  41734. * @param {number|Color|string} [color1=0x444444] - The color of the center line.
  41735. * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
  41736. */
  41737. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  41738. color1 = new Color( color1 );
  41739. color2 = new Color( color2 );
  41740. const center = divisions / 2;
  41741. const step = size / divisions;
  41742. const halfSize = size / 2;
  41743. const vertices = [], colors = [];
  41744. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  41745. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  41746. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  41747. const color = i === center ? color1 : color2;
  41748. color.toArray( colors, j ); j += 3;
  41749. color.toArray( colors, j ); j += 3;
  41750. color.toArray( colors, j ); j += 3;
  41751. color.toArray( colors, j ); j += 3;
  41752. }
  41753. const geometry = new BufferGeometry();
  41754. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41755. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41756. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41757. super( geometry, material );
  41758. this.type = 'GridHelper';
  41759. }
  41760. /**
  41761. * Frees the GPU-related resources allocated by this instance. Call this
  41762. * method whenever this instance is no longer used in your app.
  41763. */
  41764. dispose() {
  41765. this.geometry.dispose();
  41766. this.material.dispose();
  41767. }
  41768. }
  41769. /**
  41770. * This helper is an object to define polar grids. Grids are
  41771. * two-dimensional arrays of lines.
  41772. *
  41773. * ```js
  41774. * const radius = 10;
  41775. * const sectors = 16;
  41776. * const rings = 8;
  41777. * const divisions = 64;
  41778. *
  41779. * const helper = new THREE.PolarGridHelper( radius, sectors, rings, divisions );
  41780. * scene.add( helper );
  41781. * ```
  41782. *
  41783. * @augments LineSegments
  41784. */
  41785. class PolarGridHelper extends LineSegments {
  41786. /**
  41787. * Constructs a new polar grid helper.
  41788. *
  41789. * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number.
  41790. * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer.
  41791. * @param {number} [rings=16] - The number of rings. This can be any positive integer.
  41792. * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer.
  41793. * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements.
  41794. * @param {number|Color|string} [color2=0x888888] - The second color used for grid elements.
  41795. */
  41796. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  41797. color1 = new Color( color1 );
  41798. color2 = new Color( color2 );
  41799. const vertices = [];
  41800. const colors = [];
  41801. // create the sectors
  41802. if ( sectors > 1 ) {
  41803. for ( let i = 0; i < sectors; i ++ ) {
  41804. const v = ( i / sectors ) * ( Math.PI * 2 );
  41805. const x = Math.sin( v ) * radius;
  41806. const z = Math.cos( v ) * radius;
  41807. vertices.push( 0, 0, 0 );
  41808. vertices.push( x, 0, z );
  41809. const color = ( i & 1 ) ? color1 : color2;
  41810. colors.push( color.r, color.g, color.b );
  41811. colors.push( color.r, color.g, color.b );
  41812. }
  41813. }
  41814. // create the rings
  41815. for ( let i = 0; i < rings; i ++ ) {
  41816. const color = ( i & 1 ) ? color1 : color2;
  41817. const r = radius - ( radius / rings * i );
  41818. for ( let j = 0; j < divisions; j ++ ) {
  41819. // first vertex
  41820. let v = ( j / divisions ) * ( Math.PI * 2 );
  41821. let x = Math.sin( v ) * r;
  41822. let z = Math.cos( v ) * r;
  41823. vertices.push( x, 0, z );
  41824. colors.push( color.r, color.g, color.b );
  41825. // second vertex
  41826. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  41827. x = Math.sin( v ) * r;
  41828. z = Math.cos( v ) * r;
  41829. vertices.push( x, 0, z );
  41830. colors.push( color.r, color.g, color.b );
  41831. }
  41832. }
  41833. const geometry = new BufferGeometry();
  41834. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41835. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41836. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41837. super( geometry, material );
  41838. this.type = 'PolarGridHelper';
  41839. }
  41840. /**
  41841. * Frees the GPU-related resources allocated by this instance. Call this
  41842. * method whenever this instance is no longer used in your app.
  41843. */
  41844. dispose() {
  41845. this.geometry.dispose();
  41846. this.material.dispose();
  41847. }
  41848. }
  41849. const _v1 = /*@__PURE__*/ new Vector3();
  41850. const _v2 = /*@__PURE__*/ new Vector3();
  41851. const _v3 = /*@__PURE__*/ new Vector3();
  41852. /**
  41853. * Helper object to assist with visualizing a {@link DirectionalLight}'s
  41854. * effect on the scene. This consists of a plane and a line representing the
  41855. * light's position and direction.
  41856. *
  41857. * When the directional light or its target are transformed or light properties
  41858. * are changed, it's necessary to call the `update()` method of the respective helper.
  41859. *
  41860. * ```js
  41861. * const light = new THREE.DirectionalLight( 0xFFFFFF );
  41862. * scene.add( light );
  41863. *
  41864. * const helper = new THREE.DirectionalLightHelper( light, 5 );
  41865. * scene.add( helper );
  41866. * ```
  41867. *
  41868. * @augments Object3D
  41869. */
  41870. class DirectionalLightHelper extends Object3D {
  41871. /**
  41872. * Constructs a new directional light helper.
  41873. *
  41874. * @param {DirectionalLight} light - The light to be visualized.
  41875. * @param {number} [size=1] - The dimensions of the plane.
  41876. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41877. * the color of the light.
  41878. */
  41879. constructor( light, size, color ) {
  41880. super();
  41881. /**
  41882. * The light being visualized.
  41883. *
  41884. * @type {DirectionalLight}
  41885. */
  41886. this.light = light;
  41887. this.matrix = light.matrixWorld;
  41888. this.matrixAutoUpdate = false;
  41889. /**
  41890. * The color parameter passed in the constructor.
  41891. * If not set, the helper will take the color of the light.
  41892. *
  41893. * @type {number|Color|string}
  41894. */
  41895. this.color = color;
  41896. this.type = 'DirectionalLightHelper';
  41897. if ( size === undefined ) size = 1;
  41898. let geometry = new BufferGeometry();
  41899. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  41900. - size, size, 0,
  41901. size, size, 0,
  41902. size, - size, 0,
  41903. - size, - size, 0,
  41904. - size, size, 0
  41905. ], 3 ) );
  41906. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  41907. /**
  41908. * Contains the line showing the location of the directional light.
  41909. *
  41910. * @type {Line}
  41911. */
  41912. this.lightPlane = new Line( geometry, material );
  41913. this.add( this.lightPlane );
  41914. geometry = new BufferGeometry();
  41915. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  41916. /**
  41917. * Represents the target line of the directional light.
  41918. *
  41919. * @type {Line}
  41920. */
  41921. this.targetLine = new Line( geometry, material );
  41922. this.add( this.targetLine );
  41923. this.update();
  41924. }
  41925. /**
  41926. * Frees the GPU-related resources allocated by this instance. Call this
  41927. * method whenever this instance is no longer used in your app.
  41928. */
  41929. dispose() {
  41930. this.lightPlane.geometry.dispose();
  41931. this.lightPlane.material.dispose();
  41932. this.targetLine.geometry.dispose();
  41933. this.targetLine.material.dispose();
  41934. }
  41935. /**
  41936. * Updates the helper to match the position and direction of the
  41937. * light being visualized.
  41938. */
  41939. update() {
  41940. this.light.updateWorldMatrix( true, false );
  41941. this.light.target.updateWorldMatrix( true, false );
  41942. _v1.setFromMatrixPosition( this.light.matrixWorld );
  41943. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  41944. _v3.subVectors( _v2, _v1 );
  41945. this.lightPlane.lookAt( _v2 );
  41946. if ( this.color !== undefined ) {
  41947. this.lightPlane.material.color.set( this.color );
  41948. this.targetLine.material.color.set( this.color );
  41949. } else {
  41950. this.lightPlane.material.color.copy( this.light.color );
  41951. this.targetLine.material.color.copy( this.light.color );
  41952. }
  41953. this.targetLine.lookAt( _v2 );
  41954. this.targetLine.scale.z = _v3.length();
  41955. }
  41956. }
  41957. const _vector = /*@__PURE__*/ new Vector3();
  41958. const _camera = /*@__PURE__*/ new Camera();
  41959. /**
  41960. * This helps with visualizing what a camera contains in its frustum. It
  41961. * visualizes the frustum of a camera using a line segments.
  41962. *
  41963. * Based on frustum visualization in [lightgl.js shadowmap example](https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html).
  41964. *
  41965. * `CameraHelper` must be a child of the scene.
  41966. *
  41967. * When the camera is transformed or its projection matrix is changed, it's necessary
  41968. * to call the `update()` method of the respective helper.
  41969. *
  41970. * ```js
  41971. * const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
  41972. * const helper = new THREE.CameraHelper( camera );
  41973. * scene.add( helper );
  41974. * ```
  41975. *
  41976. * @augments LineSegments
  41977. */
  41978. class CameraHelper extends LineSegments {
  41979. /**
  41980. * Constructs a new arrow helper.
  41981. *
  41982. * @param {Camera} camera - The camera to visualize.
  41983. */
  41984. constructor( camera ) {
  41985. const geometry = new BufferGeometry();
  41986. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  41987. const vertices = [];
  41988. const colors = [];
  41989. const pointMap = {};
  41990. // near
  41991. addLine( 'n1', 'n2' );
  41992. addLine( 'n2', 'n4' );
  41993. addLine( 'n4', 'n3' );
  41994. addLine( 'n3', 'n1' );
  41995. // far
  41996. addLine( 'f1', 'f2' );
  41997. addLine( 'f2', 'f4' );
  41998. addLine( 'f4', 'f3' );
  41999. addLine( 'f3', 'f1' );
  42000. // sides
  42001. addLine( 'n1', 'f1' );
  42002. addLine( 'n2', 'f2' );
  42003. addLine( 'n3', 'f3' );
  42004. addLine( 'n4', 'f4' );
  42005. // cone
  42006. addLine( 'p', 'n1' );
  42007. addLine( 'p', 'n2' );
  42008. addLine( 'p', 'n3' );
  42009. addLine( 'p', 'n4' );
  42010. // up
  42011. addLine( 'u1', 'u2' );
  42012. addLine( 'u2', 'u3' );
  42013. addLine( 'u3', 'u1' );
  42014. // target
  42015. addLine( 'c', 't' );
  42016. addLine( 'p', 'c' );
  42017. // cross
  42018. addLine( 'cn1', 'cn2' );
  42019. addLine( 'cn3', 'cn4' );
  42020. addLine( 'cf1', 'cf2' );
  42021. addLine( 'cf3', 'cf4' );
  42022. function addLine( a, b ) {
  42023. addPoint( a );
  42024. addPoint( b );
  42025. }
  42026. function addPoint( id ) {
  42027. vertices.push( 0, 0, 0 );
  42028. colors.push( 0, 0, 0 );
  42029. if ( pointMap[ id ] === undefined ) {
  42030. pointMap[ id ] = [];
  42031. }
  42032. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  42033. }
  42034. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  42035. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  42036. super( geometry, material );
  42037. this.type = 'CameraHelper';
  42038. /**
  42039. * The camera being visualized.
  42040. *
  42041. * @type {Camera}
  42042. */
  42043. this.camera = camera;
  42044. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  42045. this.matrix = camera.matrixWorld;
  42046. this.matrixAutoUpdate = false;
  42047. /**
  42048. * This contains the points used to visualize the camera.
  42049. *
  42050. * @type {Object<string,Array<number>>}
  42051. */
  42052. this.pointMap = pointMap;
  42053. this.update();
  42054. // colors
  42055. const colorFrustum = new Color( 0xffaa00 );
  42056. const colorCone = new Color( 0xff0000 );
  42057. const colorUp = new Color( 0x00aaff );
  42058. const colorTarget = new Color( 0xffffff );
  42059. const colorCross = new Color( 0x333333 );
  42060. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  42061. }
  42062. /**
  42063. * Defines the colors of the helper.
  42064. *
  42065. * @param {Color} frustum - The frustum line color.
  42066. * @param {Color} cone - The cone line color.
  42067. * @param {Color} up - The up line color.
  42068. * @param {Color} target - The target line color.
  42069. * @param {Color} cross - The cross line color.
  42070. * @return {CameraHelper} A reference to this helper.
  42071. */
  42072. setColors( frustum, cone, up, target, cross ) {
  42073. const geometry = this.geometry;
  42074. const colorAttribute = geometry.getAttribute( 'color' );
  42075. // near
  42076. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  42077. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  42078. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  42079. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  42080. // far
  42081. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  42082. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  42083. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  42084. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  42085. // sides
  42086. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  42087. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  42088. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  42089. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  42090. // cone
  42091. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  42092. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  42093. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  42094. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  42095. // up
  42096. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  42097. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  42098. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  42099. // target
  42100. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  42101. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  42102. // cross
  42103. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  42104. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  42105. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  42106. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  42107. colorAttribute.needsUpdate = true;
  42108. return this;
  42109. }
  42110. /**
  42111. * Updates the helper based on the projection matrix of the camera.
  42112. */
  42113. update() {
  42114. const geometry = this.geometry;
  42115. const pointMap = this.pointMap;
  42116. const w = 1, h = 1;
  42117. let nearZ, farZ;
  42118. // we need just camera projection matrix inverse
  42119. // world matrix must be identity
  42120. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  42121. // Adjust z values based on coordinate system
  42122. if ( this.camera.reversedDepth === true ) {
  42123. nearZ = 1;
  42124. farZ = 0;
  42125. } else {
  42126. if ( this.camera.coordinateSystem === WebGLCoordinateSystem ) {
  42127. nearZ = -1;
  42128. farZ = 1;
  42129. } else if ( this.camera.coordinateSystem === WebGPUCoordinateSystem ) {
  42130. nearZ = 0;
  42131. farZ = 1;
  42132. } else {
  42133. throw new Error( 'THREE.CameraHelper.update(): Invalid coordinate system: ' + this.camera.coordinateSystem );
  42134. }
  42135. }
  42136. // center / target
  42137. setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ );
  42138. setPoint( 't', pointMap, geometry, _camera, 0, 0, farZ );
  42139. // near
  42140. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, nearZ );
  42141. setPoint( 'n2', pointMap, geometry, _camera, w, - h, nearZ );
  42142. setPoint( 'n3', pointMap, geometry, _camera, - w, h, nearZ );
  42143. setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ );
  42144. // far
  42145. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, farZ );
  42146. setPoint( 'f2', pointMap, geometry, _camera, w, - h, farZ );
  42147. setPoint( 'f3', pointMap, geometry, _camera, - w, h, farZ );
  42148. setPoint( 'f4', pointMap, geometry, _camera, w, h, farZ );
  42149. // up
  42150. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ );
  42151. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, nearZ );
  42152. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ );
  42153. // cross
  42154. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, farZ );
  42155. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, farZ );
  42156. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, farZ );
  42157. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, farZ );
  42158. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, nearZ );
  42159. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ );
  42160. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, nearZ );
  42161. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ );
  42162. geometry.getAttribute( 'position' ).needsUpdate = true;
  42163. }
  42164. /**
  42165. * Frees the GPU-related resources allocated by this instance. Call this
  42166. * method whenever this instance is no longer used in your app.
  42167. */
  42168. dispose() {
  42169. this.geometry.dispose();
  42170. this.material.dispose();
  42171. }
  42172. }
  42173. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  42174. _vector.set( x, y, z ).unproject( camera );
  42175. const points = pointMap[ point ];
  42176. if ( points !== undefined ) {
  42177. const position = geometry.getAttribute( 'position' );
  42178. for ( let i = 0, l = points.length; i < l; i ++ ) {
  42179. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  42180. }
  42181. }
  42182. }
  42183. const _box = /*@__PURE__*/ new Box3();
  42184. /**
  42185. * Helper object to graphically show the world-axis-aligned bounding box
  42186. * around an object. The actual bounding box is handled with {@link Box3},
  42187. * this is just a visual helper for debugging. It can be automatically
  42188. * resized with {@link BoxHelper#update} when the object it's created from
  42189. * is transformed. Note that the object must have a geometry for this to work,
  42190. * so it won't work with sprites.
  42191. *
  42192. * ```js
  42193. * const sphere = new THREE.SphereGeometry();
  42194. * const object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) );
  42195. * const box = new THREE.BoxHelper( object, 0xffff00 );
  42196. * scene.add( box );
  42197. * ```
  42198. *
  42199. * @augments LineSegments
  42200. */
  42201. class BoxHelper extends LineSegments {
  42202. /**
  42203. * Constructs a new box helper.
  42204. *
  42205. * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box.
  42206. * @param {number|Color|string} [color=0xffff00] - The box's color.
  42207. */
  42208. constructor( object, color = 0xffff00 ) {
  42209. 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 ] );
  42210. const positions = new Float32Array( 8 * 3 );
  42211. const geometry = new BufferGeometry();
  42212. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  42213. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  42214. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42215. /**
  42216. * The 3D object being visualized.
  42217. *
  42218. * @type {Object3D}
  42219. */
  42220. this.object = object;
  42221. this.type = 'BoxHelper';
  42222. this.matrixAutoUpdate = false;
  42223. this.update();
  42224. }
  42225. /**
  42226. * Updates the helper's geometry to match the dimensions of the object,
  42227. * including any children.
  42228. */
  42229. update() {
  42230. if ( this.object !== undefined ) {
  42231. _box.setFromObject( this.object );
  42232. }
  42233. if ( _box.isEmpty() ) return;
  42234. const min = _box.min;
  42235. const max = _box.max;
  42236. /*
  42237. 5____4
  42238. 1/___0/|
  42239. | 6__|_7
  42240. 2/___3/
  42241. 0: max.x, max.y, max.z
  42242. 1: min.x, max.y, max.z
  42243. 2: min.x, min.y, max.z
  42244. 3: max.x, min.y, max.z
  42245. 4: max.x, max.y, min.z
  42246. 5: min.x, max.y, min.z
  42247. 6: min.x, min.y, min.z
  42248. 7: max.x, min.y, min.z
  42249. */
  42250. const position = this.geometry.attributes.position;
  42251. const array = position.array;
  42252. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  42253. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  42254. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  42255. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  42256. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  42257. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  42258. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  42259. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  42260. position.needsUpdate = true;
  42261. this.geometry.computeBoundingSphere();
  42262. }
  42263. /**
  42264. * Updates the wireframe box for the passed object.
  42265. *
  42266. * @param {Object3D} object - The 3D object to create the helper for.
  42267. * @return {BoxHelper} A reference to this instance.
  42268. */
  42269. setFromObject( object ) {
  42270. this.object = object;
  42271. this.update();
  42272. return this;
  42273. }
  42274. copy( source, recursive ) {
  42275. super.copy( source, recursive );
  42276. this.object = source.object;
  42277. return this;
  42278. }
  42279. /**
  42280. * Frees the GPU-related resources allocated by this instance. Call this
  42281. * method whenever this instance is no longer used in your app.
  42282. */
  42283. dispose() {
  42284. this.geometry.dispose();
  42285. this.material.dispose();
  42286. }
  42287. }
  42288. /**
  42289. * A helper object to visualize an instance of {@link Box3}.
  42290. *
  42291. * ```js
  42292. * const box = new THREE.Box3();
  42293. * box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) );
  42294. *
  42295. * const helper = new THREE.Box3Helper( box, 0xffff00 );
  42296. * scene.add( helper )
  42297. * ```
  42298. *
  42299. * @augments LineSegments
  42300. */
  42301. class Box3Helper extends LineSegments {
  42302. /**
  42303. * Constructs a new box3 helper.
  42304. *
  42305. * @param {Box3} box - The box to visualize.
  42306. * @param {number|Color|string} [color=0xffff00] - The box's color.
  42307. */
  42308. constructor( box, color = 0xffff00 ) {
  42309. 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 ] );
  42310. 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 ];
  42311. const geometry = new BufferGeometry();
  42312. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  42313. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  42314. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42315. /**
  42316. * The box being visualized.
  42317. *
  42318. * @type {Box3}
  42319. */
  42320. this.box = box;
  42321. this.type = 'Box3Helper';
  42322. this.geometry.computeBoundingSphere();
  42323. }
  42324. updateMatrixWorld( force ) {
  42325. const box = this.box;
  42326. if ( box.isEmpty() ) return;
  42327. box.getCenter( this.position );
  42328. box.getSize( this.scale );
  42329. this.scale.multiplyScalar( 0.5 );
  42330. super.updateMatrixWorld( force );
  42331. }
  42332. /**
  42333. * Frees the GPU-related resources allocated by this instance. Call this
  42334. * method whenever this instance is no longer used in your app.
  42335. */
  42336. dispose() {
  42337. this.geometry.dispose();
  42338. this.material.dispose();
  42339. }
  42340. }
  42341. /**
  42342. * A helper object to visualize an instance of {@link Plane}.
  42343. *
  42344. * ```js
  42345. * const plane = new THREE.Plane( new THREE.Vector3( 1, 1, 0.2 ), 3 );
  42346. * const helper = new THREE.PlaneHelper( plane, 1, 0xffff00 );
  42347. * scene.add( helper );
  42348. * ```
  42349. *
  42350. * @augments Line
  42351. */
  42352. class PlaneHelper extends Line {
  42353. /**
  42354. * Constructs a new plane helper.
  42355. *
  42356. * @param {Plane} plane - The plane to be visualized.
  42357. * @param {number} [size=1] - The side length of plane helper.
  42358. * @param {number|Color|string} [hex=0xffff00] - The helper's color.
  42359. */
  42360. constructor( plane, size = 1, hex = 0xffff00 ) {
  42361. const color = hex;
  42362. 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 ];
  42363. const geometry = new BufferGeometry();
  42364. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  42365. geometry.computeBoundingSphere();
  42366. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42367. this.type = 'PlaneHelper';
  42368. /**
  42369. * The plane being visualized.
  42370. *
  42371. * @type {Plane}
  42372. */
  42373. this.plane = plane;
  42374. /**
  42375. * The side length of plane helper.
  42376. *
  42377. * @type {number}
  42378. * @default 1
  42379. */
  42380. this.size = size;
  42381. const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ];
  42382. const geometry2 = new BufferGeometry();
  42383. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  42384. geometry2.computeBoundingSphere();
  42385. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  42386. }
  42387. updateMatrixWorld( force ) {
  42388. this.position.set( 0, 0, 0 );
  42389. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  42390. this.lookAt( this.plane.normal );
  42391. this.translateZ( - this.plane.constant );
  42392. super.updateMatrixWorld( force );
  42393. }
  42394. /**
  42395. * Updates the helper to match the position and direction of the
  42396. * light being visualized.
  42397. */
  42398. dispose() {
  42399. this.geometry.dispose();
  42400. this.material.dispose();
  42401. this.children[ 0 ].geometry.dispose();
  42402. this.children[ 0 ].material.dispose();
  42403. }
  42404. }
  42405. const _axis = /*@__PURE__*/ new Vector3();
  42406. let _lineGeometry, _coneGeometry;
  42407. /**
  42408. * An 3D arrow object for visualizing directions.
  42409. *
  42410. * ```js
  42411. * const dir = new THREE.Vector3( 1, 2, 0 );
  42412. *
  42413. * //normalize the direction vector (convert to vector of length 1)
  42414. * dir.normalize();
  42415. *
  42416. * const origin = new THREE.Vector3( 0, 0, 0 );
  42417. * const length = 1;
  42418. * const hex = 0xffff00;
  42419. *
  42420. * const arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex );
  42421. * scene.add( arrowHelper );
  42422. * ```
  42423. *
  42424. * @augments Object3D
  42425. */
  42426. class ArrowHelper extends Object3D {
  42427. /**
  42428. * Constructs a new arrow helper.
  42429. *
  42430. * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector.
  42431. * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts.
  42432. * @param {number} [length=1] - Length of the arrow in world units.
  42433. * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow.
  42434. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  42435. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  42436. */
  42437. 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 ) {
  42438. super();
  42439. this.type = 'ArrowHelper';
  42440. if ( _lineGeometry === undefined ) {
  42441. _lineGeometry = new BufferGeometry();
  42442. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  42443. _coneGeometry = new ConeGeometry( 0.5, 1, 5, 1 );
  42444. _coneGeometry.translate( 0, -0.5, 0 );
  42445. }
  42446. this.position.copy( origin );
  42447. /**
  42448. * The line part of the arrow helper.
  42449. *
  42450. * @type {Line}
  42451. */
  42452. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42453. this.line.matrixAutoUpdate = false;
  42454. this.add( this.line );
  42455. /**
  42456. * The cone part of the arrow helper.
  42457. *
  42458. * @type {Mesh}
  42459. */
  42460. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  42461. this.cone.matrixAutoUpdate = false;
  42462. this.add( this.cone );
  42463. this.setDirection( dir );
  42464. this.setLength( length, headLength, headWidth );
  42465. }
  42466. /**
  42467. * Sets the direction of the helper.
  42468. *
  42469. * @param {Vector3} dir - The normalized direction vector.
  42470. */
  42471. setDirection( dir ) {
  42472. // dir is assumed to be normalized
  42473. if ( dir.y > 0.99999 ) {
  42474. this.quaternion.set( 0, 0, 0, 1 );
  42475. } else if ( dir.y < -0.99999 ) {
  42476. this.quaternion.set( 1, 0, 0, 0 );
  42477. } else {
  42478. _axis.set( dir.z, 0, - dir.x ).normalize();
  42479. const radians = Math.acos( dir.y );
  42480. this.quaternion.setFromAxisAngle( _axis, radians );
  42481. }
  42482. }
  42483. /**
  42484. * Sets the length of the helper.
  42485. *
  42486. * @param {number} length - Length of the arrow in world units.
  42487. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  42488. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  42489. */
  42490. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  42491. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  42492. this.line.updateMatrix();
  42493. this.cone.scale.set( headWidth, headLength, headWidth );
  42494. this.cone.position.y = length;
  42495. this.cone.updateMatrix();
  42496. }
  42497. /**
  42498. * Sets the color of the helper.
  42499. *
  42500. * @param {number|Color|string} color - The color to set.
  42501. */
  42502. setColor( color ) {
  42503. this.line.material.color.set( color );
  42504. this.cone.material.color.set( color );
  42505. }
  42506. copy( source ) {
  42507. super.copy( source, false );
  42508. this.line.copy( source.line );
  42509. this.cone.copy( source.cone );
  42510. return this;
  42511. }
  42512. /**
  42513. * Frees the GPU-related resources allocated by this instance. Call this
  42514. * method whenever this instance is no longer used in your app.
  42515. */
  42516. dispose() {
  42517. this.line.geometry.dispose();
  42518. this.line.material.dispose();
  42519. this.cone.geometry.dispose();
  42520. this.cone.material.dispose();
  42521. }
  42522. }
  42523. /**
  42524. * An axis object to visualize the 3 axes in a simple way.
  42525. * The X axis is red. The Y axis is green. The Z axis is blue.
  42526. *
  42527. * ```js
  42528. * const axesHelper = new THREE.AxesHelper( 5 );
  42529. * scene.add( axesHelper );
  42530. * ```
  42531. *
  42532. * @augments LineSegments
  42533. */
  42534. class AxesHelper extends LineSegments {
  42535. /**
  42536. * Constructs a new axes helper.
  42537. *
  42538. * @param {number} [size=1] - Size of the lines representing the axes.
  42539. */
  42540. constructor( size = 1 ) {
  42541. const vertices = [
  42542. 0, 0, 0, size, 0, 0,
  42543. 0, 0, 0, 0, size, 0,
  42544. 0, 0, 0, 0, 0, size
  42545. ];
  42546. const colors = [
  42547. 1, 0, 0, 1, 0.6, 0,
  42548. 0, 1, 0, 0.6, 1, 0,
  42549. 0, 0, 1, 0, 0.6, 1
  42550. ];
  42551. const geometry = new BufferGeometry();
  42552. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  42553. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  42554. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  42555. super( geometry, material );
  42556. this.type = 'AxesHelper';
  42557. }
  42558. /**
  42559. * Defines the colors of the axes helper.
  42560. *
  42561. * @param {number|Color|string} xAxisColor - The color for the x axis.
  42562. * @param {number|Color|string} yAxisColor - The color for the y axis.
  42563. * @param {number|Color|string} zAxisColor - The color for the z axis.
  42564. * @return {AxesHelper} A reference to this axes helper.
  42565. */
  42566. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  42567. const color = new Color();
  42568. const array = this.geometry.attributes.color.array;
  42569. color.set( xAxisColor );
  42570. color.toArray( array, 0 );
  42571. color.toArray( array, 3 );
  42572. color.set( yAxisColor );
  42573. color.toArray( array, 6 );
  42574. color.toArray( array, 9 );
  42575. color.set( zAxisColor );
  42576. color.toArray( array, 12 );
  42577. color.toArray( array, 15 );
  42578. this.geometry.attributes.color.needsUpdate = true;
  42579. return this;
  42580. }
  42581. /**
  42582. * Frees the GPU-related resources allocated by this instance. Call this
  42583. * method whenever this instance is no longer used in your app.
  42584. */
  42585. dispose() {
  42586. this.geometry.dispose();
  42587. this.material.dispose();
  42588. }
  42589. }
  42590. /**
  42591. * This class is used to convert a series of paths to an array of
  42592. * shapes. It is specifically used in context of fonts and SVG.
  42593. */
  42594. class ShapePath {
  42595. /**
  42596. * Constructs a new shape path.
  42597. */
  42598. constructor() {
  42599. this.type = 'ShapePath';
  42600. /**
  42601. * The color of the shape.
  42602. *
  42603. * @type {Color}
  42604. */
  42605. this.color = new Color();
  42606. /**
  42607. * The paths that have been generated for this shape.
  42608. *
  42609. * @type {Array<Path>}
  42610. * @default null
  42611. */
  42612. this.subPaths = [];
  42613. /**
  42614. * The current path that is being generated.
  42615. *
  42616. * @type {?Path}
  42617. * @default null
  42618. */
  42619. this.currentPath = null;
  42620. }
  42621. /**
  42622. * Creates a new path and moves it current point to the given one.
  42623. *
  42624. * @param {number} x - The x coordinate.
  42625. * @param {number} y - The y coordinate.
  42626. * @return {ShapePath} A reference to this shape path.
  42627. */
  42628. moveTo( x, y ) {
  42629. this.currentPath = new Path();
  42630. this.subPaths.push( this.currentPath );
  42631. this.currentPath.moveTo( x, y );
  42632. return this;
  42633. }
  42634. /**
  42635. * Adds an instance of {@link LineCurve} to the path by connecting
  42636. * the current point with the given one.
  42637. *
  42638. * @param {number} x - The x coordinate of the end point.
  42639. * @param {number} y - The y coordinate of the end point.
  42640. * @return {ShapePath} A reference to this shape path.
  42641. */
  42642. lineTo( x, y ) {
  42643. this.currentPath.lineTo( x, y );
  42644. return this;
  42645. }
  42646. /**
  42647. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  42648. * the current point with the given one.
  42649. *
  42650. * @param {number} aCPx - The x coordinate of the control point.
  42651. * @param {number} aCPy - The y coordinate of the control point.
  42652. * @param {number} aX - The x coordinate of the end point.
  42653. * @param {number} aY - The y coordinate of the end point.
  42654. * @return {ShapePath} A reference to this shape path.
  42655. */
  42656. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  42657. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  42658. return this;
  42659. }
  42660. /**
  42661. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  42662. * the current point with the given one.
  42663. *
  42664. * @param {number} aCP1x - The x coordinate of the first control point.
  42665. * @param {number} aCP1y - The y coordinate of the first control point.
  42666. * @param {number} aCP2x - The x coordinate of the second control point.
  42667. * @param {number} aCP2y - The y coordinate of the second control point.
  42668. * @param {number} aX - The x coordinate of the end point.
  42669. * @param {number} aY - The y coordinate of the end point.
  42670. * @return {ShapePath} A reference to this shape path.
  42671. */
  42672. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  42673. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  42674. return this;
  42675. }
  42676. /**
  42677. * Adds an instance of {@link SplineCurve} to the path by connecting
  42678. * the current point with the given list of points.
  42679. *
  42680. * @param {Array<Vector2>} pts - An array of points in 2D space.
  42681. * @return {ShapePath} A reference to this shape path.
  42682. */
  42683. splineThru( pts ) {
  42684. this.currentPath.splineThru( pts );
  42685. return this;
  42686. }
  42687. /**
  42688. * Converts the paths into an array of shapes.
  42689. *
  42690. * @param {boolean} isCCW - By default solid shapes are defined clockwise (CW) and holes are defined counterclockwise (CCW).
  42691. * If this flag is set to `true`, then those are flipped.
  42692. * @return {Array<Shape>} An array of shapes.
  42693. */
  42694. toShapes( isCCW ) {
  42695. function toShapesNoHoles( inSubpaths ) {
  42696. const shapes = [];
  42697. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  42698. const tmpPath = inSubpaths[ i ];
  42699. const tmpShape = new Shape();
  42700. tmpShape.curves = tmpPath.curves;
  42701. shapes.push( tmpShape );
  42702. }
  42703. return shapes;
  42704. }
  42705. function isPointInsidePolygon( inPt, inPolygon ) {
  42706. const polyLen = inPolygon.length;
  42707. // inPt on polygon contour => immediate success or
  42708. // toggling of inside/outside at every single! intersection point of an edge
  42709. // with the horizontal line through inPt, left of inPt
  42710. // not counting lowerY endpoints of edges and whole edges on that line
  42711. let inside = false;
  42712. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  42713. let edgeLowPt = inPolygon[ p ];
  42714. let edgeHighPt = inPolygon[ q ];
  42715. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  42716. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  42717. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  42718. // not parallel
  42719. if ( edgeDy < 0 ) {
  42720. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  42721. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  42722. }
  42723. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  42724. if ( inPt.y === edgeLowPt.y ) {
  42725. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  42726. // continue; // no intersection or edgeLowPt => doesn't count !!!
  42727. } else {
  42728. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  42729. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  42730. if ( perpEdge < 0 ) continue;
  42731. inside = ! inside; // true intersection left of inPt
  42732. }
  42733. } else {
  42734. // parallel or collinear
  42735. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  42736. // edge lies on the same horizontal line as inPt
  42737. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  42738. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  42739. // continue;
  42740. }
  42741. }
  42742. return inside;
  42743. }
  42744. const isClockWise = ShapeUtils.isClockWise;
  42745. const subPaths = this.subPaths;
  42746. if ( subPaths.length === 0 ) return [];
  42747. let solid, tmpPath, tmpShape;
  42748. const shapes = [];
  42749. if ( subPaths.length === 1 ) {
  42750. tmpPath = subPaths[ 0 ];
  42751. tmpShape = new Shape();
  42752. tmpShape.curves = tmpPath.curves;
  42753. shapes.push( tmpShape );
  42754. return shapes;
  42755. }
  42756. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  42757. holesFirst = isCCW ? ! holesFirst : holesFirst;
  42758. // log("Holes first", holesFirst);
  42759. const betterShapeHoles = [];
  42760. const newShapes = [];
  42761. let newShapeHoles = [];
  42762. let mainIdx = 0;
  42763. let tmpPoints;
  42764. newShapes[ mainIdx ] = undefined;
  42765. newShapeHoles[ mainIdx ] = [];
  42766. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  42767. tmpPath = subPaths[ i ];
  42768. tmpPoints = tmpPath.getPoints();
  42769. solid = isClockWise( tmpPoints );
  42770. solid = isCCW ? ! solid : solid;
  42771. if ( solid ) {
  42772. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  42773. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  42774. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  42775. if ( holesFirst ) mainIdx ++;
  42776. newShapeHoles[ mainIdx ] = [];
  42777. //log('cw', i);
  42778. } else {
  42779. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  42780. //log('ccw', i);
  42781. }
  42782. }
  42783. // only Holes? -> probably all Shapes with wrong orientation
  42784. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  42785. if ( newShapes.length > 1 ) {
  42786. let ambiguous = false;
  42787. let toChange = 0;
  42788. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42789. betterShapeHoles[ sIdx ] = [];
  42790. }
  42791. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42792. const sho = newShapeHoles[ sIdx ];
  42793. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  42794. const ho = sho[ hIdx ];
  42795. let hole_unassigned = true;
  42796. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  42797. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  42798. if ( sIdx !== s2Idx ) toChange ++;
  42799. if ( hole_unassigned ) {
  42800. hole_unassigned = false;
  42801. betterShapeHoles[ s2Idx ].push( ho );
  42802. } else {
  42803. ambiguous = true;
  42804. }
  42805. }
  42806. }
  42807. if ( hole_unassigned ) {
  42808. betterShapeHoles[ sIdx ].push( ho );
  42809. }
  42810. }
  42811. }
  42812. if ( toChange > 0 && ambiguous === false ) {
  42813. newShapeHoles = betterShapeHoles;
  42814. }
  42815. }
  42816. let tmpHoles;
  42817. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  42818. tmpShape = newShapes[ i ].s;
  42819. shapes.push( tmpShape );
  42820. tmpHoles = newShapeHoles[ i ];
  42821. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  42822. tmpShape.holes.push( tmpHoles[ j ].h );
  42823. }
  42824. }
  42825. //log("shape", shapes);
  42826. return shapes;
  42827. }
  42828. }
  42829. /**
  42830. * Abstract base class for controls.
  42831. *
  42832. * @abstract
  42833. * @augments EventDispatcher
  42834. */
  42835. class Controls extends EventDispatcher {
  42836. /**
  42837. * Constructs a new controls instance.
  42838. *
  42839. * @param {Object3D} object - The object that is managed by the controls.
  42840. * @param {?HTMLElement} domElement - The HTML element used for event listeners.
  42841. */
  42842. constructor( object, domElement = null ) {
  42843. super();
  42844. /**
  42845. * The object that is managed by the controls.
  42846. *
  42847. * @type {Object3D}
  42848. */
  42849. this.object = object;
  42850. /**
  42851. * The HTML element used for event listeners.
  42852. *
  42853. * @type {?HTMLElement}
  42854. * @default null
  42855. */
  42856. this.domElement = domElement;
  42857. /**
  42858. * Whether the controls responds to user input or not.
  42859. *
  42860. * @type {boolean}
  42861. * @default true
  42862. */
  42863. this.enabled = true;
  42864. /**
  42865. * The internal state of the controls.
  42866. *
  42867. * @type {number}
  42868. * @default -1
  42869. */
  42870. this.state = -1;
  42871. /**
  42872. * This object defines the keyboard input of the controls.
  42873. *
  42874. * @type {Object}
  42875. */
  42876. this.keys = {};
  42877. /**
  42878. * This object defines what type of actions are assigned to the available mouse buttons.
  42879. * It depends on the control implementation what kind of mouse buttons and actions are supported.
  42880. *
  42881. * @type {{LEFT: ?number, MIDDLE: ?number, RIGHT: ?number}}
  42882. */
  42883. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  42884. /**
  42885. * This object defines what type of actions are assigned to what kind of touch interaction.
  42886. * It depends on the control implementation what kind of touch interaction and actions are supported.
  42887. *
  42888. * @type {{ONE: ?number, TWO: ?number}}
  42889. */
  42890. this.touches = { ONE: null, TWO: null };
  42891. }
  42892. /**
  42893. * Connects the controls to the DOM. This method has so called "side effects" since
  42894. * it adds the module's event listeners to the DOM.
  42895. *
  42896. * @param {HTMLElement} element - The DOM element to connect to.
  42897. */
  42898. connect( element ) {
  42899. if ( element === undefined ) {
  42900. warn( 'Controls: connect() now requires an element.' ); // @deprecated, the warning can be removed with r185
  42901. return;
  42902. }
  42903. if ( this.domElement !== null ) this.disconnect();
  42904. this.domElement = element;
  42905. }
  42906. /**
  42907. * Disconnects the controls from the DOM.
  42908. */
  42909. disconnect() {}
  42910. /**
  42911. * Call this method if you no longer want use to the controls. It frees all internal
  42912. * resources and removes all event listeners.
  42913. */
  42914. dispose() {}
  42915. /**
  42916. * Controls should implement this method if they have to update their internal state
  42917. * per simulation step.
  42918. *
  42919. * @param {number} [delta] - The time delta in seconds.
  42920. */
  42921. update( /* delta */ ) {}
  42922. }
  42923. /**
  42924. * Scales the texture as large as possible within its surface without cropping
  42925. * or stretching the texture. The method preserves the original aspect ratio of
  42926. * the texture. Akin to CSS `object-fit: contain`
  42927. *
  42928. * @param {Texture} texture - The texture.
  42929. * @param {number} aspect - The texture's aspect ratio.
  42930. * @return {Texture} The updated texture.
  42931. */
  42932. function contain( texture, aspect ) {
  42933. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42934. if ( imageAspect > aspect ) {
  42935. texture.repeat.x = 1;
  42936. texture.repeat.y = imageAspect / aspect;
  42937. texture.offset.x = 0;
  42938. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42939. } else {
  42940. texture.repeat.x = aspect / imageAspect;
  42941. texture.repeat.y = 1;
  42942. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42943. texture.offset.y = 0;
  42944. }
  42945. return texture;
  42946. }
  42947. /**
  42948. * Scales the texture to the smallest possible size to fill the surface, leaving
  42949. * no empty space. The method preserves the original aspect ratio of the texture.
  42950. * Akin to CSS `object-fit: cover`.
  42951. *
  42952. * @param {Texture} texture - The texture.
  42953. * @param {number} aspect - The texture's aspect ratio.
  42954. * @return {Texture} The updated texture.
  42955. */
  42956. function cover( texture, aspect ) {
  42957. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42958. if ( imageAspect > aspect ) {
  42959. texture.repeat.x = aspect / imageAspect;
  42960. texture.repeat.y = 1;
  42961. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42962. texture.offset.y = 0;
  42963. } else {
  42964. texture.repeat.x = 1;
  42965. texture.repeat.y = imageAspect / aspect;
  42966. texture.offset.x = 0;
  42967. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42968. }
  42969. return texture;
  42970. }
  42971. /**
  42972. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42973. *
  42974. * @param {Texture} texture - The texture.
  42975. * @return {Texture} The updated texture.
  42976. */
  42977. function fill( texture ) {
  42978. texture.repeat.x = 1;
  42979. texture.repeat.y = 1;
  42980. texture.offset.x = 0;
  42981. texture.offset.y = 0;
  42982. return texture;
  42983. }
  42984. /**
  42985. * Determines how many bytes must be used to represent the texture.
  42986. *
  42987. * @param {number} width - The width of the texture.
  42988. * @param {number} height - The height of the texture.
  42989. * @param {number} format - The texture's format.
  42990. * @param {number} type - The texture's type.
  42991. * @return {number} The byte length.
  42992. */
  42993. function getByteLength( width, height, format, type ) {
  42994. const typeByteLength = getTextureTypeByteLength( type );
  42995. switch ( format ) {
  42996. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  42997. case AlphaFormat:
  42998. return width * height;
  42999. case RedFormat:
  43000. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  43001. case RedIntegerFormat:
  43002. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  43003. case RGFormat:
  43004. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  43005. case RGIntegerFormat:
  43006. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  43007. case RGBFormat:
  43008. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  43009. case RGBAFormat:
  43010. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  43011. case RGBAIntegerFormat:
  43012. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  43013. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  43014. case RGB_S3TC_DXT1_Format:
  43015. case RGBA_S3TC_DXT1_Format:
  43016. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  43017. case RGBA_S3TC_DXT3_Format:
  43018. case RGBA_S3TC_DXT5_Format:
  43019. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  43020. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  43021. case RGB_PVRTC_2BPPV1_Format:
  43022. case RGBA_PVRTC_2BPPV1_Format:
  43023. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  43024. case RGB_PVRTC_4BPPV1_Format:
  43025. case RGBA_PVRTC_4BPPV1_Format:
  43026. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  43027. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  43028. case RGB_ETC1_Format:
  43029. case RGB_ETC2_Format:
  43030. case R11_EAC_Format:
  43031. case SIGNED_R11_EAC_Format:
  43032. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  43033. case RGBA_ETC2_EAC_Format:
  43034. case RG11_EAC_Format:
  43035. case SIGNED_RG11_EAC_Format:
  43036. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  43037. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  43038. case RGBA_ASTC_4x4_Format:
  43039. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  43040. case RGBA_ASTC_5x4_Format:
  43041. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  43042. case RGBA_ASTC_5x5_Format:
  43043. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  43044. case RGBA_ASTC_6x5_Format:
  43045. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  43046. case RGBA_ASTC_6x6_Format:
  43047. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  43048. case RGBA_ASTC_8x5_Format:
  43049. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  43050. case RGBA_ASTC_8x6_Format:
  43051. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  43052. case RGBA_ASTC_8x8_Format:
  43053. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  43054. case RGBA_ASTC_10x5_Format:
  43055. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  43056. case RGBA_ASTC_10x6_Format:
  43057. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  43058. case RGBA_ASTC_10x8_Format:
  43059. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  43060. case RGBA_ASTC_10x10_Format:
  43061. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  43062. case RGBA_ASTC_12x10_Format:
  43063. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  43064. case RGBA_ASTC_12x12_Format:
  43065. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  43066. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  43067. case RGBA_BPTC_Format:
  43068. case RGB_BPTC_SIGNED_Format:
  43069. case RGB_BPTC_UNSIGNED_Format:
  43070. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  43071. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  43072. case RED_RGTC1_Format:
  43073. case SIGNED_RED_RGTC1_Format:
  43074. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  43075. case RED_GREEN_RGTC2_Format:
  43076. case SIGNED_RED_GREEN_RGTC2_Format:
  43077. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  43078. }
  43079. throw new Error(
  43080. `Unable to determine texture byte length for ${format} format.`,
  43081. );
  43082. }
  43083. function getTextureTypeByteLength( type ) {
  43084. switch ( type ) {
  43085. case UnsignedByteType:
  43086. case ByteType:
  43087. return { byteLength: 1, components: 1 };
  43088. case UnsignedShortType:
  43089. case ShortType:
  43090. case HalfFloatType:
  43091. return { byteLength: 2, components: 1 };
  43092. case UnsignedShort4444Type:
  43093. case UnsignedShort5551Type:
  43094. return { byteLength: 2, components: 4 };
  43095. case UnsignedIntType:
  43096. case IntType:
  43097. case FloatType:
  43098. return { byteLength: 4, components: 1 };
  43099. case UnsignedInt5999Type:
  43100. case UnsignedInt101111Type:
  43101. return { byteLength: 4, components: 3 };
  43102. }
  43103. throw new Error( `Unknown texture type ${type}.` );
  43104. }
  43105. /**
  43106. * A class containing utility functions for textures.
  43107. *
  43108. * @hideconstructor
  43109. */
  43110. class TextureUtils {
  43111. /**
  43112. * Scales the texture as large as possible within its surface without cropping
  43113. * or stretching the texture. The method preserves the original aspect ratio of
  43114. * the texture. Akin to CSS `object-fit: contain`
  43115. *
  43116. * @param {Texture} texture - The texture.
  43117. * @param {number} aspect - The texture's aspect ratio.
  43118. * @return {Texture} The updated texture.
  43119. */
  43120. static contain( texture, aspect ) {
  43121. return contain( texture, aspect );
  43122. }
  43123. /**
  43124. * Scales the texture to the smallest possible size to fill the surface, leaving
  43125. * no empty space. The method preserves the original aspect ratio of the texture.
  43126. * Akin to CSS `object-fit: cover`.
  43127. *
  43128. * @param {Texture} texture - The texture.
  43129. * @param {number} aspect - The texture's aspect ratio.
  43130. * @return {Texture} The updated texture.
  43131. */
  43132. static cover( texture, aspect ) {
  43133. return cover( texture, aspect );
  43134. }
  43135. /**
  43136. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  43137. *
  43138. * @param {Texture} texture - The texture.
  43139. * @return {Texture} The updated texture.
  43140. */
  43141. static fill( texture ) {
  43142. return fill( texture );
  43143. }
  43144. /**
  43145. * Determines how many bytes must be used to represent the texture.
  43146. *
  43147. * @param {number} width - The width of the texture.
  43148. * @param {number} height - The height of the texture.
  43149. * @param {number} format - The texture's format.
  43150. * @param {number} type - The texture's type.
  43151. * @return {number} The byte length.
  43152. */
  43153. static getByteLength( width, height, format, type ) {
  43154. return getByteLength( width, height, format, type );
  43155. }
  43156. }
  43157. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  43158. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  43159. revision: REVISION,
  43160. } } ) );
  43161. }
  43162. if ( typeof window !== 'undefined' ) {
  43163. if ( window.__THREE__ ) {
  43164. warn( 'WARNING: Multiple instances of Three.js being imported.' );
  43165. } else {
  43166. window.__THREE__ = REVISION;
  43167. }
  43168. }
  43169. 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, BezierInterpolant, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CineonToneMapping, CircleGeometry, ClampToEdgeWrapping, Clock, Color, ColorKeyframeTrack, ColorManagement, Compatibility, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, Controls, CubeCamera, CubeDepthTexture, 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, ExternalTexture, ExtrudeGeometry, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, Fog, FogExp2, FramebufferTexture, FrontSide, Frustum, FrustumArray, 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, InterpolateBezier, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InterpolationSamplingMode, InterpolationSamplingType, 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, MOUSE, Material, MaterialBlending, 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, NoNormalPacking, NoToneMapping, NormalAnimationBlendMode, NormalBlending, NormalGAPacking, NormalRGPacking, 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, R11_EAC_Format, RAD2DEG, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RG11_EAC_Format, 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, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, ReversedDepthFuncs, RingGeometry, SIGNED_R11_EAC_Format, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SIGNED_RG11_EAC_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, Timer, TimestampQuery, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, UniformsUtils, UnsignedByteType, UnsignedInt101111Type, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCoordinateSystem, WebGLRenderTarget, WebGPUCoordinateSystem, WebXRController, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, cloneUniforms, createCanvasElement, createElementNS, error, getByteLength, getConsoleFunction, getUnlitUniformColorSpace, isTypedArray, log, mergeUniforms, probeAsync, setConsoleFunction, warn, warnOnce, yieldToMain };
粤ICP备19079148号